noskills 4.5.1 → 4.5.2

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 (91) hide show
  1. package/chunks/{ajan-bridge-T5M4DPDT.js → ajan-bridge-BNPC757J.js} +1 -1
  2. package/chunks/{anthropic-TS7EMQML.js → anthropic-ZKOMTKX2.js} +1 -1
  3. package/chunks/{approve-HEW3VFYH.js → approve-3TKOHYHH.js} +1 -1
  4. package/chunks/{ask-AXHTCVD6.js → ask-UB26SBWQ.js} +1 -1
  5. package/chunks/{block-VN76CXZW.js → block-Q4WAIX7X.js} +1 -1
  6. package/chunks/{cancel-7WRAST62.js → cancel-DY76ADX4.js} +1 -1
  7. package/chunks/{chunk-4PF2MT7S.js → chunk-34RPTI4K.js} +7 -7
  8. package/chunks/chunk-3JTDWOAJ.js +2 -0
  9. package/chunks/{chunk-GQTHILPL.js → chunk-5FX4EBFY.js} +1 -1
  10. package/chunks/chunk-5OTECUN7.js +1 -0
  11. package/chunks/{chunk-6YSS6PEL.js → chunk-7PBHRFOZ.js} +1 -1
  12. package/chunks/{chunk-7GC46XEU.js → chunk-AB3N327V.js} +1 -1
  13. package/chunks/{chunk-KMLNG3EC.js → chunk-BYPCI5VU.js} +1 -1
  14. package/chunks/{chunk-QKWJ72HI.js → chunk-CKIZYL4O.js} +1 -1
  15. package/chunks/{chunk-S4MUTKHT.js → chunk-DYCGJ4RY.js} +1 -1
  16. package/chunks/{chunk-UE56BMAW.js → chunk-EVJYA7S3.js} +1 -1
  17. package/chunks/{chunk-LN4NDYT6.js → chunk-FYFUEK4U.js} +1 -1
  18. package/chunks/chunk-GNMOE7H3.js +48 -0
  19. package/chunks/chunk-HB62UGZI.js +2 -0
  20. package/chunks/{chunk-EIMBEXUJ.js → chunk-IM73MYMS.js} +1 -1
  21. package/chunks/{chunk-KM64FL2X.js → chunk-J25XTDQQ.js} +1 -1
  22. package/chunks/{chunk-JL3MAFYQ.js → chunk-LGQEWL5X.js} +1 -1
  23. package/chunks/{chunk-5DZHAHXW.js → chunk-LKZZ4JN5.js} +1 -1
  24. package/chunks/{chunk-DBKXMYLF.js → chunk-NPWXEWRN.js} +1 -1
  25. package/chunks/{chunk-PKEQKXZW.js → chunk-ONJVI5AZ.js} +1 -1
  26. package/chunks/{chunk-EIGFDYGQ.js → chunk-OP4XAIGW.js} +1 -1
  27. package/chunks/{chunk-W4TQLLUK.js → chunk-T6NZVA6P.js} +1 -1
  28. package/chunks/{chunk-5PBNUBBY.js → chunk-TCSIXKUD.js} +1 -1
  29. package/chunks/{chunk-KRKOWSYW.js → chunk-WDKWHGJU.js} +5 -7
  30. package/chunks/{chunk-PRQ5CRIG.js → chunk-XDPATEP5.js} +1 -1
  31. package/chunks/{chunk-CML74SNT.js → chunk-Y45DQJSS.js} +1 -1
  32. package/chunks/{chunk-RAQY37P6.js → chunk-YUTDPPXX.js} +1 -1
  33. package/chunks/claude-code-OQJIUKZP.js +1 -0
  34. package/chunks/{concern-QSENGU6C.js → concern-UIGVWDFS.js} +1 -1
  35. package/chunks/{config-S3UXTJN2.js → config-72Z4PIJN.js} +1 -1
  36. package/chunks/{decision-ledger-GY2W6VWL.js → decision-ledger-5IPPTRT7.js} +1 -1
  37. package/chunks/{delegate-WKXIER7E.js → delegate-OV6NY434.js} +1 -1
  38. package/chunks/{diagrams-A7W2EBYV.js → diagrams-OX4FBDGP.js} +1 -1
  39. package/chunks/{done-WR3UFYJT.js → done-V54GSSTY.js} +1 -1
  40. package/chunks/{followup-5EGZEF5Q.js → followup-NL7EPIGF.js} +1 -1
  41. package/chunks/{free-KJQHRYZA.js → free-KD344KRL.js} +1 -1
  42. package/chunks/{gemini-IWP24T63.js → gemini-23EOEXSF.js} +1 -1
  43. package/chunks/{init-437SU6XH.js → init-WDRNFT57.js} +1 -1
  44. package/chunks/{invoke-hook-LMCWNF65.js → invoke-hook-I3NTD36Q.js} +1 -1
  45. package/chunks/kiro-TPAAIMY6.js +1 -0
  46. package/chunks/{learn-ZTYKBZER.js → learn-WBWNJEB2.js} +1 -1
  47. package/chunks/{ledger-FOOPJ2UO.js → ledger-QYK252DV.js} +1 -1
  48. package/chunks/{list-HNGIOVBK.js → list-WO6RS7JX.js} +1 -1
  49. package/chunks/{manager-2MOLEJ4Q.js → manager-ZSPRC5R4.js} +1 -1
  50. package/chunks/{mod-AJIRKRAH.js → mod-B6LBGYON.js} +1 -1
  51. package/chunks/{mod-6EZYRKWV.js → mod-MMHDQRNF.js} +1 -1
  52. package/chunks/{mod-7X5TKHKC.js → mod-RBGAMGZA.js} +1 -1
  53. package/chunks/{mod-TGOMO3CJ.js → mod-SV4VELMH.js} +1 -1
  54. package/chunks/{next-Y6FOPM4Z.js → next-QXCLZ7P3.js} +1 -1
  55. package/chunks/node-2XIHQ2M4.js +1 -0
  56. package/chunks/node-BXYZKSJY.js +15 -0
  57. package/chunks/node-DMUOWFGA.js +69 -0
  58. package/chunks/ollama-MXRDGQDF.js +1 -0
  59. package/chunks/openai-LE47IWMQ.js +30 -0
  60. package/chunks/{openai-YES2XJDU.js → openai-MSJF4B6H.js} +1 -1
  61. package/chunks/opencode-ZDHKR2P6.js +1 -0
  62. package/chunks/{pack-KUT53Z24.js → pack-NS64WU6M.js} +1 -1
  63. package/chunks/{plan-export-PG2BVRQZ.js → plan-export-HECAF7D4.js} +1 -1
  64. package/chunks/{purge-JGNJNEET.js → purge-PSQNN42H.js} +1 -1
  65. package/chunks/{reopen-RPDXN3CF.js → reopen-L37M5XUI.js} +1 -1
  66. package/chunks/{reset-RBCQO2RF.js → reset-OOTZXW6Q.js} +1 -1
  67. package/chunks/{review-VMS5MYOV.js → review-QLD6WSOB.js} +1 -1
  68. package/chunks/{rule-IB4VKSBC.js → rule-OOANQBHB.js} +1 -1
  69. package/chunks/{run-62PWXVII.js → run-YHCIRY7Z.js} +1 -1
  70. package/chunks/{sdk-FR7Z4YSC.js → sdk-OQIHH3OY.js} +1 -1
  71. package/chunks/{session-Q43KMFL2.js → session-OWWDH7KA.js} +1 -1
  72. package/chunks/{spec-4RKLPOEM.js → spec-O7F525UN.js} +1 -1
  73. package/chunks/{status-OGLFEFF7.js → status-SZZXY7V3.js} +1 -1
  74. package/chunks/{sync-H35O5DN5.js → sync-3RYRGTEA.js} +1 -1
  75. package/chunks/{validate-JX7UTAK5.js → validate-UZD6JBSG.js} +1 -1
  76. package/chunks/{vertexai-WF5CKMYI.js → vertexai-CVCRCO24.js} +1 -1
  77. package/chunks/{watch-SOZDHLSC.js → watch-5DNM646U.js} +1 -1
  78. package/chunks/{web-3VGRM3W4.js → web-662LNB3K.js} +1 -1
  79. package/chunks/{wontfix-RBOGLLWJ.js → wontfix-UDCTLHNB.js} +1 -1
  80. package/noskills.js +1 -1
  81. package/package.json +1 -1
  82. package/chunks/chunk-3ZJ3UGQL.js +0 -48
  83. package/chunks/chunk-575Y3OEG.js +0 -1
  84. package/chunks/chunk-IGDFEGCH.js +0 -2
  85. package/chunks/claude-code-DIWRQKZA.js +0 -1
  86. package/chunks/kiro-THWCXS5L.js +0 -1
  87. package/chunks/node-AZK2C657.js +0 -12
  88. package/chunks/node-GQQ42DT2.js +0 -68
  89. package/chunks/ollama-2KAMCXVL.js +0 -1
  90. package/chunks/openai-HHE35TAX.js +0 -31
  91. package/chunks/opencode-S4M7WJTO.js +0 -1
@@ -0,0 +1,30 @@
1
+ import{c as Id,d as Pd,e as xd}from"./chunk-HISXAZ4Y.js";var bu=Id((X,ri)=>{"use strict";if(typeof ri<"u"&&ri!==globalThis.module&&typeof X<"u"&&ri.exports===X){Object.defineProperty(X,"__esModule",{value:!0}),X.findX509Credential=X.rememberX509Credential=X.findX509OAuthError=X.rememberX509OAuthError=X.isApprovedX509Client=X.markApprovedX509Client=X.isRetryableX509IssuerError=X.markRetryableX509IssuerError=X.isTransientX509ConnectionError=X.markTransientX509ConnectionError=X.rememberRegisteredX509Transport=X.findRegisteredX509Transport=void 0;let r=new WeakMap,e=new WeakSet,t=new WeakSet,n=new WeakSet,s=new WeakMap,o=new WeakMap;X.findRegisteredX509Transport=WeakMap.prototype.get.bind(r),X.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(r),X.markTransientX509ConnectionError=WeakSet.prototype.add.bind(e),X.isTransientX509ConnectionError=WeakSet.prototype.has.bind(e),X.markRetryableX509IssuerError=WeakSet.prototype.add.bind(t),X.isRetryableX509IssuerError=WeakSet.prototype.has.bind(t),X.markApprovedX509Client=WeakSet.prototype.add.bind(n),X.isApprovedX509Client=WeakSet.prototype.has.bind(n),X.rememberX509OAuthError=WeakMap.prototype.set.bind(s),X.findX509OAuthError=WeakMap.prototype.get.bind(s),X.rememberX509Credential=WeakMap.prototype.set.bind(o),X.findX509Credential=WeakMap.prototype.get.bind(o)}});function b(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 a(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 Je=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return Je=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 mt(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Js=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 h=class extends Error{},z=class r extends h{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 o=t;this.code=o?.code,this.param=o?.param,this.type=o?.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 De({message:n,cause:Js(t)});let o=t?.error;return e===400?new ot(e,o,n,s):e===401?new $t(e,o,n,s):e===403?new jt(e,o,n,s):e===404?new Lt(e,o,n,s):e===409?new Mt(e,o,n,s):e===422?new Bt(e,o,n,s):e===429?new Dt(e,o,n,s):e>=500?new Nt(e,o,n,s):new r(e,o,n,s)}},Y=class extends z{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},De=class extends z{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},re=class extends De{constructor({message:e}={}){super({message:e??"Request timed out."})}},ot=class extends z{},$t=class extends z{},jt=class extends z{},Lt=class extends z{},Mt=class extends z{},Bt=class extends z{},Dt=class extends z{},Nt=class extends z{},Ft=class extends h{constructor(){super("Could not parse response content as the length limit was reached")}},Wt=class extends h{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Oe=class extends Error{constructor(e){super(e)}},Ne=class extends z{constructor(e,t,n){let s="OAuth2 authentication error",o;if(t&&typeof t=="object"){let i=t;o=i.error;let c=i.error_description;c&&typeof c=="string"?s=c:o&&(s=o)}super(e,t,s,n),this.error_code=o}},gr=class extends h{constructor(e,t,n){super(e),this.provider=t,this.cause=n}};var Rd=/^[a-z][a-z0-9+.-]*:/i,Cc=r=>Rd.test(r),we=r=>(we=Array.isArray,we(r)),Tc=we;function Vs(r){return typeof r!="object"?{}:r??{}}function ta(r){if(!r)return!0;for(let e in r)return!1;return!0}function $(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function ye(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var ra=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new h(`${r} must be an integer`);if(e<0)throw new h(`${r} must be a positive integer`);return e};var $c=r=>{try{return JSON.parse(r)}catch{return}};var mn=(r,...e)=>new Promise((t,n)=>{let s=[...new Set(e.filter(m=>m!=null))],o,i=!1,c=()=>{for(let m of s)try{m.removeEventListener("abort",d)}catch{}},u=m=>{i||(i=!0,o!==void 0&&(clearTimeout(o),o=void 0),c(),m())},d=()=>{u(()=>n())};if(s.some(m=>m.aborted)){d();return}o=setTimeout(()=>{u(t)},r);for(let m of s){if(i)break;try{m.addEventListener("abort",d,{once:!0})}catch(y){u(()=>n(y))}}s.some(m=>m.aborted)&&d()});var _n=globalThis,Ko=typeof _n.FinalizationRegistry=="function"?new _n.FinalizationRegistry(r=>{try{r()}catch{}}):void 0,jc=new WeakMap,Gs=new WeakMap;function vd(r,e,t){let n=Gs.get(r);if(!n){let o=new Set,i=()=>{Gs.delete(r);for(let c of o)t.unregister(c),c.deref()?.();o.clear()};n={callbacks:o,abort:i},r.addEventListener("abort",i,{once:!0}),Gs.set(r,n)}let s=n;return s.callbacks.add(e),()=>{s.callbacks.delete(e),t.unregister(e),s.callbacks.size===0&&(Gs.get(r)===s&&Gs.delete(r),r.removeEventListener("abort",s.abort))}}function Od(r,e,t){r.addEventListener("abort",()=>e.deref()?.delete(t),{once:!0})}function na(r,e,t){if(typeof _n.WeakRef=="function"&&Ko&&!t.aborted){let n=jc.get(r);n||(n=new Set,jc.set(r,n)),n.add(e),Od(t,new _n.WeakRef(n),e)}}function Lc(r,e,t){if(r.aborted)return e(),()=>{};if(typeof _n.WeakRef!="function"||!Ko)return r.addEventListener("abort",e,{once:!0}),()=>r.removeEventListener("abort",e);let n=new _n.WeakRef(e),s=vd(r,n,Ko);return Ko.register(e,s,n),na(t,e,t),s}function Ys(){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 sa(...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 Qs(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return sa({start(){},async pull(t){let{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function zo(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 _t(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 Bc;function ge(r){let e;return(Bc??(e=new globalThis.TextEncoder,Bc=e.encode.bind(e)))(r)}var Dc;function Nc(r){let e;return(Dc??(e=new globalThis.TextDecoder,Dc=e.decode.bind(e)))(r)}var oa,ne,G,Z,it,br,Wc,Zs=64*1024,wr=class{constructor(){oa.add(this),ne.set(this,void 0),G.set(this,void 0),Z.set(this,void 0),it.set(this,void 0),br.set(this,void 0),b(this,ne,new Uint8Array,"f"),b(this,G,0,"f"),b(this,Z,0,"f"),b(this,it,0,"f"),b(this,br,!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(a(this,br,"f")&&(b(this,br,!1,"f"),t[0]===10&&(t=t.subarray(1)),t.length===0))return[];a(this,oa,"m",Wc).call(this,t);let n=[],s;for(;(s=Ed(a(this,ne,"f"),a(this,it,"f"),a(this,Z,"f")))!=null;){let o=Nc(a(this,ne,"f").subarray(a(this,G,"f"),s.preceding));n.push(o),b(this,G,s.index,"f"),s.carriage&&(a(this,G,"f")<a(this,Z,"f")&&a(this,ne,"f")[a(this,G,"f")]===10?b(this,G,a(this,G,"f")+1,"f"):a(this,G,"f")===a(this,Z,"f")&&b(this,br,!0,"f")),b(this,it,a(this,G,"f"),"f")}if(b(this,it,a(this,Z,"f"),"f"),a(this,G,"f")===a(this,Z,"f"))b(this,G,0,"f"),b(this,Z,0,"f"),b(this,it,0,"f"),a(this,ne,"f").length>Zs&&b(this,ne,new Uint8Array,"f");else if(n.length>0&&a(this,ne,"f").length>Zs){let o=a(this,Z,"f")-a(this,G,"f");if(o<=Zs||a(this,ne,"f").length>o*4){let i=o<=Zs?Math.min(Math.max(o*2,256),Zs):o*2,c=new Uint8Array(i);c.set(a(this,ne,"f").subarray(a(this,G,"f"),a(this,Z,"f"))),b(this,ne,c,"f"),b(this,G,0,"f"),b(this,Z,o,"f"),b(this,it,o,"f")}}return n}flush(){return b(this,br,!1,"f"),a(this,G,"f")===a(this,Z,"f")?[]:this.decode(`
2
+ `)}};ne=new WeakMap,G=new WeakMap,Z=new WeakMap,it=new WeakMap,br=new WeakMap,oa=new WeakSet,Wc=function(e){if(a(this,Z,"f")+e.length>a(this,ne,"f").length){let t=a(this,Z,"f")-a(this,G,"f");if(a(this,G,"f")>=a(this,ne,"f").length/2&&t+e.length<=a(this,ne,"f").length)a(this,ne,"f").copyWithin(0,a(this,G,"f"),a(this,Z,"f"));else{let n=Math.max(a(this,ne,"f").length*2,t+e.length,256),s=new Uint8Array(n);s.set(a(this,ne,"f").subarray(a(this,G,"f"),a(this,Z,"f"))),b(this,ne,s,"f")}b(this,it,a(this,it,"f")-a(this,G,"f"),"f"),b(this,Z,t,"f"),b(this,G,0,"f")}a(this,ne,"f").set(e,a(this,Z,"f")),b(this,Z,a(this,Z,"f")+e.length,"f")};wr.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);wr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ed(r,e,t){for(let o=e;o<t;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function Uc(r){for(let e=0;e<r.length-1;e++){let t=Fc(r,e);if(t>0){let n=e+t,s=Fc(r,n);if(s>0)return n+s}}return-1}function Fc(r,e){return r[e]===10?1:r[e]===13?r[e+1]===10?2:1:0}var Ho={off:0,error:200,warn:300,info:400,debug:500},ia=(r,e,t)=>{if(r){if($(Ho,r))return r;ee(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ho))}`)}};function eo(){}function Xo(r,e,t){return!e||Ho[r]>Ho[t]?eo:e[r].bind(e)}var kd={error:eo,warn:eo,info:eo,debug:eo},qc=new WeakMap;function ee(r){let e=r.logger,t=r.logLevel??"off";if(!e)return kd;let n=qc.get(e);if(n&&n[0]===t)return n[1];let s={error:Xo("error",e,t),warn:Xo("warn",e,t),info:Xo("info",e,t),debug:Xo("debug",e,t)};return qc.set(e,[t,s]),s}var Kc=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","xamzsecuritytoken","xamzsignature","xamzcredential"]);function to(r){let e=r.toLowerCase().replace(/[-_]/gu,"");return Kc.has(e)||Kc.has(e.replace(/^x/u,""))}var Cd=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 Vo(r){return Cd.has(r.toLowerCase().replace(/_/gu,"-"))||to(r)}function Jo(r){let e=new URL(r);e.username="",e.password="",e.hash="";for(let t of e.searchParams.keys())to(t)&&e.searchParams.set(t,"***");return e.href}var yt=r=>{if(r.options){if(r.options={...r.options},delete r.options.headers,r.options.path){let e=r.options.path,t=new URL(Jo(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,to(e)?"***":t])))}return r.url&&(r.url=Jo(r.url)),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,Vo(e)?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r};var Go,Yo,Qo,aa;function Td(r){return!(r instanceof z)&&mt(r)}function zc(){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 Ee=class r{constructor(e,t,n){Go.add(this),Yo.set(this,void 0),Qo.set(this,!1),this.iterator=e,this.controller=t,b(this,Yo,n,"f")}static fromSSEResponse(e,t,n,s){let o=!1,i=n?ee(n):console;async function*c(){if(o)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let u=!1,d=!1,m=jd(e,t),y=m.return.bind(m);m.return=f=>(d||t.abort(),y(f));try{for await(let f of m){if(f.data==="[DONE]"){d=!0;break}if(f.event===null||!f.event.startsWith("thread.")){let g;try{g=JSON.parse(f.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if(f.event==="error")throw new z(void 0,g?.error??g,void 0,e.headers);if(g&&g.error)throw new z(void 0,g.error,void 0,e.headers);yield s?{event:f.event,data:g}:g}else{let g;try{g=JSON.parse(f.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}yield{event:f.event,data:g}}}u=!0}catch(f){if(d||Td(f)||t.signal.aborted&&f===t.signal.reason)return;throw f}finally{u||t.abort()}}return new r(c,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*o(){let c=new wr,u=e.getReader(),d=!1,m,y=()=>{m??(m=u.cancel()),m.catch(()=>{})};t.signal.addEventListener("abort",y,{once:!0});try{if(t.signal.aborted){y();return}for(;;){let{value:f,done:g}=await u.read();if(g){d=!0;break}if(t.signal.aborted)return;for(let w of c.decode(f)){if(t.signal.aborted)return;yield w}}if(t.signal.aborted)return;for(let f of c.flush()){if(t.signal.aborted)return;yield f}}finally{t.signal.removeEventListener("abort",y),d||y(),u.releaseLock()}}async function*i(){if(s)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of o())if(u){let d;try{d=JSON.parse(u)}catch(m){throw m instanceof SyntaxError?new SyntaxError("Error reading response: malformed newline-delimited JSON."):m}yield d}c=!0}catch(u){if(t.signal.aborted||mt(u))return;throw u}finally{c||t.abort()}}return new r(i,t,n)}[(Yo=new WeakMap,Qo=new WeakMap,Go=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){let{controller:e}=this,t=zc(),n=zc(),s=this.iterator(),o=c=>({next:()=>{if(c.canceled)return Promise.resolve({value:void 0,done:!0});if(c.length===0){let u=s.next();t.enqueue(u),n.enqueue(u)}return c.dequeue()},return:async()=>(c.canceled||(c.cancel(),t.canceled&&n.canceled&&await a(this,Go,"m",aa).call(this,s,e)),{value:void 0,done:!0})}),i=c=>{let u=new r(()=>o(c),e,a(this,Yo,"f"));return b(u,Qo,!0,"f"),u};return[i(t),i(n)]}toReadableStream(){let{controller:e}=this,t,n,s=()=>n??(n=a(this,Go,"m",aa).call(this,t,e));return sa({start:async()=>{t=this[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:c}=await t.next();if(c)return o.close();let u=ge(JSON.stringify(i)+`
4
+ `);o.enqueue(u)}catch(i){o.error(i),s().catch(()=>{})}},cancel:s})}};aa=async function(e,t){let n=e.return;n&&(a(this,Qo,"f")||t.abort(),await Reflect.apply(n,e,[]))};function $d(r,e){let t=typeof r.getReader=="function"?r.getReader():void 0,n=t?{next:()=>t.read(),return:()=>t.cancel()}:zo(r)[Symbol.asyncIterator](),s={value:void 0,done:!0},o=!1,i=!1,c,u,d=()=>new Promise(g=>{u=g}),m=()=>{if(i||o)return c;i=!0;try{c=Promise.resolve(n.return?.())}catch(g){c=Promise.reject(g)}return c.catch(()=>{}),c},y=()=>{queueMicrotask(()=>{u?.(),m()})};return{iterator:{async next(){if(e.aborted)return s;let g=d().then(()=>s);try{let w=await Promise.race([n.next(),g]);return e.aborted?s:w.done?(o=!0,s):{value:w.value,done:!1}}catch(w){if(e.aborted&&(mt(w)||w===e.reason))return s;throw w}finally{u=void 0}},async return(){let g=m();if(g&&!e.aborted){let w=d();try{e.aborted||await Promise.race([g,w])}finally{u=void 0}}return s},[Symbol.asyncIterator](){return this}},start(){e.addEventListener("abort",y,{once:!0}),e.aborted&&y()},async cleanup(g){let w;try{e.removeEventListener("abort",y)}catch(A){w=A}if(!o){let A=m();if(A&&!g&&!e.aborted)try{await A}catch(S){w??(w=S)}}if(t)try{t.releaseLock()}catch(A){w??(w=A)}if(w!==void 0&&!g&&!e.aborted)throw w}}}async function*jd(r,e){if(!r.body)throw e.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative"?new h("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 h("Attempted to iterate over a response with no body");let t=new ca,n=new wr,{signal:s}=e,o=$d(r.body,s),i=!1;try{o.start();for await(let u of Md(o.iterator)){if(s.aborted)return;for(let d of n.decode(u)){if(s.aborted)return;let m=t.decode(d);m&&(yield m)}}if(s.aborted)return;for(let u of n.flush()){if(s.aborted)return;let d=t.decode(u);d&&(yield d)}if(s.aborted)return;let c=t.flush();c&&(yield c)}catch(c){if(i=!0,!s.aborted||!mt(c)&&c!==s.reason)throw c}finally{await o.cleanup(i)}}var Ld=3;async function*Md(r){let e=new Uint8Array,t=0,n=0,s=0;for await(let o of r){if(o==null)continue;let i;if(o instanceof ArrayBuffer?i=new Uint8Array(o):typeof o=="string"?i=ge(o):i=o,n+i.length>e.length){let u=n-t;if(t>=e.length/2&&u+i.length<=e.length)e.copyWithin(0,t,n);else{let d=new Uint8Array(Math.max(e.length*2,u+i.length));d.set(e.subarray(t,n)),e=d}s-=t,t=0,n=u}e.set(i,n),n+=i.length;let c;for(;(c=Uc(e.subarray(s,n)))!==-1;)c+=s,yield e.slice(t,c),t=c,s=t;s=Math.max(t,n-Ld)}n>t&&(yield e.slice(t,n))}var ca=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 o={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,,n]=Bd(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 Bd(r,e){let t=r.indexOf(e);return t!==-1?[r.slice(0,t),e,r.slice(t+e.length)]:[r,"",""]}async function Ar(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{if(e.options.stream)return ee(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):Ee.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(u?.includes("application/json")||u?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let f=await t.text();if(!f)return;let g=JSON.parse(f);return ro(g,t)}return await t.text()})().catch(c=>{throw Dd(c,e.controller.signal)});return ee(r).debug(`[${n}] response parsed`,yt({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function Dd(r,e){if(!e.aborted||r!==e.reason||mt(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 ro(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 Ut="7.17.0";var Vc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Nd(){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 Fd=()=>{let r=Nd();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":Hc(Deno.build.os),"X-Stainless-Arch":Xc(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":Ut,"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":Ut,"X-Stainless-OS":Hc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Xc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Wd();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"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":Ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Wd(){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,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var Xc=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Hc=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"),Jc,Gc=()=>Jc??(Jc=Fd());var no=new WeakMap;function Yc(r,e){let t=no.get(r);return t||(t=new Set,no.set(r,t)),t.add(e),()=>{let n=no.get(r);n&&(n.delete(e),n.size===0&&no.delete(r))}}var Qc=({headers:r,body:e})=>{let t=typeof e=="object"&&e!==null?no.get(e):void 0,n;if(!t||t.size===0)n=JSON.stringify(e);else{let s=[...t];n=JSON.stringify(e,function(o,i){let c=i;for(let u of s){let d=u.value(this,o,c);d!==void 0&&(c=d)}return c});for(let o of s)o.complete()}return{bodyHeaders:{"content-type":"application/json"},body:n}};var ua="RFC3986",la=String,da={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:la},Zc="RFC1738";var eu,tu=(r,e)=>{let t=eu??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return eu=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 fa=1024,ru=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,c=>"%26%23"+Number.parseInt(c.slice(2),16)+"%3B");let i="";for(let c=0;c<o.length;){let u=Math.min((Math.floor(c/fa)+1)*fa,o.length);u<o.length&&o.codePointAt(u-1)>65535&&(u+=1);let d=o.length>=fa?o.slice(c,u):o,m=[];for(let y=0;y<d.length;++y){let f=d.charCodeAt(y);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||s===Zc&&(f===40||f===41)){m[m.length]=d.charAt(y);continue}if(f<128){m[m.length]=at[f];continue}if(f<2048){m[m.length]=at[192|f>>6]+at[128|f&63];continue}if(f<55296||f>=57344){m[m.length]=at[224|f>>12]+at[128|f>>6&63]+at[128|f&63];continue}y+=1,f=65536+((f&1023)<<10|d.charCodeAt(y)&1023),m[m.length]=at[240|f>>18]+at[128|f>>12&63]+at[128|f>>6&63]+at[128|f&63]}i+=m.join(""),c=u}return i};function nu(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function pa(r,e){if(we(r)){let t=[];for(let n of r)t.push(e(n));return t}return e(r)}var ou={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},iu=function(e,t){Array.prototype.push.apply(e,we(t)?t:[t])},su,ue={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ru,encodeValuesOnly:!1,format:ua,formatter:la,indices:!1,serializeDate(r){return(su??(su=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function qd(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var ha={};function au(r,e,t,n,s,o,i,c,u,d,m,y,f,g,w,A,S,O){let P=r,L=O,I=0,T=!1;for(;(L=L.get(ha))!==void 0&&!T;){let v=L.get(r);if(I+=1,v!==void 0){if(v===I)throw new RangeError("Cyclic object value");T=!0}L.get(ha)===void 0&&(I=0)}if(typeof d=="function"?P=d(e,P):P instanceof Date?P=f?.(P):t==="comma"&&we(P)&&(P=pa(P,v=>v instanceof Date?f?.(v):v)),P===null){if(o)return u&&!A?u(e,ue.encoder,S,"key",g):e;P=""}if(qd(P)||nu(P)){if(u){let v=A?e:u(e,ue.encoder,S,"key",g);return[w?.(v)+"="+w?.(u(P,ue.encoder,S,"value",g))]}return[w?.(e)+"="+w?.(String(P))]}let x=[];if(P===void 0)return x;let M;if(t==="comma"&&we(P))A&&u&&(P=pa(P,u)),M=[{value:P.length>0?P.join(",")||null:void 0}];else if(we(d))M=d;else{let v=Object.keys(P);m&&v.sort(m),M=v}let k=c?String(e).replace(/\./g,"%2E"):String(e),E=n&&we(P)&&P.length===1?k+"[]":k;if(s&&we(P)&&P.length===0)return E+"[]";for(let v of M){let K=typeof v=="object"&&v.value!==void 0?v.value:P[v];if(i&&K===null)continue;let D=y&&c?v.replace(/\./g,"%2E"):v,N;we(P)?N=typeof t=="function"?t(E,D):E:N=E+(y?"."+D:"["+D+"]"),O.set(r,I);let q=new WeakMap([[ha,O]]);iu(x,au(K,N,t,n,s,o,i,c,t==="comma"&&A&&we(P)?null:u,d,m,y,f,g,w,A,S,q))}return x}function Kd(r=ue){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||ue.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=ua;if(r.format!==void 0){if(!tu(da,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=da[t],s=ue.filter;(typeof r.filter=="function"||we(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in ou?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=ue.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i;return r.allowDots===void 0?i=r.encodeDotInKeys?!0:ue.allowDots:i=!!r.allowDots,{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:ue.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:ue.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:ue.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:r.delimiter===void 0?ue.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:ue.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:ue.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:ue.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:ue.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:ue.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:ue.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:ue.strictNullHandling}}function cu(r,e={}){let t=r,n=Kd(e),s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):we(n.filter)&&(o=n.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let c=ou[n.arrayFormat],u=c==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);let d=new WeakMap;for(let f of s)n.skipNulls&&t[f]===null||iu(i,au(t[f],f,c,u,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 m=i.join(n.delimiter),y=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(y+=n.charset==="iso-8859-1"?"utf8=%26%2310003%3B&":"utf8=%E2%9C%93&"),m.length>0?y+m:""}function uu(r){return cu(r,{arrayFormat:"brackets"})}var Xd=new Map([["global","https://api.openai.com/v1"],["us","https://us.api.openai.com/v1"],["eu","https://eu.api.openai.com/v1"],["ae","https://ae.api.openai.com/v1"]]);function ma(r){if(r.dataResidency===null||r.dataResidency===void 0)return;if($(r,"baseURL"))throw new h("The `dataResidency` and `baseURL` options are mutually exclusive.");let e=Xd.get(r.dataResidency);if(e===void 0)throw new h("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return e}function Zo(r,e){if(r!=null)throw new h(`${e} does not support \`dataResidency\`.`)}var so,Ir=class r extends Promise{constructor(e,t,n=Ar){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,so.set(this,void 0),b(this,so,e,"f")}_thenUnwrap(e){return new r(a(this,so,"f"),this.responsePromise,async(t,n)=>ro(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(a(this,so,"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)}};so=new WeakMap;var ei,Pr=class{constructor(e,t,n,s){ei.set(this,void 0),b(this,ei,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 h("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,ei,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ei=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},oo=class extends Ir{constructor(e,t,n){super(e,t,async(s,o)=>new n(s,o.response,await Ar(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},de=class extends Pr{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}},R=class extends Pr{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:{...Vs(this.options.query),after:t}}:null}},F=class extends Pr{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:{...Vs(this.options.query),after:e}}:null}},Q=class extends Pr{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:{...Vs(this.options.query),after:e}}:null}},yn=class extends Pr{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:{...Vs(this.options.query),page:e}}:null}};var Jd={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Vd="urn:ietf:params:oauth:grant-type:token-exchange",Gd=.5;function Yd(r,e){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new h("Token exchange response has invalid 'expires_in' field");let t=Date.now(),n=t+r*1e3;if(!Number.isSafeInteger(n)||n<=t)throw new h("Token exchange response has invalid 'expires_in' field");let s=n-(performance.now()-e);if(s<=t)throw new h("Workload identity token expired before its exchange completed.");return s}function Qd(r,e,t){let n=(t??1200)*1e3,s=Math.min(n,e*1e3*Gd);return r-s}var lu=Response.prototype,Zd=lu.arrayBuffer;function ef(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 tf(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 rf(r){let e=globalThis;return new TextDecoder("utf-8",{ignoreBOM:typeof e.Bun?.version=="string"}).decode(r)}async function nf(r){let e,t=null;for(let s=0,o=r;o!==null&&s<16&&o!==lu;o=Object.getPrototypeOf(o),s+=1){ef(r,o)&&(t=o);let i=Object.getOwnPropertyDescriptor(o,"json");if(!i)continue;if(typeof i.value!="function")break;let c=Object.getOwnPropertyDescriptor(o,"text")?.value;if(typeof c=="function"&&tf(o,t)){e=c;break}return i.value.call(r)}let n=e===void 0?rf(await Zd.call(r)):await e.call(r);try{return JSON.parse(n)}catch{throw new SyntaxError("Token exchange response contains invalid JSON")}}function sf(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 ti=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:o,refreshBufferSeconds:i,provider:c}=e;this.config={identityProviderId:n,serviceAccountId:s,...o===void 0?{}:{clientId:o},...i===void 0?{}:{refreshBufferSeconds:i},provider:{tokenType:c.tokenType,getToken:c.getToken.bind(c)}},this.fetch=t??Ys()}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:Vd,subject_token:t,subject_token_type:Jd[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(),o=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),redirect:"manual"});if(!o.ok){let m=await o.text(),y;try{y=JSON.parse(m)}catch{}throw o.status===400||o.status===401||o.status===403?new Ne(o.status,y,o.headers):z.generate(o.status,y,`Token exchange failed with status ${o.status}`,o.headers)}let i=await nf(o),c=typeof i=="object"&&i!==null&&"access_token"in i?i.access_token:void 0;if(typeof c!="string"||c.trim().length===0||sf(c))throw new h("Token exchange response missing 'access_token' field");let u=i.expires_in??3600,d=Yd(u,s);return this.tokenGeneration===e&&(this.cachedToken={token:c,expiresAt:d,refreshAt:Qd(d,u,this.config.refreshBufferSeconds)}),c}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 du="https://mtls.api.openai.com/v1";function gn(r){let e;try{e=new URL(r)}catch{throw new h("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 h("X.509 workload identity requires the approved global mTLS API origin.");for(let t of e.searchParams.keys())if(to(t))throw new h("X.509 workload identity cannot send conflicting query authentication credentials.");return e}var fu=Symbol("brand.privateNullableHeaders"),of=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*af(r){if(!r)return;if(fu in r){let{values:s,nulls:o}=r;yield*s.entries();for(let i of o)yield[i,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 o=s[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=Tc(s[1])?s[1]:[s[1]],c=!1;for(let u of i)u!==void 0&&(e&&!c&&(c=!0,yield[o,null]),yield[o,u])}}var _=r=>{let e=new Headers,t=new Set;for(let n of r){let s=new Set;for(let[o,i]of af(n)){if(!of.test(o))throw new TypeError(`Header name must be a valid HTTP token ["${o}"]`);let c=o.toLowerCase();s.has(c)||(e.delete(c),s.add(c)),i===null?(e.delete(c),t.add(c)):(e.append(c,i),t.delete(c))}}return{[fu]:!0,values:e,nulls:t}};var _a={};Pd(_a,{findRegisteredX509Transport:()=>cf,findX509Credential:()=>bf,findX509OAuthError:()=>yf,isApprovedX509Client:()=>mf,isRetryableX509IssuerError:()=>pf,isTransientX509ConnectionError:()=>df,markApprovedX509Client:()=>hf,markRetryableX509IssuerError:()=>ff,markTransientX509ConnectionError:()=>lf,rememberRegisteredX509Transport:()=>uf,rememberX509Credential:()=>gf,rememberX509OAuthError:()=>_f});var pu=new WeakMap,hu=new WeakSet,mu=new WeakSet,_u=new WeakSet,yu=new WeakMap,gu=new WeakMap,cf=WeakMap.prototype.get.bind(pu),uf=WeakMap.prototype.set.bind(pu),lf=WeakSet.prototype.add.bind(hu),df=WeakSet.prototype.has.bind(hu),ff=WeakSet.prototype.add.bind(mu),pf=WeakSet.prototype.has.bind(mu),hf=WeakSet.prototype.add.bind(_u),mf=WeakSet.prototype.has.bind(_u),_f=WeakMap.prototype.set.bind(yu),yf=WeakMap.prototype.get.bind(yu),gf=WeakMap.prototype.set.bind(gu),bf=WeakMap.prototype.get.bind(gu);var ya=xd(bu(),1),wf=typeof ya.findRegisteredX509Transport=="function"?ya:_a,{findRegisteredX509Transport:wu,rememberRegisteredX509Transport:Ey,markTransientX509ConnectionError:ky,isTransientX509ConnectionError:ni,markRetryableX509IssuerError:Cy,isRetryableX509IssuerError:ga,markApprovedX509Client:Au,isApprovedX509Client:Af,rememberX509OAuthError:Ty,findX509OAuthError:Iu,rememberX509Credential:$y,findX509Credential:Pu}=wf;function xu(r){if(!r||typeof r!="object")throw new h("X.509 workload identity requires an approved X.509 transport capability.");let e=wu(r);if(!e)throw new h("X.509 workload identity requires an approved X.509 transport capability.");return e}var U,Pe,xr,Sr,ct,Fe,bt,wt,fe,Rr,gt,Ue,We,Ou,oi,Eu,Su,ku,Cu,Ru,Tu,H,wa,If=["dispatcher","agent","client","tls","proxy"],bn=(r,e)=>Headers.prototype.get.call(r,e),Pf=1200*1e3,vu=1e3,si=r=>{let e=new Y;return Object.defineProperty(e,"cause",{value:r.reason,writable:!0,configurable:!0}),e};function ba(r){for(let e of Headers.prototype.keys.call(r)){let t=e.toLowerCase().split("_").join("-");if(t!=="authorization"&&Vo(t)||t==="host")throw new h("X.509 workload identity cannot send conflicting authentication credentials.")}}function xf(r,e){let t=new AbortController,n=r===void 0?void 0:setTimeout(()=>t.abort(new re),r),s=n;typeof s=="object"&&s!==null&&"unref"in s&&typeof s.unref=="function"&&s.unref();let o=()=>t.abort(e?.reason);return e?.addEventListener("abort",o,{once:!0}),e?.aborted&&o(),{signal:t.signal,dispose:()=>{e?.removeEventListener("abort",o),n&&clearTimeout(n)}}}function Sf(r,e){let t,n=new Promise((s,o)=>{t=()=>o(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 ii(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 h("X.509 workload identity type must be a plain data property.");return n.value==="x509"}t=Object.getPrototypeOf(t)}return!1}function Aa(r){if(!r)return;for(let t of If)if($(r,t))throw new h("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 h("X.509 workload identity requests require manual redirects.")}function io(r){if(Aa(r),r&&["body","headers","method","signal"].some(e=>$(r,e)))throw new h("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.")}function Ia(r){io(r);let e={...r};return io(e),e}var Ae=class{constructor(e,t,n,s){if(U.add(this),xr.set(this,void 0),Sr.set(this,void 0),ct.set(this,void 0),Fe.set(this,void 0),bt.set(this,void 0),wt.set(this,void 0),fe.set(this,void 0),Rr.set(this,void 0),gt.set(this,void 0),Ue.set(this,void 0),We.set(this,0),b(this,fe,xu(t),"f"),b(this,xr,e.identityProviderId,"f"),b(this,Sr,e.serviceAccountId,"f"),b(this,ct,e.refreshBufferMs,"f"),b(this,Fe,e.refreshBufferSeconds,"f"),b(this,bt,n,"f"),b(this,wt,s,"f"),a(this,ct,"f")!==void 0&&a(this,Fe,"f")!==void 0)throw new h("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");if(a(this,ct,"f")!==void 0&&(!Number.isSafeInteger(a(this,ct,"f"))||a(this,ct,"f")<0))throw new h("X.509 workload identity requires a nonnegative integer refreshBufferMs.");if(a(this,Fe,"f")!==void 0&&(!Number.isSafeInteger(a(this,Fe,"f"))||a(this,Fe,"f")<0||!Number.isSafeInteger(a(this,Fe,"f")*1e3)))throw new h("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");b(this,Rr,a(this,Fe,"f")===void 0?a(this,ct,"f")??Pf:a(this,Fe,"f")*1e3,"f")}identitySnapshot(){return{type:"x509",identityProviderId:a(this,xr,"f"),serviceAccountId:a(this,Sr,"f"),...a(this,ct,"f")===void 0?{}:{refreshBufferMs:a(this,ct,"f")},...a(this,Fe,"f")===void 0?{}:{refreshBufferSeconds:a(this,Fe,"f")}}}static shouldAuthenticate(e,t,n=e.headers){return!_([t,n]).nulls.has("authorization")}snapshotHeaders(e,t){let n=a(this,U,"m",H).call(this);return n.defaultHeaders??(n.defaultHeaders=_([e])),n.requestHeaders??(n.requestHeaders=_([t])),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:t}=a(this,U,"m",H).call(this);if(!e||!t)throw new h("X.509 workload identity requires snapshotted request headers.");return{defaultHeaders:e,requestHeaders:t}}snapshotTenant(e,t){if(e!==a(this,bt,"f")||t!==a(this,wt,"f"))throw new h("X.509 workload identity cannot override its enrolled organization or project.");let n=a(this,U,"m",H).call(this);return n.tenant={organization:e,project:t},n.tenant}tenantSnapshot(){let{tenant:e}=a(this,U,"m",H).call(this);if(!e)throw new h("X.509 workload identity requires snapshotted tenant selectors.");return e}snapshotAPIURL(e){gn(e),a(this,U,"m",H).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=a(this,U,"m",H).call(this);if(e===void 0)throw new h("X.509 workload identity requires a snapshotted API destination.");return e}snapshotRequest(e,t,n){var s;(s=a(this,U,"m",H).call(this)).request??(s.request={signal:e,timeout:t,fetchOptions:n})}requestSnapshot(){let{request:e}=a(this,U,"m",H).call(this);if(!e)throw new h("X.509 workload identity requires snapshotted request settings.");return e}beginRequestPreparation(){let e=a(this,U,"m",H).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){a(this,U,"m",H).call(this).phase="planning"}beginRequestNetwork(){let e=a(this,U,"m",H).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 a(this,U,"m",H).call(this).phase==="planning"}authorizePlannedRequest(e,t,n,s=!1){let o=a(this,U,"m",H).call(this),i=Object.getOwnPropertyDescriptor(t,"headers"),c=Object.getOwnPropertyDescriptor(t,"body"),u=Object.getOwnPropertyDescriptor(t,"signal"),d=Object.getOwnPropertyDescriptor(t,"redirect");if(o.phase!=="planning"||!i||!(i.value instanceof Headers)||!c&&"body"in t||[c,u,d].some(y=>y&&!("value"in y)))throw new h("X.509 workload identity requires an approved final request.");this.snapshotAPIURL(e),Aa(t);try{ba(i.value)}catch{throw new h("X.509 workload identity cannot use caller-supplied authentication credentials.")}if(bn(i.value,"Authorization")!==null)throw new h("X.509 workload identity cannot use caller-supplied authorization credentials.");if(a(this,U,"m",wa).call(this,i.value),!s&&(u?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new h("X.509 workload identity must preserve its approved request signal.");let m=this.requestSnapshot();o.request={...m,timeout:Math.min(m.timeout,n)},o.phase="authorizing"}ownRequestBody(e,t){e instanceof ReadableStream&&e!==t&&(a(this,U,"m",H).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=a(this,U,"m",H).call(this),t=e.materializedBody;delete e.materializedBody,t&&a(Pe,Pe,"m",Ou).call(Pe,t)}releaseRequestBody(e){let t=a(this,U,"m",H).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?a(this,U,"m",H).call(this).effectiveSignal=e:delete a(this,U,"m",H).call(this).effectiveSignal}effectiveSignal(){let e=a(this,U,"m",H).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,t){return a(this,fe,"f").run(async()=>{let n=a(this,fe,"f").current();if(!n)throw new h("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=a(this,fe,"f").current();return t?.owner===this&&t.requestOwner===e&&t.phase!=="authorizing"}matches(e){return a(this,fe,"f")===a(e,fe,"f")&&a(this,xr,"f")===a(e,xr,"f")&&a(this,Sr,"f")===a(e,Sr,"f")&&a(this,bt,"f")===a(e,bt,"f")&&a(this,wt,"f")===a(e,wt,"f")&&a(this,Rr,"f")===a(e,Rr,"f")}continuation(){let{wallStartedAt:e,monotonicStartedAt:t,deadlineArmed:n,request:s,requestOwner:o,effectiveSignal:i}=a(this,U,"m",H).call(this),c={wallStartedAt:e,monotonicStartedAt:t,owner:this,...n?{deadlineArmed:n}:{},...s?{request:s}:{},...i?{effectiveSignal:i}:{},...o?{requestOwner:o}:{}};return u=>a(this,fe,"f").resume(c,async()=>{try{return await u()}finally{this.releaseRequestCredentials(),delete c.requestOwner,delete c.owner}})}releaseRequestCredentials(){let e=a(this,U,"m",H).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 a(this,fe,"f").current()?.wallStartedAt}usedWorkloadToken(e){return a(this,fe,"f").current()?.token!==void 0}remainingTimeout(e,t){let n=a(this,fe,"f").current();if(n===void 0)return t;let s=t-(performance.now()-n.monotonicStartedAt);if(s<=0)throw new re;return s}async waitForRetry(e,t){try{await a(this,fe,"f").sleep(e,t)}catch(n){throw t?.aborted?si(t):n}}static isRetryableFailure(e){return typeof e=="object"&&e!==null&&(ni(e)||ga(e))}static retryHeaders(e){if(!e||typeof e!="object"||!ga(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 si(n);e&&io(t?t.fetchOptions:e.fetchOptions),a(this,U,"m",Tu).call(this,t);let s=e?a(this,U,"m",H).call(this):void 0,o=a(this,gt,"f");if(o&&performance.now()<o.refreshAt&&Date.now()<o.wallRefreshAt)return a(Pe,Pe,"m",oi).call(Pe,s,o);let i=t&&e?this.remainingTimeout(e,t.timeout):t?.timeout,{signal:c,dispose:u}=xf(i,n);if(n?.aborted)throw u(),si(n);let d=a(this,Ue,"f")??a(this,U,"m",Cu).call(this);d.waiters+=1;let m=Sf(d,c);try{let y=await m.result,f=a(this,gt,"f");if(!f||f.accessToken!==y.accessToken)throw new Y;return a(Pe,Pe,"m",oi).call(Pe,s,f)}catch(y){return await a(this,U,"m",Eu).call(this,y,d,o,s,e,t)}finally{m.dispose(),u(),d.waiters-=1,a(this,U,"m",ku).call(this,d)}}invalidateToken(){let e=a(this,fe,"f").current();if(!e?.token||a(this,gt,"f")?.accessToken!==e.token||a(this,gt,"f").generation!==e.tokenGeneration)return;b(this,We,a(this,We,"f")+1,"f"),b(this,gt,void 0,"f");let t=a(this,Ue,"f");b(this,Ue,void 0,"f"),t?.controller.abort(new Y)}bindRequest(e,t,n){if(!(t.headers instanceof Headers))throw new h("X.509 workload identity requires the original workload authorization headers.");let s=a(this,U,"m",H).call(this),{token:o}=s,i=e.__security??{bearerAuth:!0},c=o?`Bearer ${o}`:null;!o&&i.adminAPIKeyAuth&&n!==null&&bn(t.headers,"Authorization")!==null&&(c=new Headers({Authorization:`Bearer ${n}`}).get("Authorization")),s.headers=t.headers,s.authorization=c,this.assertRequest(t)}adoptRequestHeaders(e){let t=a(this,U,"m",H).call(this),n=t.headers;if(!(n instanceof Headers)||!(e.headers instanceof Headers))throw new h("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 h("X.509 workload identity must preserve its issued workload authorization.");let n=a(this,fe,"f").current();if(!n||n.headers!==t||n.authorization===void 0||bn(t,"Authorization")!==n.authorization)throw new h("X.509 workload identity must preserve its issued workload authorization.");a(this,U,"m",wa).call(this,t),ba(t)}fetch(){return async(e,t={})=>{let n=gn(typeof e=="string"||e instanceof URL?e:e.url);Aa(t),this.assertRequest(t);let s=t.headers;if(!(s instanceof Headers))throw new h("X.509 workload identity must preserve its issued workload authorization.");let o=new Headers([...Headers.prototype.entries.call(s)]);return ba(o),t.headers=o,t.redirect="manual",await a(this,fe,"f").dispatch(n,t)}}};Pe=Ae,xr=new WeakMap,Sr=new WeakMap,ct=new WeakMap,Fe=new WeakMap,bt=new WeakMap,wt=new WeakMap,fe=new WeakMap,Rr=new WeakMap,gt=new WeakMap,Ue=new WeakMap,We=new WeakMap,U=new WeakSet,Ou=async function(e){try{await _t(e)}catch{}},oi=function(e,t){return e&&(e.token=t.accessToken,e.tokenGeneration=t.generation),t.accessToken},Eu=async function(e,t,n,s,o,i){let c=i?i.signal:o?.signal;if(c?.aborted)throw si(c);if(t.controller.signal.aborted&&t.generation!==a(this,We,"f"))return await this.getToken(o,i);let u=a(this,U,"m",Su).call(this,e,n,s);if(u!==void 0)return u;if(e&&typeof e=="object"&&!(e instanceof Ne)){let d=Iu(e);if(d)throw new Ne(d.status,d.error,d.headers)}throw e},Su=function(e,t,n){if(!t||t!==a(this,gt,"f")||performance.now()>=t.expiresAt||Date.now()>=t.wallExpiresAt||!Pe.isRetryableFailure(e))return;let s=Pe.retryHeaders(e),o=s?.get("retry-after-ms"),i=o?Number(o):void 0,c=s?.get("retry-after");if(c&&(i===void 0||Number.isNaN(i))){let d=Number(c);i=Number.isNaN(d)?Date.parse(c)-Date.now():d*1e3}let u=i!==void 0&&Number.isFinite(i)&&i>=0&&i<=6e4?Math.max(vu,i):vu;return t.refreshAt=Math.min(t.expiresAt,performance.now()+u),t.wallRefreshAt=Math.min(t.wallExpiresAt,Date.now()+u),a(Pe,Pe,"m",oi).call(Pe,n,t)},ku=function(e){e.waiters!==0||a(this,Ue,"f")!==e||queueMicrotask(()=>{e.waiters===0&&a(this,Ue,"f")===e&&(b(this,Ue,void 0,"f"),b(this,We,a(this,We,"f")+1,"f"),e.controller.abort(new Y))})},Cu=function(){let e=new AbortController,t=a(this,We,"f"),n={controller:e,generation:t,waiters:0,promise:a(this,U,"m",Ru).call(this,e,t)};return b(this,Ue,n,"f"),n},Ru=async function(e,t){let n=performance.now(),s=Date.now();try{let o=await a(this,fe,"f").exchange(a(this,xr,"f"),a(this,Sr,"f"),e.signal),i=o.expiresIn*1e3,c=n+i,u=s+i;if(performance.now()>=c||Date.now()>=u)throw new h("X.509 workload identity token expired before its exchange completed.");if(a(this,We,"f")!==t||e.signal.aborted||a(this,Ue,"f")?.controller!==e)throw new Y;return b(this,We,a(this,We,"f")+1,"f"),b(this,gt,{accessToken:o.accessToken,generation:a(this,We,"f"),expiresAt:c,refreshAt:c-Math.min(a(this,Rr,"f"),i/2),wallExpiresAt:u,wallRefreshAt:u-Math.min(a(this,Rr,"f"),i/2)},"f"),o}finally{a(this,Ue,"f")?.controller===e&&b(this,Ue,void 0,"f")}},Tu=function(e){if(!e)return;if(e.organization!==a(this,bt,"f")||e.project!==a(this,wt,"f"))throw new h("X.509 workload identity cannot override its enrolled organization or project.");gn(e.apiURL);let t=_([e.defaultHeaders,e.requestHeaders]);if(a(this,bt,"f")!==null&&t.nulls.has("openai-organization")||a(this,wt,"f")!==null&&t.nulls.has("openai-project"))throw new h("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||bn(t.values,n)!==(s==="openai-organization"?e.organization:e.project)))throw new h("X.509 workload identity cannot override its enrolled organization or project.");if(Vo(s)||s==="host")throw new h("X.509 workload identity cannot use caller-supplied authentication credentials.")}},H=function(){let e=a(this,fe,"f").current();if(!e||e.owner!==this)throw new h("X.509 workload identity requires an active certificate request scope.");return e},wa=function(e){if(bn(e,"OpenAI-Organization")!==a(this,bt,"f")||bn(e,"OpenAI-Project")!==a(this,wt,"f"))throw new h("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 h("X.509 workload identity cannot override its enrolled organization or project.")}};function $u(r){let{credential:e}=r;if(e===void 0)return{credential:e,options:r};let t=Pu(e);if(!t)throw new h("An X.509 credential must be created by the SDK authentication helper.");let n=["apiKey","adminAPIKey","workloadIdentity","x509Transport"].filter(s=>{let o=r[s];return o!=null});if(n.length>0)throw new h(`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 Rf({apiKey:r,adminAPIKey:e}){return r!=null||e!=null}function vf(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 ju(r,e,t,n){let s=$(e,"workloadIdentity")?e.workloadIdentity:r.workloadIdentity,o=t!==void 0&&(Rf(e)&&e.workloadIdentity===void 0||e.provider!==void 0);t!==void 0&&$(e,"workloadIdentity")&&delete r.x509Transport;let i=t!==void 0&&!o&&e.credential===void 0&&!$(e,"workloadIdentity")&&!$(e,"x509Transport")?t:void 0,c=e.credential===void 0?i:e.credential,u=c!==void 0||!o&&ii(s);return n!==u&&(delete r.fetch,delete r.baseURL,delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions,u?r.apiKey=null:(delete r.x509Transport,o&&delete r.workloadIdentity)),c!==void 0&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.x509Transport,r.credential=c,e.credential!==void 0&&(delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions)),{credential:c,provider:vf(r,e)}}var Mu=Symbol("brand.privateStreamingFile");function ci(r,e,t){if(typeof e!="string"||!e)throw new TypeError("toStreamingFile requires a non-empty file name");let n=t?.type;return n&&Wu(n),{[Mu]:!0,data:r,name:e,...n?{type:n}:{}}}var va=()=>{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 At(r,e,t){return va(),new File(r,e??"unknown_file",t)}function vr(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?Bu(n):ao(n);let s="url"in r&&r.url&&String(r.url);if(s)try{return ao(new URL(s).pathname)}catch{return ao(s)}let o="path"in r&&r.path&&String(r.path);return o?ao(o):void 0}function ao(r){return r.split(/[\\/]/).pop()||void 0}function Bu(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 Of=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get;function Oa(r){try{return Of?.call(r)!==void 0}catch{return!1}}var wn=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",qt=async(r,e,t)=>xa(r.body)?ai(r.body)?Nu(r,t):{...r,body:await Du(r.body,e,t)}:r,se=async(r,e,t)=>ai(r.body)?Nu(r,t):{...r,body:await Du(r.body,e,t)},Lu=new WeakMap;function Ef(r){let e=typeof r=="function"?r:r.fetch,t=Lu.get(e);if(t)return t;let n=(async()=>{try{let s;if("Response"in e)s=e.Response;else{let i=await e("data:,");await i.arrayBuffer(),s=i.constructor}let o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Lu.set(e,n),n}var Du=async(r,e,t={})=>{if(!await Ef(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,o])=>Ra(n,s,o,t))),n},ui=r=>r instanceof Blob,Ea=r=>typeof r=="object"&&r!==null&&"getReader"in r&&typeof r.getReader=="function",uo=r=>typeof r=="object"&&r!==null&&Mu in r,li=r=>typeof r=="object"&&r!==null&&(r instanceof Response||wn(r)||Ea(r)||uo(r)||ui(r)),ai=r=>{if(uo(r)||wn(r)||Ea(r))return!0;if(Array.isArray(r))return r.some(ai);if(r&&typeof r=="object"&&!ui(r)&&!(r instanceof Response)){for(let e of Object.keys(r))if(ai(r[e]))return!0}return!1},xa=r=>{if(li(r))return!0;if(Array.isArray(r))return r.some(xa);if(r&&typeof r=="object"){for(let e of Object.keys(r))if(xa(r[e]))return!0}return!1},kf=(r,e)=>{let t=[];for(let n of r)li(n.value)&&!e.has(n.value)&&e.set(n.value,Fu(n.value,{stripFilenames:!1})),t.push(n);return t},Nu=(r,e={})=>{let t=Tf(r.body),n=e.stripFilenames===!1?new WeakMap:void 0,s=n?kf(t,n):t,o=`openai-${Math.random().toString(36).slice(2)}`,i=Qs(Cf(s,o,e,n));return{...r,body:i,headers:_([{"content-type":`multipart/form-data; boundary=${o}`},r.headers])}};async function*Cf(r,e,t,n){for await(let{key:s,value:o}of r){if(li(o)){let i=n?.get(o)??Fu(o,t),c=$f(o);yield ge(`--${e}\r
6
+ `),yield ge(`Content-Disposition: form-data; name="${Pa(s)}"; filename="${Pa(i)}"\r
7
+ Content-Type: ${c}\r
8
+ \r
9
+ `),yield*co(jf(o))}else yield ge(`--${e}\r
10
+ `),yield ge(`Content-Disposition: form-data; name="${Pa(s)}"\r
11
+ \r
12
+ ${String(o)}`);yield ge(`\r
13
+ `)}yield ge(`--${e}--\r
14
+ `)}function*Tf(r){if(!(!r||typeof r!="object"))for(let[e,t]of Object.entries(r))yield*Sa(e,t)}function*Sa(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"||li(e))yield{key:r,value:e};else if(Array.isArray(e))for(let t of e)yield*Sa(r+"[]",t);else if(typeof e=="object")for(let[t,n]of Object.entries(e))yield*Sa(`${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 Fu(r,e){if(uo(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?Bu(t):ao(t)??"unknown_file"}return vr(r,{stripFilename:e.stripFilenames})??"unknown_file"}function $f(r){let e;return uo(r)||ui(r)?{type:e}=r:r instanceof Response&&(e=r.headers.get("content-type")??void 0),Wu(e||"application/octet-stream")}function Wu(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 jf(r){return uo(r)?r.data:r}async function*co(r){if(typeof r=="string")yield ge(r);else if(ArrayBuffer.isView(r))yield new Uint8Array(r.buffer,r.byteOffset,r.byteLength);else if(Oa(r))yield new Uint8Array(r);else if(r instanceof Response)yield*co(r.body||await r.blob());else if(r instanceof Blob)typeof r.stream=="function"?yield*co(r.stream()):yield new Uint8Array(await r.arrayBuffer());else if(Ea(r))for await(let e of zo(r))yield*co(e);else if(wn(r))for await(let e of r)yield*co(e);else throw new TypeError(`Invalid streaming file chunk: ${String(r)}`)}function Pa(r){return Array.from(r,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e==='"'||e==="\\"?encodeURIComponent(e):e}).join("")}var Ra=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,At([s],vr(t,{stripFilename:n.stripFilenames}),{type:s.type}))}else if(wn(t))r.append(e,At([await new Response(Qs(t)).blob()],vr(t,{stripFilename:n.stripFilenames})));else if(ui(t)){let s=vr(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 o=>{let i=new FormData;return await Ra(i,e+"[]",o,n),i}));for(let o of s)if(o)for(let[i,c]of o.entries())r.append(i,c)}else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,o])=>Ra(r,`${e}[${s}]`,o,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 Uu=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",Lf=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Uu(r),Mf=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Bf=(r,e)=>e?.type!=null&&e.type!==r.type||e?.lastModified!=null&&e.lastModified!==r.lastModified||e?.endings!=null,Df=(r,e,t)=>(e==null||e===r.name)&&!Bf(r,t);async function di(r,e,t){if(va(),r=await r,Lf(r)){let s={...t,type:t?.type??r.type,lastModified:t?.lastModified??r.lastModified};return r instanceof File?Df(r,e,t)?r:At([r],e??r.name,s):At([await r.arrayBuffer()],e??r.name,s)}if(Mf(r)){let s=await r.blob();e??(e=vr(r));let o=t?.type===void 0&&s.type?{...t,type:s.type}:t;return At(await ka(s),e,o)}let n=await ka(r);if(e??(e=vr(r)),t?.type===void 0){let s=n.find(o=>typeof o=="object"&&"type"in o&&!!o.type);s&&(t={...t,type:s.type})}return At(n,e,t)}async function ka(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||Oa(r))e.push(r);else if(Uu(r))e.push(r instanceof Blob?r:new Blob([await r.arrayBuffer()],{type:r.type}));else if(wn(r))for await(let t of r)e.push(...await ka(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Nf(r)}`)}return e}function Nf(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var p=class{constructor(e){this._client=e}};function Ku(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var qu=Object.freeze(Object.create(null)),Wf=(r=Ku)=>function(t,...n){if(t.length===1)return t[0];let s=!1,o=[],i="";for(let m=0;m<t.length;m+=1)if(m in t){let y=t[m];/[?#]/.test(y)&&(s=!0);let f=n[m],g=(s?encodeURIComponent:r)(""+f);m!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??qu)??qu)?.toString)&&(g=f+"",o.push({start:i.length+y.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),i+=y+(m===n.length?"":g)}let c=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=u.exec(c))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((m,y)=>m.start-y.start),o.length>0){let m=0,y="";for(let f of o){let g=" ".repeat(f.start-m),w="^".repeat(f.length);m=f.start+f.length,y+=g+w}throw new h(`Path parameters result in path with invalid segments:
15
+ ${o.map(f=>f.error).join(`
16
+ `)}
17
+ ${i}
18
+ ${y}`)}return i},l=Wf(Ku);var Or=class extends p{list(e,t={},n){return this._client.getAPIList(l`/chat/completions/${e}/messages`,R,{query:t,...n,__security:{bearerAuth:!0}})}};function ut(r){return r!==void 0&&"function"in r&&r.function!==void 0}function qf(r){return r?.$brand==="auto-parseable-response-format"}function lt(r){return qf(r)||r?.type==="json_schema"}function It(r,e){if(!lt(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 Ve(r){return r?.$brand==="auto-parseable-tool"}function zu(r,e){return!e||!Ta(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}}))}:lo(r,e)}function lo(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new Ft;if(n.finish_reason==="content_filter")throw new Wt;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>zf(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)?Kf(e,n.message.content):null}}});return{...r,choices:t}}function Kf(r,e){return It(r.response_format,e)}function zf(r,e){if(e.type==="custom")return e;if(e.type!=="function"){let s=e.type;throw new h(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${s}\``)}let t=r.tools?.find(s=>ut(s)&&s.function?.name===e.function.name),n=null;return Ve(t)?n=t.$parseRaw(e.function.arguments):t?.function.strict&&(n=It({type:"json_schema",$parseRaw:void 0},e.function.arguments)),{...e,function:{...e.function,parsed_arguments:n}}}function fi(r,e){if(!r||!("tools"in r)||!r.tools||e.type!=="function")return!1;let t=r.tools?.find(n=>ut(n)&&n.function?.name===e.function?.name);return ut(t)&&(Ve(t)||t?.function.strict||!1)}function Ta(r){return lt(r.response_format)?!0:r.tools?.some(e=>Ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function Xu(r){for(let e of r??[])if(e.type!=="custom"){if(e.type!=="function"){let t=e.type;throw new h(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${t}\``)}if(e.function.strict!==!0)throw new h(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Pt=r=>r?.role==="assistant",fo=r=>r?.role==="tool";var ke,mi,_i,yo,ho,yi,go,qe,bo,wo,mo,An,Kt,Er,bi,wi,In,kr,Da,Zu,Na,el,Fa,gi,tl,Hu=4096,_o=8*1024*1024,Xf=4096,Ao=256,Hf=JSON.stringify,Jf=JSON.parse,$a=new WeakSet,Vf=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,Gf=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,Yf=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,Ju=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,Qf=Date.prototype.getTime,Zf=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,ep=typeof SharedArrayBuffer=="function"?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,po=Object.getOwnPropertyDescriptor(new Error("native stack descriptor"),"stack"),dt=Function.prototype.toString,tp=Object.prototype.toString,pi=Object.getOwnPropertyDescriptor(Error,"isError"),Vu=pi&&"value"in pi&&typeof pi.value=="function"?pi.value:void 0,rp=dt.call(Error),np=dt.call(Date),sp=dt.call(Function),Ai=new Set([De.prototype,re.prototype,z.prototype,h.prototype,Y.prototype,$t.prototype,ot.prototype,Mt.prototype,Wt.prototype,Nt.prototype,Oe.prototype,Ft.prototype,Lt.prototype,Ne.prototype,jt.prototype,Dt.prototype,gr.prototype,Bt.prototype]),rl=new Set,nl=new Map,Gu=new WeakMap;function op(){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 ip=op();function Ii(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;Ai.add(e.value);let t=dt.call(r);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(t)&&e.configurable===!1&&e.writable===!1){rl.add(t);let n=new Map;for(let s of Reflect.ownKeys(e.value)){let o=Object.getOwnPropertyDescriptor(e.value,s);o&&n.set(s,o)}nl.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])Ii(r);for(let r of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){let e=Object.getOwnPropertyDescriptor(globalThis,r);e&&"value"in e&&Ii(e.value)}var ja=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");ja&&"value"in ja&&Ii(ja.value);typeof Buffer=="function"&&Ii(Buffer);var ap=(()=>{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}})(),cp=Map.prototype.entries,up=Set.prototype.values,hi=typeof Headers=="function"?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,Yu=hi&&"value"in hi&&typeof hi.value=="function"?hi.value:void 0,lp=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);function Pi(r){let e=Object.getOwnPropertyDescriptor(r,"constructor");if(!e||!("value"in e)||typeof e.value!="function")return;let t=e.value,n=dt.call(t),s=nl.get(n);if(!rl.has(n)||!s)return;let o=Object.getOwnPropertyDescriptor(t,"prototype");if(!(!o||!("value"in o)||o.value!==r||o.configurable!==!1||o.writable!==!1))return{constructor:t,descriptors:s,functionPrototype:Object.getPrototypeOf(t)}}function dp(r){return Ai.has(r)||Pi(r)!==void 0}function La(r,e,t){if(e===void 0)return r===void 0;if(typeof r!="function"||typeof e!="function")return!1;let n=dt.call(e);if(dt.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 o=Pi(s);return o!==void 0&&dt.call(o.constructor)===sp}function fp(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"?La(r.value,e.value,t):e.value!==null&&typeof e.value=="object"?!1:Object.is(r.value,e.value):La(r.get,e.get,t)&&La(r.set,e.set,t)}function Qu(r){if(Vu)return Vu.call(Error,r);let e=r;for(let t=0;e!==null&&t<Ao;t+=1){if(Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))return!1;e=Object.getPrototypeOf(e)}return e===null&&tp.call(r)==="[object Error]"}function pp(r,e){if(typeof e.get!="function"||typeof e.set!="function")return;let t=Object.getPrototypeOf(r);for(let n=0;t!==null&&n<Ao;n+=1){let s=Object.getOwnPropertyDescriptor(t,"constructor");if(s&&"value"in s&&typeof s.value=="function"){let o=s.value;if(dt.call(o)===rp&&dp(t)){let i=Object.getPrototypeOf(o);return Object.getPrototypeOf(e.get)===i&&Object.getPrototypeOf(e.set)===i?{constructor:o,prototype:t}:void 0}}t=Object.getPrototypeOf(t)}}function hp(r,e){if(!Qu(r))return!1;if(po&&!("value"in po)&&typeof po.get=="function"&&Object.prototype.isPrototypeOf.call(Error.prototype,r)&&e.get===po.get&&e.set===po.set)return!0;let t=pp(r,e);if(!t)return!1;let n=Gu.get(t.prototype);if(!n){let s=Reflect.construct(t.constructor,[]);if(typeof s!="object"||s===null||!Qu(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;Gu.set(t.prototype,n)}return e.get===n.get&&e.set===n.set}function Ma(){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 mp(r){let e=Object.getPrototypeOf(r);for(let t=0;e!==null&&t<Ao;t+=1){if(e===Date.prototype)return"Date";if(!Ai.has(e)){let s=Object.getOwnPropertyDescriptor(e,"constructor");if(s&&"value"in s&&typeof s.value=="function"&&dt.call(s.value)===np&&Pi(e))return"Date"}let n=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);if(n&&"value"in n&&typeof n.value=="string"&&lp.has(n.value))return n.value;e=Object.getPrototypeOf(e)}}function _p(r,e,t){if(ArrayBuffer.isView(r)){let c,u="typed-array";try{c=Vf?.call(r)}catch{u="data-view",c=Yf?.call(r)}return typeof c!="object"||c===null?{bytes:Number.POSITIVE_INFINITY,kind:u}:(e(c,t+1),{bytes:0,kind:u})}let n=mp(r);if(!n)return;let s,o="buffer";switch(n){case"ArrayBuffer":{s=Zf;break}case"SharedArrayBuffer":{s=ep;break}case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(Qf,r,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}let i=s?.call(r);return{bytes:typeof i=="number"&&Number.isSafeInteger(i)&&i>=0?i:Number.POSITIVE_INFINITY,kind:o}}function yp(r,e,t){if(e==="map"){for(let[n,s]of cp.call(r))if(!t(n,8)||!t(s,8))return!1}if(e==="set"){for(let n of up.call(r))if(!t(n,8))return!1}if(e==="headers"){if(!Yu)return!1;for(let[n,s]of Yu.call(r))if(!t(n,8)||!t(s,8))return!1}return!0}function gp(r,e,t){if(Array.isArray(r)){let s=Object.getOwnPropertyDescriptor(r,"length"),o=s&&"value"in s?s.value:void 0;if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>Math.floor(t/16))return}if(e!=="typed-array")return Reflect.ownKeys(r);let n=Gf?.call(r);if(!(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>Xf))return Reflect.ownKeys(r).filter(s=>{if(typeof s!="string")return!0;let o=Number(s);return!Number.isInteger(o)||o<0||o>=n||String(o)!==s})}function sl(r,e,t,n,s,o){let i=gp(r,e,n());if(i===void 0)return!1;for(let c of i){if(!s(typeof c=="string"?c.length*2+8:8))return!1;typeof c=="symbol"&&o(c,t+1);let u=Object.getOwnPropertyDescriptor(r,c);if(!u)return!1;if(!("value"in u)){if(c==="stack"&&hp(r,u))continue;return!1}o(u.value,t+1,e==="blob")}return!0}function bp(r,e,t,n,s,o,i,c){let u=Object.getPrototypeOf(r);for(let d=e+1;u!==null;d+=1){if(d>=Ao)return!1;if(Ai.has(u)||t&&u===ap)return!0;if(n.has(u))return i(u,d),s()>=0;n.add(u);let m=u;if(!c(m,()=>{if(!o(16))return!1;let f=Pi(m);if(!f)return sl(m,void 0,d,s,o,i);for(let g of Reflect.ownKeys(m)){let w=Object.getOwnPropertyDescriptor(m,g);if(!w)return!1;if(!fp(w,f.descriptors.get(g),f.functionPrototype)){if(!o(typeof g=="string"?g.length*2+8:8)||!("value"in w))return!1;typeof g=="symbol"&&i(g,d+1),i(w.value,d+1)}}return s()>=0}))return!1;u=Object.getPrototypeOf(m)}return!0}var wp=32,Ap=32,ol=8,il=16,Ip=128*1024;function Ba(r,e){let t=0,n=0,s=new WeakSet,o=new Set,i=new Set,c=new Map,u,d=()=>e-t,m=A=>!Number.isSafeInteger(A)||A<0?(t=e+1,!1):(t+=A,u?u.bytes+=A:n+=A,t<=e),y=A=>{u?u.edges.add(A):i.add(A)},f=(A,S)=>{y(A);let O={bytes:0,edges:new Set};c.set(A,O);let P=u;u=O;try{return S()}finally{u=P}},g=A=>{if(o.has(A)){y(A),m(8);return}o.add(A),f(A,()=>{if(!Ju)return!1;let S=Reflect.apply(Ju,A,[]);return m(8+(S?.length??0)*2)})||(t=e+1)},w=(A,S,O=!1)=>{if(!(t>e)){if(typeof A=="string"){m(A.length*2);return}if(typeof A=="symbol"){g(A);return}if(typeof A=="function"){t=e+1;return}if(A===null||typeof A!="object"){m(8);return}if(ip?.(A)){t=e+1;return}if(S>=Ao){t=e+1;return}if(s.has(A)){y(A),m(8);return}s.add(A),f(A,()=>{if(!m(16))return!1;let P=_p(A,w,S);return!bp(A,S,O,s,d,m,w,f)||P!==void 0&&!m(P.bytes)||!yp(A,P?.kind,(L,I)=>m(I)?(w(L,S+1),t<=e):!1)?!1:sl(A,P?.kind,S,d,m,w)})||(t=e+1)}};try{w(r,0)}catch{return}return t<=e?{scalarBytes:n,roots:i,nodes:c}:void 0}function Pp(r,e){if(r.size!==e.size)return!1;for(let t of r)if(!e.has(t))return!1;return!0}function Wa(r,e){return r.bytes+Ap+r.edges.size*ol+e*il}function Ua(r){return wp+r.scalarBytes+r.roots.size*ol}function xp(r,e,t,n){let s=new Set,o=[...r];for(;o.length;){if(n.remaining-=1,n.remaining<0)return;let i=o.pop();if(s.has(i))continue;let c=e.get(i)??t.get(i);if(!c)return;s.add(i);for(let u of c.edges)o.push(u)}return s}function qa(r,e,t,n,s){let o=n.get(r);if(o)return s&&(o.node=s),o;let i=s??e.nodes.get(r)??t.get(r);if(!i)return;let c={node:i,ownerDelta:0};return n.set(r,c),c}function Sp(r,e,t,n,s){let o=new Set([r]);for(let[i,c]of e.nodes){if(s.remaining-=1,s.remaining<0)return;let u=t.get(i);if(!u)continue;let d=!Pp(u.edges,c.edges);if((u.bytes!==c.bytes||d)&&qa(i,e,t,n,c),!!d)for(let m of u.owners){if(s.remaining-=1,s.remaining<0)return;o.add(m)}}return o}function Rp(r,e,t,n,s,o){for(let i of r.identities){if(o.remaining-=1,o.remaining<0)return!1;if(!e.has(i)){let c=qa(i,t,n,s);if(!c)return!1;c.ownerDelta-=1}}for(let i of e){if(o.remaining-=1,o.remaining<0)return!1;if(!r.identities.has(i)){let c=qa(i,t,n,s);if(!c)return!1;c.ownerDelta+=1}}return!0}function vp(r,e,t,n,s,o){let i=new Map;for(let c of t){let u=c===r?e.roots:c.roots,d=xp(u,e.nodes,n,o);if(!d||!Rp(c,d,e,n,s,o))return;i.set(c,d)}return i}function Op(r,e,t,n,s,o){let i=r-(n?0:Ua(e))+Ua(t);for(let[c,u]of s){let d=o.get(c),m=(d?.owners.size??0)+u.ownerDelta;if(m<0)return;d&&(i-=Wa(d,d.owners.size)),m&&(i+=Wa(u.node,m))}return Number.isSafeInteger(i)&&i>=0&&i<=_o?i:void 0}function Ep(r,e,t){for(let[n,s]of e){let o=r.get(n);(o?.owners.size??0)+s.ownerDelta&&(o?(o.bytes=s.node.bytes,o.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 o of n.identities)s.has(o)||r.get(o)?.owners.delete(n);for(let o of s)n.identities.has(o)||r.get(o).owners.add(n);n.identities=s}for(let n of e.keys())r.get(n)?.owners.size===0&&r.delete(n)}function kp(){let r=new Map,e=0,t=(s,o,i)=>{let c={remaining:Ip},u=new Map,d=Sp(s,o,r,u,c);if(!d)return!1;let m=vp(s,o,d,r,u,c);if(!m)return!1;let y=Op(e,s,o,i,u,r);return y===void 0?!1:(Ep(r,u,m),s.scalarBytes=o.scalarBytes,s.roots=o.roots,e=y,!0)};return{retain(s){let o={scalarBytes:0,roots:new Set,identities:new Set};return t(o,s,!0)?o:void 0},refresh(s,o){return t(s,o,!1)},release:s=>{e-=Ua(s);for(let o of s.identities){let i=r.get(o);i?.owners.delete(s)&&(e-=il,i.owners.size===0&&(e-=Wa(i,0),r.delete(o)))}s.identities.clear()},clear(){r.clear(),e=0}}}var zt=class{constructor(){ke.add(this),this.controller=new AbortController,mi.set(this,void 0),_i.set(this,()=>{}),yo.set(this,()=>{}),ho.set(this,void 0),yi.set(this,()=>{}),go.set(this,()=>{}),qe.set(this,Object.create(null)),bo.set(this,[]),wo.set(this,new WeakMap),mo.set(this,new Set),An.set(this,new Set),Kt.set(this,0),Er.set(this,!1),bi.set(this,!1),wi.set(this,!1),In.set(this,!1),kr.set(this,void 0),b(this,mi,new Promise((e,t)=>{b(this,_i,e,"f"),b(this,yo,t,"f")}),"f"),b(this,ho,new Promise((e,t)=>{b(this,yi,e,"f"),b(this,go,t,"f")}),"f"),a(this,mi,"f").catch(()=>{}),a(this,ho,"f").catch(()=>{})}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(n=>{t=!0,a(this,ke,"m",gi).call(this,n)}).then(()=>{if(!t){try{this._emitFinal()}catch(n){a(this,ke,"m",gi).call(this,n);return}this._emit("end")}})},0)}_connected(){this.ended||(a(this,_i,"f").call(this),this._emit("connect"))}get ended(){return a(this,Er,"f")}get errored(){return a(this,bi,"f")}get aborted(){return a(this,wi,"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){a(this,ke,"m",Da).call(this,e);return}if(a(this,bo,"f").some(n=>n.signal===e))return;let t=()=>a(this,ke,"m",Da).call(this,e);e.addEventListener("abort",t,{once:!0}),a(this,bo,"f").push({signal:e,listener:t})}on(e,t){var n;return((n=a(this,qe,"f"))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=a(this,qe,"f")[e];if(!n)return this;let s=a(this,wo,"f").get(t);if(s?.event===e&&!s.registration.removed&&!s.registration.detached)return a(this,ke,"m",el).call(this,e,s.registration),this;let o=n.findIndex(i=>!i.removed&&i.listener===t);return o!==-1&&n.splice(o,1),this}once(e,t){var n;return((n=a(this,qe,"f"))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{b(this,In,!0,"f");let s=i=>{this.off(e,o),n(i)},o=(...i)=>{e!=="error"&&this.off("error",s),t(i.length>1?i:i[0])};e!=="error"&&a(this,ke,"m",Na).call(this,"error",s),a(this,ke,"m",Na).call(this,e,o)})}events(e){return this._createIterator(t=>{let n=(...s)=>{$a.add(s);try{t(s)}finally{$a.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 o=Ma(),i=Ma(),c=Ma(),u=kp(),d=this.ended,m,y=!1,f=()=>{},g=()=>({value:void 0,done:!0}),w=()=>{for(;c.length;)c.dequeue().resolve(g())},A=()=>{!m||y||!c.length||(y=!0,c.dequeue().reject(m))},S=()=>{f(),this.off("end",M),t&&this.off("error",T),n&&this.off("abort",T)},O=k=>{k.active=!1,k.check&&(a(this,An,"f").delete(k.check),k.check=void 0)},P=(k=!1)=>{if(k){for(;i.length;)O(i.dequeue());o.clear(),u.clear()}let E=new h(`Event stream iterator buffer limit exceeded (${Hu} events or ${_o} bytes); consume events as they arrive.`);try{a(this,ke,"m",gi).call(this,E)}finally{this.controller.abort()}return E},L=(k,E)=>{if(!E.active||a(this,Er,"f"))return;let v=Ba(k,_o);(!v||!u.refresh(E.retention,v))&&P(!0)},I=k=>{if(d)return;let E=c.dequeue();if(E)E.resolve({value:k,done:!1});else{if(o.length>=Hu){P();return}let v=Ba(k,_o),K=v&&u.retain(v);if(!K){P();return}if(typeof k=="object"&&k!==null&&$a.has(k)){let q=k;for(let be=0;be<q.length;be+=1){let W=q[be];typeof W=="string"&&(q[be]=Jf(Hf(W)))}}let D={retention:K,active:!0,check:void 0};o.enqueue(k),i.enqueue(D);let N=()=>{D.check=void 0,L(k,D)};D.check=N,a(this,An,"f").add(N)}},T=k=>{m=k,o.length||A()},x=()=>{if(m)return;let k=a(this,kr,"f");k&&(k.kind==="error"?t:n)&&(m=k.error)},M=()=>{d=!0,x(),S(),o.length||(A(),w())};return d||(f=e(I),this.on("end",M),t&&this.on("error",T),n&&this.on("abort",T)),{next:()=>{if(o.length){let k=o.dequeue(),E=i.dequeue();O(E);let v=Ba(k,_o);if(!v||!u.refresh(E.retention,v)){let K=P(!0);return y=!0,Promise.reject(K)}return u.release(E.retention),Promise.resolve({value:k,done:!1})}return(d||this.ended)&&x(),m&&!y?(y=!0,Promise.reject(m)):d?Promise.resolve(g()):new Promise((k,E)=>{c.enqueue({resolve:k,reject:E})})},return:()=>{for(d=!0,y=!0;i.length;)O(i.dequeue());return o.clear(),u.clear(),S(),w(),s&&(this.done().catch(()=>{}),s()),Promise.resolve(g())},[Symbol.asyncIterator](){return this}}}async done(){b(this,In,!0,"f"),await a(this,ho,"f")}_hasListeners(e){return!!a(this,qe,"f")[e]?.some(t=>!t.removed)}_emit(e,...t){if(a(this,Er,"f"))return;e==="end"&&(a(this,ke,"m",Zu).call(this),b(this,Er,!0,"f"),a(this,yi,"f").call(this));let n=a(this,qe,"f")[e],s,o=!1;try{if(n){a(this,qe,"f")[e]=n.filter(i=>(i.once&&(i.detached=!0),!i.once&&!i.removed)),b(this,Kt,a(this,Kt,"f")+1,"f");try{for(let i of n)if(!i.removed){let{listener:c}=i;c(...t)}}finally{if(b(this,Kt,a(this,Kt,"f")-1,"f"),a(this,Kt,"f")===0){a(this,ke,"m",Fa).call(this);for(let i of a(this,An,"f"))a(this,An,"f").delete(i),a(this,Er,"f")||i()}}}}catch(i){s=i,o=!0}try{a(this,ke,"m",tl).call(this,e,t,!!n?.length)}catch(i){o||(s=i,o=!0)}if(o)throw s}_emitFinal(){}};mi=new WeakMap,_i=new WeakMap,yo=new WeakMap,ho=new WeakMap,yi=new WeakMap,go=new WeakMap,qe=new WeakMap,bo=new WeakMap,wo=new WeakMap,mo=new WeakMap,An=new WeakMap,Kt=new WeakMap,Er=new WeakMap,bi=new WeakMap,wi=new WeakMap,In=new WeakMap,kr=new WeakMap,ke=new WeakSet,Da=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},Zu=function(){for(let{signal:e,listener:t}of a(this,bo,"f").splice(0))e.removeEventListener("abort",t)},Na=function(e,t){let n=a(this,qe,"f")[e],s=n?.length??0;this.once(e,t);let o=a(this,qe,"f")[e],[i]=o?.slice(-1)??[];(n===void 0||o===n)&&o?.length===s+1&&i?.listener===t&&i.once&&a(this,wo,"f").set(t,{event:e,registration:i})},el=function(e,t){t.removed||(t.removed=!0,a(this,wo,"f").delete(t.listener),a(this,mo,"f").add(e),a(this,Kt,"f")===0&&a(this,ke,"m",Fa).call(this))},Fa=function(){for(let e of a(this,mo,"f")){let t=e,n=a(this,qe,"f")[t];n&&(a(this,qe,"f")[t]=n.filter(s=>!s.removed))}a(this,mo,"f").clear()},gi=function(e){if(b(this,bi,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=this._userAbortError()),e instanceof Y)return b(this,wi,!0,"f"),this._emit("abort",e);if(e instanceof h)return this._emit("error",e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new h(String(e)))},tl=function(e,t,n){if(e==="abort"){let s=t[0];b(this,kr,a(this,kr,"f")??{kind:"abort",error:s},"f"),!a(this,In,"f")&&!n&&Promise.reject(s),a(this,yo,"f").call(this,s),a(this,go,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];b(this,kr,a(this,kr,"f")??{kind:"error",error:s},"f"),!a(this,In,"f")&&!n&&Promise.reject(s),a(this,yo,"f").call(this,s),a(this,go,"f").call(this,s),this._emit("end")}};function al(r){return typeof r.parse=="function"}var xe,Cr,xi,Si,Ka,Ri,za,Xa,Ha,Ja,cl,ul,Cp=10;function Tp(r){for(let e of r.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${Je()}`)}function $p(r){if(!Pt(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 Tr=class extends zt{constructor(){super(...arguments),xe.add(this),this._chatCompletions=[],xi.set(this,!1),Si.set(this,!1),this.messages=[]}_addChatCompletion(e){b(this,xi,!this.controller.signal.aborted,"f"),Tp(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),fo(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Pt(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 h("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),a(this,xe,"m",Ka).call(this)}async finalMessage(){return await this.done(),a(this,xe,"m",Ri).call(this)}async finalFunctionToolCall(){return await this.done(),a(this,xe,"m",za).call(this)}async finalFunctionToolCallResult(){return await this.done(),a(this,xe,"m",Xa).call(this)}async totalUsage(){return await this.done(),a(this,xe,"m",Ha).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){a(this,Si,"f")&&a(this,xe,"m",Ja).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=a(this,xe,"m",Ri).call(this);t&&this._emit("finalMessage",t);let n=a(this,xe,"m",Ka).call(this);n&&this._emit("finalContent",n);let s=a(this,xe,"m",za).call(this);s&&this._emit("finalFunctionToolCall",s);let o=a(this,xe,"m",Xa).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",a(this,xe,"m",Ha).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),a(Cr,Cr,"m",cl).call(Cr,t);let s=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(lo(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 o="tool",{tool_choice:i="auto",stream:c,toolContext:u,...d}=t,m=u,y=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:f=Cp,afterCompletion:g}=s||{},w=async I=>{g!=null&&(b(this,Si,!0,"f"),await g(I,n),a(this,xe,"m",Ja).call(this))},A=t.tools.map(I=>{if(Ve(I)){if(!I.$callback)throw new h("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:I.$callback,name:I.function.name,description:I.function.description||"",parameters:I.function.parameters,parse:I.$parseRaw,strict:!0}}}return I}),S=Object.create(null);for(let I of A)I.type==="function"&&(S[I.function.name||I.function.function.name]=I.function);let O="tools"in t?A.map(I=>I.type==="function"?{type:"function",function:{name:I.function.name||I.function.function.name,parameters:I.function.parameters,description:I.function.description,strict:I.function.strict}}:I):void 0;for(let I of t.messages)this._addMessage(I,!1,!1);let P=!1,L=async I=>{let T=P;if(P=!1,I.type!=="function")return{message:void 0,functionCalled:!1};let x=I.id,{name:M,arguments:k}=I.function,E=S[M];if(!E){let D=`Invalid tool_call: ${JSON.stringify(M)}. Available options are: ${Object.keys(S).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:x,content:D},functionCalled:!1}}if(y&&y!==M){let D=`Invalid tool_call: ${JSON.stringify(M)}. ${JSON.stringify(y)} requested. Please try again`;return{message:{role:o,tool_call_id:x,content:D},functionCalled:!1}}let v;if(al(E)){let D;try{D=await E.parse(k)}catch(N){if(this.controller.signal.aborted)throw this._userAbortError();let q=N instanceof Error?N.message:String(N);return{message:{role:o,tool_call_id:x,content:q},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{v=await E.function(D,n,m)}catch(N){throw this.controller.signal.aborted&&Object.is(N,this.controller.signal.reason)?this._userAbortError():N}}else{if(this.controller.signal.aborted&&!T)throw this._userAbortError();try{v=await E.function(k,n,m)}catch(D){throw this.controller.signal.aborted&&Object.is(D,this.controller.signal.reason)?this._userAbortError():D}}let K=a(Cr,Cr,"m",ul).call(Cr,v);return{message:{role:o,tool_call_id:x,content:K},functionCalled:!0}};for(let I=0;I<f;++I){let T=await this._createChatCompletion(e,{...d,tool_choice:i,tools:O,messages:this.messages.map($p)},s);P=this.controller.signal.aborted&&a(this,xi,"f");let x=T.choices[0]?.message;if(!x)throw new h("missing message in ChatCompletion response");if(!x.tool_calls?.length){await w(T);return}if(y||t.parallel_tool_calls===!1)for(let M of x.tool_calls){let k=await L(M);if(k.message&&this._addMessage(k.message),this.controller.signal.aborted)throw this._userAbortError();if(y&&k.functionCalled){await w(T);return}}else{let M=await Promise.allSettled(x.tool_calls.map(L));if(!this.controller.signal.aborted){for(let k of M)if(k.status==="rejected")throw k.reason}for(let k of M)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await w(T)}}};Cr=Tr,xi=new WeakMap,Si=new WeakMap,xe=new WeakSet,Ka=function(){return a(this,xe,"m",Ri).call(this).content??null},Ri=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Pt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new h("stream ended without producing a ChatCompletionMessage with role=assistant")},za=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Pt(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}}},Xa=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(fo(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}},Ha=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ja=function(){if(this.controller.signal.aborted)throw this._userAbortError()},cl=function(e){if(e.n!=null&&e.n>1)throw new h("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ul=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Io=class r extends Tr{static runTools(e,t,n){let s=new r,o={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,o)),s}_addMessage(e,t=!0,n=!0){super._addMessage(e,t,n),t&&Pt(e)&&e.content&&this._emit("content",e.content)}};var pe={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},Va=class extends Error{},Po=class extends Error{};function jp(r,e=pe.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Lp(r.trim(),e)}var Lp=(r,e)=>{let t=r.length,n=0,s=f=>{throw new Va(`${f} at position ${n}`)},o=f=>{throw new Po(`${f} at position ${n}`)},i=()=>(y(),n>=t&&s("Unexpected end of input"),r[n]==='"'?c():r[n]==="{"?u():r[n]==="["?d():r.substring(n,n+4)==="null"||pe.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||pe.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||pe.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||pe.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||pe.MINUS_INFINITY&e&&t-n>1&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||pe.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,Number.NaN):m()),c=()=>{let f=n,g=!1;for(n++;n<t&&(r[n]!=='"'||g&&r[n-1]==="\\");)g=r[n]==="\\"?!g:!1,n++;if(r.charAt(n)==='"')try{return JSON.parse(r.substring(f,++n-Number(g)))}catch(w){o(String(w))}else if(pe.STR&e)try{return JSON.parse(r.substring(f,n-Number(g))+'"')}catch{return JSON.parse(r.substring(f,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,y();let f={};try{for(;r[n]!=="}";){if(y(),n>=t&&pe.OBJ&e)return f;let g=c();y(),n++;try{let w=i();Object.defineProperty(f,g,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(pe.OBJ&e)return f;throw w}y(),r[n]===","&&n++}}catch{if(pe.OBJ&e)return f;s("Expected '}' at end of object")}return n++,f},d=()=>{n++;let f=[];try{for(;r[n]!=="]";)f.push(i()),y(),r[n]===","&&n++}catch{if(pe.ARR&e)return f;s("Expected ']' at end of array")}return n++,f},m=()=>{if(n===0){r==="-"&&pe.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(w){if(pe.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(w))}}let f=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n===t&&!(pe.NUM&e)&&s("Unterminated number literal");let g=r.substring(f,n);try{return JSON.parse(g)}catch{g==="-"&&pe.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(g.substring(0,g.lastIndexOf("e")))}catch(w){o(String(w))}}},y=()=>{for(;n<t&&`
19
+ \r `.includes(r[n]);)n++};return i()},ll=r=>jp(r,pe.ALL^pe.NUM);var J,oe,vi,Xt,$r,Se,Ke,$e,Ga,Pn,Ya,Qa,Za,xn,xo,dl;function fl(r){try{return ll(r)}catch(e){if(e instanceof Po||e instanceof SyntaxError)return It({type:"json_schema",$parseRaw:void 0},r);throw e}}var lc="chat.completion.chunk.message:";function gl(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:`${lc}${JSON.stringify(n)}`}}function Mp(r){return"type"in r&&r.type==="message"&&"message"in r||"object"in r&&typeof r.object=="string"&&r.object.startsWith(lc)}function Bp(r){return"type"in r?r:JSON.parse(r.object.slice(lc.length))}var Oi=128,Ht=128,Dp=16*1024*1024,Np=65536,dc=128,bl=64*1024*1024,pl=1024;function ic(){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 ac(r,e,t,n){if(e.fragments>=Np)throw new h("Chat completion stream exceeded its structured JSON fragment limit");let s=0,{depth:o,escaped:i,has_non_whitespace:c,in_string:u}=r,d=!1,m=!0;for(let f of t){let g=s,w=f.codePointAt(0);if(m&&r.pending_high_surrogate&&w>=56320&&w<=57343||w<=127?s+=1:w<=2047?s+=2:w<=65535?s+=3:s+=4,m=!1,e.bytes+s>Dp)throw new h("Chat completion stream exceeded its structured JSON byte limit");if(n&&n.work+s>bl)throw n.work+=g,new h("Chat completion stream exceeded its structured JSON parse-work limit");if(f!==" "&&f!==`
20
+ `&&f!=="\r"&&f!==" "&&(c=!0),u){i?i=!1:f==="\\"?i=!0:f==='"'&&(u=!1,d||(d=o===0));continue}if(f==='"')u=!0;else if(f==="{"||f==="["){if(o+=1,o>dc)throw new h("Chat completion stream exceeded its structured JSON nesting depth limit")}else(f==="}"||f==="]")&&o>0&&(o-=1,d||(d=o===0))}if(r.bytes+=s,r.fragments+=1,r.depth=o,r.escaped=i,r.has_non_whitespace=c,r.in_string=u,t.length>0){let f=t.codePointAt(t.length-1)??0;r.pending_high_surrogate=f>=55296&&f<=56319}if(e.bytes+=s,e.fragments+=1,n&&(n.work+=s),!c||s===0)return!1;let y=Math.max(pl,Math.floor(r.last_parsed_bytes/2));return!(r.bytes>pl&&!d&&r.bytes-r.last_parsed_bytes<y)}function cc(r,e){return e.work+r.bytes>bl?!1:(e.work+=r.bytes,r.work+=r.bytes,r.last_parsed_bytes=r.bytes,!0)}function ze(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>=dc||Object.getOwnPropertyDescriptor(n,e))throw new h("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 h("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}function So(r){let e=Object.getOwnPropertyDescriptor(r,"message");if(!e||!("value"in e)||typeof e.value!="object"||e.value===null)throw new h("Chat completion stream contains an unsafe structured JSON snapshot");return e.value}function hl(r,e,t,n){let s=Object.getOwnPropertyDescriptor(r,e);if(!s){let i=Object.getPrototypeOf(r);for(let c=0;i!==null;c+=1){if(c>=dc||Object.getOwnPropertyDescriptor(i,e))throw new h(`Chat completion stream contains an unsafe snapshot ${n} collection`);i=Object.getPrototypeOf(i)}return}if(!("value"in s)||!Array.isArray(s.value))throw new h(`Chat completion stream contains an unsafe snapshot ${n} collection`);let o=Object.getOwnPropertyDescriptor(s.value,"length");if(!o||!("value"in o)||!Number.isSafeInteger(o.value)||o.value>t)throw new h(`Chat completion stream exceeded its snapshot ${n} limit`);return s.value}function ec(r,e){let t=Object.getOwnPropertyDescriptor(r,e);if(t){if(!("value"in t))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}}function ml(r,e,t,n){let s=Object.getOwnPropertyDescriptor(r,"length"),o=s&&"value"in s?s.value:void 0;if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>e)throw new h(`Chat completion stream exceeded its snapshot ${t} limit`);let i=[];i.length=o;for(let c=0;c<o;c+=1){let u=Object.getOwnPropertyDescriptor(r,c);if(u){if(!("value"in u))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");i[c]=n(u.value,c)}}return i}function jr(r,e,t){let n=ic(),s=e??{bytes:0,fragments:0,work:0};if(ac(n,s,r,t),!cc(n,s))throw new h("Chat completion stream exceeded its structured JSON parse-work limit");return r}function Ei(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 tc(r,e){let t=Ei(r);if(!t||t.name!==e.name||t.type!==e.type)throw new h("Chat completion stream contains a changed tool call identity")}function Ro(r,e){return Object.prototype.propertyIsEnumerable.call(e,"__proto__")&&!$(r,"__proto__")&&Object.defineProperty(r,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(r,e)}function vo(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 Fp(r){let e=vo(r);if(r.tools){let t=[],n=Object.getOwnPropertyDescriptor(r.tools,"length"),s=n&&"value"in n?n.value:void 0,o=typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?Math.min(s,Ht):0;for(let i=0;i<o;i+=1){let c=Object.getOwnPropertyDescriptor(r.tools,String(i));if(!c||!("value"in c)){t.length=i+1;continue}let u=c.value,d=vo(u,["type","$brand","$parseRaw","$callback","function"]),m=Object.getOwnPropertyDescriptors(d);if(ut(d)){let y=m.function;m.function={...y&&"value"in y?y:{configurable:!0,enumerable:!0,writable:!0},value:vo(d.function,["name","strict"])}}t[i]=Object.create(Object.getPrototypeOf(u),m)}e.tools=t}return r.response_format&&(e.response_format=vo(r.response_format,["type","$brand","$parseRaw"])),e}var rc=4096,nc=JSON.stringify,Wp=1024*1024,Up=64,sc=Symbol("omitted serialized parser value"),he=Symbol("unsafe serialized parser value");function wl(r,e){let t=new WeakSet,n=o=>!Number.isSafeInteger(o)||o<0||e.bytes+o>Wp?!1:(e.bytes+=o,!0),s=(o,i)=>{if(i>Up||e.nodes>=rc)return he;if(e.nodes+=1,o===void 0||typeof o=="function"||typeof o=="symbol")return sc;if(typeof o=="bigint")return he;if(o===null||typeof o=="boolean"||typeof o=="number"){let d=nc(o);return typeof d=="string"&&n(d.length)?d:he}if(typeof o=="string")return n(o.length*6+2)?nc(o):he;if(typeof o!="object"||t.has(o))return he;let c=Array.isArray(o),u=Object.getPrototypeOf(o);if(c&&u!==Array.prototype||!c&&u!==null&&u!==Object.prototype)return he;for(let d=o;d!==null;d=Object.getPrototypeOf(d)){let m=Object.getOwnPropertyDescriptor(d,"toJSON");if(m){if(!("value"in m)||typeof m.value=="function")return he;break}}t.add(o);try{if(!n(2))return he;if(c){let f=Object.getOwnPropertyDescriptor(o,"length"),g=f&&"value"in f?f.value:void 0;if(typeof g!="number"||!Number.isSafeInteger(g)||g<0||g>rc-e.nodes)return he;let w=[];for(let A=0;A<g;A+=1){let S=String(A),O=Object.getOwnPropertyDescriptor(o,S);if(!O){if(Object.getOwnPropertyDescriptor(Array.prototype,S)||Object.getOwnPropertyDescriptor(Object.prototype,S)||(e.nodes+=1,!n(4)))return he;w.push("null");continue}if(!("value"in O))return he;let P=s(O.value,i+1);if(P===he)return P;w.push(P===sc?"null":P)}return`[${w.join(",")}]`}let d=Reflect.ownKeys(o);if(d.length>rc-e.nodes)return he;let m=[];for(let f of d){if(typeof f!="string")continue;let g=Object.getOwnPropertyDescriptor(o,f);if(!g)return he;if(g.enumerable){if(!("value"in g))return he;m.push([f,g.value])}}m.sort(([f],[g])=>f===g?0:f<g?-1:1);let y=[];for(let[f,g]of m){let w=s(g,i+1);if(w===he)return w;if(w!==sc){if(!n(f.length*6+3))return he;y.push(`${nc(f)}:${w}`)}}return`{${y.join(",")}}`}finally{t.delete(o)}};try{let o=s(r,0);return typeof o=="string"?o:void 0}catch{return}}function _l(r,e,t,n){let s=Object.getOwnPropertyDescriptor(e,"$parseRaw"),o=Object.getOwnPropertyDescriptor(t,n);if(!s||!("value"in s)||typeof s.value!="function"||!o||!("value"in o))return;let i=wl(o.value,{nodes:0,bytes:0});i!==void 0&&r.set(e,i)}function yl(r,e,t,n,s){let o=e&&r.get(e),i=Object.getOwnPropertyDescriptor(t,n);return o!==void 0&&i!==void 0&&"value"in i&&wl(s,{nodes:0,bytes:0})===o}function Sn(r,e){return r&&"value"in r?{...r,value:e}:{configurable:!0,enumerable:!0,writable:!0,value:e}}function uc(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 qp(r){let e=r.source??{type:r.type,...r.type==="function"?{function:{}}:{}},t=Object.getOwnPropertyDescriptors(e);if(t.type=Sn(t.type,r.type),r.type!=="function"||!r.function)return t.function&&(t.function=Sn(t.function,void 0)),uc(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:{},o=Object.getOwnPropertyDescriptors(s);return o.name=Sn(o.name,r.function.name),o.strict=Sn(o.strict,r.function.strict),t.function=Sn(n,Object.create(Object.getPrototypeOf(s),o)),r.function.schemaMatches||uc(t,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),t)}function Kp(r){let e=r.source??{type:r.type},t=Object.getOwnPropertyDescriptors(e);return t.type=Sn(t.type,r.type),(r.type!=="json_schema"||!r.source||!r.schemaMatches)&&uc(t,e,["$brand","$parseRaw"]),Object.create(Object.getPrototypeOf(e),t)}function oc(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 zp(r,e,t){let n=new WeakMap,s=new WeakMap;if(r.tools)for(let g=0;g<r.tools.length&&g<Ht;g+=1){let w=oc(r.tools,String(g)),A=e.tools?.[g];if(w&&A){n.set(w,A);let S=oc(A,"function");S&&_l(s,A,S,"parameters")}}e.response_format&&_l(s,e.response_format,e.response_format,"json_schema");let o,i,c,u,d=[],m=new WeakMap,y=new Map,f=new WeakMap;return Yc(r,{value(g,w,A){if(!o&&w===""&&typeof A=="object"&&A!==null){o=A,i=void 0,c=void 0,u=void 0,d=[],m=new WeakMap,y=new Map,f=new WeakMap;return}if(g===o&&w==="response_format"){typeof A=="object"&&A!==null&&(c=A,u={source:oc(g,w)===r.response_format?e.response_format:void 0,schemaMatches:!1});return}if(g===o&&w==="tools")return Array.isArray(A)?(i=new Proxy(A,{get(P,L){let I=Reflect.get(P,L,P);if(typeof L=="string"){let T=Number(L);Number.isSafeInteger(T)&&T>=0&&T<Ht&&String(T)===L&&y.set(T,typeof I=="object"&&I!==null?I:void 0)}return I}}),i):void 0;if(g===i){let P=Number(w);if(!Number.isSafeInteger(P)||P<0||P>=Ht||typeof A!="object"||A===null)return;let L=y.get(P),T={source:L?n.get(L):void 0};d[P]=T,m.set(A,T);return}let S=m.get(g);if(S){if(w==="type"&&typeof A=="string")S.type=A;else if(w==="function"&&typeof A=="object"&&A!==null){let P={source:S.source,schemaMatches:!1};S.function=P,f.set(A,P)}return}if(g===c&&u){w==="type"&&typeof A=="string"?u.type=A:w==="json_schema"&&(u.schemaMatches=yl(s,u.source,g,w,A));return}let O=f.get(g);O&&(w==="name"&&typeof A=="string"?O.name=A:w==="strict"&&typeof A=="boolean"?O.strict=A:w==="parameters"&&(O.schemaMatches=yl(s,O.source,g,w,A)))},complete(){if(!o)return;let g=vo(e);if(i){let w=[];for(let A=0;A<d.length;A+=1){let S=d[A];S&&(w[A]=qp(S))}g.tools=w}else delete g.tools;u?g.response_format=Kp(u):delete g.response_format,t(g),o=void 0,i=void 0,c=void 0,u=void 0,d=[],m=new WeakMap,y=new Map,f=new WeakMap}})}var Lr=class r extends Tr{constructor(e){super(),J.add(this),oe.set(this,void 0),vi.set(this,!1),Xt.set(this,void 0),$r.set(this,void 0),Se.set(this,void 0),Ke.set(this,void 0),$e.set(this,void 0),b(this,oe,e,"f"),b(this,Xt,new Set,"f"),b(this,$r,[],"f"),b(this,Ke,!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 o=0;o<Math.min(s,Ht);o+=1){let i=Object.getOwnPropertyDescriptor(t,String(o));if(!i||!("value"in i))continue;let c=i.value;if(ut(c)&&(Ve(c)||c.function.strict===!0)){b(this,Ke,!0,"f");break}}b(this,$e,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return a(this,Se,"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 b(this,vi,!0,"f"),super._runTools(e,t,n,s)}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0};b(this,oe,s,"f"),a(this,J,"m",Ga).call(this);let o=Fp(s);b(this,oe,o,"f"),b(this,Ke,o.tools?.some(u=>ut(u)&&(Ve(u)||u.function.strict===!0))??!1,"f");let i=s.tools||s.response_format?zp(s,o,u=>{b(this,oe,u,"f"),b(this,Ke,u.tools?.some(d=>ut(d)&&(Ve(d)||d.function.strict===!0))??!1,"f")}):void 0,c=await e.chat.completions.create(s,{...n,signal:this.controller.signal}).finally(i);this._connected();for await(let u of c)a(this,J,"m",Ya).call(this,u);if(c.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(a(this,J,"m",xo).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,J,"m",Ga).call(this),this._connected();let n=Ee.fromReadableStream(e,this.controller),s;for await(let i of n){if("error"in i&&$(i,"error")&&typeof i.error=="object"&&i.error!==null)throw new z(void 0,i.error,void 0,void 0);if(Mp(i)){let u=Bp(i);if(a(this,Se,"f")){let d=a(this,Se,"f").choices[0]?.message.tool_calls;for(let[m,y]of u.tool_call_ids?.entries()??[]){let f=d?.[m];f&&y&&(f.id=y)}this._addChatCompletion(a(this,J,"m",xo).call(this)),s=void 0}this._addMessage(u.message);continue}let c=i;s&&c.id&&s!==c.id&&this._addChatCompletion(a(this,J,"m",xo).call(this)),a(this,J,"m",Ya).call(this,c),c.id&&(s=c.id)}if(n.controller.signal?.aborted)throw this._userAbortError();if(a(this,Se,"f"))return this._addChatCompletion(a(this,J,"m",xo).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new h("request ended without sending any chunks")}[(oe=new WeakMap,vi=new WeakMap,Xt=new WeakMap,$r=new WeakMap,Se=new WeakMap,Ke=new WeakMap,$e=new WeakMap,J=new WeakSet,Ga=function(){this.ended||(b(this,Xt,new Set,"f"),b(this,Se,void 0,"f"),b(this,$e,{bytes:0,fragments:0,work:0},"f"))},Pn=function(t){let n=a(this,$r,"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},a(this,$r,"f")[t.index]=n,n)},Ya=function(t){if(this.ended)return;let n=new WeakMap,s=a(this,J,"m",dl).call(this,t,n);this._emit("chunk",t,s);for(let o of t.choices){let i=n.get(o),c=s.choices[i?.index??o.index],u=i?.tool_calls??[],{delta:d}=o,m=lt(a(this,oe,"f")?.response_format),y=m||a(this,Ke,"f"),f=y?So(c):c.message,g=y?ze(f,"refusal"):f.refusal,A=!g&&m?ze(f,"content"):f.content;d?.content!=null&&f.role==="assistant"&&A&&(this._emit("content",d.content,A),this._emit("content.delta",{delta:d.content,snapshot:A,parsed:f.parsed})),d?.refusal!=null&&f.role==="assistant"&&g&&this._emit("refusal.delta",{delta:d.refusal,snapshot:g}),o.logprobs?.content!=null&&f.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:c.logprobs?.content??[]}),o.logprobs?.refusal!=null&&f.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:c.logprobs?.refusal??[]});let S=a(this,J,"m",Pn).call(this,c);c.finish_reason&&(a(this,J,"m",Za).call(this,c),S.current_tool_call_index!=null&&a(this,J,"m",Qa).call(this,c,S.current_tool_call_index));for(let O of u)S.current_tool_call_index!==O.index&&(a(this,J,"m",Za).call(this,c),S.current_tool_call_index!=null&&a(this,J,"m",Qa).call(this,c,S.current_tool_call_index)),S.current_tool_call_index=O.index;for(let O of u){let P=f.tool_calls?.[O.index];if(P?.type)if(P.type==="function"){let L=S.tool_call_identities.get(O.index),I;if(L?.parseable){let T=ze(P.function,"arguments");if(typeof T!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");I=T}else I=P.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:P.function.name,index:O.index,arguments:I,parsed_arguments:P.function.parsed_arguments,arguments_delta:O.arguments_delta})}else P.type!=="custom"&&P}}},Qa=function(t,n){let s=a(this,J,"m",Pn).call(this,t);if(s.done_tool_calls.has(n))return;let i=(a(this,Ke,"f")?So(t):t.message).tool_calls?.[n];if(!i)throw new Error("no tool call snapshot");let c=s.tool_call_identities.get(n);if(c&&tc(i,c),!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let u=a(this,oe,"f")?.tools?.find(f=>ut(f)&&f.function.name===i.function.name),d=null,m=Ve(u)||u?.function.strict===!0,y;if(m){a(this,Se,"f")&&a(this,J,"m",xn).call(this,a(this,Se,"f"));let f=ze(i.function,"arguments");if(typeof f!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");y=f}else y=i.function.arguments;Ve(u)?d=u.$parseRaw(jr(y)):u?.function.strict&&(d=It({type:"json_schema",$parseRaw:void 0},jr(y))),t.finish_reason&&s.done_tool_calls.add(n),this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:n,arguments:y,parsed_arguments:d})}else i.type!=="custom"&&i},Za=function(t){let n=a(this,J,"m",Pn).call(this,t),s=lt(a(this,oe,"f")?.response_format),o=s||a(this,Ke,"f"),i=o?So(t):t.message,c=o?ze(i,"refusal"):i.refusal,u=!c&&s,d=u?ze(i,"content"):i.content;d!=null&&(d!==""||!c&&!i.tool_calls?.length&&!i.function_call)&&!n.content_done&&(u&&a(this,Se,"f")&&a(this,J,"m",xn).call(this,a(this,Se,"f")),n.content_done=!0,this._emit("content.done",{content:d,parsed:c?null:It(a(this,oe,"f")?.response_format,u?jr(d):d)})),c&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:c})),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}))},xn=function(t){let n={bytes:0,fragments:0,work:0},s=lt(a(this,oe,"f")?.response_format),o=new WeakMap,i=hl(t,"choices",Oi,"choice");if(!i)throw new h("Chat completion stream contains an unsafe snapshot choice collection");for(let c=0;c<i.length;c+=1){let u=ec(i,c);if(!u)continue;let d=So(u),m=ze(d,"refusal"),y=ze(d,"content"),f=new Map,g=hl(d,"tool_calls",Ht,"tool-call");o.set(u,Object.freeze({message:d,content:y,refusal:m,toolCallCollection:g,toolCalls:f}));let w=a(this,$r,"f")[u.index];s&&!m&&typeof y=="string"&&jr(y,n,a(this,$e,"f"));for(let[A,S]of w?.tool_call_identities??[]){let O=g&&ec(g,A);if(!O)throw new h("Chat completion stream contains a changed tool call identity");tc(O,S)}if(a(this,Ke,"f"))for(let A=0;A<(g?.length??0);A+=1){let S=ec(g,A);if(!S)continue;let O=Ei(S);if(!O){let T=Object.getOwnPropertyDescriptor(S,"type");if(T&&!("value"in T))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");if(T?.value!=="function")continue;let x=Object.getOwnPropertyDescriptor(S,"function");if(x&&!("value"in x))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");if(x&&typeof x.value=="object"&&x.value!==null){let M=Object.getOwnPropertyDescriptor(x.value,"name");if(M&&!("value"in M))throw new h("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!fi(a(this,oe,"f"),{type:O.type,function:{name:O.name}}))continue;let P=Object.getOwnPropertyDescriptor(S,"function");if(!P||!("value"in P))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");let L=P.value,I=ze(L,"arguments");if(typeof I!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");jr(I,n,a(this,$e,"f")),f.set(A,Object.freeze({tool:S,function:L,type:O.type,name:O.name,arguments:I}))}}return o},xo=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=a(this,Se,"f");if(!t)throw new h("request ended without sending any chunks");let n=a(this,J,"m",xn).call(this,t),s=a(this,Xt,"f");return b(this,Xt,new Set,"f"),b(this,Se,void 0,"f"),b(this,$r,[],"f"),Xp(t,a(this,oe,"f"),s,n)},dl=function(t,n){var s,o,i,c,u;let d=a(this,Se,"f"),{choices:m,obfuscation:y,...f}=t;if(d)t.id&&Ro(d,f);else{let A={...f,choices:[]};b(this,Se,A,"f"),d=A}let g=a(this,oe,"f")?.n,w=typeof g=="number"&&Number.isSafeInteger(g)&&g>0?Math.min(g,Oi):Oi;for(let A of t.choices){let{delta:S,finish_reason:O,index:P,logprobs:L=null,...I}=A,T=[];if(n.set(A,Object.freeze({index:P,tool_calls:T})),!Number.isSafeInteger(P)||P<0||P>=w)throw new h(`Chat completion stream contains an invalid choice index: ${P}`);let x=d.choices[P];if(!x){let W={finish_reason:O,index:P,message:{},logprobs:null,...I};d.choices[P]=W,x=W}if((lt(a(this,oe,"f")?.response_format)||a(this,Ke,"f"))&&ze(So(x),"refusal"),L)if(x.logprobs){let{content:W,refusal:rt,...te}=L;Ro(x.logprobs,te),W&&((s=x.logprobs).content??(s.content=[]),x.logprobs.content.push(...W)),rt&&((o=x.logprobs).refusal??(o.refusal=[]),x.logprobs.refusal.push(...rt))}else x.logprobs={...L},L.content&&(x.logprobs.content=[...L.content]),L.refusal&&(x.logprobs.refusal=[...L.refusal]);if(O&&(x.finish_reason=O,a(this,oe,"f")&&(a(this,vi,"f")||Ta(a(this,oe,"f"))))){if(O==="length")throw new Ft;if(O==="content_filter")throw new Wt}if(Ro(x,I),!S){Object.freeze(T);continue}a(this,Xt,"f").delete(P);let{audio:M,content:k,refusal:E,function_call:v,role:K,...D}=S,{tool_calls:N,...q}=D,be=$(D,"tool_calls")?N:S.tool_calls;if(Ro(x.message,q),M?.expires_at!=null&&M.id==null&&M.data==null&&M.transcript==null&&k==null&&E==null&&v==null&&K==null&&be==null&&Object.keys(q).length===0&&a(this,Xt,"f").add(P),E&&(x.message.refusal=(x.message.refusal||"")+E),K&&(x.message.role=K),M){let W=(i=x.message).audio??(i.audio={});M.id!=null&&(W.id=M.id),M.data!=null&&(W.data=(W.data??"")+M.data),M.transcript!=null&&(W.transcript=(W.transcript??"")+M.transcript),M.expires_at!=null&&(W.expires_at=M.expires_at)}if(v&&(x.message.function_call?(v.name&&(x.message.function_call.name=v.name),v.arguments&&((c=x.message.function_call).arguments??(c.arguments=""),x.message.function_call.arguments+=v.arguments)):x.message.function_call=v),k!=null)if(!x.message.refusal&&lt(a(this,oe,"f")?.response_format)){let W=a(this,J,"m",Pn).call(this,x),rt=W.content_parse_state??(W.content_parse_state=ic()),te=ac(rt,a(this,$e,"f"),k);x.message.content=(ze(x.message,"content")||"")+k,rt.has_non_whitespace?te&&cc(rt,a(this,$e,"f"))?(a(this,J,"m",xn).call(this,d),x.message.parsed=fl(jr(x.message.content))):k.length>0&&(x.message.parsed=null):x.message.parsed=null}else x.message.content=(x.message.content||"")+k;if(be){let W=(u=x.message).tool_calls??(u.tool_calls=[]);for(let rt of be){let{index:te,id:qo,type:pn,function:hn,custom:ht,...Zi}=rt;if(!Number.isSafeInteger(te)||te<0||te>=Ht)throw new h(`Chat completion stream contains an invalid tool call index: ${te}`);let Le="",ce=W[te]??(W[te]={}),He=hn?.name,nt=a(this,Ke,"f")?a(this,J,"m",Pn).call(this,x):void 0,Me=nt?.tool_call_identities.get(te);if(Me&&(tc(ce,Me),pn!==void 0&&pn!==Me.type||He!==void 0&&He!==Me.name))throw new h("Chat completion stream contains a changed tool call identity");if(Ro(ce,Zi),qo&&(ce.id=qo),pn&&(ce.type=pn),ht){let ve=ce.custom??(ce.custom={name:ht.name??"",input:""});ht.name&&(ve.name=ht.name),ht.input&&(ve.input+=ht.input)}if(hn){let ve=ce.function??(ce.function={name:He??"",arguments:""});if(He&&(ve.name=He),nt&&!Me){let Be=Ei(ce),ea=Be&&a(this,oe,"f")?.tools?.find(st=>ut(st)&&st.function.name===Be.name);if(Be&&(Me={...Be,parseable:ea!==void 0&&fi(a(this,oe,"f"),{type:Be.type,function:{name:Be.name}})},nt.tool_call_identities.set(te,Me),!Me.parseable)){let st=nt.tool_call_parse_states.get(te);st&&(a(this,$e,"f").bytes-=st.bytes,a(this,$e,"f").fragments-=st.fragments,a(this,$e,"f").work-=st.work,nt.tool_call_parse_states.delete(te))}}let Tt=hn.arguments;if(Tt!=null)if(Le=Tt,nt&&Me?.parseable!==!1){let Be=nt.tool_call_parse_states.get(te);Be||(Be=ic(),nt.tool_call_parse_states.set(te,Be));let ea=ac(Be,a(this,$e,"f"),Tt),st=ze(ve,"arguments");if(typeof st!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");ve.arguments=st+Tt,ea&&Me?.parseable===!0&&cc(Be,a(this,$e,"f"))?(a(this,J,"m",xn).call(this,d),ve.parsed_arguments=fl(jr(ve.arguments))):Tt.length>0&&$(ve,"parsed_arguments")&&(ve.parsed_arguments=void 0)}else ve.arguments+=Tt}T.push(Object.freeze({index:te,arguments_delta:Le}))}}Object.freeze(T)}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 Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Xp(r,e,t,n){let{id:s,choices:o,created:i,model:c,system_fingerprint:u,...d}=r,m={...d,id:s,choices:ml(o,Oi,"choice",y=>{let f=n.get(y);if(!f)throw new h("Chat completion stream contains an unsafe structured JSON snapshot");let g=new Proxy(y,{get(D,N,q){return N==="message"?f.message:Reflect.get(D,N,q)}}),{message:w,finish_reason:A,index:S,logprobs:O,...P}=g,L=new Proxy(w,{get(D,N,q){return N==="content"?f.content:N==="refusal"?f.refusal:N==="tool_calls"?f.toolCallCollection:Reflect.get(D,N,q)}}),{content:I=null,function_call:T,tool_calls:x,audio:M,...k}=L,E=A??(t.has(S)&&Hp(M)?"stop":null);if(!E)throw new h(`missing finish_reason for choice ${S}`);let v=M?{audio:M}:{},K=L.role;if(!K)throw new h(`missing role for choice ${S}`);if(T){let{arguments:D,name:N}=T;if(D==null)throw new h(`missing function_call.arguments for choice ${S}`);if(!N)throw new h(`missing function_call.name for choice ${S}`);return{...P,message:{...v,content:I,function_call:{arguments:D,name:N},role:K,refusal:L.refusal??null},finish_reason:E,index:S,logprobs:O}}return x?{...P,index:S,finish_reason:E,logprobs:O,message:{...k,...v,role:K,content:I,refusal:L.refusal??null,tool_calls:ml(x,Ht,"tool-call",(D,N)=>{let q=f.toolCalls.get(N);if(!q){let Le=Ei(D);if(Le&&fi(e,{type:Le.type,function:{name:Le.name}}))throw new h("Chat completion stream contains an unsafe structured JSON snapshot")}if(q&&q.tool!==D)throw new h("Chat completion stream contains a changed tool call identity");let be=q&&new Proxy(q.function,{get(Le,ce,He){return ce==="arguments"?q.arguments:ce==="name"?q.name:Reflect.get(Le,ce,He)}}),W=q&&be?new Proxy(D,{get(Le,ce,He){return ce==="type"?q.type:ce==="function"?be:Reflect.get(Le,ce,He)}}):D;if(W.type==null)throw new h(`missing choices[${S}].tool_calls[${N}].type`);if(W.type==="custom"){let{custom:Le,type:ce,id:He,...nt}=W,{input:Me="",name:ve,...Tt}=Le||{};if(ve==null)throw new h(`missing choices[${S}].tool_calls[${N}].custom.name`);return{...nt,id:He||`call_${Je()}`,type:ce,custom:{...Tt,name:ve,input:Me}}}let{function:rt,type:te,id:qo,...pn}=W,{arguments:hn,name:ht,...Zi}=rt||{};if(ht==null)throw new h(`missing choices[${S}].tool_calls[${N}].function.name`);if(hn==null)throw new h(`missing choices[${S}].tool_calls[${N}].function.arguments`);return{...pn,id:qo||`call_${Je()}`,type:te,function:{...Zi,name:ht,arguments:hn}}})}}:{...P,message:{...k,...v,content:I,role:K,refusal:L.refusal??null},finish_reason:E,index:S,logprobs:O}}),created:i,model:c,object:"chat.completion",...u?{system_fingerprint:u}:{}};return zu(m,e)}function Hp(r){return r?.id!=null&&r.data!=null&&r.transcript!=null&&r.expires_at!=null}var Oo=class r extends Lr{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e,t,n=this._createIterator(o=>{let i=u=>{e=u,o(u)},c=u=>{if(Pt(u)){t=u.tool_calls?.map(d=>d.id);return}if(fo(u)){if(!e)throw new h("cannot serialize a tool message before receiving any chunks");o(gl(e,u,t)),t=void 0}};return this.on("chunk",i),this.on("message",c),()=>{this.off("chunk",i),this.off("message",c)}},{onReturn:()=>this.abort()});return new Ee(()=>n,this.controller).toReadableStream()}static runTools(e,t,n){let s=new r(t),o={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,o)),s}};var xt=class extends p{constructor(){super(...arguments),this.messages=new Or(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Xu(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap(n=>lo(n,e))}runTools(e,t){return e.stream?Oo.runTools(this._client,e,t):Io.runTools(this._client,e,t)}stream(e,t){return Lr.createChatCompletion(this._client,e,t)}};xt.Messages=Or;var Jt=class extends p{constructor(){super(...arguments),this.completions=new xt(this._client)}};Jt.Completions=xt;var Rn=class extends p{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",R,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var vn=class extends p{list(e={},t){return this._client.getAPIList("/organization/audit_logs",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var On=class extends p{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(l`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",de,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",de,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var En=class extends p{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}};var kn=class extends p{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Cn=class extends p{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",Q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Tn=class extends p{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var $n=class extends p{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}};var jn=class extends p{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Ln=class extends p{create(e,t,n){return this._client.post(l`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(l`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/groups/${e}/roles`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(l`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Mn=class extends p{create(e,t,n){return this._client.post(l`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(l`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/groups/${e}/users`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(l`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends p{constructor(){super(...arguments),this.users=new Mn(this._client),this.roles=new Ln(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",Q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Vt.Users=Mn;Vt.Roles=Ln;var Bn=class extends p{retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/api_keys`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Dn=class extends p{list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/certificates`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(l`/organization/projects/${e}/certificates/activate`,de,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(l`/organization/projects/${e}/certificates/deactivate`,de,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Nn=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}};var Fn=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}};var Wn=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Un=class extends p{listRateLimits(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/rate_limits`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/rate_limits/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}};var qn=class extends p{create(e,t,n){return this._client.post(l`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/projects/${s}/roles/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/projects/${e}/roles`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Kn=class extends p{create(e,t,n){return this._client.post(l`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/spend_alerts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/spend_alerts`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var zn=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Xn=class extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/projects/${s}/groups/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,group_id:o}=t;return this._client.get(l`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(l`/projects/${s}/groups/${e}/roles`,Q,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,group_id:o}=t;return this._client.delete(l`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Mr=class extends p{constructor(){super(...arguments),this.roles=new Xn(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,...o}=t;return this._client.get(l`/organization/projects/${s}/groups/${e}`,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/groups`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Mr.Roles=Xn;var Hn=class extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/service_accounts/${e}/api_keys`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends p{constructor(){super(...arguments),this.apiKeys=new Hn(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/service_accounts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/service_accounts`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Br.APIKeys=Hn;var Jn=class extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/projects/${s}/users/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,user_id:o}=t;return this._client.get(l`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(l`/projects/${s}/users/${e}/roles`,Q,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,user_id:o}=t;return this._client.delete(l`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Dr=class extends p{constructor(){super(...arguments),this.roles=new Jn(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/users/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/users`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Dr.Roles=Jn;var me=class extends p{constructor(){super(...arguments),this.users=new Dr(this._client),this.serviceAccounts=new Br(this._client),this.apiKeys=new Bn(this._client),this.rateLimits=new Un(this._client),this.modelPermissions=new Wn(this._client),this.hostedToolPermissions=new Fn(this._client),this.groups=new Mr(this._client),this.roles=new qn(this._client),this.dataRetention=new Nn(this._client),this.spendLimit=new zn(this._client),this.spendAlerts=new Kn(this._client),this.certificates=new Dn(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(l`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};me.Users=Dr;me.ServiceAccounts=Br;me.APIKeys=Bn;me.RateLimits=Un;me.ModelPermissions=Wn;me.HostedToolPermissions=Fn;me.Groups=Mr;me.Roles=qn;me.DataRetention=Nn;me.SpendLimit=zn;me.SpendAlerts=Kn;me.Certificates=Dn;var Vn=class extends p{create(e,t,n){return this._client.post(l`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:s}=t;return this._client.get(l`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/users/${e}/roles`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:s}=t;return this._client.delete(l`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Nr=class extends p{constructor(){super(...arguments),this.roles=new Vn(this._client)}retrieve(e,t){return this._client.get(l`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Nr.Roles=Vn;var _e=class extends p{constructor(){super(...arguments),this.auditLogs=new vn(this._client),this.adminAPIKeys=new Rn(this._client),this.usage=new jn(this._client),this.invites=new kn(this._client),this.users=new Nr(this._client),this.groups=new Vt(this._client),this.roles=new Cn(this._client),this.dataRetention=new En(this._client),this.spendLimit=new $n(this._client),this.spendAlerts=new Tn(this._client),this.certificates=new On(this._client),this.projects=new me(this._client)}};_e.AuditLogs=vn;_e.AdminAPIKeys=Rn;_e.Usage=jn;_e.Invites=kn;_e.Users=Nr;_e.Groups=Vt;_e.Roles=Cn;_e.DataRetention=En;_e.SpendLimit=$n;_e.SpendAlerts=Tn;_e.Certificates=On;_e.Projects=me;var Gt=class extends p{constructor(){super(...arguments),this.organization=new _e(this._client)}};Gt.Organization=_e;var Gn=class extends p{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Yn=class extends p{create(e,t){return this._client.post("/audio/transcriptions",se({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Qn=class extends p{create(e,t){return this._client.post("/audio/translations",se({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var ft=class extends p{constructor(){super(...arguments),this.transcriptions=new Yn(this._client),this.translations=new Qn(this._client),this.speech=new Gn(this._client)}};ft.Transcriptions=Yn;ft.Translations=Qn;ft.Speech=Gn;var Fr=class extends p{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",R,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var Zn=class extends p{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/assistants/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var es=class extends p{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var ts=class extends p{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Yt=class extends p{constructor(){super(...arguments),this.sessions=new es(this._client),this.transcriptionSessions=new ts(this._client)}};Yt.Sessions=es;Yt.TranscriptionSessions=ts;var rs=class extends p{create(e,t,n){return this._client.post(l`/agents/environments/${e}/files`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/environments/${e}/files`,yn,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var ns=class extends p{create(e={},t){return this._client.post("/agents/environments/templates",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/agents/environments/templates/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(l`/agents/environments/templates/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/environments/templates",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/agents/environments/templates/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var Qt=class extends p{constructor(){super(...arguments),this.files=new rs(this._client),this.templates=new ns(this._client)}retrieve(e,t){return this._client.get(l`/agents/environments/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};Qt.Files=rs;Qt.Templates=ns;var ss,ki,Wr,Ci,Ti=class{constructor(){ss.set(this,void 0),ki.set(this,!1),Wr.set(this,new Set),Ci.set(this,new Set)}accept(e){if(a(this,Wr,"f").has(e.event_id))return!1;if(a(this,Wr,"f").size===1024){let t=a(this,Wr,"f").values().next();t.done||a(this,Wr,"f").delete(t.value)}return a(this,Wr,"f").add(e.event_id),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&a(this,ss,"f")===void 0&&b(this,ss,e.turn_id,"f"),(e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled")&&a(this,ss,"f")!==void 0&&e.turn_id===a(this,ss,"f")&&b(this,ki,!0,"f"),!0}terminal(e){return e.type==="agent.session.failed"||e.type==="agent.session.idle"&&a(this,ki,"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(!a(this,Ci,"f").has(n))return a(this,Ci,"f").add(n),t}};ss=new WeakMap,ki=new WeakMap,Wr=new WeakMap,Ci=new WeakMap;var ie,$i,os,ji,Li,Ur,qr,Mi,Bi,is,Eo,Pl,Al,Ge,fc,pc,Il;function Mh(r){if(!ye(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 $(e,"type")&&$(e,t)&&typeof e[t]=="string"}function Bh(r){if(r===null)return null;if(typeof r=="string"||Array.isArray(r)&&r.every(Mh))return r;throw new h("Tool output must be text, content, a JSON object, or null")}function Dh(r,e){let t=ye(e)?JSON.stringify(e):e,n=JSON.stringify(t);if(n===void 0)throw new h("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:Bh(typeof t=="string"?t:JSON.parse(n))}}async function Nh(r){try{await r?.body?.cancel()}catch{}}var Di=class{constructor(e,t,n,s){ie.add(this),this.controller=new AbortController,$i.set(this,!1),os.set(this,void 0),ji.set(this,void 0),Li.set(this,!1),Ur.set(this,void 0),qr.set(this,void 0),Mi.set(this,void 0),Bi.set(this,void 0),is.set(this,void 0),Eo.set(this,void 0);let o=typeof n.input=="string"?[{role:"user",content:[{type:"input_text",text:n.input}]}]:n.input;if(n.input.length===0)throw new h("input must not be empty");b(this,Ur,e,"f"),b(this,qr,t,"f"),b(this,Mi,{type:"agent.session.input.message",input:o},"f"),b(this,Bi,new Map(Object.entries(n.toolHandlers??{})),"f");let i=_([s?.headers]);b(this,is,i.nulls.has("idempotency-key")?void 0:i.values.get("idempotency-key")??n.idempotencyKey??s?.idempotencyKey??Je(),"f"),i.values.delete("idempotency-key"),i.nulls.delete("idempotency-key");let{idempotencyKey:c,...u}=s??{};b(this,Eo,{...u,headers:i},"f")}abort(e){this.controller.abort(e),a(this,os,"f")?.controller.abort(this.controller.signal.reason),a(this,Li,"f")||Nh(a(this,ji,"f"))}[($i=new WeakMap,os=new WeakMap,ji=new WeakMap,Li=new WeakMap,Ur=new WeakMap,qr=new WeakMap,Mi=new WeakMap,Bi=new WeakMap,is=new WeakMap,Eo=new WeakMap,ie=new WeakSet,Symbol.asyncIterator)](){if(a(this,$i,"f"))throw new h("An AgentSessionStream can only be consumed once");return b(this,$i,!0,"f"),a(this,ie,"m",Pl).call(this)}};Pl=async function*(){let e=a(this,Eo,"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={...a(this,Eo,"f"),signal:this.controller.signal},s=new Ti;try{if(e?.aborted&&this.abort(e.reason),a(this,ie,"m",Ge).call(this),(await a(this,Ur,"f").retrieve(a(this,qr,"f"),n)).status!=="idle")throw new h("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let i=await a(this,Ur,"f").events.stream(a(this,qr,"f"),n).withResponse();b(this,os,i.data,"f"),b(this,ji,i.response,"f"),a(this,ie,"m",Ge).call(this),await a(this,Ur,"f").events.create(a(this,qr,"f"),{events:[a(this,Mi,"f")],...a(this,is,"f")===void 0?{}:{"Idempotency-Key":a(this,is,"f")}},{...n,headers:_([n.headers,{"Idempotency-Key":a(this,is,"f")??null}])}),a(this,ie,"m",Ge).call(this),b(this,Li,!0,"f");for await(let c of a(this,os,"f")){if(a(this,ie,"m",Ge).call(this),!s.accept(c))continue;let u=s.terminal(c),d=s.call(c),m=d&&a(this,Bi,"f").get(d.name),y=d&&m?structuredClone(d):void 0;if(u&&a(this,os,"f").controller.abort(),yield c,u)return;if(a(this,ie,"m",Ge).call(this),!y||!m)continue;let f=await a(this,ie,"m",Al).call(this,y,m);a(this,ie,"m",Ge).call(this),await a(this,ie,"m",Il).call(this,f,n)}throw a(this,ie,"m",Ge).call(this),new h("Session event stream ended before the turn reached idle or failed")}finally{e?.removeEventListener("abort",t),this.controller.signal.removeEventListener("abort",t),this.abort()}},Al=async function(e,t){try{let n=typeof e.arguments=="string"?JSON.parse(e.arguments):e.arguments;if(!ye(n))throw new h("Function arguments must be a JSON object");return Dh(e,await a(this,ie,"m",pc).call(this,()=>t(n)))}catch{return a(this,ie,"m",Ge).call(this),{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!1,error:"Tool handler failed."}}},Ge=function(){if(this.controller.signal.aborted)throw a(this,ie,"m",fc).call(this)},fc=function(){let e=new Y;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e},pc=async function(e){let t,n=new Promise((s,o)=>{t=()=>o(a(this,ie,"m",fc).call(this)),this.controller.signal.addEventListener("abort",t,{once:!0})});try{a(this,ie,"m",Ge).call(this);let s=async()=>await e();return await Promise.race([s(),n])}finally{t&&this.controller.signal.removeEventListener("abort",t)}},Il=async function r(e,t,n=Je(),s=0){a(this,ie,"m",Ge).call(this);try{await a(this,Ur,"f").events.create(a(this,qr,"f"),{events:[e],"Idempotency-Key":n},t)}catch(o){let i=[100,300,600][s];if(i===void 0||!(o instanceof ot)||o.code!=="invalid_request_error"||!o.error||!("message"in o.error)||o.error.message!==`Unknown pending tool call: ${e.call_id}`)throw o;let c;try{await a(this,ie,"m",pc).call(this,()=>new Promise(u=>{c=setTimeout(u,i)}))}finally{c!==void 0&&clearTimeout(c)}await a(this,ie,"m",r).call(this,e,t,n,s+1)}};var as=class extends p{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/artifacts`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{session_id:s}=t;return this._client.delete(l`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}content(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/artifacts/${e}/content`,{...n,headers:_([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var cs=class extends p{create(e,t,n){let{"Idempotency-Key":s,...o}=t;return this._client.post(l`/agents/sessions/${e}/events`,{body:o,...n,headers:_([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...s!=null?{"Idempotency-Key":s}:void 0},n?.headers]),__security:{bearerAuth:!0}})}stream(e,t){return this._client.get(l`/agents/sessions/${e}/events`,{...t,headers:_([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},t?.headers]),stream:!0,__security:{bearerAuth:!0}})}};var us=class extends p{list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/items`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var ls=class extends p{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/turns/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/turns`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var ds=class extends p{list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${e}/items`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var fs=class extends p{list(e,t,n){let{session_id:s,subagent_id:o,...i}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${o}/turns/${e}/items`,R,{query:i,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Kr=class extends p{constructor(){super(...arguments),this.items=new fs(this._client)}retrieve(e,t,n){let{session_id:s,subagent_id:o}=t;return this._client.get(l`/agents/sessions/${s}/subagents/${o}/turns/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${e}/turns`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};Kr.Items=fs;var Zt=class extends p{constructor(){super(...arguments),this.items=new ds(this._client),this.turns=new Kr(this._client)}retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/subagents/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/subagents`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};Zt.Items=ds;Zt.Turns=Kr;var Ye=class extends p{constructor(){super(...arguments),this.subagents=new Zt(this._client),this.artifacts=new as(this._client),this.items=new us(this._client),this.events=new cs(this._client),this.turns=new ls(this._client)}stream(e,t,n){return new Di(this,e,t,n)}create(e,t){return this._client.post("/agents/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/agents/sessions/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(l`/agents/sessions/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/sessions",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/agents/sessions/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};Ye.Subagents=Zt;Ye.Artifacts=as;Ye.Items=us;Ye.Events=cs;Ye.Turns=ls;var ps=class extends p{create(e,t,n){return this._client.post(l`/vaults/${e}/credentials`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vault_id:s}=t;return this._client.get(l`/vaults/${s}/credentials/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vault_id:s,...o}=t;return this._client.post(l`/vaults/${s}/credentials/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/vaults/${e}/credentials`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vault_id:s}=t;return this._client.delete(l`/vaults/${s}/credentials/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var zr=class extends p{constructor(){super(...arguments),this.credentials=new ps(this._client)}create(e={},t){return this._client.post("/vaults",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/vaults/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vaults",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/vaults/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};zr.Credentials=ps;var St=class extends p{constructor(){super(...arguments),this.environments=new Qt(this._client),this.vaults=new zr(this._client),this.sessions=new Ye(this._client)}create(e,t){return this._client.post("/agents",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/agents/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(l`/agents/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/agents/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};St.Environments=Qt;St.Vaults=zr;St.Sessions=Ye;var hs=class extends p{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var ms=class extends p{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",F,{query:e,...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,F,{query:t,...n,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var er=class extends p{constructor(){super(...arguments),this.sessions=new hs(this._client),this.threads=new ms(this._client)}};er.Sessions=hs;er.Threads=ms;var _s=class extends p{list(e,t={},n){let{betas:s,...o}=t??{};return this._client.getAPIList(l`/responses/${e}/input_items?beta=true`,R,{query:o,...n,headers:_([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}};var ys=class extends p{count(e={},t){let{betas:n,...s}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:s,...t,headers:_([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var tr=class extends p{constructor(){super(...arguments),this.inputItems=new _s(this._client),this.inputTokens=new ys(this._client)}create(e,t){let{betas:n,...s}=e;return this._client.post("/responses?beta=true",{body:s,...t,headers:_([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:s,...o}=t??{};return this._client.get(l`/responses/${e}?beta=true`,{query:o,...n,headers:_([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.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`,{...n,headers:_([{Accept:"*/*",...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:s}=t??{};return this._client.post(l`/responses/${e}/cancel?beta=true`,{...n,headers:_([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...s}=e;return this._client.post("/responses/compact?beta=true",{body:s,...t,headers:_([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};tr.InputItems=_s;tr.InputTokens=ys;var gs=class extends p{create(e,t,n){return this._client.post(l`/threads/${e}/messages`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/threads/${e}/messages`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var bs=class extends p{retrieve(e,t,n){let{thread_id:s,run_id:o,...i}=t;return this._client.get(l`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:s,...o}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ni=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 h("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},xl=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 le=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 Rl=1024,im=65536;function am(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 ko=new WeakMap,rr=new WeakSet;function vl(r){return{arrays:new Map,cacheArrays:r,records:new WeakMap}}function Ol(r){for(let[e,t]of r.arrays)t.cacheable&&!rr.has(e)?ko.set(e,{length:t.length,ownEntryCount:t.ownEntryCount}):ko.delete(e)}function Sl(r){return typeof r=="string"||typeof r=="number"}function El(r,e){return e.every(Sl)&&r.every(Sl)}function cm(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 um(r,e,t){return e?t?.length===r.length?t.ownEntryCount:cm(r):0}function lm(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+Rl||n>=im){let s=typeof n=="number"?n:"unknown";throw new h(`Assistant stream delta contains an invalid ${e} index: ${s}`)}return n}function kl(r,e,t,n,s){let o=n.arrays.get(r);if(!o){let i=n.cacheArrays&&!rr.has(r),c=i?ko.get(r):void 0;o={baselineLength:r.length,cacheable:i,enforceSparseHoleBudget:i,entries:new Map,length:r.length,ownEntryCount:um(r,i,c)},n.arrays.set(r,o)}for(let i of e){if(!ye(i))throw new Error("Expected array delta entry to be an object but got an invalid value");let c=lm(i,t,o.baselineLength),u;o.entries.has(c)?u=o.entries.get(c):$(r,c)?(u=r[c],u==null&&o.entries.set(c,i)):(o.entries.set(c,i),o.ownEntryCount+=1);let d=Math.max(o.length,c+1);if(o.enforceSparseHoleBudget&&d-o.ownEntryCount>Rl)throw new h(`Assistant stream delta contains an invalid ${t} index: ${c}`);ye(u)&&s(u,i,n),o.length=d}}function Fi(r,e,t){let n=t.records.get(r);for(let[s,o]of Object.entries(e)){if(s==="index"||s==="type")continue;let i;if(n?.has(s)?i=n.get(s):$(r,s)&&(i=r[s]),i==null){n||(n=new Map,t.records.set(r,n)),n.set(s,o);continue}ye(i)&&ye(o)?Fi(i,o,t):Array.isArray(i)&&Array.isArray(o)&&!El(i,o)&&kl(i,o,"array",t,Fi)}}function Wi(r){return(ye(r)||Array.isArray(r))&&rr.has(r)}function Qe(r){if(!(!ye(r)&&!Array.isArray(r)||rr.has(r))){rr.add(r),Array.isArray(r)&&ko.delete(r);for(let e of Reflect.ownKeys(r)){let t=Object.getOwnPropertyDescriptor(r,e);t&&"value"in t&&Qe(t.value)}}}function mc(r,e,t){rr.has(r)&&Qe(t),Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}function dm(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 fm(r,e,t){if(El(r,e)){r.push(...e),ko.delete(r);return}for(let n of e){if(!ye(n))throw new Error("Expected array delta entry to be an object but got an invalid value");let s=dm(n);if($(r,s)){let o=r[s];o==null?(rr.has(r)&&Qe(n),r[s]=n):r[s]=t(o,n)}else mc(r,s,n)}}function hc(r,e){let t=rr.has(r);for(let[n,s]of Object.entries(e)){if(n==="__proto__"||n==="constructor"||n==="prototype")throw new h(`Assistant stream delta contains an unsafe property: ${n}`);if(!$(r,n)){t&&Qe(s),r[n]=s;continue}let o=r[n];if(o==null){t&&Qe(s),r[n]=s;continue}if(n==="index"||n==="type"){r[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(ye(o)&&ye(s))o=hc(o,s);else if(Array.isArray(o)&&Array.isArray(s)){fm(o,s,hc);continue}else throw new TypeError(`Unhandled record type: ${am(n)}`);r[n]=o}return r}function Co(r){if(!(!ye(r)&&!Array.isArray(r)))for(let[e,t]of Object.entries(r)){if(e==="__proto__"||e==="constructor"||e==="prototype")throw new h(`Assistant stream delta contains an unsafe property: ${e}`);Co(t)}}function Ui(r,e,t=!1){Co(e);let n=r,s=e,o=vl(t&&!Wi(r));return Fi(n,s,o),hc(n,s),Ol(o),r}function Cl(r,e,t,n=!0){Co(e);let s=vl(n&&!Wi(r));return kl(r,e,t,s,Fi),()=>Ol(s)}var j,Re,nr,Xe,Is,As,Ie,Rt,Hr,sr,vt,Xr,Ce,$o,jo,or,Lo,Mo,Tl,ws,$l,To,jl,Ll,ae,Ml,Bl,Dl,Nl,Fl;function pm(r){let e=Object.getOwnPropertyDescriptor(r,"event"),t=Object.getOwnPropertyDescriptor(r,"data"),n=Reflect.get(r,"event",r),s=Reflect.get(r,"data",r),o=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 u=Object.getOwnPropertyDescriptor(s,"id");if(u&&"value"in u&&s.id!==u.value){let d=u.value;o=new Proxy(s,{get(m,y){return y==="id"?d:Reflect.get(m,y,m)}})}}let i=Object.freeze({event:n,data:o}),c=e!==void 0&&"value"in e&&e.value===n&&t!==void 0&&"value"in t&&t.value===s&&o===s;return{event:i,exposedEvent:c?r:{event:n,data:o}}}var ir=class r extends zt{constructor(){super(...arguments),j.add(this),Re.set(this,Object.create(null)),nr.set(this,new Map),Xe.set(this,void 0),Is.set(this,Object.create(null)),As.set(this,new Map),Ie.set(this,void 0),Rt.set(this,void 0),Hr.set(this,void 0),sr.set(this,void 0),vt.set(this,void 0),Xr.set(this,void 0),Ce.set(this,void 0),$o.set(this,void 0),jo.set(this,void 0),or.set(this,void 0)}[(Re=new WeakMap,nr=new WeakMap,Xe=new WeakMap,Is=new WeakMap,As=new WeakMap,Ie=new WeakMap,Rt=new WeakMap,Hr=new WeakMap,sr=new WeakMap,vt=new WeakMap,Xr=new WeakMap,Ce=new WeakMap,$o=new WeakMap,jo=new WeakMap,or=new WeakMap,j=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=Ee.fromReadableStream(e,this.controller);for await(let s of n)a(this,j,"m",Lo).call(this,s);if(n.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).call(this))}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let o=new r;return o._run(()=>o._runToolAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}async _createToolAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},i=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let c of i)a(this,j,"m",Lo).call(this,c);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).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 o=new r;return o._run(()=>o._runAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}currentEvent(){return Qe(a(this,$o,"f")),a(this,$o,"f")}currentRun(){return Qe(a(this,jo,"f")),a(this,jo,"f")}currentMessageSnapshot(){return Qe(a(this,Ie,"f")),a(this,Ie,"f")}currentRunStepSnapshot(){return Qe(a(this,or,"f")),a(this,or,"f")}async finalRunSteps(){return await this.done(),Object.values(a(this,Re,"f"))}async finalMessages(){return await this.done(),Object.values(a(this,Is,"f"))}async finalRun(){if(await this.done(),!a(this,Hr,"f"))throw new Error("Final run was not received.");return a(this,Hr,"f")}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0},o=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let i of o)a(this,j,"m",Lo).call(this,i);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).call(this))}async _createAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},i=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let c of i)a(this,j,"m",Lo).call(this,c);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).call(this))}static accumulateDelta(e,t){return Ui(e,t)}_addRun(e){return a(this,j,"m",ae).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)}};Lo=function(e){if(this.ended)return;let{event:t,exposedEvent:n}=pm(e),s,o,i,c;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=a(this,j,"m",$l).call(this,t),o=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":{i=a(this,j,"m",Tl).call(this,t),c=t.data;break}}switch(b(this,$o,n,"f"),a(this,j,"m",Ml).call(this,n),s!==void 0&&o!==void 0&&a(this,j,"m",To).call(this,o,s),i!==void 0&&c!==void 0&&a(this,j,"m",ws).call(this,c,i),i===void 0&&a(this,Xe,"f")!==void 0&&a(this,or,"f")&&a(this,j,"m",ws).call(this,a(this,or,"f"),a(this,Xe,"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":{a(this,j,"m",Fl).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(i===void 0)throw new h("Received assistant run-step event without a canonical run-step ID");let u=a(this,Re,"f")[i];u&&a(this,j,"m",ws).call(this,u,i),a(this,j,"m",Ll).call(this,t,i),a(this,j,"m",ws).call(this,t.data,i);let d=a(this,Re,"f")[i];d&&a(this,j,"m",ws).call(this,d,i);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&&a(this,Ie,"f")&&a(this,j,"m",To).call(this,a(this,Ie,"f"),s),a(this,j,"m",jl).call(this,t),s!==void 0){a(this,j,"m",To).call(this,t.data,s);let u=a(this,Is,"f")[s];u&&a(this,j,"m",To).call(this,u,s)}break}case"error":throw new z(void 0,t.data,void 0,void 0);default:}},Mo=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");if(!a(this,Hr,"f"))throw new Error("Final run has not been received");return a(this,Hr,"f")},Tl=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 h("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&&$(s,"id"))throw new h("Run-step deltas must not contain an id field")}if(e.event==="thread.run.step.created"){if(a(this,Xe,"f")!==void 0)throw new h(`Received run-step creation for "${n}" before the active run step "${a(this,Xe,"f")}" reached a terminal state`);if($(a(this,Re,"f"),n)||a(this,nr,"f").has(n))throw new h(`Received run-step creation for run step "${n}", which has already been created`);return b(this,Xe,n,"f"),a(this,nr,"f").set(n,n),n}if(a(this,Xe,"f")!==void 0){if(n!==a(this,Xe,"f"))throw new h(`Received ${e.event} for run step "${n}", which does not match the active run step "${a(this,Xe,"f")}"`);return n}if(e.event==="thread.run.step.delta")throw $(a(this,Re,"f"),n)?new h(`Received run-step delta for "${n}" with no active run step`):new h("Received a RunStepDelta before creation of a snapshot");if($(a(this,Re,"f"),n)||a(this,nr,"f").has(n))throw new h(`Received run-step event for run step "${n}", which has already been created`);return a(this,nr,"f").set(n,n),e.event==="thread.run.step.in_progress"&&b(this,Xe,n,"f"),n},ws=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 h("Received assistant run-step event with an invalid run-step ID");let o=a(this,nr,"f").get(s);if(o!==void 0&&o!==t)throw new h(`Received run-step creation for run step "${s}", which has already been created`);a(this,nr,"f").set(s,t)},$l=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 h("Received assistant message event with an invalid message ID");if(e.event==="thread.message.created"){if(a(this,Ie,"f"))throw new h(`Received message creation for "${n}" before the active message "${a(this,Rt,"f")}" reached a terminal state`);if($(a(this,Is,"f"),n)||a(this,As,"f").has(n))throw new h(`Received message creation for message "${n}", which has already been created`);return b(this,Rt,n,"f"),a(this,As,"f").set(n,n),n}if(!a(this,Ie,"f"))throw e.event==="thread.message.delta"?new h("Received a delta with no existing snapshot (there should be one from message creation)"):new h("Received thread message event with no existing snapshot");if(n!==a(this,Rt,"f"))throw new h(`Received ${e.event} for message "${n}", which does not match the active message "${a(this,Rt,"f")}"`);return n},To=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 h("Received assistant message event with an invalid message ID");let o=a(this,As,"f").get(s);if(o!==void 0&&o!==t)throw new h(`Received message creation for message "${s}", which has already been created`);a(this,As,"f").set(s,t)},jl=function(e){let[t,n]=a(this,j,"m",Dl).call(this,e,a(this,Ie,"f"));if(b(this,Ie,t,"f"),!a(this,Rt,"f"))throw new h("Received thread message event with no active message ID");a(this,Is,"f")[a(this,Rt,"f")]=t;for(let s of n){let o=t.content[s.index];o?.type==="text"&&a(this,j,"m",ae).call(this,"textCreated",o.text)}switch(e.event){case"thread.message.created":{b(this,sr,void 0,"f"),b(this,vt,void 0,"f"),a(this,j,"m",ae).call(this,"messageCreated",e.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(a(this,j,"m",ae).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 o=s.text,i=t.content[s.index];if(i&&i.type==="text")a(this,j,"m",ae).call(this,"textDelta",o,i.text);else throw new Error("The snapshot associated with this text delta is not text or missing")}if(s.index!==a(this,sr,"f")){if(a(this,vt,"f"))switch(a(this,vt,"f").type){case"text":{a(this,j,"m",ae).call(this,"textDone",a(this,vt,"f").text,a(this,Ie,"f"));break}case"image_file":{a(this,j,"m",ae).call(this,"imageFileDone",a(this,vt,"f").image_file,a(this,Ie,"f"));break}}b(this,sr,s.index,"f")}b(this,vt,t.content[s.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(a(this,sr,"f")!==void 0){let s=e.data.content[a(this,sr,"f")];if(s)switch(s.type){case"image_file":{a(this,j,"m",ae).call(this,"imageFileDone",s.image_file,a(this,Ie,"f"));break}case"text":{a(this,j,"m",ae).call(this,"textDone",s.text,a(this,Ie,"f"));break}}}a(this,Ie,"f")&&a(this,j,"m",ae).call(this,"messageDone",e.data),b(this,sr,void 0,"f"),b(this,vt,void 0,"f"),b(this,Ie,void 0,"f"),b(this,Rt,void 0,"f")}}},Ll=function(e,t){let n=a(this,j,"m",Bl).call(this,e,t);switch(b(this,or,n,"f"),e.event){case"thread.run.step.created":{b(this,Xr,void 0,"f"),b(this,Ce,void 0,"f"),a(this,j,"m",ae).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 o of s.step_details.tool_calls)o.index===a(this,Xr,"f")?a(this,j,"m",ae).call(this,"toolCallDelta",o,n.step_details.tool_calls[o.index]):(a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallDone",a(this,Ce,"f")),b(this,Xr,o.index,"f"),b(this,Ce,n.step_details.tool_calls[o.index],"f"),a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallCreated",a(this,Ce,"f")));a(this,j,"m",ae).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":{b(this,or,void 0,"f"),b(this,Xe,void 0,"f"),e.data.step_details.type==="tool_calls"&&a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallDone",a(this,Ce,"f")),a(this,j,"m",ae).call(this,"runStepDone",e.data,n),b(this,Xr,void 0,"f"),b(this,Ce,void 0,"f");break}case"thread.run.step.in_progress":break}},ae=function(e,...t){if(this._hasListeners(e))for(let n of t)Qe(n);this._emit(e,...t)},Ml=function(e){a(this,j,"m",ae).call(this,"event",e)},Bl=function(e,t){switch(e.event){case"thread.run.step.created":return a(this,Re,"f")[t]=e.data,e.data;case"thread.run.step.delta":{let n=a(this,Re,"f")[t];if(!n)throw new Error("Received a RunStepDelta before creation of a snapshot");let s=e.data.delta;if(s){if($(s,"id"))throw new h("Run-step deltas must not contain an id field");let o=Ui(n,s,!0);a(this,Re,"f")[t]=o}return a(this,Re,"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":{a(this,Re,"f")[t]=e.data;break}}if(a(this,Re,"f")[t])return a(this,Re,"f")[t];throw new Error("No snapshot available")},Dl=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){Co(s.delta);let o=!Wi(t),i=Cl(t.content,s.delta.content,"content",o);for(let c of s.delta.content)if($(t.content,c.index)){let u=t.content[c.index];t.content[c.index]=a(this,j,"m",Nl).call(this,c,u,o)}else mc(t.content,c.index,c),n.push(c);i()}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")},Nl=function(e,t,n){return Ui(t,e,n)},Fl=function(e){switch(b(this,jo,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":{b(this,Hr,e.data,"f"),a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallDone",a(this,Ce,"f")),b(this,Xr,void 0,"f"),b(this,Ce,void 0,"f");break}case"thread.run.cancelling":break}};function hm(r,e){return new Promise((t,n)=>{let s,o,i=!1,c=m=>{try{e.removeEventListener("abort",m)}catch{}},u=()=>{if(s!==void 0&&(clearTimeout(s),s=void 0),o){let m=o;o=void 0,c(m)}},d=()=>{if(!i){i=!0,u();try{let m=new Y;Object.defineProperty(m,"cause",{value:e.reason,writable:!0,configurable:!0}),n(m)}catch(m){n(m)}}};if(e.aborted){d();return}s=setTimeout(()=>{i||(i=!0,u(),t())},r),o=d;try{e.addEventListener("abort",d,{once:!0}),i?c(d):e.aborted&&d()}catch(m){i?c(d):(i=!0,u(),n(m))}})}async function Bo(r,e,t,n){let s=_([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await r(s).withResponse(),{status:c}=o;if(e.includes(c)){let u=5e3,d=n?.pollIntervalMs;if(d||d===0)u=d;else{let y=i.headers.get("openai-poll-after-ms");if(y){let f=Number.parseInt(y);Number.isNaN(f)||(u=f)}}let m=n&&Object.prototype.propertyIsEnumerable.call(n,"signal")?n.signal:void 0;await(m?hm(u,m):mn(u))}else if(t.includes(c))return o}}function Wl(r,e,t,n){return Bo(s=>r.retrieve(e,t,{...n,headers:{...n?.headers,...s}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],n)}var Jr=class extends p{constructor(){super(...arguments),this.steps=new bs(this._client)}create(e,t,n){let{include:s,...o}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/threads/${e}/runs`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!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)}async poll(e,t,n){return await Wl(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,...o}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!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)}};Jr.Steps=bs;var ar=class extends p{constructor(){super(...arguments),this.runs=new Jr(this._client),this.messages=new gs(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/threads/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return ir.createThreadAssistantStream(e,this._client.beta.threads,t)}};ar.Runs=Jr;ar.Messages=gs;var je=class extends p{constructor(){super(...arguments),this.realtime=new Yt(this._client),this.agents=new St(this._client),this.responses=new tr(this._client),this.chatkit=new er(this._client),this.assistants=new Zn(this._client),this.threads=new ar(this._client)}};je.Realtime=Yt;je.Agents=St;je.Responses=tr;je.ChatKit=er;je.Assistants=Zn;je.Threads=ar;var Vr=class extends p{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Ps=class extends p{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...n,headers:_([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Gr=class extends p{constructor(){super(...arguments),this.content=new Ps(this._client)}create(e,t,n){return this._client.post(l`/containers/${e}/files`,qt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/containers/${e}/files`,R,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Gr.Content=Ps;var cr=class extends p{constructor(){super(...arguments),this.files=new Gr(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};cr.Files=Gr;var Yr=class extends p{create(e,t){return this._client.post("/content_provenance_checks",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}};var xs=class extends p{create(e,t,n){let{include:s,...o}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:o,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:s,...o}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:o,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/conversations/${e}/items`,F,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var ur=class extends p{constructor(){super(...arguments),this.items=new xs(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};ur.Items=xs;function Ul(r,e,t){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&ee(r).debug("embeddings/user defined encoding_format:",e.encoding_format);let i={body:{...e,encoding_format:s},...t,__security:{bearerAuth:!0}},c=r.post("/embeddings",i);return n?c:(ee(r).debug("embeddings/decoding base64 embeddings from base64"),c._thenUnwrap(u=>{let d=u?.data;if(d!==void 0){if(!Array.isArray(d))throw new TypeError("Expected embeddings response data to be an array");let{length:m}=d;for(let y=0;y<m;y+=1)if(y in d){let f=d[y],{embedding:g}=f;if(Array.isArray(g))continue;f.embedding=xl(g)}}return u}))}var Qr=class extends p{create(e,t){return Ul(this._client,e,t)}};var Ss=class extends p{retrieve(e,t,n){let{eval_id:s,run_id:o}=t;return this._client.get(l`/evals/${s}/runs/${o}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:s,...o}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,R,{query:o,...n,__security:{bearerAuth:!0}})}};var Zr=class extends p{constructor(){super(...arguments),this.outputItems=new Ss(this._client)}create(e,t,n){return this._client.post(l`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/evals/${e}/runs`,R,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Zr.OutputItems=Ss;var lr=class extends p{constructor(){super(...arguments),this.runs=new Zr(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};lr.Runs=Zr;async function ql(r,e,t,n){let s=new Set(["processed","error","deleted"]),o=performance.now(),i=await r.retrieve(e);for(;!i.status||!s.has(i.status);)if(await mn(t),i=await r.retrieve(e),performance.now()-o>n)throw new re({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}var en=class extends p{create(e,t){return this._client.post("/files",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){return await ql(this,e,t,n)}};var Rs=class extends p{};var vs=class extends p{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}};var tn=class extends p{constructor(){super(...arguments),this.graders=new vs(this._client)}};tn.Graders=vs;var Os=class extends p{create(e,t,n){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,de,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,F,{query:t,...n,__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}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var rn=class extends p{constructor(){super(...arguments),this.permissions=new Os(this._client)}};rn.Permissions=Os;var Es=class extends p{list(e,t={},n){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,R,{query:t,...n,__security:{bearerAuth:!0}})}};var nn=class extends p{constructor(){super(...arguments),this.checkpoints=new Es(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,R,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};nn.Checkpoints=Es;var Ze=class extends p{constructor(){super(...arguments),this.methods=new Rs(this._client),this.jobs=new nn(this._client),this.checkpoints=new rn(this._client),this.alpha=new tn(this._client)}};Ze.Methods=Rs;Ze.Jobs=nn;Ze.Checkpoints=rn;Ze.Alpha=tn;var ks=class extends p{};var dr=class extends p{constructor(){super(...arguments),this.graderModels=new ks(this._client)}};dr.GraderModels=ks;var sn=class extends p{createVariation(e,t){return this._client.post("/images/variations",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",se({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Cs=class extends p{accept(e,t,n){return this._client.post(l`/live/sessions/${e}/accept`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,t){return this._client.get(l`/live/sessions/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,t,n){return this._client.post(l`/live/sessions/${e}/fork`,{body:t,...n,__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(l`/live/sessions/${e}/hangup`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(l`/live/sessions/${e}/refer`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t,n){return this._client.post(l`/live/sessions/${e}/reject`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var Ts=class extends p{};var $s=class extends p{};var pt=class extends p{constructor(){super(...arguments),this.sideband=new $s(this._client),this.forks=new Ts(this._client),this.sessions=new Cs(this._client)}create(e,t){return this._client.post("/live/sessions",{body:e,...t,__security:{bearerAuth:!0}})}};pt.Sideband=$s;pt.Forks=Ts;pt.Sessions=Cs;var on=class extends p{retrieve(e,t){return this._client.get(l`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",de,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var an=class extends p{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};async function Kl(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(([,u])=>u!==void 0));if(n!==null&&Object.keys(s).length===1&&Object.prototype.hasOwnProperty.call(s,n)){let u=s[n];if(typeof u!="string")throw new TypeError("Raw multipart alternative must be a string");return{...r,body:u,headers:_([r.headers,{"content-type":t[n].content_type}])}}let o=[];for(let[u,d]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(s,u))continue;let m=s[u],y=d.json?JSON.stringify(m):m;if(typeof y!="string")throw new TypeError(`Multipart field ${u} must encode as a string`);o.push([u,At([y],"",{type:d.content_type})]),delete s[u]}let c=(await se({...r,body:s},e)).body;if(!(c instanceof FormData))throw await c.cancel(),new TypeError("Unexpected streaming upload in typed multipart request body");for(let[u,d]of o)c.append(u,d,"");return{...r,body:c,headers:_([r.headers,{"content-type":null}])}}var js=class extends p{create(e,t){return this._client.post("/realtime/calls",Kl({body:e,...t,headers:_([{Accept:"application/sdp"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp"))}accept(e,t,n){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var Ls=class extends p{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ot=class extends p{constructor(){super(...arguments),this.clientSecrets=new Ls(this._client),this.calls=new js(this._client)}};Ot.ClientSecrets=Ls;Ot.Calls=js;function zl(r,e){if(!e||!Mm(e)){let t={...r,output_parsed:null,output:r.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)};return Xl(r,t)&&cn(t),t}return yc(r,e)}function yc(r,e){let t=!r.status||r.status==="completed",n=r.output.map(o=>{if(o.type==="function_call")return t?Dm(e,o):{...o,parsed_arguments:null};if(o.type==="message"){let i=o.content.map(c=>c.type==="output_text"?{...c,parsed:t?Lm(e,c.text):null}:c);return{...o,content:i}}return o}),s={...r,output:n};return Xl(r,s)&&cn(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let o of s.output)if(o.type==="message"){for(let i of o.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),s}function Lm(r,e){return It(r.text?.format,e)}function Mm(r){return lt(r.text?.format)?!0:Array.isArray(r.tools)&&r.tools.some(e=>_c(e)||e.type==="function"&&e.strict===!0||e.type==="namespace"&&e.tools.some(t=>t.type==="function"&&(_c(t)||t.strict===!0)))}function _c(r){return r?.$brand==="auto-parseable-tool"}function Bm(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)}function Dm(r,e){let t=Bm(r.tools??[],e.name,e.namespace),n=null;return _c(t)?n=t.$parseRaw(e.arguments):t?.strict&&(n=It({type:"json_schema",$parseRaw:void 0},e.arguments)),{...e,parsed_arguments:n}}function Xl(r,e){return!Object.getOwnPropertyDescriptor(r,"output_text")||e.output_text==null}function cn(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 Ms=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 gc(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Ms}}function Bs(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 fr(r,e){if(r.canonicalSnapshot===e)return;let t=new Ms,n="";for(let s of e.output){let o=Bs(r,s);n+=o,t.append(o.length)}e.output_text=n,r.outputTextIndex=t,r.canonicalSnapshot=e}function Jl(r,e){r.canonicalSnapshot=void 0,r.outputTextLengths=new WeakMap,r.outputTextIndex=new Ms;let t=structuredClone(e);return!Object.getOwnPropertyDescriptor(t,"output_text")||t.output_text===null||t.output_text===void 0?fr(r,t):t.output.length===0&&t.output_text===""&&(r.canonicalSnapshot=t),t}function Do(r,e,t,n,s){let o=r.outputTextLengths.get(e);if(o!==void 0){let i=o-n.length+s.length;r.outputTextLengths.set(e,i),r.outputTextIndex.update(t,i)}}function Hl(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 Nm(r,e,t,n){if(t===void 0||e?.type!=="message")return 0;if(t<e.content.length-t-1){let i=0;for(let c=0;c<t;c+=1){let u=e.content[c];u?.type==="output_text"&&(i+=u.text.length)}return i}let s=0;for(let i=t+1;i<e.content.length;i+=1){let c=e.content[i];c?.type==="output_text"&&(s+=c.text.length)}return(r.outputTextLengths.get(e)??Bs(r,e).length)-s-n.length}function Ds(r,e,t,n,s,o){if(n===s)return;let i=e.output[t];if(t===e.output.length-1&&(o===void 0||i?.type==="message"&&o===i.content.length-1)){Hl(e,n,s);return}let c=Nm(r,i,o,s),u=r.outputTextIndex.prefixSum(t)+c;if(u+n.length===e.output_text.length){Hl(e,n,s);return}e.output_text=e.output_text.slice(0,u)+s+e.output_text.slice(u+n.length)}var bc=new WeakMap;function pr(r,e,t,n=!1){if(!Array.isArray(r)||!Number.isSafeInteger(e)||e<0||e>r.length||(e===r.length?!n||e in r:!$(r,e)))throw new h(`missing ${t} at index ${e}`)}function Ki(r,e,t){if(e!==r.length)throw new h(`missing ${t} at index ${e}`);pr(r,e,t,!0)}function B(r,e){pr(r.output,e,"output");let t=r.output[e];if(!t)throw new h(`missing output at index ${e}`);return t}function wc(r){return r.type==="function_call"||r.type==="custom_tool_call"||r.type==="shell_call"||r.type==="shell_call_output"}function zi(r,e){if(!$(r,"type")||typeof r.type!="string")throw new h(`expected an own output item type for ${e}`);let t=r.type==="function_call"||r.type==="custom_tool_call",n=[];if($(r,"id")){if(typeof r.id!="string"||r.id.length===0)throw new h(`expected a non-empty output item id for ${e}`);n.push(`id:${r.id}`)}else if(!t)throw new h(`expected a non-empty output item id for ${e}`);if(wc(r)){if(!$(r,"call_id")||typeof r.call_id!="string"||r.call_id.length===0)throw new h(`expected a non-empty output item call_id for ${e}`);n.push(`call:${r.type}:${r.call_id}`)}return n}function Yl(r,e){for(let t of e)if(r.has(t))throw new h(`duplicate output item identity '${t}'`)}function Ql(r,e){Yl(r,e);for(let t of e)r.add(t)}function Zl(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=B(r,t);Ql(e.identities,zi(n,"response snapshot"))}return e}function Fm(r,e){let t=bc.get(r);if(t&&t.snapshot===e&&t.output===e.output&&t.length===e.output.length)return t;let n=Zl(e);return bc.set(r,n),n}function Vl(r,e){let t=gc(),n=Jl(t,e),s=Zl(n);return r.canonicalSnapshot=t.canonicalSnapshot,r.outputTextLengths=t.outputTextLengths,r.outputTextIndex=t.outputTextIndex,bc.set(r,s),n}var Ac={"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 Wm(r){return r.type==="response.content_part.added"||r.type==="response.content_part.done"?r.part.type==="reasoning_text"?"reasoning":"message":Ac[r.type]}function Um(r,e){let t=B(e,r.output_index),n=r.item;if(zi(t,r.type),zi(n,r.type),!$(n,"type")||t.type!==n.type)throw new h(`expected output item type '${t.type}', got '${n.type}'`);let s=$(t,"id")?t.id:void 0,o=$(n,"id")?n.id:void 0;if(s!==o)throw new h(`expected output item id '${s}', got '${o}'`);if(wc(t)&&wc(n)&&t.call_id!==n.call_id)throw new h(`expected output item call_id '${t.call_id}', got '${n.call_id}'`)}function qm(r,e,t){if(r.type==="response.output_item.done"){Um(r,e);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 c=B(e,r.output_index);if(!$(c,"type")||c.type!=="shell_call")throw new h(`expected output item type 'shell_call', got '${c.type}'`);return}if(r.type!=="response.content_part.added"&&r.type!=="response.content_part.done"&&!$(Ac,r.type))return;let n=r;if(!$(r,"item_id")||typeof n.item_id!="string"||n.item_id.length===0)throw new h(`expected a non-empty item_id for ${r.type}`);let s=B(e,n.output_index),o=$(s,"id")?s.id:void 0;if(o!==n.item_id)throw new h(`expected item_id '${o}', got '${n.item_id}'`);let i=Wm(n);if(s.type!==i)throw new h(`expected output item type '${i}', got '${s.type}'`)}function Te(r,e){pr(r,e,"content");let t=r[e];if(!t)throw new h(`missing content at index ${e}`);return t}function Gl(r,e,t){let n=r.output.find(s=>s.type==="shell_call"&&s.call_id===e.call_id);for(n?pr(n.action.commands,t,"command"):pr(e.output,t,"content",!0);e.output.length<=t;)e.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return Te(e.output,t)}function Km(r){return new Set(r)}var zm=Km(["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 qi(r){throw new h("Unhandled response stream event: unknown")}var Xm=["item_id","output_index","content_index","annotation_index","command_index","summary_index"];function Hm(r){let e;try{e=Object.getOwnPropertyDescriptor(r,"type")}catch{return qi(r)}let t=e?.value;if(typeof t!="string"||!zm.has(t))return qi(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"||$(Ac,t))try{for(let o of Xm){let i=Object.getOwnPropertyDescriptor(r,o);n.set(o,i?r[o]:void 0)}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 qi(r)}return new Proxy(r,{get(o,i){return n.has(i)?n.get(i):Reflect.get(o,i,o)}})}function Jm(r,e,t){switch(r.type){case"response.output_item.added":{Ki(e.output,r.output_index,"output");let n=Fm(t,e),s=structuredClone(r.item),o=zi(s,r.type);Yl(n.identities,o),s.type==="message"&&fr(t,e),e.output.push(s),Ql(n.identities,o),n.length=e.output.length;let i=Bs(t,s);return t.canonicalSnapshot===e&&t.outputTextIndex.append(i.length),i&&(e.output_text+=i),!0}case"response.output_item.done":{let n=B(e,r.output_index),s=Bs(t,n),o=r.item;(n.type==="message"||o.type==="message")&&fr(t,e),e.output[r.output_index]=o;let i=Bs(t,o);return t.canonicalSnapshot===e&&t.outputTextIndex.update(r.output_index,i.length),Ds(t,e,r.output_index,s,i),!0}default:return!1}}function Vm(r,e,t){switch(r.type){case"response.content_part.added":{let n=B(e,r.output_index),{type:s}=n,{part:o}=r;if(s==="message"&&o.type!=="reasoning_text"){Ki(n.content,r.content_index,"content");let i=o;i.type==="output_text"&&fr(t,e),n.content.push(i),i.type==="output_text"&&(Do(t,n,r.output_index,"",i.text),Ds(t,e,r.output_index,"",i.text,r.content_index))}else if(s==="reasoning"&&o.type==="reasoning_text"){let i=n.content??[];Ki(i,r.content_index,"content"),n.content||(n.content=i),i.push(o)}return!0}default:return!1}}function Gm(r,e,t){switch(r.type){case"response.content_part.done":{let n=B(e,r.output_index),{part:s}=r;if(n.type==="message"&&s.type!=="reasoning_text"){let o=Te(n.content,r.content_index),i=o.type==="output_text"?o.text:"",c=s;(o.type==="output_text"||c.type==="output_text")&&fr(t,e),n.content[r.content_index]=c;let u=c.type==="output_text"?c.text:"";Do(t,n,r.output_index,i,u),Ds(t,e,r.output_index,i,u,r.content_index)}else if(n.type==="reasoning"&&s.type==="reasoning_text"){let{content:o}=n;if(!o)throw new h(`missing content at index ${r.content_index}`);Te(o,r.content_index),o[r.content_index]=s}return!0}default:return!1}}function Ym(r,e,t){switch(r.type){case"response.output_text.delta":{let n=B(e,r.output_index);if(n.type==="message"){let s=Te(n.content,r.content_index);if(s.type!=="output_text")throw new h(`expected content to be 'output_text', got ${s.type}`);let o=s.text;fr(t,e),s.text=o+r.delta,Do(t,n,r.output_index,o,s.text),r.output_index===e.output.length-1&&r.content_index===n.content.length-1?e.output_text+=r.delta:Ds(t,e,r.output_index,o,s.text,r.content_index)}return!0}case"response.output_text.done":{let n=B(e,r.output_index);if(n.type==="message"){let s=Te(n.content,r.content_index);if(s.type!=="output_text")throw new h(`expected content to be 'output_text', got ${s.type}`);let o=s.text;fr(t,e),s.text=r.text,Do(t,n,r.output_index,o,r.text),Ds(t,e,r.output_index,o,r.text,r.content_index)}return!0}case"response.output_text.annotation.added":{let n=B(e,r.output_index);if(n.type==="message"){let s=Te(n.content,r.content_index);if(s.type!=="output_text")throw new h(`expected content to be 'output_text', got ${s.type}`);pr(s.annotations,r.annotation_index,"annotation",!0),s.annotations[r.annotation_index]=structuredClone(r.annotation)}return!0}default:return!1}}function Qm(r,e){switch(r.type){case"response.refusal.delta":{let t=B(e,r.output_index);if(t.type==="message"){let n=Te(t.content,r.content_index);if(n.type!=="refusal")throw new h(`expected content to be 'refusal', got ${n.type}`);n.refusal+=r.delta}return!0}case"response.refusal.done":{let t=B(e,r.output_index);if(t.type==="message"){let n=Te(t.content,r.content_index);if(n.type!=="refusal")throw new h(`expected content to be 'refusal', got ${n.type}`);n.refusal=r.refusal}return!0}case"response.function_call_arguments.delta":{let t=B(e,r.output_index);return t.type==="function_call"&&(t.arguments+=r.delta),!0}case"response.function_call_arguments.done":{let t=B(e,r.output_index);return t.type==="function_call"&&(t.arguments=r.arguments),!0}case"response.custom_tool_call_input.delta":{let t=B(e,r.output_index);return t.type==="custom_tool_call"&&(t.input+=r.delta),!0}case"response.custom_tool_call_input.done":{let t=B(e,r.output_index);return t.type==="custom_tool_call"&&(t.input=r.input),!0}case"response.mcp_call_arguments.delta":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.arguments+=r.delta),!0}case"response.mcp_call_arguments.done":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.arguments=r.arguments),!0}default:return!1}}function Zm(r,e){switch(r.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let t=B(e,r.output_index);if(t.type==="shell_call"){let n=r.type==="response.shell_call_command.added";pr(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=B(e,r.output_index);return t.type==="shell_call"&&(pr(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=B(e,r.output_index);if(t.type==="shell_call_output"){let n=Gl(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=B(e,r.output_index);if(t.type==="shell_call_output"){let n=Te(r.output,0);Gl(e,t,r.command_index),t.output[r.command_index]=structuredClone(n)}return!0}default:return!1}}function e_(r,e){switch(r.type){case"response.reasoning_text.delta":{let t=B(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new h(`missing content at index ${r.content_index}`);let n=Te(t.content,r.content_index);if(n.type!=="reasoning_text")throw new h(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=r.delta}return!0}case"response.reasoning_text.done":{let t=B(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new h(`missing content at index ${r.content_index}`);let n=Te(t.content,r.content_index);if(n.type!=="reasoning_text")throw new h(`expected content to be 'reasoning_text', got ${n.type}`);n.text=r.text}return!0}case"response.reasoning_summary_part.added":{let t=B(e,r.output_index);return t.type==="reasoning"&&(Ki(t.summary,r.summary_index,"content"),t.summary.push(structuredClone(r.part))),!0}case"response.reasoning_summary_part.done":{let t=B(e,r.output_index);return t.type==="reasoning"&&(Te(t.summary,r.summary_index),t.summary[r.summary_index]=structuredClone(r.part)),!0}case"response.reasoning_summary_text.delta":{let t=B(e,r.output_index);if(t.type==="reasoning"){let n=Te(t.summary,r.summary_index);n.text+=r.delta}return!0}case"response.reasoning_summary_text.done":{let t=B(e,r.output_index);if(t.type==="reasoning"){let n=Te(t.summary,r.summary_index);n.text=r.text}return!0}default:return!1}}function t_(r,e){switch(r.type){case"response.code_interpreter_call_code.delta":{let t=B(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=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.code=r.code),!0}case"response.code_interpreter_call.in_progress":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="in_progress"),!0}case"response.code_interpreter_call.interpreting":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="interpreting"),!0}case"response.code_interpreter_call.completed":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="completed"),!0}default:return!1}}function r_(r,e){switch(r.type){case"response.file_search_call.in_progress":{let t=B(e,r.output_index);return t.type==="file_search_call"&&(t.status="in_progress"),!0}case"response.file_search_call.searching":{let t=B(e,r.output_index);return t.type==="file_search_call"&&(t.status="searching"),!0}case"response.file_search_call.completed":{let t=B(e,r.output_index);return t.type==="file_search_call"&&(t.status="completed"),!0}case"response.web_search_call.in_progress":{let t=B(e,r.output_index);return t.type==="web_search_call"&&(t.status="in_progress"),!0}case"response.web_search_call.searching":{let t=B(e,r.output_index);return t.type==="web_search_call"&&(t.status="searching"),!0}case"response.web_search_call.completed":{let t=B(e,r.output_index);return t.type==="web_search_call"&&(t.status="completed"),!0}default:return!1}}function n_(r,e){switch(r.type){case"response.image_generation_call.in_progress":{let t=B(e,r.output_index);return t.type==="image_generation_call"&&(t.status="in_progress"),!0}case"response.image_generation_call.generating":{let t=B(e,r.output_index);return t.type==="image_generation_call"&&(t.status="generating"),!0}case"response.image_generation_call.completed":{let t=B(e,r.output_index);return t.type==="image_generation_call"&&(t.status="completed"),!0}case"response.mcp_call.in_progress":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.status="in_progress"),!0}case"response.mcp_call.completed":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.status="completed"),!0}case"response.mcp_call.failed":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.status="failed"),!0}default:return!1}}function s_(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 o_(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 Xi(){return gc()}function ed(r,e,t,n=!1,s){let o=Hm(r);if(s&&o.type!=="keepalive"&&s(o),!e){if(o.type!=="response.created")throw new h(`When snapshot hasn't been set yet, expected 'response.created' event, got ${o.type}`);return Vl(t,o.response)}return qm(o,e,n),Jm(o,e,t)||Vm(o,e,t)||Gm(o,e,t)||Ym(o,e,t)||Qm(o,e)||Zm(o,e)||e_(o,e)||t_(o,e)||r_(o,e)||n_(o,e)?e:s_(o)?Vl(t,o.response):o_(o)?e:qi(o)}var hr,Hi,un,Ji,No,Ic,Pc,xc,Vi=class r extends zt{constructor(e){super(),hr.add(this),Hi.set(this,void 0),un.set(this,void 0),Ji.set(this,void 0),No.set(this,Xi()),b(this,Hi,e,"f")}static createResponse(e,t,n){let s=new r(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),a(this,hr,"m",Ic).call(this);let s,o=null;"response_id"in t?(s=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):s=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let i of s)a(this,hr,"m",Pc).call(this,i,o);if(s.controller.signal?.aborted)throw this._userAbortError();return a(this,hr,"m",xc).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,hr,"m",Ic).call(this),this._connected();let n=Ee.fromReadableStream(e,this.controller);for await(let s of n)a(this,hr,"m",Pc).call(this,s,null);if(n.controller.signal?.aborted)throw this._userAbortError();return a(this,hr,"m",xc).call(this)}[(Hi=new WeakMap,un=new WeakMap,Ji=new WeakMap,No=new WeakMap,hr=new WeakSet,Ic=function(){this.ended||(b(this,un,void 0,"f"),b(this,No,Xi(),"f"))},Pc=function(t,n){if(this.ended)return;let s=(c,u)=>{(n==null||u.sequence_number>n)&&this._emit(c,u)};if(t.type==="error"){let c="error"in t&&typeof t.error=="object"&&t.error!==null?t.error:t;throw new z(void 0,c,t.message,void 0)}let o=t,i=ed(t,a(this,un,"f"),a(this,No,"f"),!0,c=>{o=c});switch(b(this,un,i,"f"),s("event",t),o.type){case"response.output_text.delta":{let c=i.output[o.output_index];if(!c)throw new h(`missing output at index ${o.output_index}`);if(c.type==="message"){let u=c.content[o.content_index];if(!u)throw new h(`missing content at index ${o.content_index}`);if(u.type!=="output_text")throw new h(`expected content to be 'output_text', got ${u.type}`);s("response.output_text.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,content_index:o.content_index,snapshot:u.text})}break}case"response.function_call_arguments.delta":{let c=i.output[o.output_index];if(!c)throw new h(`missing output at index ${o.output_index}`);c.type==="function_call"&&s("response.function_call_arguments.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,snapshot:c.arguments});break}default:{s(o.type,t);break}}},xc=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=a(this,un,"f");if(!t)throw new h("request ended without sending any events");b(this,un,void 0,"f"),b(this,No,Xi(),"f");let n=i_(t,a(this,Hi,"f"));return b(this,Ji,n,"f"),n},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=a(this,Ji,"f");if(!e)throw new h("stream ended without producing a Response");return e}};function i_(r,e){return zl(r,e)}var Ns=class extends p{list(e,t={},n){return this._client.getAPIList(l`/responses/${e}/input_items`,R,{query:t,...n,__security:{bearerAuth:!0}})}};var Fs=class extends p{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var et=class extends p{constructor(){super(...arguments),this.inputItems=new Ns(this._client),this.inputTokens=new Fs(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&cn(n),n))}retrieve(e,t={},n){return this._client.get(l`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&cn(s),s))}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>yc(n,e))}stream(e,t){return Vi.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};et.InputItems=Ns;et.InputTokens=Fs;var Ws=class extends p{retrieve(e,t){return this._client.get(l`/safety/alerts/${e}`,{...t,__security:{bearerAuth:!0}})}};var mr=class extends p{constructor(){super(...arguments),this.alerts=new Ws(this._client)}};mr.Alerts=Ws;var Us=class extends p{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var qs=class extends p{retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...n,headers:_([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ln=class extends p{constructor(){super(...arguments),this.content=new qs(this._client)}create(e,t={},n){return this._client.post(l`/skills/${e}/versions`,qt({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/skills/${e}/versions`,R,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};ln.Content=qs;var Et=class extends p{constructor(){super(...arguments),this.content=new Us(this._client),this.versions=new ln(this._client)}create(e={},t){return this._client.post("/skills",qt({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(l`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};Et.Content=Us;Et.Versions=ln;var Ks=class extends p{create(e,t,n){return this._client.post(l`/uploads/${e}/parts`,se({body:t,...n,__security:{bearerAuth:!0}},this._client))}};var _r=class extends p{constructor(){super(...arguments),this.parts=new Ks(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(l`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};_r.Parts=Ks;function td(r,e,t,n){return Bo(s=>r.retrieve(t,{vector_store_id:e},{...n,headers:s}),["in_progress"],["failed","cancelled","completed"],n)}function rd(r,e,t,n){return Bo(s=>r.retrieve(t,{vector_store_id:e},{...n,headers:s}),["in_progress"],["failed","cancelled","completed"],n)}var nd=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 sd(r,e,t,n,s,o){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 i=o?.maxConcurrency??5,c=Math.min(i,n.length);if(c===0)throw new RangeError("maxConcurrency must be greater than 0");let u=n.values(),d=[...s];async function m(f){for(let g of f){let w=await e.files.create({file:g,purpose:"assistants"},o);d.push(w.id)}}let y=[];y.length=c;for(let f=0;f<y.length;f+=1)y[f]=m(u);return await nd(y),await r.createAndPoll(t,{file_ids:d},o)}var zs=class extends p{create(e,t,n){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.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}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.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`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.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,...o}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){return await rd(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){return await sd(this,this._client,e,t,n,s)}};var Xs=class extends p{create(e,t,n){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:s,...o}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/vector_stores/${e}/files`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.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 td(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`,de,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var kt=class extends p{constructor(){super(...arguments),this.files=new Xs(this._client),this.fileBatches=new zs(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/vector_stores/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(l`/vector_stores/${e}/search`,de,{body:t,method:"post",...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};kt.Files=Xs;kt.FileBatches=zs;var dn=class extends p{create(e,t){return this._client.post("/videos",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",F,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(l`/videos/${e}/content`,{query:t,...n,headers:_([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(l`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(l`/videos/${e}/remix`,qt({body:t,...n,__security:{bearerAuth:!0}},this._client))}};var od=32,__=32;function Sc(r){return r.split(" ",od+1).length>od}function*Rc(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 id(r){try{let e=Ni(r);return e.byteLength===__?e:void 0}catch{return}}function y_(r){for(let e of Rc(r)){let t=id(e);if(t)return t}}function g_(r,e,t){let n=t;for(let s of Rc(r)){let o=id(s);if(!o)continue;let i=0;for(let[c,u]of o.entries())i|=u^(e[c]??0);i===0&&(n=o)}return n}async function ad(r,e,t,n,s,o){let i=Number.parseInt(t,10);if(Number.isNaN(i))throw new Oe("Invalid webhook timestamp format");let c=Math.floor(Date.now()/1e3);if(c-i>o)throw new Oe("Webhook timestamp is too old");if(i>c+o)throw new Oe("Webhook timestamp is too new");let u=Sc(e),d=u?y_(e):void 0;if(u&&!d)throw new Oe("The given webhook signature does not match the expected signature");let m=Uint8Array.from(s.startsWith("whsec_")?Ni(s.slice(6)):ge(s)),y=n?`${n}.${t}.${r}`:`${t}.${r}`,f=Uint8Array.from(ge(y)),g=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,u?["sign","verify"]:["verify"]);if(u&&d){let w=new Uint8Array(await crypto.subtle.sign("HMAC",g,f)),A=g_(e,w,d);try{if(await crypto.subtle.verify("HMAC",g,Uint8Array.from(A),f))return}catch{}throw new Oe("The given webhook signature does not match the expected signature")}for(let w of Rc(e))try{let A=Uint8Array.from(Ni(w));if(await crypto.subtle.verify("HMAC",g,A,f))return}catch{}throw new Oe("The given webhook signature does not match the expected signature")}var Hs,cd,Gi,fn=class extends p{constructor(){super(...arguments),Hs.add(this)}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");a(this,Hs,"m",cd).call(this,n);let o=_([t]).values,i=a(this,Hs,"m",Gi).call(this,o,"webhook-signature"),c=a(this,Hs,"m",Gi).call(this,o,"webhook-timestamp"),u=a(this,Hs,"m",Gi).call(this,o,"webhook-id");if(Sc(i)&&typeof crypto.subtle.sign!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");return await ad(e,i,c,u,n,s)}};Hs=new WeakSet,cd=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")},Gi=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};async function Yi(r){let e,t=await r._callApiKey(n=>{e=n});return{apiKey:e===void 0?r.apiKey:e,isProvider:t}}var ld=Symbol.for("openai.node.providerDefinitions.v1"),dd=globalThis,fd=dd[ld],pd=fd??new WeakMap;fd||Object.defineProperty(dd,ld,{value:pd});function hd(r){let e=pd.get(r);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var vc,tt,Fo,V,Qi,Ct,Uo,Wo,gd;function md(){if(Vc())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 b_="workload-identity-auth",_d=Symbol("inheritedDataResidencySelection"),C=class{constructor(e={}){vc.add(this),Fo.set(this,void 0),V.set(this,void 0),Qi.set(this,void 0),Ct.set(this,void 0),Uo.set(this,!1),Wo.set(this,new WeakMap),this.completions=new Vr(this),this.chat=new Jt(this),this.embeddings=new Qr(this),this.files=new en(this),this.images=new sn(this),this.contentProvenanceChecks=new Yr(this),this.audio=new ft(this),this.moderations=new an(this),this.models=new on(this),this.fineTuning=new Ze(this),this.graders=new dr(this),this.vectorStores=new kt(this),this.safety=new mr(this),this.webhooks=new fn(this),this.beta=new je(this),this.batches=new Fr(this),this.uploads=new _r(this),this.admin=new Gt(this),this.responses=new et(this),this.live=new pt(this),this.realtime=new Ot(this),this.conversations=new ur(this),this.evals=new lr(this),this.containers=new cr(this),this.skills=new Et(this),this.videos=new dn(this);let{credential:t,options:n}=$u(e);e=n;let s=ma(e),o=e.provider,{baseURL:i=o?null:le("OPENAI_BASE_URL"),dataResidency:c,[_d]:u=!1,apiKey:d=o?null:le("OPENAI_API_KEY")??null,adminAPIKey:m=o?null:le("OPENAI_ADMIN_KEY")??null,organization:y=o?null:le("OPENAI_ORG_ID")??null,project:f=o?null:le("OPENAI_PROJECT_ID")??null,webhookSecret:g=le("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:w,x509Transport:A,credential:S,...O}=e;if(o){let E=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter(v=>(v==="workloadIdentity"?w:e[v])!=null);if(E.length)throw new h(`The \`provider\` option cannot be used with ${E.map(v=>`\`${v}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let P=ii(w)?{x509:w,legacy:void 0}:{x509:void 0,legacy:w},L=P.x509,I=L!==void 0,T=o?hd(o):void 0,x={apiKey:d,adminAPIKey:m,organization:y,project:f,webhookSecret:g,workloadIdentity:w,x509Transport:A,provider:o,...O,baseURL:T?.baseURL??s??(i||(I?du:"https://api.openai.com/v1"))};if(A&&!I)throw new h("An X.509 transport requires an X.509 workload identity.");if(I){if(s!==void 0||u)throw new h("X.509 workload identity does not support data residency selection.");if(e.fetch!==void 0)throw new h("X.509 workload identity does not support a custom fetch implementation.");if(gn(x.baseURL),io(x.fetchOptions),this.fetchWithAuth!==tt.prototype.fetchWithAuth||this.fetchWithTimeout!==tt.prototype.fetchWithTimeout)throw new h("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(d&&w)throw new h("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!T&&!d&&!m&&!w)throw new h("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!x.dangerouslyAllowBrowser&&md())throw new h(`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=x.baseURL,b(this,Uo,s!==void 0||u,"f"),this.timeout=x.timeout??tt.DEFAULT_TIMEOUT,this.logger=x.logger??console;let M="warn";this.logLevel=M,this.logLevel=ia(x.logLevel,"ClientOptions.logLevel",this)??ia(le("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??M,this.fetchOptions=x.fetchOptions,this.maxRetries=x.maxRetries??2,this.fetch=x.fetch??Ys(),b(this,Fo,Qc,"f");let k=o||t?void 0:le("OPENAI_CUSTOM_HEADERS");if(k){let E={};for(let v of k.split(`
30
+ `)){let K=v.indexOf(":");K>=0&&(E[v.substring(0,K).trim()]=v.substring(K+1).trim())}x.defaultHeaders=_([E,x.defaultHeaders])}if(this._options=x,this._provider=T,L){let E=new Ae(L,A,y,f);this._workloadIdentityAuth=E,b(this,V,E,"f"),b(this,Qi,t,"f"),b(this,Ct,E.fetch(),"f"),this.fetch=a(this,Ct,"f"),Au(this)}else P.legacy&&(this._workloadIdentityAuth=new ti(P.legacy,this.fetch));this.apiKey=typeof d=="string"?d:null,this.adminAPIKey=m,this.organization=y,this.project=f,this.webhookSecret=g}withOptions(e){let t=ma(e),n=a(this,V,"f"),s={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:a(this,V,"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:o,provider:i}=ju(s,e,a(this,Qi,"f"),n!==void 0);t!==void 0&&delete s.baseURL;let c={...s,...e,credential:o,provider:i,[_d]:a(this,Uo,"f")&&t===void 0&&!$(e,"baseURL")&&e.credential===void 0&&!i},u=new this.constructor(c);return i&&new URL(u.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(u._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),u.fetchOptions=e.fetchOptions,u.fetch=e.fetch??Ys(),u.organization=e.organization??null,u.project=e.project??null),a(this,V,"f")&&a(u,V,"f")&&this.baseURL===u.baseURL&&a(this,V,"f").matches(a(u,V,"f"))&&(u._workloadIdentityAuth=a(this,V,"f"),b(u,V,a(this,V,"f"),"f"),b(u,Ct,a(this,Ct,"f"),"f")),u}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw 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(a(this,V,"f")??this._workloadIdentityAuth)instanceof Ae&&t.adminAPIKeyAuth&&this.adminAPIKey!==null?await this.adminAPIKeyAuth(e):_([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=a(this,V,"f")??this._workloadIdentityAuth;if(t){if(t instanceof Ae){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==tt.prototype.fetchWithAuth||this.fetchWithTimeout!==tt.prototype.fetchWithTimeout))throw new h("X.509 workload identity does not support overridden fetch dispatch hooks.");let o=t.headerSnapshots();if(!Ae.shouldAuthenticate(e,o.defaultHeaders,o.requestHeaders))return}let s=t instanceof Ae?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken();return _([{Authorization:`Bearer ${s}`}])}let{apiKey:n}=await Yi(this);if(n!=null)return _([{Authorization:`Bearer ${n}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return _([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return uu(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${Je()}`}makeStatusError(e,t,n,s){let o=t&&typeof t=="object"&&t.error==null?{error:t}:t;return z.generate(e,o,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;try{n=await t()}catch(s){throw s instanceof h?s:new h(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new h(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,e?.(this.apiKey),!0}buildURL(e,t,n){let s=!a(this,vc,"m",gd).call(this)&&n||this.baseURL,o=Cc(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),c=Object.fromEntries(o.searchParams);return(!ta(i)||!ta(c))&&(t={...c,...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.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=a(this,V,"f")??this._workloadIdentityAuth,s=n instanceof Ae?Promise.resolve(e).then(o=>n.runRequest(()=>this.makeRequest(o,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 Ir(this,e,(s,o)=>{let i=a(this,Wo,"f").get(o.controller)?.continueRequest;return i?i(()=>t(s,o)):t(s,o)});return n.withResponse=async()=>{let s=await n,{response:o}=await e;return{data:s,response:o,request_id:o.headers.get("x-request-id")}},n._thenUnwrap=s=>this.responsePromise(e,async(o,i)=>ro(s(await t(o,i),i),i.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 Ar(e,t);for(;;){let n=a(this,Wo,"f").get(t.controller),s=n?.timeout??t.options.timeout??this.timeout,o=n?.authentication,i=o?t.controller.signal:t.options.signal,c=()=>o&&i?this._makeUserAbortError(i):new Y,u;try{u=o?.remainingTimeout(t.options,s)??Math.max(0,t.startTime+s-Date.now())}catch(f){let g=i?.aborted?c():void 0;throw t.controller.abort(),_t(t.response.body).catch(()=>{}),g??f}let d,m,y=!1;try{if(i?.aborted&&n?.helperMethod!=="runTools")throw c();let f=new Promise((g,w)=>{d=setTimeout(()=>{y=!0,t.controller.abort(),w(new re)},u),i&&(m=()=>{y||w(c())},i.addEventListener("abort",m,{once:!0}))});return await Promise.race([Ar(e,t),f])}catch(f){if(i?.aborted&&!y)throw c();if(!y)throw o&&f instanceof SyntaxError?new SyntaxError("X.509 workload identity API response contains invalid JSON."):o&&!(f instanceof h)?new De({message:"X.509 workload identity API response body could not be read."}):f;let g=n?.retriesRemaining??0;if(!g||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 re;d!==void 0&&clearTimeout(d),m&&i?.removeEventListener("abort",m),m=void 0;let w=await this.retryRequest(t.options,g,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,w)}finally{d!==void 0&&clearTimeout(d),m&&i?.removeEventListener("abort",m)}}}async readX509ResponseError(e,t,n,s,o){let i=new AbortController,c=s.signal,u=!1,d=()=>i.abort(c.reason);c.addEventListener("abort",d,{once:!0}),c.aborted&&d();try{let m=o.remainingTimeout(t,n),y=o.waitForRetry(m,i.signal).then(()=>{throw new re}),f=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),y]);if(c.aborted)throw this._makeUserAbortError(c);return f}catch(m){throw m instanceof re&&(u=!c.aborted,s.abort(),_t(e.body).catch(()=>{})),c.aborted&&!u?this._makeUserAbortError(c):m}finally{c.removeEventListener("abort",d),i.abort()}}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o);let i=a(this,V,"f");i?.beginRequestPreparation(),await this.prepareOptions(s),i?.beginRequestPlanning();let c;try{let E=await this.buildRequest(s,{retryCount:o-t});if(c={req:E.req,url:E.url,timeout:E.timeout},i){ra("timeout",c.timeout),i.authorizePlannedRequest(c.url,c.req,c.timeout),Ae.isStreamingRequestBody(c.req.body)&&(s.__metadata={...s.__metadata,hasStreamingBody:!0}),await this.prepareRequest(c.req,{url:c.url,options:s}),await this._provider?.prepareRequest?.(c.req,{url:c.url,options:s}),i.beginRequestPlanning(),i.authorizePlannedRequest(c.url,c.req,c.timeout,!0),Ae.isStreamingRequestBody(c.req.body)&&(s.__metadata={...s.__metadata,hasStreamingBody:!0});let v=i.requestSnapshot().signal;if(v?.aborted||c.req.signal?.aborted)throw this._makeUserAbortError(v?.aborted?v:c.req.signal);i.setEffectiveSignal(c.req.signal||v?yd(c.req.signal??v,v).signal:void 0),i.beginRequestNetwork();let K=s.__security??{bearerAuth:!0},D=await this.authHeaders(s,K),N=i.headerSnapshots(),q=_([N.defaultHeaders,N.requestHeaders]);for(let[be,W]of D?.values??[])!q.nulls.has(be)&&!c.req.headers.has(be)&&c.req.headers.set(be,W);this.validateHeaders(_([q,c.req.headers]),K)}}catch(E){if(i?.retireRequestBody(),i&&t&&!s.__metadata?.hasStreamingBody&&Ae.isRetryableFailure(E))return await this.retryRequest(s,t,n??"x509-token-exchange",Ae.retryHeaders(E));throw E}let{req:u,url:d}=c,m=i?Math.min(c.timeout,i.requestSnapshot().timeout):c.timeout;i?.bindRequest(s,u,this.adminAPIKey);let y=s.__metadata?.hasStreamingBody===!0;i||(await this.prepareRequest(u,{url:d,options:s}),await this._provider?.prepareRequest?.(u,{url:d,options:s})),i?.adoptRequestHeaders(u),i&&Ae.isStreamingRequestBody(u.body)&&(y=!0);let f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=n===void 0?"":`, retryOf: ${n}`,w=i?.requestStartedAt(s)??Date.now();ee(this).debug(`[${f}] sending request`,yt({retryOfRequestLogID:n,method:s.method,url:d,options:i?{body:u.body,...i.requestSnapshot()}:s,headers:u.headers}));let A=i?i.requestSnapshot().signal:s.signal;if(A?.aborted||u.signal?.aborted)throw this._makeUserAbortError(A?.aborted?A:u.signal);let S=s.__security??{bearerAuth:!0},O=i||this.fetchWithTimeout===tt.prototype.fetchWithTimeout?yd(u.signal??(i?A:void 0),i?A:void 0):new AbortController,P=i?.remainingTimeout(s,m)??m,L=i?tt.prototype.fetchWithAuth:this.fetchWithAuth;i?.releaseRequestBody(u.body);let I=await L.call(this,d,u,P,O,S).catch(Js),T=Date.now();if(I instanceof globalThis.Error){let E=`retrying, ${t} attempts remaining`;if(A?.aborted||u.signal?.aborted)throw this._makeUserAbortError(A?.aborted?A:u.signal);let v=mt(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(t&&!y&&(!i||ni(I)))return ee(this).info(`[${f}] connection ${v?"timed out":"failed"} - ${E}`),ee(this).debug(`[${f}] connection ${v?"timed out":"failed"} (${E})`,yt({retryOfRequestLogID:n,url:d,durationMs:T-w,message:i?"X.509 workload identity API connection failed.":I.message})),this.retryRequest(s,t,n??f,void 0,u.signal);let K=y?"error; streaming body cannot be retried":"error; no more retries left";if(ee(this).info(`[${f}] connection ${v?"timed out":"failed"} - ${K}`),ee(this).debug(`[${f}] connection ${v?"timed out":"failed"} (${K})`,yt({retryOfRequestLogID:n,url:d,durationMs:T-w,message:i?"X.509 workload identity API connection failed.":I.message})),I instanceof Ne||I instanceof gr)throw I;if(v){let D="cause"in I?I.cause:void 0,q=typeof D=="object"&&D!==null&&"code"in D&&D.code==="UND_ERR_HEADERS_TIMEOUT"?new re({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new re;throw i?new re:Object.assign(q,{cause:I})}throw i?new De({message:"X.509 workload identity API connection failed."}):new De({message:w_(I),cause:I})}let x=[...I.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,v])=>", "+E+": "+JSON.stringify(v)).join(""),M=`[${f}${g}${x}] ${u.method} ${Jo(d)} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${T-w}ms`;if(!I.ok){let E=I.status===401&&i&&S.bearerAuth&&i.usedWorkloadToken(s);if(E&&i.invalidateToken(),I.status===401&&(i||this._workloadIdentityAuth)&&S.bearerAuth&&(!i||i.usedWorkloadToken(s))&&(!i||t>0)&&!y&&!s.__metadata?.workloadIdentityTokenRefreshed){i?_t(I.body).catch(()=>{}):(await _t(I.body),this._workloadIdentityAuth?.invalidateToken());let W={...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(W,i?t-1:t,n??f)}let v=E&&s.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(I);if(t&&v&&!y){let W=`retrying, ${t} attempts remaining`;return i?_t(I.body).catch(()=>{}):await _t(I.body),ee(this).info(`${M} - ${W}`),ee(this).debug(`[${f}] response error (${W})`,yt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,durationMs:T-w})),this.retryRequest(s,t,n??f,I.headers,u.signal)}let K=v?y?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";ee(this).info(`${M} - ${K}`);let D=i?await this.readX509ResponseError(I,s,m,O,i):await I.text().catch(W=>Js(W).message),N=$c(D),q=N?void 0:D;throw ee(this).debug(`[${f}] response error (${K})`,yt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,message:q,durationMs:Date.now()-w})),this.makeStatusError(I.status,N,q,I.headers)}ee(this).info(M),ee(this).debug(`[${f}] response start`,yt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,durationMs:T-w}));let k=i?.continuation();return i?.releaseRequestCredentials(),a(this,Wo,"f").set(O,{timeout:m,retriesRemaining:t,hasStreamingBody:y,...i?{authentication:i}:{},helperMethod:s.__metadata?.helperMethod,...k?{continueRequest:k}:{}}),{response:I,options:s,controller:O,requestSignal:u.signal,requestLogID:f,retryOfRequestLogID:n,startTime:w}}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=a(this,V,"f")??this._workloadIdentityAuth,s=n instanceof Ae?Promise.resolve(t).then(c=>n.runRequest(()=>this.makeRequest(c,null,void 0),this)):this.makeRequest(t,null,void 0),o=new oo(this,s,e),i=this.responsePromise(s,async(c,u)=>{let d=await this.parseResponseWithTimeout(c,u);return new e(c,u.response,d,u.options)});return o.then=i.then.bind(i),o.catch=i.catch.bind(i),o.finally=i.finally.bind(i),o.withResponse=i.withResponse.bind(i),o._thenUnwrap=i._thenUnwrap.bind(i),o}async fetchWithAuth(e,t,n,s,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!a(this,Ct,"f")&&o.bearerAuth){let u=t.headers;if(u.get("Authorization")===`Bearer ${b_}`){let m=await this._workloadIdentityAuth.getToken();u.set("Authorization",`Bearer ${m}`)}}return await(a(this,Ct,"f")?tt.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,n,s)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:i,...c}=t||{},u=this._makeAbort(s),d=!!o&&bd.get(s)===o,m=o&&!d?Lc(o,u,s.signal):void 0,y=setTimeout(u,n),f=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,g={signal:s.signal,...f?{duplex:"half"}:{},method:"GET",...c};i&&(g.method=i.toUpperCase());try{let w=await(a(this,Ct,"f")??this.fetch).call(void 0,e,g);return m&&na(w.body??w,u,s.signal),w}catch(w){throw m?.(),w}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,o=e.signal){let i,c=s?.get("retry-after-ms");if(c){let m=parseFloat(c);Number.isNaN(m)||(i=m)}let u=s?.get("retry-after");if(u&&i===void 0){let m=parseFloat(u);Number.isNaN(m)?i=Date.parse(u)-Date.now():i=m*1e3}if(i===void 0||!Number.isFinite(i)||i<0||i>60*1e3){let m=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,m)}let d=a(this,V,"f");if(d){let m=d.remainingTimeout(e,d.requestSnapshot().timeout);if(i>=m)throw new re}if(d)await d.waitForRetry(i,d.effectiveSignal());else{let m=o===e.signal?[o]:[o,e.signal];try{await mn(i,...m)}catch(y){let f=m.find(g=>g?.aborted);throw f?this._makeUserAbortError(f):y}}return this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return i*c*1e3}async buildRequest(e,{retryCount:t=0}={}){if(a(this,V,"f")&&!a(this,V,"f").inRequest(this)){let T=a(this,V,"f");return await T.runRequest(async()=>{let x=await tt.prototype.buildRequest.call(this,e,{retryCount:t});return T.releaseRequestBody(x.req.body),x},this)}let n={...e},s=a(this,V,"f"),o=s?.snapshotTenant(this.organization,this.project),i=s?.snapshotHeaders(this._options.defaultHeaders,n.headers);i&&(n.headers=i.requestHeaders);let c=s?Ia(this.fetchOptions):void 0,u=s?Ia(n.fetchOptions):void 0,{method:d,path:m,query:y,defaultBaseURL:f}=n,g=this.buildURL(m,y,f);s?.snapshotAPIURL(g);let w="timeout"in n;if(w&&ra("timeout",n.timeout),n.timeout=n.timeout??this.timeout,s&&u&&s.snapshotRequest(n.signal,n.timeout,u),s){let T=s.requestSnapshot();n.timeout=T.timeout,T.signal===void 0?delete n.signal:n.signal=T.signal}let A=this._provider||s?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),{bodyHeaders:S,body:O,isStreamingBody:P}=this.buildBody({options:n});P&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},s?.ownRequestBody(O,n.body));let L=await this.buildHeaders({options:e,method:d,bodyHeaders:S,authenticationHeaders:A,retryCount:t,x509Headers:i,x509Timeout:w?n.timeout:void 0,x509Tenant:o});return{req:{method:d,headers:L,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&O instanceof globalThis.ReadableStream&&{duplex:"half"},...O&&{body:O},...(s?c:this.fetchOptions)??{},...(s?u:n.fetchOptions)??{}},url:g,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,authenticationHeaders:s,retryCount:o,x509Headers:i,x509Timeout:c,x509Tenant:u}){let d={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),d[this.idempotencyHeader]=e.idempotencyKey);let m=e.__metadata?.helperMethod,y=i?c:e.timeout,f=_([d,{Accept:"application/json",...md()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(o),...y?{"X-Stainless-Timeout":String(Math.trunc(y/1e3))}:{},...Gc(),...typeof m=="string"?{"X-Stainless-Helper-Method":m}:{},"OpenAI-Organization":u?u.organization:this.organization,"OpenAI-Project":u?u.project:this.project},a(this,V,"f")&&!a(this,V,"f").isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):s,i?.defaultHeaders??this._options.defaultHeaders,n,i?.requestHeaders??e.headers]);return!this._provider&&!a(this,V,"f")?.isPlanningRequest()&&this.validateHeaders(f,e.__security??{bearerAuth:!0}),f.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?{...a(this,Fo,"f").call(this,{body:t,headers:_([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let s=_([n]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,i=!o&&(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||o?{bodyHeaders:void 0,body:t,isStreamingBody:!i}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Qs(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}:{...a(this,Fo,"f").call(this,{body:t,headers:s}),isStreamingBody:!1}}};tt=C,Fo=new WeakMap,V=new WeakMap,Qi=new WeakMap,Ct=new WeakMap,Uo=new WeakMap,Wo=new WeakMap,vc=new WeakSet,gd=function(){return a(this,Uo,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=tt;C.DEFAULT_TIMEOUT=6e5;C.OpenAIError=h;C.APIError=z;C.APIConnectionError=De;C.APIConnectionTimeoutError=re;C.APIUserAbortError=Y;C.NotFoundError=Lt;C.ConflictError=Mt;C.RateLimitError=Dt;C.BadRequestError=ot;C.AuthenticationError=$t;C.InternalServerError=Nt;C.PermissionDeniedError=jt;C.UnprocessableEntityError=Bt;C.InvalidWebhookSignatureError=Oe;C.toFile=di;C.toStreamingFile=ci;C.Completions=Vr;C.Chat=Jt;C.Embeddings=Qr;C.Files=en;C.Images=sn;C.ContentProvenanceChecks=Yr;C.Audio=ft;C.Moderations=an;C.Models=on;C.FineTuning=Ze;C.Graders=dr;C.VectorStores=kt;C.Safety=mr;C.Webhooks=fn;C.Beta=je;C.Batches=Fr;C.Uploads=_r;C.Admin=Gt;C.Responses=et;C.Live=pt;C.Realtime=Ot;C.Conversations=ur;C.Evals=lr;C.Containers=cr;C.Skills=Et;C.Videos=dn;C.ConversationCursorPage=F;C.CursorPage=R;C.NextCursorPage=Q;C.Page=de;C.TokenPage=yn;var bd=new WeakMap;function yd(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 o=n.any(s);Object.defineProperty(t,"signal",{value:o,configurable:!0}),bd.set(t,r)}catch{}return t}function w_(r){if(A_(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 A_(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}var Oc=class extends C{constructor({baseURL:e=le("OPENAI_BASE_URL"),apiKey:t=le("AZURE_OPENAI_API_KEY"),apiVersion:n=le("OPENAI_API_VERSION"),endpoint:s,deployment:o,azureADTokenProvider:i,dangerouslyAllowBrowser:c,dataResidency:u,...d}={}){if(Zo(u,"AzureOpenAI"),!n)throw new h("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 i=="function"&&(c??(c=!0)),!i&&!t)throw new h("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&t)throw new h("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 h("baseURL and endpoint are mutually exclusive")}else{if(s||(s=process.env.AZURE_OPENAI_ENDPOINT),!s)throw new h("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let m=s.length;for(;m>0&&s[m-1]==="/";)m--;e=`${s.slice(0,m)}/openai`}super({apiKey:i??t,baseURL:e,...d,...c===void 0?{}:{dangerouslyAllowBrowser:c}}),this.apiVersion="",this.apiVersion=n,this.deploymentName=o}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};return $(e,"endpoint")&&e.endpoint!==void 0&&!$(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(!ye(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&&!I_(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,o){return new Headers(t.headers).has("api-key")&&(t.redirect="manual"),super.fetchWithAuth(e,t,n,s,o)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey=="string"?_([{"api-key":this.apiKey}]):super.authHeaders(e,n)}};function I_(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 wd=Symbol.for("openai.privateBedrockClient");function yr(r,e){let t=new URL(r),n=new URL(e),s=t.origin,o=n.origin;if(t.protocol!=="http:"&&t.protocol!=="https:"||n.protocol!=="http:"&&n.protocol!=="https:"||o!==s)throw new h(`Bedrock request origin \`${o}\` does not match the configured base URL origin \`${s}\`.`)}function Ec(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.")}}var Ad;function x_(r){let e=r?.trim();if(!e)throw new h("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 h("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 S_(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 R_(r){return Object.getOwnPropertyDescriptor(r,"output_text")||cn(r),r}function v_(r){let e=r.stream.bind(r);return r.stream=((t,n)=>{let s=e(t,n),o=s.finalResponse.bind(s);return s.finalResponse=async()=>R_(await o()),s}),r}var kc=class extends C{constructor({baseURL:e=le("AWS_BEDROCK_BASE_URL"),apiKey:t,awsRegion:n=le("AWS_REGION")??le("AWS_DEFAULT_REGION"),bedrockTokenProvider:s,adminAPIKey:o,workloadIdentity:i,x509Transport:c,dataResidency:u,...d}={}){if(Zo(u,"BedrockOpenAI"),o||i||c)throw new h("BedrockOpenAI only supports Bedrock bearer token authentication.");if(t===void 0&&!s&&(t=le("AWS_BEARER_TOKEN_BEDROCK")??null),typeof t=="function")throw new h("Pass refreshable Bedrock credentials via `bedrockTokenProvider`, not `apiKey`.");if(t&&s)throw new h("The `apiKey` and `bedrockTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(!t&&!s)throw new h("Missing credentials. Please pass an `apiKey` or `bedrockTokenProvider`, or set the `AWS_BEARER_TOKEN_BEDROCK` environment variable.");let m=e?.trim()?e:x_(n);super({apiKey:s??t,adminAPIKey:null,baseURL:S_(m),...d}),this[Ad]=!0;let y=this.apiKey;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,get(){return y!==null&&Ec(y),y},set(w){y=w}});let f=this.baseURL,g=f;Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!1,get(){return g},set(w){yr(f,w),g=w}}),this.bedrockTokenProvider=s,this.responses=v_(new et(this))}async prepareOptions(e){let t=this._options.baseURL??this.baseURL;yr(t,this.buildURL(e.path,null,e.defaultBaseURL)),await super.prepareOptions(e),yr(t,this.buildURL(e.path,null,e.defaultBaseURL))}async prepareRequest(e,t){yr(this._options.baseURL??this.baseURL,t.url),await super.prepareRequest(e,t),yr(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){yr(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL));let{apiKey:s}=await Yi(this);if(yr(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL)),s===null)return;Ec(s);try{return _([{Authorization:`Bearer ${s}`}])}catch(o){throw o instanceof TypeError?new TypeError("Bedrock bearer credential contains an invalid HTTP header value."):o}}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}:{}})}};Ad=wd;export{De as APIConnectionError,re as APIConnectionTimeoutError,z as APIError,Ir as APIPromise,Y as APIUserAbortError,$t as AuthenticationError,Oc as AzureOpenAI,ot as BadRequestError,kc as BedrockOpenAI,Mt as ConflictError,Nt as InternalServerError,Oe as InvalidWebhookSignatureError,Lt as NotFoundError,Ne as OAuthError,C as OpenAI,h as OpenAIError,oo as PagePromise,jt as PermissionDeniedError,Dt as RateLimitError,gr as SubjectTokenProviderError,Bt as UnprocessableEntityError,C as default,di as toFile,ci as toStreamingFile};