noskills 4.5.0 → 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
@@ -1 +0,0 @@
1
- import{a,b}from"./chunk-5PBNUBBY.js";import"./chunk-CML74SNT.js";import"./chunk-JYVB6UAV.js";import"./chunk-IGDFEGCH.js";import"./chunk-ENP4P2YH.js";import"./chunk-575Y3OEG.js";import"./chunk-4PF2MT7S.js";import"./chunk-OAWYVETM.js";import"./chunk-Y5E7ZCCX.js";import"./chunk-LJEWPIEI.js";import"./chunk-FE4MKOI4.js";import"./chunk-HISXAZ4Y.js";export{a as OllamaModel,b as ollamaFactory};
@@ -1,31 +0,0 @@
1
- import"./chunk-HISXAZ4Y.js";function w(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function u(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var He=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return He=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function qr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Hr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var _=class extends Error{},N=class s extends _{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.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,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:Hr(t)});let o=t?.error;return e===400?new xt(e,o,r,n):e===401?new Rt(e,o,r,n):e===403?new St(e,o,r,n):e===404?new Ct(e,o,r,n):e===409?new $t(e,o,r,n):e===422?new kt(e,o,r,n):e===429?new Et(e,o,r,n):e>=500?new Ot(e,o,r,n):new s(e,o,r,n)}},L=class extends N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ce=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},xt=class extends N{},Rt=class extends N{},St=class extends N{},Ct=class extends N{},$t=class extends N{},kt=class extends N{},Et=class extends N{},Ot=class extends N{},vt=class extends _{constructor(){super("Could not parse response content as the length limit was reached")}},Tt=class extends _{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},pe=class extends Error{constructor(e){super(e)}},We=class extends N{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let a=t;o=a.error;let l=a.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},Wr=class extends _{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var ei=/^[a-z][a-z0-9+.-]*:/i,Bn=s=>ei.test(s),Q=s=>(Q=Array.isArray,Q(s)),Ws=Q;function ys(s){return typeof s!="object"?{}:s??{}}function Js(s){if(!s)return!0;for(let e in s)return!1;return!0}function Un(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function jt(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var zn=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new _(`${s} must be an integer`);if(e<0)throw new _(`${s} must be a positive integer`);return e};var Dn=s=>{try{return JSON.parse(s)}catch{return}};var he=s=>new Promise(e=>setTimeout(e,s));var $e="7.4.0";var Jn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ti(){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 ri=()=>{let s=ti();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$e,"X-Stainless-OS":Hn(Deno.build.os),"X-Stainless-Arch":qn(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":$e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$e,"X-Stainless-OS":Hn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=si();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$e,"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":$e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function si(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\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 s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var qn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Hn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Wn,Vn=()=>Wn??(Wn=ri());function gs(){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 Vs(...s){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(...s)}function Jr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Vs({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function As(s){if(s[Symbol.asyncIterator])return s;let e=s.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 Xs(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var Gn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Gs="RFC3986",Qs=s=>String(s),Ys={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Qs},Qn="RFC1738";var bs=(s,e)=>(bs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),bs(s,e)),fe=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Zs=1024,Yn=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<o.length;l+=Zs){let h=o.length>=Zs?o.slice(l,l+Zs):o,d=[];for(let f=0;f<h.length;++f){let y=h.charCodeAt(f);if(y===45||y===46||y===95||y===126||y>=48&&y<=57||y>=65&&y<=90||y>=97&&y<=122||n===Qn&&(y===40||y===41)){d[d.length]=h.charAt(f);continue}if(y<128){d[d.length]=fe[y];continue}if(y<2048){d[d.length]=fe[192|y>>6]+fe[128|y&63];continue}if(y<55296||y>=57344){d[d.length]=fe[224|y>>12]+fe[128|y>>6&63]+fe[128|y&63];continue}f+=1,y=65536+((y&1023)<<10|h.charCodeAt(f)&1023),d[d.length]=fe[240|y>>18]+fe[128|y>>12&63]+fe[128|y>>6&63]+fe[128|y&63]}a+=d.join("")}return a};function Zn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function en(s,e){if(Q(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var to={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},ro=function(s,e){Array.prototype.push.apply(s,Q(e)?e:[e])},eo,z={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Yn,encodeValuesOnly:!1,format:Gs,formatter:Qs,indices:!1,serializeDate(s){return(eo??(eo=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function oi(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var tn={};function so(s,e,t,r,n,o,a,l,h,d,f,y,m,b,P,A,I,O){let g=s,E=O,S=0,j=!1;for(;(E=E.get(tn))!==void 0&&!j;){let v=E.get(s);if(S+=1,typeof v<"u"){if(v===S)throw new RangeError("Cyclic object value");j=!0}typeof E.get(tn)>"u"&&(S=0)}if(typeof d=="function"?g=d(e,g):g instanceof Date?g=m?.(g):t==="comma"&&Q(g)&&(g=en(g,function(v){return v instanceof Date?m?.(v):v})),g===null){if(o)return h&&!A?h(e,z.encoder,I,"key",b):e;g=""}if(oi(g)||Zn(g)){if(h){let v=A?e:h(e,z.encoder,I,"key",b);return[P?.(v)+"="+P?.(h(g,z.encoder,I,"value",b))]}return[P?.(e)+"="+P?.(String(g))]}let k=[];if(typeof g>"u")return k;let K;if(t==="comma"&&Q(g))A&&h&&(g=en(g,h)),K=[{value:g.length>0?g.join(",")||null:void 0}];else if(Q(d))K=d;else{let v=Object.keys(g);K=f?v.sort(f):v}let T=l?String(e).replace(/\./g,"%2E"):String(e),F=r&&Q(g)&&g.length===1?T+"[]":T;if(n&&Q(g)&&g.length===0)return F+"[]";for(let v=0;v<K.length;++v){let V=K[v],Pt=typeof V=="object"&&typeof V.value<"u"?V.value:g[V];if(a&&Pt===null)continue;let X=y&&l?V.replace(/\./g,"%2E"):V,ms=Q(g)?typeof t=="function"?t(F,X):F:F+(y?"."+X:"["+X+"]");O.set(s,S);let _s=new WeakMap;_s.set(tn,O),ro(k,so(Pt,ms,t,r,n,o,a,l,t==="comma"&&A&&Q(g)?null:h,d,f,y,m,b,P,A,I,_s))}return k}function ii(s=z){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||z.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Gs;if(typeof s.format<"u"){if(!bs(Ys,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Ys[t],n=z.filter;(typeof s.filter=="function"||Q(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in to?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=z.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:z.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:z.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:z.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:z.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?z.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:z.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:z.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:z.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:z.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:z.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:z.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:z.strictNullHandling}}function no(s,e={}){let t=s,r=ii(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):Q(r.filter)&&(o=r.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let l=to[r.arrayFormat],h=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let d=new WeakMap;for(let m=0;m<n.length;++m){let b=n[m];r.skipNulls&&t[b]===null||ro(a,so(t[b],b,l,h,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let f=a.join(r.delimiter),y=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?y+="utf8=%26%2310003%3B&":y+="utf8=%E2%9C%93&"),f.length>0?y+f:""}function oo(s){return no(s,{arrayFormat:"brackets"})}function co(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var io;function re(s){let e;return(io??(e=new globalThis.TextEncoder,io=e.encode.bind(e)))(s)}var ao;function rn(s){let e;return(ao??(e=new globalThis.TextDecoder,ao=e.decode.bind(e)))(s)}var se,ne,Je=class{constructor(){se.set(this,void 0),ne.set(this,void 0),w(this,se,new Uint8Array,"f"),w(this,ne,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?re(e):e;w(this,se,co([u(this,se,"f"),t]),"f");let r=[],n;for(;(n=ci(u(this,se,"f"),u(this,ne,"f")))!=null;){if(n.carriage&&u(this,ne,"f")==null){w(this,ne,n.index,"f");continue}if(u(this,ne,"f")!=null&&(n.index!==u(this,ne,"f")+1||n.carriage)){r.push(rn(u(this,se,"f").subarray(0,u(this,ne,"f")-1))),w(this,se,u(this,se,"f").subarray(u(this,ne,"f")),"f"),w(this,ne,null,"f");continue}let o=u(this,ne,"f")!==null?n.preceding-1:n.preceding,a=rn(u(this,se,"f").subarray(0,o));r.push(a),w(this,se,u(this,se,"f").subarray(n.index),"f"),w(this,ne,null,"f")}return r}flush(){return u(this,se,"f").length?this.decode(`
2
- `):[]}};se=new WeakMap,ne=new WeakMap;Je.NEWLINE_CHARS=new Set([`
3
- `,"\r"]);Je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ci(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function uo(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var Is={off:0,error:200,warn:300,info:400,debug:500},sn=(s,e,t)=>{if(s){if(Un(Is,s))return s;M(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Is))}`)}};function Vr(){}function ws(s,e,t){return!e||Is[s]>Is[t]?Vr:e[s].bind(e)}var ui={error:Vr,warn:Vr,info:Vr,debug:Vr},lo=new WeakMap;function M(s){let e=s.logger,t=s.logLevel??"off";if(!e)return ui;let r=lo.get(e);if(r&&r[0]===t)return r[1];let n={error:ws("error",e,t),warn:ws("warn",e,t),info:ws("info",e,t),debug:ws("debug",e,t)};return lo.set(e,[t,n]),n}var ye=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Xr,ee=class s{constructor(e,t,r){this.iterator=e,Xr.set(this,void 0),this.controller=t,w(this,Xr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,a=r?M(r):console;async function*l(){if(o)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let h=!1;try{for await(let d of li(e,t))if(!h){if(d.data.startsWith("[DONE]")){h=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let f;try{f=JSON.parse(d.data)}catch(y){throw a.error("Could not parse message into JSON:",d.data),a.error("From chunk:",d.raw),y}if(f&&f.error)throw new N(void 0,f.error,void 0,e.headers);yield n?{event:d.event,data:f}:f}else{let f;try{f=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new N(void 0,f.error,f.message,void 0);yield{event:d.event,data:f}}}h=!0}catch(d){if(qr(d))return;throw d}finally{h||t.abort()}}return new s(l,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new Je,h=e.getReader(),d=!1,f,y=()=>{f??(f=h.cancel()),f.catch(()=>{})};t.signal.addEventListener("abort",y,{once:!0});try{if(t.signal.aborted){y();return}for(;;){let{value:m,done:b}=await h.read();if(b){d=!0;break}if(t.signal.aborted)return;for(let P of l.decode(m)){if(t.signal.aborted)return;yield P}}if(t.signal.aborted)return;for(let m of l.flush()){if(t.signal.aborted)return;yield m}}finally{t.signal.removeEventListener("abort",y),d||y(),h.releaseLock()}}async function*a(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let h of o())l||h&&(yield JSON.parse(h));l=!0}catch(h){if(t.signal.aborted||qr(h))return;throw h}finally{l||t.abort()}}return new s(a,t,r)}[(Xr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let a=r.next();e.push(a),t.push(a)}return o.shift()}});return[new s(()=>n(e),this.controller,u(this,Xr,"f")),new s(()=>n(t),this.controller,u(this,Xr,"f"))]}toReadableStream(){let e=this,t;return Vs({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let a=re(JSON.stringify(n)+`
4
- `);r.enqueue(a)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*li(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("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 _("Attempted to iterate over a response with no body");let t=new nn,r=new Je,n=As(s.body);for await(let o of di(n))for(let a of r.decode(o)){let l=t.decode(a);l&&(yield l)}for(let o of r.flush()){let a=t.decode(o);a&&(yield a)}}async function*di(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?re(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=uo(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var nn=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-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,r,n]=pi(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function pi(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function Ps(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,a=await(async()=>{if(e.options.stream)return M(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):ee.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let h=t.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let m=await t.json();return on(m,t)}return await t.text()})();return M(s).debug(`[${r}] response parsed`,ye({retryOfRequestLogID:n,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function on(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Gr,Ve=class s extends Promise{constructor(e,t,r=Ps){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Gr.set(this,void 0),w(this,Gr,e,"f")}_thenUnwrap(e){return new s(u(this,Gr,"f"),this.responsePromise,async(t,r)=>on(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(u(this,Gr,"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)}};Gr=new WeakMap;var xs,Ft=class{constructor(e,t,r,n){xs.set(this,void 0),w(this,xs,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,xs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(xs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Qr=class extends Ve{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await Ps(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Y=class extends Ft{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Ft{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...ys(this.options.query),after:t}}:null}},$=class extends Ft{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ys(this.options.query),after:e}}:null}},B=class extends Ft{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ys(this.options.query),after:e}}:null}};var fi={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},mi="urn:ietf:params:oauth:grant-type:token-exchange",Rs=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??gs()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),t={grant_type:mi,subject_token:e,subject_token_type:fi[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let h=await r.text(),d;try{d=JSON.parse(h)}catch{}throw r.status===400||r.status===401||r.status===403?new We(r.status,d,r.headers):N.generate(r.status,d,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new _("Token exchange response missing 'access_token' field");let o=n.access_token,a=n.expires_in??3600,l=Date.now()+a*1e3;return this.cachedToken={token:o,expiresAt:l},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var po=Symbol("brand.privateNullableHeaders"),_i=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*yi(s){if(!s)return;if(po in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():Ws(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Ws(r[1])?r[1]:[r[1]],a=!1;for(let l of o)l!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,l])}}var p=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,a]of yi(r)){if(!_i.test(o))throw new TypeError(`Header name must be a valid HTTP token ["${o}"]`);let l=o.toLowerCase();n.has(l)||(e.delete(l),n.add(l)),a===null?(e.delete(l),t.add(l)):(e.append(l,a),t.delete(l))}}return{[po]:!0,values:e,nulls:t}};var fo=Symbol("brand.privateStreamingFile");function Cs(s,e,t){if(!e)throw new TypeError("toStreamingFile requires a non-empty file name");return{[fo]:!0,data:s,name:e,...t?.type?{type:t.type}:{}}}var dn=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<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 Lt(s,e,t){return dn(),new File(s,e??"unknown_file",t)}function Kt(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var Mt=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",ke=async(s,e)=>cn(s.body)?Ss(s.body)?_o(s):{...s,body:await mo(s.body,e)}:s,D=async(s,e)=>Ss(s.body)?_o(s):{...s,body:await mo(s.body,e)},ho=new WeakMap;function gi(s){let e=typeof s=="function"?s:s.fetch,t=ho.get(e);if(t)return t;let r=(async()=>{try{let n;if("Response"in e)n=e.Response;else{let a=await e("data:,");await a.arrayBuffer(),n=a.constructor}let o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return ho.set(e,r),r}var mo=async(s,e)=>{if(!await gi(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(s||{}).map(([r,n])=>ln(t,r,n))),t},$s=s=>s instanceof Blob&&"name"in s,pn=s=>typeof s=="object"&&s!==null&&"getReader"in s&&typeof s.getReader=="function",Yr=s=>typeof s=="object"&&s!==null&&fo in s,hn=s=>typeof s=="object"&&s!==null&&(s instanceof Response||Mt(s)||pn(s)||Yr(s)||$s(s)),Ss=s=>{if(Yr(s)||Mt(s)||pn(s))return!0;if(Array.isArray(s))return s.some(Ss);if(s&&typeof s=="object"&&!$s(s)&&!(s instanceof Response)){for(let e in s)if(Ss(s[e]))return!0}return!1},cn=s=>{if(hn(s))return!0;if(Array.isArray(s))return s.some(cn);if(s&&typeof s=="object"){for(let e in s)if(cn(s[e]))return!0}return!1},_o=s=>{let e=`openai-${Math.random().toString(36).slice(2)}`,t=Jr(Ai(s.body,e));return{...s,body:t,headers:p([{"content-type":`multipart/form-data; boundary=${e}`},s.headers])}};async function*Ai(s,e){for await(let{key:t,value:r}of bi(s)){if(yield re(`--${e}\r
6
- `),hn(r)){let n=wi(r),o=Ii(r);yield re(`Content-Disposition: form-data; name="${an(t)}"; filename="${an(n)}"\r
7
- Content-Type: ${o}\r
8
- \r
9
- `),yield*Nt(Pi(r))}else yield re(`Content-Disposition: form-data; name="${an(t)}"\r
10
- \r
11
- ${String(r)}`);yield re(`\r
12
- `)}yield re(`--${e}--\r
13
- `)}async function*bi(s){if(!(!s||typeof s!="object"))for(let[e,t]of Object.entries(s))yield*un(e,t)}async function*un(s,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${s}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||hn(e))yield{key:s,value:e};else if(Array.isArray(e))for(let t of e)yield*un(s+"[]",t);else if(typeof e=="object")for(let[t,r]of Object.entries(e))yield*un(`${s}[${t}]`,r);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function wi(s){return Yr(s)?s.name:Kt(s)??"unknown_file"}function Ii(s){return Yr(s)?s.type||"application/octet-stream":$s(s)&&s.type?s.type:s instanceof Response&&s.headers.get("content-type")||"application/octet-stream"}function Pi(s){return Yr(s)?s.data:s}async function*Nt(s){if(typeof s=="string")yield re(s);else if(ArrayBuffer.isView(s))yield new Uint8Array(s.buffer,s.byteOffset,s.byteLength);else if(s instanceof ArrayBuffer)yield new Uint8Array(s);else if(s instanceof Response)s.body?yield*Nt(s.body):yield*Nt(await s.blob());else if(s instanceof Blob)typeof s.stream=="function"?yield*Nt(s.stream()):yield new Uint8Array(await s.arrayBuffer());else if(pn(s))for await(let e of As(s))yield*Nt(e);else if(Mt(s))for await(let e of s)yield*Nt(e);else throw new TypeError(`Invalid streaming file chunk: ${String(s)}`)}function an(s){return s.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var ln=async(s,e,t)=>{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")s.append(e,String(t));else if(t instanceof Response)s.append(e,Lt([await t.blob()],Kt(t)));else if(Mt(t))s.append(e,Lt([await new Response(Jr(t)).blob()],Kt(t)));else if($s(t))s.append(e,t,Kt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>ln(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>ln(s,`${e}[${r}]`,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 yo=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",xi=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&yo(s),Ri=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function ks(s,e,t){if(dn(),s=await s,xi(s))return s instanceof File?s:Lt([await s.arrayBuffer()],s.name);if(Ri(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Lt(await fn(n),e,t)}let r=await fn(s);if(e||(e=Kt(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Lt(r,e,t)}async function fn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(yo(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Mt(s))for await(let t of s)e.push(...await fn(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${Si(s)}`)}return e}function Si(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var c=class{constructor(e){this._client=e}};function Ao(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var go=Object.freeze(Object.create(null)),$i=(s=Ao)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],a=t.reduce((f,y,m)=>{/[?#]/.test(y)&&(n=!0);let b=r[m],P=(n?encodeURIComponent:s)(""+b);return m!==r.length&&(b==null||typeof b=="object"&&b.toString===Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??go)??go)?.toString)&&(P=b+"",o.push({start:f.length+y.length,length:P.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),f+y+(m===r.length?"":P)},""),l=a.split(/[?#]/,1)[0],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=h.exec(l))!==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((f,y)=>f.start-y.start),o.length>0){let f=0,y=o.reduce((m,b)=>{let P=" ".repeat(b.start-f),A="^".repeat(b.length);return f=b.start+b.length,m+P+A},"");throw new _(`Path parameters result in path with invalid segments:
14
- ${o.map(m=>m.error).join(`
15
- `)}
16
- ${a}
17
- ${y}`)}return a},i=$i(Ao);var Xe=class extends c{list(e,t={},r){return this._client.getAPIList(i`/chat/completions/${e}/messages`,R,{query:t,...r,__security:{bearerAuth:!0}})}};function Zr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function es(s){return s?.$brand==="auto-parseable-response-format"}function Ge(s){return s?.$brand==="auto-parseable-tool"}function wo(s,e){return!e||!mn(e)?{...s,choices:s.choices.map(t=>(Po(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:ts(s,e)}function ts(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new vt;if(r.finish_reason==="content_filter")throw new Tt;return Po(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>Oi(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Ei(e,r.message.content):null}}});return{...s,choices:t}}function Ei(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function Oi(s,e){let t=s.tools?.find(r=>Zr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ge(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Io(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Zr(r)&&r.function?.name===e.function.name);return Zr(t)&&(Ge(t)||t?.function.strict||!1)}function mn(s){return es(s.response_format)?!0:s.tools?.some(e=>Ge(e)||e.type==="function"&&e.function.strict===!0)??!1}function Po(s){for(let e of s||[])if(e.type!=="function")throw new _(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function xo(s){for(let e of s??[]){if(e.type!=="function")throw new _(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new _(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var ge=s=>s?.role==="assistant",rs=s=>s?.role==="tool";var ss,Es,Os,ns,os,vs,is,Ae,Ts,as,js,Fs,Bt,Ro,_n,Ee=class{constructor(){ss.add(this),this.controller=new AbortController,Es.set(this,void 0),Os.set(this,()=>{}),ns.set(this,()=>{}),os.set(this,void 0),vs.set(this,()=>{}),is.set(this,()=>{}),Ae.set(this,{}),Ts.set(this,[]),as.set(this,!1),js.set(this,!1),Fs.set(this,!1),Bt.set(this,!1),w(this,Es,new Promise((e,t)=>{w(this,Os,e,"f"),w(this,ns,t,"f")}),"f"),w(this,os,new Promise((e,t)=>{w(this,vs,e,"f"),w(this,is,t,"f")}),"f"),u(this,Es,"f").catch(()=>{}),u(this,os,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(t){u(this,ss,"m",_n).call(this,t);return}this._emit("end")},u(this,ss,"m",_n).bind(this))},0)}_connected(){this.ended||(u(this,Os,"f").call(this),this._emit("connect"))}get ended(){return u(this,as,"f")}get errored(){return u(this,js,"f")}get aborted(){return u(this,Fs,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener("abort",t,{once:!0}),u(this,Ts,"f").push({signal:e,listener:t})}on(e,t){return(u(this,Ae,"f")[e]||(u(this,Ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,Ae,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(u(this,Ae,"f")[e]||(u(this,Ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,Bt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}events(e){let t=[],r=[],n=this.ended,o,a=!1,l=()=>({value:void 0,done:!0}),h=()=>{for(;r.length;)r.shift().resolve(l())},d=()=>{!o||a||!r.length||(a=!0,r.shift().reject(o))},f=()=>{this.off(e,y),this.off("end",b),e!=="error"&&this.off("error",m),e!=="abort"&&this.off("abort",m)},y=(...P)=>{if(n)return;let A=r.shift();A?A.resolve({value:P,done:!1}):t.push(P)},m=P=>{o=P,t.length||d()},b=()=>{n=!0,f(),t.length||(d(),h())};return n||(this.on(e,y),this.on("end",b),e!=="error"&&this.on("error",m),e!=="abort"&&this.on("abort",m)),{next:()=>{let P=t.shift();return P?Promise.resolve({value:P,done:!1}):o&&!a?(a=!0,Promise.reject(o)):n?Promise.resolve(l()):new Promise((A,I)=>{r.push({resolve:A,reject:I})})},return:()=>(n=!0,t.length=0,f(),h(),Promise.resolve(l())),[Symbol.asyncIterator](){return this}}}async done(){w(this,Bt,!0,"f"),await u(this,os,"f")}_emit(e,...t){if(u(this,as,"f"))return;e==="end"&&(u(this,ss,"m",Ro).call(this),w(this,as,!0,"f"),u(this,vs,"f").call(this));let r=u(this,Ae,"f")[e];if(r&&(u(this,Ae,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,Bt,"f")&&!r?.length&&Promise.reject(n),u(this,ns,"f").call(this,n),u(this,is,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,Bt,"f")&&!r?.length&&Promise.reject(n),u(this,ns,"f").call(this,n),u(this,is,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Es=new WeakMap,Os=new WeakMap,ns=new WeakMap,os=new WeakMap,vs=new WeakMap,is=new WeakMap,Ae=new WeakMap,Ts=new WeakMap,as=new WeakMap,js=new WeakMap,Fs=new WeakMap,Bt=new WeakMap,ss=new WeakSet,Ro=function(){for(let{signal:e,listener:t}of u(this,Ts,"f").splice(0))e.removeEventListener("abort",t)},_n=function(e){if(w(this,js,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new L),e instanceof L)return w(this,Fs,!0,"f"),this._emit("abort",e);if(e instanceof _)return this._emit("error",e);if(e instanceof Error){let t=new _(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new _(String(e)))};function So(s){return typeof s.parse=="function"}var Z,yn,Ns,gn,An,bn,Co,$o,vi=10;function Ti(s){for(let e of s.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${He()}`)}function ji(s){if(!ge(s))return s;let e={role:"assistant"};return s.audio!=null&&(e.audio={id:s.audio.id}),s.content!==void 0&&(e.content=s.content),s.function_call!=null&&(e.function_call=s.function_call),s.name!==void 0&&(e.name=s.name),s.refusal!=null&&(e.refusal=s.refusal),s.tool_calls!==void 0&&(e.tool_calls=s.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 Ut=class extends Ee{constructor(){super(...arguments),Z.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Ti(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){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),rs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ge(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new _("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,Z,"m",yn).call(this)}async finalMessage(){return await this.done(),u(this,Z,"m",Ns).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,Z,"m",gn).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,Z,"m",An).call(this)}async totalUsage(){return await this.done(),u(this,Z,"m",bn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=u(this,Z,"m",Ns).call(this);t&&this._emit("finalMessage",t);let r=u(this,Z,"m",yn).call(this);r&&this._emit("finalContent",r);let n=u(this,Z,"m",gn).call(this);n&&this._emit("finalFunctionToolCall",n);let o=u(this,Z,"m",An).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",u(this,Z,"m",bn).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),u(this,Z,"m",Co).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ts(n,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r,n){let o="tool",{tool_choice:a="auto",stream:l,toolContext:h,...d}=t,f=h,y=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:m=vi,afterCompletion:b}=n||{},P=t.tools.map(g=>{if(Ge(g)){if(!g.$callback)throw new _("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:g.$callback,name:g.function.name,description:g.function.description||"",parameters:g.function.parameters,parse:g.$parseRaw,strict:!0}}}return g}),A={};for(let g of P)g.type==="function"&&(A[g.function.name||g.function.function.name]=g.function);let I="tools"in t?P.map(g=>g.type==="function"?{type:"function",function:{name:g.function.name||g.function.function.name,parameters:g.function.parameters,description:g.function.description,strict:g.function.strict}}:g):void 0;for(let g of t.messages)this._addMessage(g,!1);let O=async g=>{if(g.type!=="function")return{message:void 0,functionCalled:!1};let E=g.id,{name:S,arguments:j}=g.function,k=A[S];if(!k){let F=`Invalid tool_call: ${JSON.stringify(S)}. Available options are: ${Object.keys(A).map(v=>JSON.stringify(v)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:E,content:F},functionCalled:!1}}if(y&&y!==S){let F=`Invalid tool_call: ${JSON.stringify(S)}. ${JSON.stringify(y)} requested. Please try again`;return{message:{role:o,tool_call_id:E,content:F},functionCalled:!1}}let K;if(So(k)){let F;try{F=await k.parse(j)}catch(v){let V=v instanceof Error?v.message:String(v);return{message:{role:o,tool_call_id:E,content:V},functionCalled:!1}}K=await k.function(F,r,f)}else K=await k.function(j,r,f);let T=u(this,Z,"m",$o).call(this,K);return{message:{role:o,tool_call_id:E,content:T},functionCalled:!0}};for(let g=0;g<m;++g){let E=await this._createChatCompletion(e,{...d,tool_choice:a,tools:I,messages:this.messages.map(ji)},n),S=E.choices[0]?.message;if(!S)throw new _("missing message in ChatCompletion response");if(!S.tool_calls?.length){await b?.(E,r);return}if(y||t.parallel_tool_calls===!1)for(let j of S.tool_calls){let k=await O(j);if(k.message&&this._addMessage(k.message),y&&k.functionCalled){await b?.(E,r);return}}else{let j=await Promise.allSettled(S.tool_calls.map(O));for(let k of j)if(k.status==="rejected")throw k.reason;for(let k of j)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message)}await b?.(E,r)}}};Z=new WeakSet,yn=function(){return u(this,Z,"m",Ns).call(this).content??null},Ns=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(ge(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new _("stream ended without producing a ChatCompletionMessage with role=assistant")},gn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(ge(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let n=t.tool_calls[r];if(n?.type==="function")return n.function}}},An=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(rs(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},bn=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},Co=function(e){if(e.n!=null&&e.n>1)throw new _("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},$o=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var cs=class s extends Ut{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),ge(e)&&e.content&&this._emit("content",e.content)}};var q={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},wn=class extends Error{},In=class extends Error{};function Fi(s,e=q.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return Ni(s.trim(),e)}var Ni=(s,e)=>{let t=s.length,r=0,n=m=>{throw new wn(`${m} at position ${r}`)},o=m=>{throw new In(`${m} at position ${r}`)},a=()=>(y(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?h():s[r]==="["?d():s.substring(r,r+4)==="null"||q.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||q.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||q.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||q.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||q.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||q.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):f()),l=()=>{let m=r,b=!1;for(r++;r<t&&(s[r]!=='"'||b&&s[r-1]==="\\");)b=s[r]==="\\"?!b:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(m,++r-Number(b)))}catch(P){o(String(P))}else if(q.STR&e)try{return JSON.parse(s.substring(m,r-Number(b))+'"')}catch{return JSON.parse(s.substring(m,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},h=()=>{r++,y();let m={};try{for(;s[r]!=="}";){if(y(),r>=t&&q.OBJ&e)return m;let b=l();y(),r++;try{let P=a();Object.defineProperty(m,b,{value:P,writable:!0,enumerable:!0,configurable:!0})}catch(P){if(q.OBJ&e)return m;throw P}y(),s[r]===","&&r++}}catch{if(q.OBJ&e)return m;n("Expected '}' at end of object")}return r++,m},d=()=>{r++;let m=[];try{for(;s[r]!=="]";)m.push(a()),y(),s[r]===","&&r++}catch{if(q.ARR&e)return m;n("Expected ']' at end of array")}return r++,m},f=()=>{if(r===0){s==="-"&&q.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(b){if(q.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(b))}}let m=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(q.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(m,r))}catch{s.substring(m,r)==="-"&&q.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(m,s.lastIndexOf("e")))}catch(P){o(String(P))}}},y=()=>{for(;r<t&&`
18
- \r `.includes(s[r]);)r++};return a()},Pn=s=>Fi(s,q.ALL^q.NUM);var U,be,Oe,zt,ce,xn,Ks,Rn,Sn,Cn,us,$n,ko,En="chat.completion.chunk.message:";function Eo(s,e,t){let r={type:"message",message:e,...t?{tool_call_ids:t}:{}};return{id:s.id,choices:[],created:s.created,model:s.model,object:`${En}${JSON.stringify(r)}`}}function Ki(s){return"type"in s&&s.type==="message"&&"message"in s||"object"in s&&typeof s.object=="string"&&s.object.startsWith(En)}function Li(s){return"type"in s?s:JSON.parse(s.object.slice(En.length))}var Qe=class s extends Ut{constructor(e){super(),U.add(this),be.set(this,void 0),Oe.set(this,void 0),zt.set(this,void 0),ce.set(this,void 0),w(this,be,e,"f"),w(this,Oe,new Set,"f"),w(this,zt,[],"f")}get currentChatCompletionSnapshot(){return u(this,ce,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion,this._listenForAbort(r?.signal),u(this,U,"m",xn).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)u(this,U,"m",Rn).call(this,o);if(n.controller.signal?.aborted)throw new L;return this._addChatCompletion(u(this,U,"m",us).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,U,"m",xn).call(this),this._connected();let r=ee.fromReadableStream(e,this.controller),n;for await(let a of r){if(Ki(a)){let h=Li(a);if(u(this,ce,"f")){let d=u(this,ce,"f").choices[0]?.message.tool_calls;for(let[f,y]of h.tool_call_ids?.entries()??[]){let m=d?.[f];m&&y&&(m.id=y)}this._addChatCompletion(u(this,U,"m",us).call(this)),n=void 0}this._addMessage(h.message);continue}let l=a;n&&l.id&&n!==l.id&&this._addChatCompletion(u(this,U,"m",us).call(this)),u(this,U,"m",Rn).call(this,l),l.id&&(n=l.id)}if(r.controller.signal?.aborted)throw new L;if(u(this,ce,"f"))return this._addChatCompletion(u(this,U,"m",us).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new _("request ended without sending any chunks")}[(be=new WeakMap,Oe=new WeakMap,zt=new WeakMap,ce=new WeakMap,U=new WeakSet,xn=function(){this.ended||(w(this,Oe,new Set,"f"),w(this,ce,void 0,"f"))},Ks=function(t){let r=u(this,zt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},u(this,zt,"f")[t.index]=r,r)},Rn=function(t){if(this.ended)return;let r=u(this,U,"m",ko).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index],{delta:a}=n;a?.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",a.content,o.message.content),this._emit("content.delta",{delta:a.content,snapshot:o.message.content,parsed:o.message.parsed})),a?.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:a.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let l=u(this,U,"m",Ks).call(this,o);o.finish_reason&&(u(this,U,"m",Cn).call(this,o),l.current_tool_call_index!=null&&u(this,U,"m",Sn).call(this,o,l.current_tool_call_index));for(let h of a?.tool_calls??[])l.current_tool_call_index!==h.index&&(u(this,U,"m",Cn).call(this,o),l.current_tool_call_index!=null&&u(this,U,"m",Sn).call(this,o,l.current_tool_call_index)),l.current_tool_call_index=h.index;for(let h of a?.tool_calls??[]){let d=o.message.tool_calls?.[h.index];d?.type&&(d?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:d.function?.name,index:h.index,arguments:d.function.arguments,parsed_arguments:d.function.parsed_arguments,arguments_delta:h.function?.arguments??""}):(d?.type,void 0))}}},Sn=function(t,r){if(u(this,U,"m",Ks).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let a=u(this,be,"f")?.tools?.find(l=>Zr(l)&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ge(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Cn=function(t){let r=u(this,U,"m",Ks).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=u(this,U,"m",$n).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},us=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=u(this,ce,"f");if(!t)throw new _("request ended without sending any chunks");let r=u(this,Oe,"f");return w(this,Oe,new Set,"f"),w(this,ce,void 0,"f"),w(this,zt,[],"f"),Mi(t,u(this,be,"f"),r)},$n=function(){let t=u(this,be,"f")?.response_format;return es(t)?t:null},ko=function(t){var r,n,o,a,l;let h=u(this,ce,"f"),{choices:d,...f}=t;h?t.id&&Object.assign(h,f):h=w(this,ce,{...f,choices:[]},"f");for(let{delta:y,finish_reason:m,index:b,logprobs:P=null,...A}of t.choices){let I=h.choices[b];if(I||(I=h.choices[b]={finish_reason:m,index:b,message:{},logprobs:P,...A}),P)if(!I.logprobs)I.logprobs=Object.assign({},P);else{let{content:T,refusal:F,...v}=P;Object.assign(I.logprobs,v),T&&((r=I.logprobs).content??(r.content=[]),I.logprobs.content.push(...T)),F&&((n=I.logprobs).refusal??(n.refusal=[]),I.logprobs.refusal.push(...F))}if(m&&(I.finish_reason=m,u(this,be,"f")&&mn(u(this,be,"f")))){if(m==="length")throw new vt;if(m==="content_filter")throw new Tt}if(Object.assign(I,A),!y)continue;u(this,Oe,"f").delete(b);let{audio:O,content:g,refusal:E,function_call:S,role:j,tool_calls:k,...K}=y;if(Object.assign(I.message,K),O?.expires_at!=null&&O.id==null&&O.data==null&&O.transcript==null&&g==null&&E==null&&S==null&&j==null&&k==null&&Object.keys(K).length===0&&u(this,Oe,"f").add(b),E&&(I.message.refusal=(I.message.refusal||"")+E),j&&(I.message.role=j),O){let T=(o=I.message).audio??(o.audio={});O.id!=null&&(T.id=O.id),O.data!=null&&(T.data=(T.data??"")+O.data),O.transcript!=null&&(T.transcript=(T.transcript??"")+O.transcript),O.expires_at!=null&&(T.expires_at=O.expires_at)}if(S&&(I.message.function_call?(S.name&&(I.message.function_call.name=S.name),S.arguments&&((a=I.message.function_call).arguments??(a.arguments=""),I.message.function_call.arguments+=S.arguments)):I.message.function_call=S),g&&(I.message.content=(I.message.content||"")+g,!I.message.refusal&&u(this,U,"m",$n).call(this)&&(I.message.parsed=I.message.content.trim()?Pn(I.message.content):null)),k){I.message.tool_calls||(I.message.tool_calls=[]);for(let{index:T,id:F,type:v,function:V,...Pt}of k){let X=(l=I.message.tool_calls)[T]??(l[T]={});Object.assign(X,Pt),F&&(X.id=F),v&&(X.type=v),V&&(X.function??(X.function={name:V.name??"",arguments:""})),V?.name&&(X.function.name=V.name),V?.arguments&&(X.function.arguments+=V.arguments,Io(u(this,be,"f"),X)&&(X.function.parsed_arguments=Pn(X.function.arguments)))}}}return h},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Mi(s,e,t){let{id:r,choices:n,created:o,model:a,system_fingerprint:l,...h}=s,d={...h,id:r,choices:n.map(({message:f,finish_reason:y,index:m,logprobs:b,...P})=>{let{content:A=null,function_call:I,tool_calls:O,audio:g,...E}=f,S=y??(t.has(m)&&Bi(g)?"stop":null);if(!S)throw new _(`missing finish_reason for choice ${m}`);let j=g?{audio:g}:{},k=f.role;if(!k)throw new _(`missing role for choice ${m}`);if(I){let{arguments:K,name:T}=I;if(K==null)throw new _(`missing function_call.arguments for choice ${m}`);if(!T)throw new _(`missing function_call.name for choice ${m}`);return{...P,message:{...j,content:A,function_call:{arguments:K,name:T},role:k,refusal:f.refusal??null},finish_reason:S,index:m,logprobs:b}}return O?{...P,index:m,finish_reason:S,logprobs:b,message:{...E,...j,role:k,content:A,refusal:f.refusal??null,tool_calls:O.map((K,T)=>{let{function:F,type:v,id:V,...Pt}=K,{arguments:X,name:ms,..._s}=F||{};if(v==null)throw new _(`missing choices[${m}].tool_calls[${T}].type
19
- ${kn(s)}`);if(ms==null)throw new _(`missing choices[${m}].tool_calls[${T}].function.name
20
- ${kn(s)}`);if(X==null)throw new _(`missing choices[${m}].tool_calls[${T}].function.arguments
21
- ${kn(s)}`);return{...Pt,id:V||`call_${He()}`,type:v,function:{..._s,name:ms,arguments:X}}})}}:{...P,message:{...E,...j,content:A,role:k,refusal:f.refusal??null},finish_reason:S,index:m,logprobs:b}}),created:o,model:a,object:"chat.completion",...l?{system_fingerprint:l}:{}};return wo(d,e)}function Bi(s){return s?.id!=null&&s.data!=null&&s.transcript!=null&&s.expires_at!=null}function kn(s){return JSON.stringify(s)}var ls=class s extends Qe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e=[],t=[],r=!1,n,o,a=d=>{let f=t.shift();f?f.resolve(d):e.push(d)};this.on("chunk",d=>{n=d,a(d)}),this.on("message",d=>{if(ge(d)){o=d.tool_calls?.map(f=>f.id);return}if(rs(d)){if(!n)throw new _("cannot serialize a tool message before receiving any chunks");a(Eo(n,d,o))}}),this.on("end",()=>{r=!0;for(let d of t)d.resolve(void 0);t.length=0}),this.on("abort",d=>{r=!0;for(let f of t)f.reject(d);t.length=0}),this.on("error",d=>{r=!0;for(let f of t)f.reject(d);t.length=0});let l=()=>({next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((f,y)=>t.push({resolve:f,reject:y})).then(f=>f?{value:f,done:!1}:{value:void 0,done:!0});let d=e.shift();return d?{value:d,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})});return new ee(l,this.controller).toReadableStream()}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}};var we=class extends c{constructor(){super(...arguments),this.messages=new Xe(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(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/chat/completions/${e}`,{body:t,...r,__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(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return xo(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ts(r,e))}runTools(e,t){return e.stream?ls.runTools(this._client,e,t):cs.runTools(this._client,e,t)}stream(e,t){return Qe.createChatCompletion(this._client,e,t)}};we.Messages=Xe;var ve=class extends c{constructor(){super(...arguments),this.completions=new we(this._client)}};ve.Completions=we;var Dt=class extends c{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/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(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends c{list(e={},t){return this._client.getAPIList("/organization/audit_logs",$,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends c{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",$,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",Y,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",Y,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends c{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 Jt=class extends c{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",$,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends c{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends c{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",$,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends c{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 Qt=class extends c{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 Yt=class extends c{create(e,t,r){return this._client.post(i`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends c{create(e,t,r){return this._client.post(i`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/users`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Te=class extends c{constructor(){super(...arguments),this.users=new Zt(this._client),this.roles=new Yt(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Te.Users=Zt;Te.Roles=Yt;var er=class extends c{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/api_keys`,$,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tr=class extends c{list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,$,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/activate`,Y,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/deactivate`,Y,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends c{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var sr=class extends c{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends c{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var or=class extends c{listRateLimits(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,$,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var ir=class extends c{create(e,t,r){return this._client.post(i`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/projects/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ar=class extends c{create(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/spend_alerts`,$,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var cr=class extends c{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_limit`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}};var ur=class extends c{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/groups/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,group_id:o}=t;return this._client.get(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/groups/${e}/roles`,B,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ye=class extends c{constructor(){super(...arguments),this.roles=new ur(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(i`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/groups`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ye.Roles=ur;var lr=class extends c{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}/api_keys`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var Ze=class extends c{constructor(){super(...arguments),this.apiKeys=new lr(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/service_accounts`,$,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ze.APIKeys=lr;var dr=class extends c{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/users/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,user_id:o}=t;return this._client.get(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/users/${e}/roles`,B,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var et=class extends c{constructor(){super(...arguments),this.roles=new dr(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/users`,$,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};et.Roles=dr;var H=class extends c{constructor(){super(...arguments),this.users=new et(this._client),this.serviceAccounts=new Ze(this._client),this.apiKeys=new er(this._client),this.rateLimits=new or(this._client),this.modelPermissions=new nr(this._client),this.hostedToolPermissions=new sr(this._client),this.groups=new Ye(this._client),this.roles=new ir(this._client),this.dataRetention=new rr(this._client),this.spendLimit=new cr(this._client),this.spendAlerts=new ar(this._client),this.certificates=new tr(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",$,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};H.Users=et;H.ServiceAccounts=Ze;H.APIKeys=er;H.RateLimits=or;H.ModelPermissions=nr;H.HostedToolPermissions=sr;H.Groups=Ye;H.Roles=ir;H.DataRetention=rr;H.SpendLimit=cr;H.SpendAlerts=ar;H.Certificates=tr;var pr=class extends c{create(e,t,r){return this._client.post(i`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/users/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tt=class extends c{constructor(){super(...arguments),this.roles=new pr(this._client)}retrieve(e,t){return this._client.get(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",$,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};tt.Roles=pr;var W=class extends c{constructor(){super(...arguments),this.auditLogs=new qt(this._client),this.adminAPIKeys=new Dt(this._client),this.usage=new Qt(this._client),this.invites=new Jt(this._client),this.users=new tt(this._client),this.groups=new Te(this._client),this.roles=new Vt(this._client),this.dataRetention=new Wt(this._client),this.spendLimit=new Gt(this._client),this.spendAlerts=new Xt(this._client),this.certificates=new Ht(this._client),this.projects=new H(this._client)}};W.AuditLogs=qt;W.AdminAPIKeys=Dt;W.Usage=Qt;W.Invites=Jt;W.Users=tt;W.Groups=Te;W.Roles=Vt;W.DataRetention=Wt;W.SpendLimit=Gt;W.SpendAlerts=Xt;W.Certificates=Ht;W.Projects=H;var je=class extends c{constructor(){super(...arguments),this.organization=new W(this._client)}};je.Organization=W;var hr=class extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:p([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var fr=class extends c{create(e,t){return this._client.post("/audio/transcriptions",D({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var mr=class extends c{create(e,t){return this._client.post("/audio/translations",D({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var me=class extends c{constructor(){super(...arguments),this.transcriptions=new fr(this._client),this.translations=new mr(this._client),this.speech=new hr(this._client)}};me.Transcriptions=fr;me.Translations=mr;me.Speech=hr;var rt=class extends c{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/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(i`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var _r=class extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/assistants/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",R,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var yr=class extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var gr=class extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Fe=class extends c{constructor(){super(...arguments),this.sessions=new yr(this._client),this.transcriptionSessions=new gr(this._client)}};Fe.Sessions=yr;Fe.TranscriptionSessions=gr;var Ar=class extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/chatkit/sessions/${e}/cancel`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var br=class extends c{retrieve(e,t){return this._client.get(i`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",$,{query:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,$,{query:t,...r,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Ne=class extends c{constructor(){super(...arguments),this.sessions=new Ar(this._client),this.threads=new br(this._client)}};Ne.Sessions=Ar;Ne.Threads=br;var wr=class extends c{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(i`/responses/${e}/input_items?beta=true`,R,{query:o,...r,headers:p([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var Ir=class extends c{count(e={},t){let{betas:r,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:p([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var Ke=class extends c{constructor(){super(...arguments),this.inputItems=new wr(this._client),this.inputTokens=new Ir(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:p([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},r){let{betas:n,...o}=t??{};return this._client.get(i`/responses/${e}?beta=true`,{query:o,...r,headers:p([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(i`/responses/${e}?beta=true`,{...r,headers:p([{Accept:"*/*",...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},r){let{betas:n}=t??{};return this._client.post(i`/responses/${e}/cancel?beta=true`,{...r,headers:p([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:r,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:p([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};Ke.InputItems=wr;Ke.InputTokens=Ir;var Pr=class extends c{create(e,t,r){return this._client.post(i`/threads/${e}/messages`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/messages/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/messages`,R,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(i`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var xr=class extends c{retrieve(e,t,r){let{thread_id:n,run_id:o,...a}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:a,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(i`/threads/${n}/runs/${e}/steps`,R,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Oo=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var J=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()||void 0};var G,nt,On,_e,Ls,ue,ot,Rr,st,Us,oe,Ms,Bs,hs,ds,ps,vo,To,jo,Fo,No,Ko,Lo,Ie=class extends Ee{constructor(){super(...arguments),G.add(this),On.set(this,[]),_e.set(this,{}),Ls.set(this,{}),ue.set(this,void 0),ot.set(this,void 0),Rr.set(this,void 0),st.set(this,void 0),Us.set(this,void 0),oe.set(this,void 0),Ms.set(this,void 0),Bs.set(this,void 0),hs.set(this,void 0)}[(On=new WeakMap,_e=new WeakMap,Ls=new WeakMap,ue=new WeakMap,ot=new WeakMap,Rr=new WeakMap,st=new WeakMap,Us=new WeakMap,oe=new WeakMap,Ms=new WeakMap,Bs=new WeakMap,hs=new WeakMap,G=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=structuredClone(n),a=t.shift();a?a.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new nt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=ee.fromReadableStream(e,this.controller);for await(let n of r)u(this,G,"m",ds).call(this,n);if(r.controller.signal?.aborted)throw new L;return this._addRun(u(this,G,"m",ps).call(this))}toReadableStream(){return new ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new nt;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)u(this,G,"m",ds).call(this,l);if(a.controller.signal?.aborted)throw new L;return this._addRun(u(this,G,"m",ps).call(this))}static createThreadAssistantStream(e,t,r){let n=new nt;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new nt;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return u(this,Ms,"f")}currentRun(){return u(this,Bs,"f")}currentMessageSnapshot(){return u(this,ue,"f")}currentRunStepSnapshot(){return u(this,hs,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,_e,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,Ls,"f"))}async finalRun(){if(await this.done(),!u(this,ot,"f"))throw Error("Final run was not received.");return u(this,ot,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)u(this,G,"m",ds).call(this,a);if(o.controller.signal?.aborted)throw new L;return this._addRun(u(this,G,"m",ps).call(this))}async _createAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},a=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)u(this,G,"m",ds).call(this,l);if(a.controller.signal?.aborted)throw new L;return this._addRun(u(this,G,"m",ps).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(jt(o)&&jt(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...n);continue}for(let a of n){if(!jt(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let h=o[l];h==null?o[l]=a:o[l]=this.accumulateDelta(h,a)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};nt=Ie,ds=function(e){if(!this.ended)switch(w(this,Ms,e,"f"),u(this,G,"m",jo).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":u(this,G,"m",Lo).call(this,e);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":u(this,G,"m",To).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":u(this,G,"m",vo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ps=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");if(!u(this,ot,"f"))throw Error("Final run has not been received");return u(this,ot,"f")},vo=function(e){let[t,r]=u(this,G,"m",No).call(this,e,u(this,ue,"f"));w(this,ue,t,"f"),u(this,Ls,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=t.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=u(this,Rr,"f")){if(u(this,st,"f"))switch(u(this,st,"f").type){case"text":this._emit("textDone",u(this,st,"f").text,u(this,ue,"f"));break;case"image_file":this._emit("imageFileDone",u(this,st,"f").image_file,u(this,ue,"f"));break}w(this,Rr,n.index,"f")}w(this,st,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,Rr,"f")!==void 0){let n=e.data.content[u(this,Rr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,u(this,ue,"f"));break;case"text":this._emit("textDone",n.text,u(this,ue,"f"));break}}u(this,ue,"f")&&this._emit("messageDone",e.data),w(this,ue,void 0,"f")}},To=function(e){let t=u(this,G,"m",Fo).call(this,e);switch(w(this,hs,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==u(this,Us,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(u(this,oe,"f")&&this._emit("toolCallDone",u(this,oe,"f")),w(this,Us,o.index,"f"),w(this,oe,t.step_details.tool_calls[o.index],"f"),u(this,oe,"f")&&this._emit("toolCallCreated",u(this,oe,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,hs,void 0,"f"),e.data.step_details.type=="tool_calls"&&u(this,oe,"f")&&(this._emit("toolCallDone",u(this,oe,"f")),w(this,oe,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},jo=function(e){u(this,On,"f").push(e),this._emit("event",e)},Fo=function(e){switch(e.event){case"thread.run.step.created":return u(this,_e,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=u(this,_e,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=nt.accumulateDelta(t,r.delta);u(this,_e,"f")[e.data.id]=n}return u(this,_e,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":u(this,_e,"f")[e.data.id]=e.data;break}if(u(this,_e,"f")[e.data.id])return u(this,_e,"f")[e.data.id];throw new Error("No snapshot available")},No=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=u(this,G,"m",Ko).call(this,o,a)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ko=function(e,t){return nt.accumulateDelta(t,e)},Lo=function(e){switch(w(this,Bs,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":w(this,ot,e.data,"f"),u(this,oe,"f")&&(this._emit("toolCallDone",u(this,oe,"f")),w(this,oe,void 0,"f"));break;case"thread.run.cancelling":break}};var it=class extends c{constructor(){super(...arguments),this.steps=new xr(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/runs/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/runs`,R,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(i`/threads/${n}/runs/${e}/cancel`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return Ie.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=a.headers.get("openai-poll-after-ms");if(h){let d=parseInt(h);isNaN(d)||(l=d)}}await he(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return Ie.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return Ie.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};it.Steps=xr;var Le=class extends c{constructor(){super(...arguments),this.runs=new it(this._client),this.messages=new Pr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/threads/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Ie.createThreadAssistantStream(e,this._client.beta.threads,t)}};Le.Runs=it;Le.Messages=Pr;var ie=class extends c{constructor(){super(...arguments),this.realtime=new Fe(this._client),this.responses=new Ke(this._client),this.chatkit=new Ne(this._client),this.assistants=new _r(this._client),this.threads=new Le(this._client)}};ie.Realtime=Fe;ie.Responses=Ke;ie.ChatKit=Ne;ie.Assistants=_r;ie.Threads=Le;var at=class extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Sr=class extends c{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ct=class extends c{constructor(){super(...arguments),this.content=new Sr(this._client)}create(e,t,r){return this._client.post(i`/containers/${e}/files`,ke({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/containers/${e}/files`,R,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(i`/containers/${n}/files/${e}`,{...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};ct.Content=Sr;var Me=class extends c{constructor(){super(...arguments),this.files=new ct(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/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(i`/containers/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Me.Files=ct;var ut=class extends c{create(e,t){return this._client.post("/content_provenance_checks",D({body:e,...t,__security:{bearerAuth:!0}},this._client))}};var Cr=class extends c{create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/conversations/${e}/items`,{query:{include:n},body:o,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(i`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/conversations/${e}/items`,$,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(i`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var Be=class extends c{constructor(){super(...arguments),this.items=new Cr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Be.Items=Cr;var lt=class extends c{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&M(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t,__security:{bearerAuth:!0}});return r?o:(M(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{let h=l.embedding;l.embedding=Oo(h)}),a)))}};var $r=class extends c{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(i`/evals/${n}/runs/${o}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(i`/evals/${n}/runs/${e}/output_items`,R,{query:o,...r,__security:{bearerAuth:!0}})}};var dt=class extends c{constructor(){super(...arguments),this.outputItems=new $r(this._client)}create(e,t,r){return this._client.post(i`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/evals/${e}/runs`,R,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};dt.OutputItems=$r;var Ue=class extends c{constructor(){super(...arguments),this.runs=new dt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/evals/${e}`,{body:t,...r,__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(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Ue.Runs=dt;var pt=class extends c{create(e,t){return this._client.post("/files",D({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/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(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(i`/files/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await he(t),a=await this.retrieve(e),Date.now()-o>r)throw new Ce({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}};var kr=class extends c{};var Er=class extends c{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 ht=class extends c{constructor(){super(...arguments),this.graders=new Er(this._client)}};ht.Graders=Er;var Or=class extends c{create(e,t,r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,Y,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,$,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ft=class extends c{constructor(){super(...arguments),this.permissions=new Or(this._client)}};ft.Permissions=Or;var vr=class extends c{list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,R,{query:t,...r,__security:{bearerAuth:!0}})}};var mt=class extends c{constructor(){super(...arguments),this.checkpoints=new vr(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(i`/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(i`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/events`,R,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};mt.Checkpoints=vr;var le=class extends c{constructor(){super(...arguments),this.methods=new kr(this._client),this.jobs=new mt(this._client),this.checkpoints=new ft(this._client),this.alpha=new ht(this._client)}};le.Methods=kr;le.Jobs=mt;le.Checkpoints=ft;le.Alpha=ht;var Tr=class extends c{};var ze=class extends c{constructor(){super(...arguments),this.graderModels=new Tr(this._client)}};ze.GraderModels=Tr;var _t=class extends c{createVariation(e,t){return this._client.post("/images/variations",D({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",D({body:e,...t,stream:e.stream??!1,__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 yt=class extends c{retrieve(e,t){return this._client.get(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Y,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var gt=class extends c{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var jr=class extends c{accept(e,t,r){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i`/realtime/calls/${e}/hangup`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Fr=class extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Pe=class extends c{constructor(){super(...arguments),this.clientSecrets=new Fr(this._client),this.calls=new jr(this._client)}};Pe.ClientSecrets=Fr;Pe.Calls=jr;function Mo(s,e){if(!e||!Ya(e)){let t={...s,output_parsed:null,output:s.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)};return Uo(s,t)&&te(t),t}return vn(s,e)}function vn(s,e){let t=!s.status||s.status==="completed",r=s.output.map(o=>{if(o.type==="function_call")return t?ec(e,o):{...o,parsed_arguments:null};if(o.type==="message"){let a=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?Qa(e,l.text):null}:l);return{...o,content:a}}return o}),n=Object.assign({},s,{output:r});return Uo(s,n)&&te(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function Qa(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Ya(s){return es(s.text?.format)?!0:Array.isArray(s.tools)&&s.tools.some(e=>Bo(e)||e.type==="function"&&e.strict===!0)}function Bo(s){return s?.$brand==="auto-parseable-tool"}function Za(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function ec(s,e){let t=Za(s.tools??[],e.name);return{...e,...e,parsed_arguments:Bo(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Uo(s,e){return!Object.getOwnPropertyDescriptor(s,"output_text")||e.output_text==null}function te(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}function Do(s,e){if(!e){if(s.type!=="response.created")throw new _(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return zo(s.response)}switch(s.type){case"response.output_item.added":{e.output.push(structuredClone(s.item)),s.item.type==="message"&&te(e);break}case"response.output_item.done":{C(e,s.output_index),e.output[s.output_index]=structuredClone(s.item),s.item.type==="message"&&te(e);break}case"response.content_part.added":{let t=C(e,s.output_index),r=t.type,n=s.part;r==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&te(e)):r==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{let t=C(e,s.output_index),r=s.part;if(t.type==="message"&&r.type!=="reasoning_text")ae(t.content,s.content_index),t.content[s.content_index]=structuredClone(r),r.type==="output_text"&&te(e);else if(t.type==="reasoning"&&r.type==="reasoning_text"){let n=t.content;if(!n)throw new _(`missing content at index ${s.content_index}`);ae(n,s.content_index),n[s.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let t=C(e,s.output_index);if(t.type==="message"){let r=ae(t.content,s.content_index);if(r.type!=="output_text")throw new _(`expected content to be 'output_text', got ${r.type}`);r.text+=s.delta,e.output_text+=s.delta}break}case"response.output_text.done":{let t=C(e,s.output_index);if(t.type==="message"){let r=ae(t.content,s.content_index);if(r.type!=="output_text")throw new _(`expected content to be 'output_text', got ${r.type}`);r.text=s.text,te(e)}break}case"response.output_text.annotation.added":{let t=C(e,s.output_index);if(t.type==="message"){let r=ae(t.content,s.content_index);if(r.type!=="output_text")throw new _(`expected content to be 'output_text', got ${r.type}`);r.annotations[s.annotation_index]=structuredClone(s.annotation)}break}case"response.refusal.delta":{let t=C(e,s.output_index);if(t.type==="message"){let r=ae(t.content,s.content_index);if(r.type!=="refusal")throw new _(`expected content to be 'refusal', got ${r.type}`);r.refusal+=s.delta}break}case"response.refusal.done":{let t=C(e,s.output_index);if(t.type==="message"){let r=ae(t.content,s.content_index);if(r.type!=="refusal")throw new _(`expected content to be 'refusal', got ${r.type}`);r.refusal=s.refusal}break}case"response.function_call_arguments.delta":{let t=C(e,s.output_index);t.type==="function_call"&&(t.arguments+=s.delta);break}case"response.function_call_arguments.done":{let t=C(e,s.output_index);t.type==="function_call"&&(t.arguments=s.arguments);break}case"response.reasoning_text.delta":{let t=C(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new _(`missing content at index ${s.content_index}`);let r=ae(t.content,s.content_index);if(r.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=s.delta}break}case"response.reasoning_text.done":{let t=C(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new _(`missing content at index ${s.content_index}`);let r=ae(t.content,s.content_index);if(r.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${r.type}`);r.text=s.text}break}case"response.reasoning_summary_part.added":{let t=C(e,s.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(s.part));break}case"response.reasoning_summary_part.done":{let t=C(e,s.output_index);t.type==="reasoning"&&(ae(t.summary,s.summary_index),t.summary[s.summary_index]=structuredClone(s.part));break}case"response.reasoning_summary_text.delta":{let t=C(e,s.output_index);if(t.type==="reasoning"){let r=ae(t.summary,s.summary_index);r.text+=s.delta}break}case"response.reasoning_summary_text.done":{let t=C(e,s.output_index);if(t.type==="reasoning"){let r=ae(t.summary,s.summary_index);r.text=s.text}break}case"response.custom_tool_call_input.delta":{let t=C(e,s.output_index);t.type==="custom_tool_call"&&(t.input+=s.delta);break}case"response.custom_tool_call_input.done":{let t=C(e,s.output_index);t.type==="custom_tool_call"&&(t.input=s.input);break}case"response.mcp_call_arguments.delta":{let t=C(e,s.output_index);t.type==="mcp_call"&&(t.arguments+=s.delta);break}case"response.mcp_call_arguments.done":{let t=C(e,s.output_index);t.type==="mcp_call"&&(t.arguments=s.arguments);break}case"response.code_interpreter_call_code.delta":{let t=C(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+s.delta);break}case"response.code_interpreter_call_code.done":{let t=C(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=s.code);break}case"response.code_interpreter_call.in_progress":{let t=C(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=C(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=C(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=C(e,s.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=C(e,s.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=C(e,s.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=C(e,s.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=C(e,s.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=C(e,s.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=C(e,s.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=C(e,s.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=C(e,s.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=C(e,s.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=C(e,s.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=C(e,s.output_index);t.type==="mcp_call"&&(t.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=zo(s.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":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":break;default:tc(s)}return e}function zo(s){let e=structuredClone(s);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&te(e),e}function C(s,e){let t=s.output[e];if(!t)throw new _(`missing output at index ${e}`);return t}function ae(s,e){let t=s[e];if(!t)throw new _(`missing content at index ${e}`);return t}function tc(s){throw new _(`Unhandled response stream event: ${JSON.stringify(s)}`)}var De,zs,At,Ds,Tn,jn,Fn,qs=class s extends Ee{constructor(e){super(),De.add(this),zs.set(this,void 0),At.set(this,void 0),Ds.set(this,void 0),w(this,zs,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,r){this._listenForAbort(r?.signal),u(this,De,"m",Tn).call(this);let n,o=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of n)u(this,De,"m",jn).call(this,a,o);if(n.controller.signal?.aborted)throw new L;return u(this,De,"m",Fn).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,De,"m",Tn).call(this),this._connected();let r=ee.fromReadableStream(e,this.controller);for await(let n of r)u(this,De,"m",jn).call(this,n,null);if(r.controller.signal?.aborted)throw new L;return u(this,De,"m",Fn).call(this)}[(zs=new WeakMap,At=new WeakMap,Ds=new WeakMap,De=new WeakSet,Tn=function(){this.ended||w(this,At,void 0,"f")},jn=function(t,r){if(this.ended)return;let n=(a,l)=>{(r==null||l.sequence_number>r)&&this._emit(a,l)},o=Do(t,u(this,At,"f"));switch(w(this,At,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new _(`missing output at index ${t.output_index}`);if(a.type==="message"){let l=a.content[t.content_index];if(!l)throw new _(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new _(`expected content to be 'output_text', got ${l.type}`);n("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new _(`missing output at index ${t.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:n(t.type,t);break}},Fn=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=u(this,At,"f");if(!t)throw new _("request ended without sending any events");w(this,At,void 0,"f");let r=rc(t,u(this,zs,"f"));return w(this,Ds,r,"f"),r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=u(this,Ds,"f");if(!e)throw new _("stream ended without producing a ChatCompletion");return e}};function rc(s,e){return Mo(s,e)}var Nr=class extends c{list(e,t={},r){return this._client.getAPIList(i`/responses/${e}/input_items`,R,{query:t,...r,__security:{bearerAuth:!0}})}};var Kr=class extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var de=class extends c{constructor(){super(...arguments),this.inputItems=new Nr(this._client),this.inputTokens=new Kr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&te(r),r))}retrieve(e,t={},r){return this._client.get(i`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&te(n),n))}delete(e,t){return this._client.delete(i`/responses/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>vn(r,e))}stream(e,t){return qs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(i`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};de.InputItems=Nr;de.InputTokens=Kr;var Lr=class extends c{retrieve(e,t){return this._client.get(i`/skills/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Mr=class extends c{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var bt=class extends c{constructor(){super(...arguments),this.content=new Mr(this._client)}create(e,t={},r){return this._client.post(i`/skills/${e}/versions`,ke({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/skills/${e}/versions`,R,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};bt.Content=Mr;var xe=class extends c{constructor(){super(...arguments),this.content=new Lr(this._client),this.versions=new bt(this._client)}create(e={},t){return this._client.post("/skills",ke({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/skills/${e}`,{body:t,...r,__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(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};xe.Content=Lr;xe.Versions=bt;var Br=class extends c{create(e,t,r){return this._client.post(i`/uploads/${e}/parts`,D({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var qe=class extends c{constructor(){super(...arguments),this.parts=new Br(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post(i`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};qe.Parts=Br;var qo=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var Ur=class extends c{create(e,t,r){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/file_batches/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(i`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(i`/vector_stores/${n}/file_batches/${e}/files`,R,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=a.headers.get("openai-poll-after-ms");if(h){let d=parseInt(h);isNaN(d)||(l=d)}}await he(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,a=Math.min(o,t.length),l=this._client,h=t.values(),d=[...r];async function f(m){for(let b of m){let P=await l.files.create({file:b,purpose:"assistants"},n);d.push(P.id)}}let y=Array(a).fill(h).map(f);return await qo(y),await this.createAndPoll(e,{file_ids:d})}};var zr=class extends c{create(e,t,r){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(i`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/vector_stores/${e}/files`,R,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(i`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),a=o.data;switch(a.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=o.response.headers.get("openai-poll-after-ms");if(h){let d=parseInt(h);isNaN(d)||(l=d)}}await he(l);break;case"failed":case"completed":return a}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(i`/vector_stores/${n}/files/${e}/content`,Y,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Re=class extends c{constructor(){super(...arguments),this.files=new zr(this._client),this.fileBatches=new Ur(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/vector_stores/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",R,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(i`/vector_stores/${e}/search`,Y,{body:t,method:"post",...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};Re.Files=zr;Re.FileBatches=Ur;var wt=class extends c{create(e,t){return this._client.post("/videos",D({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",$,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",D({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(i`/videos/${e}/content`,{query:t,...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",D({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",D({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(i`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post(i`/videos/${e}/remix`,ke({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Dr,Ho,Hs,It=class extends c{constructor(){super(...arguments),Dr.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");u(this,Dr,"m",Ho).call(this,r);let o=p([t]).values,a=u(this,Dr,"m",Hs).call(this,o,"webhook-signature"),l=u(this,Dr,"m",Hs).call(this,o,"webhook-timestamp"),h=u(this,Dr,"m",Hs).call(this,o,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new pe("Invalid webhook timestamp format");let f=Math.floor(Date.now()/1e3);if(f-d>n)throw new pe("Webhook timestamp is too old");if(d>f+n)throw new pe("Webhook timestamp is too new");let y=a.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),m=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),b=h?`${h}.${l}.${e}`:`${l}.${e}`,P=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of y)try{let I=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",P,I,new TextEncoder().encode(b)))return}catch{continue}throw new pe("The given webhook signature does not match the expected signature")}};Dr=new WeakSet,Ho=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")},Hs=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Jo=Symbol.for("openai.node.providerDefinitions.v1"),Vo=globalThis,Xo=Vo[Jo],Go=Xo??new WeakMap;Xo||Object.defineProperty(Vo,Jo,{value:Go});function Qo(s){let e=Go.get(s);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Nn,Kn,fs,Yo,dc="workload-identity-auth",x=class{constructor(e={}){Nn.add(this),fs.set(this,void 0),this.completions=new at(this),this.chat=new ve(this),this.embeddings=new lt(this),this.files=new pt(this),this.images=new _t(this),this.contentProvenanceChecks=new ut(this),this.audio=new me(this),this.moderations=new gt(this),this.models=new yt(this),this.fineTuning=new le(this),this.graders=new ze(this),this.vectorStores=new Re(this),this.webhooks=new It(this),this.beta=new ie(this),this.batches=new rt(this),this.uploads=new qe(this),this.admin=new je(this),this.responses=new de(this),this.realtime=new Pe(this),this.conversations=new Be(this),this.evals=new Ue(this),this.containers=new Me(this),this.skills=new xe(this),this.videos=new wt(this);let t=e.provider;if(t){let A=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(I=>e[I]!=null);if(A.length)throw new _(`The \`provider\` option cannot be used with ${A.map(I=>`\`${I}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=t?null:J("OPENAI_BASE_URL"),apiKey:n=t?null:J("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:J("OPENAI_ADMIN_KEY")??null,organization:a=t?null:J("OPENAI_ORG_ID")??null,project:l=t?null:J("OPENAI_PROJECT_ID")??null,webhookSecret:h=J("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:d,...f}=e,y=t?Qo(t):void 0,m={apiKey:n,adminAPIKey:o,organization:a,project:l,webhookSecret:h,workloadIdentity:d,provider:t,...f,baseURL:y?.baseURL??(r||"https://api.openai.com/v1")};if(n&&d)throw new _("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!y&&!n&&!o&&!d)throw new _("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!m.dangerouslyAllowBrowser&&Jn())throw new _(`It looks like you're running in a browser-like environment.
22
-
23
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
24
- If you understand the risks and have appropriate mitigations in place,
25
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
26
-
27
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
28
-
29
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
30
- `);this.baseURL=m.baseURL,this.timeout=m.timeout??Kn.DEFAULT_TIMEOUT,this.logger=m.logger??console;let b="warn";this.logLevel=b,this.logLevel=sn(m.logLevel,"ClientOptions.logLevel",this)??sn(J("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??b,this.fetchOptions=m.fetchOptions,this.maxRetries=m.maxRetries??2,this.fetch=m.fetch??gs(),w(this,fs,Gn,"f");let P=t?void 0:J("OPENAI_CUSTOM_HEADERS");if(P){let A={};for(let I of P.split(`
31
- `)){let O=I.indexOf(":");O>=0&&(A[I.substring(0,O).trim()]=I.substring(O+1).trim())}m.defaultHeaders=p([A,m.defaultHeaders])}this._options=m,this._provider=y,d&&(this._workloadIdentityAuth=new Rs(d,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=a,this.project=l,this.webhookSecret=h}withOptions(e){let t=this._options.provider,r=e.provider??t,n={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return p([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return p([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return p([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return p([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return oo(e)}getUserAgent(){return`${this.constructor.name}/JS ${$e}`}defaultIdempotencyKey(){return`stainless-node-retry-${He()}`}makeStatusError(e,t,r,n){return N.generate(e,t,r,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof _?r:new _(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new _(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!u(this,Nn,"m",Yo).call(this)&&r||this.baseURL,o=Bn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!Js(a)||!Js(l))&&(t={...l,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Ve(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:l,timeout:h}=await this.buildRequest(n,{retryCount:o-t}),d=n.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:l,options:n}),await this._provider?.prepareRequest?.(a,{url:l,options:n});let f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),y=r===void 0?"":`, retryOf: ${r}`,m=Date.now();if(M(this).debug(`[${f}] sending request`,ye({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:a.headers})),n.signal?.aborted)throw new L;let b=n.__security??{bearerAuth:!0},P=new AbortController,A=await this.fetchWithAuth(l,a,h,P,b).catch(Hr),I=Date.now();if(A instanceof globalThis.Error){let E=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new L;let S=qr(A)||/timed? ?out/i.test(String(A)+("cause"in A?String(A.cause):""));if(t&&!d)return M(this).info(`[${f}] connection ${S?"timed out":"failed"} - ${E}`),M(this).debug(`[${f}] connection ${S?"timed out":"failed"} (${E})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-m,message:A.message})),this.retryRequest(n,t,r??f);let j=d?"error; streaming body cannot be retried":"error; no more retries left";throw M(this).info(`[${f}] connection ${S?"timed out":"failed"} - ${j}`),M(this).debug(`[${f}] connection ${S?"timed out":"failed"} (${j})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-m,message:A.message})),A instanceof We||A instanceof Wr?A:S?new Ce:new Se({message:pc(A),cause:A})}let O=[...A.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,S])=>", "+E+": "+JSON.stringify(S)).join(""),g=`[${f}${y}${O}] ${a.method} ${l} ${A.ok?"succeeded":"failed"} with status ${A.status} in ${I-m}ms`;if(!A.ok){if(A.status===401&&this._workloadIdentityAuth&&b.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Xs(A.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??f);let E=await this.shouldRetry(A);if(t&&E&&!d){let F=`retrying, ${t} attempts remaining`;return await Xs(A.body),M(this).info(`${g} - ${F}`),M(this).debug(`[${f}] response error (${F})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-m})),this.retryRequest(n,t,r??f,A.headers)}let S=E?d?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";M(this).info(`${g} - ${S}`);let j=await A.text().catch(F=>Hr(F).message),k=Dn(j),K=k?void 0:j;throw M(this).debug(`[${f}] response error (${S})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,message:K,durationMs:Date.now()-m})),this.makeStatusError(A.status,k,K,A.headers)}return M(this).info(g),M(this).debug(`[${f}] response start`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-m})),{response:A,options:n,controller:P,requestLogID:f,retryOfRequestLogID:r,startTime:m}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Qr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,h=l.get("Authorization");if(!h||h===`Bearer ${dc}`){let d=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${d}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:a,...l}=t||{},h=this._makeAbort(n);o&&o.addEventListener("abort",h,{once:!0});let d=setTimeout(h,r),f=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,y={signal:n.signal,...f?{duplex:"half"}:{},method:"GET",...l};a&&(y.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,a=n?.get("retry-after-ms");if(a){let h=parseFloat(a);Number.isNaN(h)||(o=h)}let l=n?.get("retry-after");if(l&&!o){let h=parseFloat(l);Number.isNaN(h)?o=Date.parse(l)-Date.now():o=h*1e3}if(o===void 0){let h=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,h)}return await he(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:a,defaultBaseURL:l}=r,h=this.buildURL(o,a,l);"timeout"in r&&zn("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:f,isStreamingBody:y}=this.buildBody({options:r});y&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let m=await this.buildHeaders({options:e,method:n,bodyHeaders:d,retryCount:t});return{req:{method:n,headers:m,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...r.fetchOptions??{}},url:h,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=p([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Vn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...u(this,fs,"f").call(this,{body:t,headers:p([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=p([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!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"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Jr(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...u(this,fs,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};Kn=x,fs=new WeakMap,Nn=new WeakSet,Yo=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};x.OpenAI=Kn;x.DEFAULT_TIMEOUT=6e5;x.OpenAIError=_;x.APIError=N;x.APIConnectionError=Se;x.APIConnectionTimeoutError=Ce;x.APIUserAbortError=L;x.NotFoundError=Ct;x.ConflictError=$t;x.RateLimitError=Et;x.BadRequestError=xt;x.AuthenticationError=Rt;x.InternalServerError=Ot;x.PermissionDeniedError=St;x.UnprocessableEntityError=kt;x.InvalidWebhookSignatureError=pe;x.toFile=ks;x.toStreamingFile=Cs;x.Completions=at;x.Chat=ve;x.Embeddings=lt;x.Files=pt;x.Images=_t;x.ContentProvenanceChecks=ut;x.Audio=me;x.Moderations=gt;x.Models=yt;x.FineTuning=le;x.Graders=ze;x.VectorStores=Re;x.Webhooks=It;x.Beta=ie;x.Batches=rt;x.Uploads=qe;x.Admin=je;x.Responses=de;x.Realtime=Pe;x.Conversations=Be;x.Evals=Ue;x.Containers=Me;x.Skills=xe;x.Videos=wt;function pc(s){if(hc(s))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 hc(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Ln=class extends x{constructor({baseURL:e=J("OPENAI_BASE_URL"),apiKey:t=J("AZURE_OPENAI_API_KEY"),apiVersion:r=J("OPENAI_API_VERSION"),endpoint:n,deployment:o,azureADTokenProvider:a,dangerouslyAllowBrowser:l,...h}={}){if(!r)throw new _("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a=="function"&&(l=!0),!a&&!t)throw new _("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new _("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(h.defaultQuery={...h.defaultQuery,"api-version":r},e){if(n)throw new _("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new _("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let d=n.length;for(;d>0&&n[d-1]==="/";)d--;e=`${n.slice(0,d)}/openai`}super({apiKey:a??t,baseURL:e,...h,...l!==void 0?{dangerouslyAllowBrowser:l}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=o}async buildRequest(e,t={}){if(fc.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!jt(e.body))throw new Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;r!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${r}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e,t){let r=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return r.bearerAuth&&typeof this._options.apiKey=="string"?p([{"api-key":this.apiKey}]):super.authHeaders(e,r)}},fc=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);function mc(s){let e=s?.trim();if(!e)throw new _("Must provide one of the `baseURL` or `awsRegion` arguments, or set the `AWS_BEDROCK_BASE_URL`, `AWS_REGION`, or `AWS_DEFAULT_REGION` environment variable.");return`https://bedrock-mantle.${e}.api.aws/openai/v1`}function _c(s){let e=new URL(s),t=e.pathname.match(/\/responses(?:\/.*)?$/);return t?.index!==void 0&&(e.pathname=e.pathname.slice(0,t.index)||"/"),e.toString().replace(/\/$/,"")}function yc(s){return Object.getOwnPropertyDescriptor(s,"output_text")||te(s),s}function gc(s){let e=s.stream.bind(s);return s.stream=((t,r)=>{let n=e(t,r),o=n.finalResponse.bind(n);return n.finalResponse=async()=>yc(await o()),n}),s}var Mn=class extends x{constructor({baseURL:e=J("AWS_BEDROCK_BASE_URL"),apiKey:t,awsRegion:r=J("AWS_REGION")??J("AWS_DEFAULT_REGION"),bedrockTokenProvider:n,adminAPIKey:o,workloadIdentity:a,...l}={}){if(o||a)throw new _("BedrockOpenAI only supports Bedrock bearer token authentication.");if(t===void 0&&!n&&(t=J("AWS_BEARER_TOKEN_BEDROCK")??null),typeof t=="function")throw new _("Pass refreshable Bedrock credentials via `bedrockTokenProvider`, not `apiKey`.");if(t&&n)throw new _("The `apiKey` and `bedrockTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(!t&&!n)throw new _("Missing credentials. Please pass an `apiKey` or `bedrockTokenProvider`, or set the `AWS_BEARER_TOKEN_BEDROCK` environment variable.");let h=e?.trim()?e:mc(r);super({apiKey:n??t,adminAPIKey:null,baseURL:_c(h),...l}),this.bedrockTokenProvider=n,this.responses=gc(new de(this))}async prepareOptions(e){let t=e.__security??{bearerAuth:!0};t.adminAPIKeyAuth&&!t.bearerAuth&&await this._callApiKey(),await super.prepareOptions(e)}async authHeaders(e,t){let r=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return(r.bearerAuth||r.adminAPIKeyAuth)&&this.apiKey!==null?p([{Authorization:`Bearer ${this.apiKey}`}]):super.authHeaders(e,r)}withOptions(e){let t=e.apiKey!==void 0?void 0:e.bedrockTokenProvider??this.bedrockTokenProvider;return super.withOptions({...e,...t?{apiKey:void 0,bedrockTokenProvider:t}:{}})}};export{Se as APIConnectionError,Ce as APIConnectionTimeoutError,N as APIError,Ve as APIPromise,L as APIUserAbortError,Rt as AuthenticationError,Ln as AzureOpenAI,xt as BadRequestError,Mn as BedrockOpenAI,$t as ConflictError,Ot as InternalServerError,pe as InvalidWebhookSignatureError,Ct as NotFoundError,We as OAuthError,x as OpenAI,_ as OpenAIError,Qr as PagePromise,St as PermissionDeniedError,Et as RateLimitError,Wr as SubjectTokenProviderError,kt as UnprocessableEntityError,x as default,ks as toFile,Cs as toStreamingFile};
@@ -1 +0,0 @@
1
- import{a,b}from"./chunk-JL3MAFYQ.js";import"./chunk-CML74SNT.js";import"./chunk-JYVB6UAV.js";import"./chunk-IGDFEGCH.js";import"./chunk-ENP4P2YH.js";import"./chunk-575Y3OEG.js";import"./chunk-4PF2MT7S.js";import"./chunk-OAWYVETM.js";import"./chunk-Y5E7ZCCX.js";import"./chunk-LJEWPIEI.js";import"./chunk-FE4MKOI4.js";import"./chunk-HISXAZ4Y.js";export{a as OpenCodeModel,b as openCodeFactory};