@maincode-ai/matilda-code 0.21.10 → 0.21.11-nightly.20261018.c0a604b33

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 (138) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +10 -1
  2. package/bundled/mainy/docs/matilda-serve.md +6 -6
  3. package/chunks/agent-JGPVXC63.js +3 -0
  4. package/chunks/agent-headless-MKWVWSTI.js +3 -0
  5. package/chunks/{anthropicContentGenerator-SFJGSZHT.js → anthropicContentGenerator-IYZILRDW.js} +1 -1
  6. package/chunks/{askUserQuestion-MJ4FTAOQ.js → askUserQuestion-XWHJY3DM.js} +1 -1
  7. package/chunks/{ca-H4HPSGTI.js → ca-EUJBUYX5.js} +1 -1
  8. package/chunks/{chunk-B3NVKOSU.js → chunk-25NCTG5H.js} +63 -54
  9. package/chunks/{chunk-INAZKGGR.js → chunk-2HQMJ2IU.js} +1 -1
  10. package/chunks/{todoWrite-7BZMVNBC.js → chunk-4CSSDBOS.js} +2 -2
  11. package/chunks/{chunk-5PMMY47S.js → chunk-4FVBPNTZ.js} +1 -1
  12. package/chunks/{chunk-LSDMWVW6.js → chunk-5427BPR2.js} +2 -2
  13. package/chunks/{chunk-GC2F575A.js → chunk-6GBNB5Z2.js} +1 -1
  14. package/chunks/{chunk-32PTAACU.js → chunk-ELH4YHJR.js} +1 -1
  15. package/chunks/{chunk-3HUM74NZ.js → chunk-EQGA7LH7.js} +2 -2
  16. package/chunks/{chunk-FWIVFCKF.js → chunk-FFFZ2QMG.js} +1 -1
  17. package/chunks/chunk-GHBKFIHC.js +35 -0
  18. package/chunks/{chunk-EQEQPZLQ.js → chunk-GO2GA2GY.js} +1 -1
  19. package/chunks/{chunk-QHA3ZBRO.js → chunk-GUFIMKF5.js} +1 -1
  20. package/chunks/{chunk-RJX7DK4Y.js → chunk-HWOQNYAO.js} +1 -1
  21. package/chunks/chunk-HYVP4472.js +8 -0
  22. package/chunks/chunk-JJQEEMCE.js +113 -0
  23. package/chunks/chunk-JL4MGYP5.js +2625 -0
  24. package/chunks/{chunk-VWWEEU4V.js → chunk-JXUDKX6D.js} +1 -1
  25. package/chunks/chunk-LXXDSWWA.js +39 -0
  26. package/chunks/chunk-M53RP3YP.js +31 -0
  27. package/chunks/{chunk-VLYRNOD3.js → chunk-MH2P4YXC.js} +10 -10
  28. package/chunks/{chunk-VYTYYCBR.js → chunk-NYEWHSBL.js} +1 -1
  29. package/chunks/{chunk-LIWYWWOK.js → chunk-ODZOYHIC.js} +1 -1
  30. package/chunks/{chunk-DJSOHDUB.js → chunk-OHFTFZDW.js} +1 -1
  31. package/chunks/{chunk-C62LTEOV.js → chunk-P2EJ7L75.js} +2 -2
  32. package/chunks/{chunk-Q2I3ARPJ.js → chunk-QH7736R5.js} +1 -1
  33. package/chunks/chunk-QN6WSWMM.js +9 -0
  34. package/chunks/chunk-SNLH42QJ.js +10 -0
  35. package/chunks/chunk-SPW5DXX4.js +35 -0
  36. package/chunks/{chunk-S7G6QPEP.js → chunk-SUH3UUWZ.js} +1 -1
  37. package/chunks/chunk-T2T2UEPY.js +4 -0
  38. package/chunks/{chunk-6B5BDE7S.js → chunk-T4P4KEDW.js} +8 -8
  39. package/chunks/chunk-VI74YQQO.js +8 -0
  40. package/chunks/{chunk-DCQKJTAX.js → chunk-W5CGKUM4.js} +8 -3
  41. package/chunks/{chunk-32T6RWWT.js → chunk-WHG6N5X2.js} +1 -1
  42. package/chunks/{chunk-XCJYORZX.js → chunk-XCFLI3OC.js} +1 -1
  43. package/chunks/{chunk-EXIO3QHE.js → chunk-XMREPBZQ.js} +9 -9
  44. package/chunks/{chunk-3ZAMYREW.js → chunk-YMIF2DMT.js} +1 -1
  45. package/chunks/{chunk-K3ELACN2.js → chunk-ZWWK3LOA.js} +17 -17
  46. package/chunks/{computer-use-DJV6HTND.js → computer-use-74O2RS5O.js} +7 -7
  47. package/chunks/contextCommand-ORWYIKKD.js +3 -0
  48. package/chunks/{cron-create-BTTPO3JC.js → cron-create-2UI4AT4Q.js} +1 -1
  49. package/chunks/{cron-delete-U55RHRID.js → cron-delete-ZB6BOTFF.js} +1 -1
  50. package/chunks/{cron-list-J4HRR46K.js → cron-list-YYAXNHB6.js} +1 -1
  51. package/chunks/{de-S7F37S4F.js → de-DNEPG7S7.js} +1 -1
  52. package/chunks/{dist-SVKXQXJX.js → dist-ME6647DQ.js} +1 -1
  53. package/chunks/{dist-SCXU6QWY.js → dist-P6SLWL5V.js} +1 -1
  54. package/chunks/{dist-PVENOVGI.js → dist-VG3ZDJ2A.js} +1 -1
  55. package/chunks/{dist-N66KF4KX.js → dist-YTCHM57U.js} +1 -1
  56. package/chunks/{edit-7XEZHXE4.js → edit-OIBH4BLL.js} +1 -1
  57. package/chunks/{en-S6DMCJQZ.js → en-NOD6KQNM.js} +1 -1
  58. package/chunks/{enter-worktree-MR64QLS4.js → enter-worktree-AIU3KJBK.js} +1 -1
  59. package/chunks/{enterPlanMode-UNWCEVYY.js → enterPlanMode-SVXQCL26.js} +1 -1
  60. package/chunks/{exit-worktree-D4BMN6LH.js → exit-worktree-LJPQWUWN.js} +1 -1
  61. package/chunks/{exitPlanMode-AKLFFYT2.js → exitPlanMode-EBNIDKOG.js} +1 -1
  62. package/chunks/{fr-RFJP3KVL.js → fr-2OE5WLJ4.js} +1 -1
  63. package/chunks/{geminiContentGenerator-JBASUS2T.js → geminiContentGenerator-ZZ5QAWZB.js} +1 -1
  64. package/chunks/glob-IT3EACPK.js +22 -0
  65. package/chunks/goal-tools-6QTC3UI7.js +12 -0
  66. package/chunks/grep-3BB6FQKH.js +22 -0
  67. package/chunks/{ja-UTJHPL3M.js → ja-3B6V5KS7.js} +1 -1
  68. package/chunks/{keychain-token-storage-HAFQQIXL.js → keychain-token-storage-54BNK6VH.js} +1 -1
  69. package/chunks/{ls-CLDNF3YS.js → ls-YWZU3FYL.js} +1 -1
  70. package/chunks/{lsp-7SKRKR5Q.js → lsp-4CJDKEEC.js} +1 -1
  71. package/chunks/{matildaAgentContentGenerator-GMDJPWES.js → matildaAgentContentGenerator-NFEYGURX.js} +1 -1
  72. package/chunks/matildaContentGenerator-SXG4OZTI.js +8 -0
  73. package/chunks/{matildaOAuth2-W2DQO2NK.js → matildaOAuth2-WOY7ZS43.js} +1 -1
  74. package/chunks/monitor-6O6VBEJI.js +32 -0
  75. package/chunks/notebook-edit-STXOZN2Q.js +17 -0
  76. package/chunks/{openaiContentGenerator-XDOQRO4G.js → openaiContentGenerator-43XA6RSY.js} +1 -1
  77. package/chunks/{pt-KXMOTADP.js → pt-KP2JCPUY.js} +1 -1
  78. package/chunks/read-file-6EAPS2KG.js +3 -0
  79. package/chunks/ripGrep-PZRHD4DM.js +3 -0
  80. package/chunks/{ru-EWGWZPQH.js → ru-K7IQQKHC.js} +1 -1
  81. package/chunks/scheduler-5HVKP7US.js +8 -0
  82. package/chunks/{send-message-XXRROIL7.js → send-message-OO2HAKCC.js} +1 -1
  83. package/chunks/{serve-4MDSDWP7.js → serve-GNAEOLUJ.js} +31 -31
  84. package/chunks/shell-OLBIQ5NE.js +3 -0
  85. package/chunks/{skill-JIISRKQN.js → skill-ED2FVJW3.js} +1 -1
  86. package/chunks/src-DNZKTGVD.js +3 -0
  87. package/chunks/{symbol-search-3MVTK4KV.js → symbol-search-ALYOX5JN.js} +1 -1
  88. package/chunks/{syntheticOutput-QEUQIVQJ.js → syntheticOutput-UASKABJH.js} +1 -1
  89. package/chunks/task-create-EBJD55TB.js +3 -0
  90. package/chunks/task-detach-I67ZE5MX.js +9 -0
  91. package/chunks/{task-list-ZEJTNZ2O.js → task-list-5BGX4G5N.js} +1 -1
  92. package/chunks/{task-stop-JO3CXG2K.js → task-stop-ERI5X4AO.js} +1 -1
  93. package/chunks/{task-update-3YY37VFN.js → task-update-CD3W556L.js} +1 -1
  94. package/chunks/{team-create-GMI5DIH7.js → team-create-SHNPWPTO.js} +1 -1
  95. package/chunks/{team-delete-4YYLUV23.js → team-delete-5U3GBFKJ.js} +1 -1
  96. package/chunks/todoWrite-YGG6AZ3A.js +3 -0
  97. package/chunks/{tool-search-OWJC3UTX.js → tool-search-JFCD5W5M.js} +1 -1
  98. package/chunks/{web-fetch-K575OWZ7.js → web-fetch-REWGIRWQ.js} +1 -1
  99. package/chunks/{web-search-F6JRBXFV.js → web-search-OX2DPEVN.js} +1 -1
  100. package/chunks/{workflow-H5DWTI5W.js → workflow-WASIJJUX.js} +2 -2
  101. package/chunks/write-file-VHYWOKNS.js +15 -0
  102. package/cli.js +480 -475
  103. package/locales/ca.js +8 -2
  104. package/locales/de.js +9 -2
  105. package/locales/en.js +15 -8
  106. package/locales/fr.js +9 -2
  107. package/locales/ja.js +8 -2
  108. package/locales/pt.js +8 -2
  109. package/locales/ru.js +9 -2
  110. package/package.json +2 -2
  111. package/sandbox-macos-restrictive-closed.sb +4 -0
  112. package/sandbox-macos-restrictive-open.sb +4 -0
  113. package/sandbox-macos-restrictive-proxied.sb +4 -0
  114. package/chunks/agent-2ZM5WMHY.js +0 -3
  115. package/chunks/agent-headless-PX4INULZ.js +0 -3
  116. package/chunks/chunk-2UDXLDSZ.js +0 -34
  117. package/chunks/chunk-34DXSYJZ.js +0 -34
  118. package/chunks/chunk-ESSYHTAZ.js +0 -8
  119. package/chunks/chunk-FRL6KOLY.js +0 -35
  120. package/chunks/chunk-I7TAYS6D.js +0 -108
  121. package/chunks/chunk-JSFA3NEP.js +0 -5
  122. package/chunks/chunk-ROETRE5J.js +0 -9
  123. package/chunks/chunk-RYLWDCCN.js +0 -2594
  124. package/chunks/chunk-TZIDSCTF.js +0 -31
  125. package/chunks/contextCommand-TAFFF6V7.js +0 -3
  126. package/chunks/glob-3QKPKP7Z.js +0 -22
  127. package/chunks/grep-6CL6HJ5Y.js +0 -22
  128. package/chunks/matildaContentGenerator-EFK4QDRS.js +0 -8
  129. package/chunks/monitor-6W2R25LH.js +0 -32
  130. package/chunks/notebook-edit-WL6MZ6AW.js +0 -17
  131. package/chunks/read-file-J5UBJYDO.js +0 -3
  132. package/chunks/ripGrep-2AMYRBCZ.js +0 -3
  133. package/chunks/scheduler-LFSCKDU6.js +0 -8
  134. package/chunks/shell-SMTFAOAE.js +0 -3
  135. package/chunks/src-OF7NIVIL.js +0 -3
  136. package/chunks/task-create-AEJQ73GE.js +0 -3
  137. package/chunks/update-goal-CF6G57J7.js +0 -16
  138. package/chunks/write-file-RUHYPLKF.js +0 -15
@@ -1,19 +1,19 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{e as Nn,l as Hr,n as fo}from"./chunk-FWDMPRKU.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();i();i();i();function w(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t}function l(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}i();var qr=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return qr=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};i();i();i();function Bt(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Ut=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var b=class extends Error{},N=class r extends b{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new me({message:n,cause:Ut(t)});let o=t?.error;return e===400?new tt(e,o,n,s):e===401?new rt(e,o,n,s):e===403?new nt(e,o,n,s):e===404?new st(e,o,n,s):e===409?new ot(e,o,n,s):e===422?new it(e,o,n,s):e===429?new at(e,o,n,s):e>=500?new lt(e,o,n,s):new r(e,o,n,s)}},v=class extends N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},me=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends me{constructor({message:e}={}){super({message:e??"Request timed out."})}},tt=class extends N{},rt=class extends N{},nt=class extends N{},st=class extends N{},ot=class extends N{},it=class extends N{},at=class extends N{},lt=class extends N{},ct=class extends b{constructor(){super("Could not parse response content as the length limit was reached")}},ut=class extends b{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ee=class extends Error{constructor(e){super(e)}};var ho=/^[a-z][a-z0-9+.-]*:/i,Mn=r=>ho.test(r),H=r=>(H=Array.isArray,H(r)),Gr=H;function Fn(r){return typeof r!="object"?{}:r??{}}function jn(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ln(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Wt(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Bn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new b(`${r} must be an integer`);if(e<0)throw new b(`${r} must be a positive integer`);return e};var Un=r=>{try{return JSON.parse(r)}catch{return}};i();var te=r=>new Promise(e=>setTimeout(e,r));i();i();var _e="5.11.0";var Gn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function mo(){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 go=()=>{let r=mo();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":Hn(Deno.build.os),"X-Stainless-Arch":Wn(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(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":Hn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Wn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=_o();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 _o(){if(typeof navigator>"u"||!navigator)return null;let r=[{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 r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:e,version:`${s}.${o}.${a}`}}}return null}var Wn=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Hn=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),qn,Jn=()=>qn??(qn=go());i();function Xn(){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 Jr(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function cr(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Jr({start(){},async pull(t){let{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Xr(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vn(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}i();var zn=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});i();i();var ur="RFC3986",Vr=r=>String(r),fr={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:Vr},zr="RFC1738";i();i();var dr=(r,e)=>(dr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),dr(r,e)),re=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var Kr=1024,Kn=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<o.length;c+=Kr){let u=o.length>=Kr?o.slice(c,c+Kr):o,m=[];for(let _=0;_<u.length;++_){let p=u.charCodeAt(_);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===zr&&(p===40||p===41)){m[m.length]=u.charAt(_);continue}if(p<128){m[m.length]=re[p];continue}if(p<2048){m[m.length]=re[192|p>>6]+re[128|p&63];continue}if(p<55296||p>=57344){m[m.length]=re[224|p>>12]+re[128|p>>6&63]+re[128|p&63];continue}_+=1,p=65536+((p&1023)<<10|u.charCodeAt(_)&1023),m[m.length]=re[240|p>>18]+re[128|p>>12&63]+re[128|p>>6&63]+re[128|p&63]}a+=m.join("")}return a};function Qn(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Qr(r,e){if(H(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var Zn={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},es=function(r,e){Array.prototype.push.apply(r,H(e)?e:[e])},Yn,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Kn,encodeValuesOnly:!1,format:ur,formatter:Vr,indices:!1,serializeDate(r){return(Yn??(Yn=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function wo(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var Yr={};function ts(r,e,t,n,s,o,a,c,u,m,_,p,y,f,P,A,T,E){let x=r,j=E,C=0,J=!1;for(;(j=j.get(Yr))!==void 0&&!J;){let $=j.get(r);if(C+=1,typeof $<"u"){if($===C)throw new RangeError("Cyclic object value");J=!0}typeof j.get(Yr)>"u"&&(C=0)}if(typeof m=="function"?x=m(e,x):x instanceof Date?x=y?.(x):t==="comma"&&H(x)&&(x=Qr(x,function($){return $ instanceof Date?y?.($):$})),x===null){if(o)return u&&!A?u(e,M.encoder,T,"key",f):e;x=""}if(wo(x)||Qn(x)){if(u){let $=A?e:u(e,M.encoder,T,"key",f);return[P?.($)+"="+P?.(u(x,M.encoder,T,"value",f))]}return[P?.(e)+"="+P?.(String(x))]}let q=[];if(typeof x>"u")return q;let O;if(t==="comma"&&H(x))A&&u&&(x=Qr(x,u)),O=[{value:x.length>0?x.join(",")||null:void 0}];else if(H(m))O=m;else{let $=Object.keys(x);O=_?$.sort(_):$}let L=c?String(e).replace(/\./g,"%2E"):String(e),B=n&&H(x)&&x.length===1?L+"[]":L;if(s&&H(x)&&x.length===0)return B+"[]";for(let $=0;$<O.length;++$){let D=O[$],$n=typeof D=="object"&&typeof D.value<"u"?D.value:x[D];if(a&&$n===null)continue;let Wr=p&&c?D.replace(/\./g,"%2E"):D,uo=H(x)?typeof t=="function"?t(B,Wr):B:B+(p?"."+Wr:"["+Wr+"]");E.set(r,C);let Dn=new WeakMap;Dn.set(Yr,E),es(q,ts($n,uo,t,n,s,o,a,c,t==="comma"&&A&&H(x)?null:u,m,_,p,y,f,P,A,T,Dn))}return q}function xo(r=M){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||M.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=ur;if(typeof r.format<"u"){if(!dr(fr,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=fr[t],s=M.filter;(typeof r.filter=="function"||H(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in Zn?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=M.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:M.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:M.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?M.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:M.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:M.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:M.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:M.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:M.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:M.strictNullHandling}}function Zr(r,e={}){let t=r,n=xo(e),s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):H(n.filter)&&(o=n.filter,s=o);let a=[];if(typeof t!="object"||t===null)return"";let c=Zn[n.arrayFormat],u=c==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);let m=new WeakMap;for(let y=0;y<s.length;++y){let f=s[y];n.skipNulls&&t[f]===null||es(a,ts(t[f],f,c,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,m))}let _=a.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),_.length>0?p+_:""}i();i();i();i();i();function ss(r){let e=0;for(let s of r)e+=s.length;let t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var rs;function ft(r){let e;return(rs??(e=new globalThis.TextEncoder,rs=e.encode.bind(e)))(r)}var ns;function en(r){let e;return(ns??(e=new globalThis.TextDecoder,ns=e.decode.bind(e)))(r)}var X,V,ke=class{constructor(){X.set(this,void 0),V.set(this,void 0),w(this,X,new Uint8Array,"f"),w(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ft(e):e;w(this,X,ss([l(this,X,"f"),t]),"f");let n=[],s;for(;(s=Io(l(this,X,"f"),l(this,V,"f")))!=null;){if(s.carriage&&l(this,V,"f")==null){w(this,V,s.index,"f");continue}if(l(this,V,"f")!=null&&(s.index!==l(this,V,"f")+1||s.carriage)){n.push(en(l(this,X,"f").subarray(0,l(this,V,"f")-1))),w(this,X,l(this,X,"f").subarray(l(this,V,"f")),"f"),w(this,V,null,"f");continue}let o=l(this,V,"f")!==null?s.preceding-1:s.preceding,a=en(l(this,X,"f").subarray(0,o));n.push(a),w(this,X,l(this,X,"f").subarray(s.index),"f"),w(this,V,null,"f")}return n}flush(){return l(this,X,"f").length?this.decode(`
4
- `):[]}};X=new WeakMap,V=new WeakMap;ke.NEWLINE_CHARS=new Set([`
5
- `,"\r"]);ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Io(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function os(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}i();var hr={off:0,error:200,warn:300,info:400,debug:500},tn=(r,e,t)=>{if(r){if(Ln(hr,r))return r;k(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(hr))}`)}};function Ht(){}function pr(r,e,t){return!e||hr[r]>hr[t]?Ht:e[r].bind(e)}var Po={error:Ht,warn:Ht,info:Ht,debug:Ht},is=new WeakMap;function k(r){let e=r.logger,t=r.logLevel??"off";if(!e)return Po;let n=is.get(e);if(n&&n[0]===t)return n[1];let s={error:pr("error",e,t),warn:pr("warn",e,t),info:pr("info",e,t),debug:pr("debug",e,t)};return is.set(e,[t,s]),s}var ce=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var qt,ne=class r{constructor(e,t,n){this.iterator=e,qt.set(this,void 0),this.controller=t,w(this,qt,n,"f")}static fromSSEResponse(e,t,n){let s=!1,o=n?k(n):console;async function*a(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of So(e,t))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let m;try{m=JSON.parse(u.data)}catch(_){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),_}if(m&&m.error)throw new N(void 0,m.error,void 0,e.headers);yield m}else{let m;try{m=JSON.parse(u.data)}catch(_){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),_}if(u.event=="error")throw new N(void 0,m.error,m.message,void 0);yield{event:u.event,data:m}}}c=!0}catch(u){if(Bt(u))return;throw u}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*o(){let c=new ke,u=Xr(e);for await(let m of u)for(let _ of c.decode(m))yield _;for(let m of c.flush())yield m}async function*a(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of o())c||u&&(yield JSON.parse(u));c=!0}catch(u){if(Bt(u))return;throw u}finally{c||t.abort()}}return new r(a,t,n)}[(qt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let a=n.next();e.push(a),t.push(a)}return o.shift()}});return[new r(()=>s(e),this.controller,l(this,qt,"f")),new r(()=>s(t),this.controller,l(this,qt,"f"))]}toReadableStream(){let e=this,t;return Jr({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await t.next();if(o)return n.close();let a=ft(JSON.stringify(s)+`
6
- `);n.enqueue(a)}catch(s){n.error(s)}},async cancel(){await t.return?.()}})}};async function*So(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new b("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 b("Attempted to iterate over a response with no body");let t=new rn,n=new ke,s=Xr(r.body);for await(let o of Ro(s))for(let a of n.decode(o)){let c=t.decode(a);c&&(yield c)}for(let o of n.flush()){let a=t.decode(o);a&&(yield a)}}async function*Ro(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ft(t):t,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=os(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var rn=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(`
7
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=Eo(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function Eo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function mr(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,a=await(async()=>{if(e.options.stream)return k(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):ne.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let p=await t.json();return nn(p,t)}return await t.text()})();return k(r).debug(`[${n}] response parsed`,ce({retryOfRequestLogID:s,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function nn(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}i();var Gt,Te=class r extends Promise{constructor(e,t,n=mr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,Gt.set(this,void 0),w(this,Gt,e,"f")}_thenUnwrap(e){return new r(l(this,Gt,"f"),this.responsePromise,async(t,n)=>nn(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(l(this,Gt,"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)}};Gt=new WeakMap;var gr,_r=class{constructor(e,t,n,s){gr.set(this,void 0),w(this,gr,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await l(this,gr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Jt=class extends Te{constructor(e,t,n){super(e,t,async(s,o)=>new n(s,o.response,await mr(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},se=class extends _r{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},S=class extends _r{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Fn(this.options.query),after:t}}:null}};i();i();i();var on=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function dt(r,e,t){return on(),new File(r,e??"unknown_file",t)}function Xt(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var an=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var z=async(r,e)=>({...r,body:await Oo(r.body,e)}),as=new WeakMap;function vo(r){let e=typeof r=="function"?r:r.fetch,t=as.get(e);if(t)return t;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return as.set(e,n),n}var Oo=async(r,e)=>{if(!await vo(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(r||{}).map(([n,s])=>sn(t,n,s))),t},ko=r=>r instanceof Blob&&"name"in r;var sn=async(r,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")r.append(e,String(t));else if(t instanceof Response)r.append(e,dt([await t.blob()],Xt(t)));else if(an(t))r.append(e,dt([await new Response(cr(t)).blob()],Xt(t)));else if(ko(t))r.append(e,t,Xt(t));else if(Array.isArray(t))await Promise.all(t.map(n=>sn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>sn(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var ls=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",To=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&ls(r),$o=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function br(r,e,t){if(on(),r=await r,To(r))return r instanceof File?r:dt([await r.arrayBuffer()],r.name);if($o(r)){let s=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),dt(await ln(s),e,t)}let n=await ln(r);if(e||(e=Xt(r)),!t?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return dt(n,e,t)}async function ln(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(ls(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(an(r))for await(let t of r)e.push(...await ln(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Do(r)}`)}return e}function Do(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}i();i();i();i();var h=class{constructor(e){this._client=e}};i();i();i();function us(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var cs=Object.freeze(Object.create(null)),Mo=(r=us)=>function(t,...n){if(t.length===1)return t[0];let s=!1,o=[],a=t.reduce((_,p,y)=>{/[?#]/.test(p)&&(s=!0);let f=n[y],P=(s?encodeURIComponent:r)(""+f);return y!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??cs)??cs)?.toString)&&(P=f+"",o.push({start:_.length+p.length,length:P.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),_+p+(y===n.length?"":P)},""),c=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,m;for(;(m=u.exec(c))!==null;)o.push({start:m.index,length:m[0].length,error:`Value "${m[0]}" can't be safely passed as a path parameter`});if(o.sort((_,p)=>_.start-p.start),o.length>0){let _=0,p=o.reduce((y,f)=>{let P=" ".repeat(f.start-_),A="^".repeat(f.length);return _=f.start+f.length,y+P+A},"");throw new b(`Path parameters result in path with invalid segments:
3
+ import{e as Nn,l as Hr,n as fo}from"./chunk-FWDMPRKU.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();i();i();i();function w(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t}function l(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}i();var qr=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return qr=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};i();i();i();function Bt(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Ut=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var b=class extends Error{},N=class r extends b{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new me({message:n,cause:Ut(t)});let o=t?.error;return e===400?new tt(e,o,n,s):e===401?new rt(e,o,n,s):e===403?new nt(e,o,n,s):e===404?new st(e,o,n,s):e===409?new ot(e,o,n,s):e===422?new it(e,o,n,s):e===429?new at(e,o,n,s):e>=500?new lt(e,o,n,s):new r(e,o,n,s)}},v=class extends N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},me=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends me{constructor({message:e}={}){super({message:e??"Request timed out."})}},tt=class extends N{},rt=class extends N{},nt=class extends N{},st=class extends N{},ot=class extends N{},it=class extends N{},at=class extends N{},lt=class extends N{},ct=class extends b{constructor(){super("Could not parse response content as the length limit was reached")}},ut=class extends b{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ee=class extends Error{constructor(e){super(e)}};var ho=/^[a-z][a-z0-9+.-]*:/i,Mn=r=>ho.test(r),H=r=>(H=Array.isArray,H(r)),Gr=H;function Fn(r){return typeof r!="object"?{}:r??{}}function jn(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ln(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Wt(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Bn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new b(`${r} must be an integer`);if(e<0)throw new b(`${r} must be a positive integer`);return e};var Un=r=>{try{return JSON.parse(r)}catch{return}};i();var te=r=>new Promise(e=>setTimeout(e,r));i();i();var _e="5.11.0";var Gn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function mo(){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 go=()=>{let r=mo();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":Hn(Deno.build.os),"X-Stainless-Arch":Wn(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(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":Hn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Wn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=_o();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 _o(){if(typeof navigator>"u"||!navigator)return null;let r=[{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 r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:e,version:`${s}.${o}.${a}`}}}return null}var Wn=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Hn=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),qn,Jn=()=>qn??(qn=go());i();function Xn(){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 Jr(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function cr(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Jr({start(){},async pull(t){let{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Xr(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vn(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}i();var zn=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});i();i();var ur="RFC3986",Vr=r=>String(r),fr={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:Vr},zr="RFC1738";i();i();var dr=(r,e)=>(dr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),dr(r,e)),re=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var Kr=1024,Kn=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<o.length;c+=Kr){let u=o.length>=Kr?o.slice(c,c+Kr):o,m=[];for(let _=0;_<u.length;++_){let p=u.charCodeAt(_);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===zr&&(p===40||p===41)){m[m.length]=u.charAt(_);continue}if(p<128){m[m.length]=re[p];continue}if(p<2048){m[m.length]=re[192|p>>6]+re[128|p&63];continue}if(p<55296||p>=57344){m[m.length]=re[224|p>>12]+re[128|p>>6&63]+re[128|p&63];continue}_+=1,p=65536+((p&1023)<<10|u.charCodeAt(_)&1023),m[m.length]=re[240|p>>18]+re[128|p>>12&63]+re[128|p>>6&63]+re[128|p&63]}a+=m.join("")}return a};function Qn(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Qr(r,e){if(H(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var Zn={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},es=function(r,e){Array.prototype.push.apply(r,H(e)?e:[e])},Yn,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Kn,encodeValuesOnly:!1,format:ur,formatter:Vr,indices:!1,serializeDate(r){return(Yn??(Yn=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function wo(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var Yr={};function ts(r,e,t,n,s,o,a,c,u,m,_,p,y,f,P,A,k,E){let x=r,j=E,C=0,J=!1;for(;(j=j.get(Yr))!==void 0&&!J;){let $=j.get(r);if(C+=1,typeof $<"u"){if($===C)throw new RangeError("Cyclic object value");J=!0}typeof j.get(Yr)>"u"&&(C=0)}if(typeof m=="function"?x=m(e,x):x instanceof Date?x=y?.(x):t==="comma"&&H(x)&&(x=Qr(x,function($){return $ instanceof Date?y?.($):$})),x===null){if(o)return u&&!A?u(e,M.encoder,k,"key",f):e;x=""}if(wo(x)||Qn(x)){if(u){let $=A?e:u(e,M.encoder,k,"key",f);return[P?.($)+"="+P?.(u(x,M.encoder,k,"value",f))]}return[P?.(e)+"="+P?.(String(x))]}let q=[];if(typeof x>"u")return q;let O;if(t==="comma"&&H(x))A&&u&&(x=Qr(x,u)),O=[{value:x.length>0?x.join(",")||null:void 0}];else if(H(m))O=m;else{let $=Object.keys(x);O=_?$.sort(_):$}let L=c?String(e).replace(/\./g,"%2E"):String(e),B=n&&H(x)&&x.length===1?L+"[]":L;if(s&&H(x)&&x.length===0)return B+"[]";for(let $=0;$<O.length;++$){let D=O[$],$n=typeof D=="object"&&typeof D.value<"u"?D.value:x[D];if(a&&$n===null)continue;let Wr=p&&c?D.replace(/\./g,"%2E"):D,uo=H(x)?typeof t=="function"?t(B,Wr):B:B+(p?"."+Wr:"["+Wr+"]");E.set(r,C);let Dn=new WeakMap;Dn.set(Yr,E),es(q,ts($n,uo,t,n,s,o,a,c,t==="comma"&&A&&H(x)?null:u,m,_,p,y,f,P,A,k,Dn))}return q}function xo(r=M){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||M.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=ur;if(typeof r.format<"u"){if(!dr(fr,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=fr[t],s=M.filter;(typeof r.filter=="function"||H(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in Zn?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=M.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:M.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:M.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?M.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:M.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:M.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:M.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:M.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:M.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:M.strictNullHandling}}function Zr(r,e={}){let t=r,n=xo(e),s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):H(n.filter)&&(o=n.filter,s=o);let a=[];if(typeof t!="object"||t===null)return"";let c=Zn[n.arrayFormat],u=c==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);let m=new WeakMap;for(let y=0;y<s.length;++y){let f=s[y];n.skipNulls&&t[f]===null||es(a,ts(t[f],f,c,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,m))}let _=a.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),_.length>0?p+_:""}i();i();i();i();i();function ss(r){let e=0;for(let s of r)e+=s.length;let t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var rs;function ft(r){let e;return(rs??(e=new globalThis.TextEncoder,rs=e.encode.bind(e)))(r)}var ns;function en(r){let e;return(ns??(e=new globalThis.TextDecoder,ns=e.decode.bind(e)))(r)}var X,V,Te=class{constructor(){X.set(this,void 0),V.set(this,void 0),w(this,X,new Uint8Array,"f"),w(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ft(e):e;w(this,X,ss([l(this,X,"f"),t]),"f");let n=[],s;for(;(s=Io(l(this,X,"f"),l(this,V,"f")))!=null;){if(s.carriage&&l(this,V,"f")==null){w(this,V,s.index,"f");continue}if(l(this,V,"f")!=null&&(s.index!==l(this,V,"f")+1||s.carriage)){n.push(en(l(this,X,"f").subarray(0,l(this,V,"f")-1))),w(this,X,l(this,X,"f").subarray(l(this,V,"f")),"f"),w(this,V,null,"f");continue}let o=l(this,V,"f")!==null?s.preceding-1:s.preceding,a=en(l(this,X,"f").subarray(0,o));n.push(a),w(this,X,l(this,X,"f").subarray(s.index),"f"),w(this,V,null,"f")}return n}flush(){return l(this,X,"f").length?this.decode(`
4
+ `):[]}};X=new WeakMap,V=new WeakMap;Te.NEWLINE_CHARS=new Set([`
5
+ `,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Io(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function os(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}i();var hr={off:0,error:200,warn:300,info:400,debug:500},tn=(r,e,t)=>{if(r){if(Ln(hr,r))return r;T(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(hr))}`)}};function Ht(){}function pr(r,e,t){return!e||hr[r]>hr[t]?Ht:e[r].bind(e)}var Po={error:Ht,warn:Ht,info:Ht,debug:Ht},is=new WeakMap;function T(r){let e=r.logger,t=r.logLevel??"off";if(!e)return Po;let n=is.get(e);if(n&&n[0]===t)return n[1];let s={error:pr("error",e,t),warn:pr("warn",e,t),info:pr("info",e,t),debug:pr("debug",e,t)};return is.set(e,[t,s]),s}var ce=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var qt,ne=class r{constructor(e,t,n){this.iterator=e,qt.set(this,void 0),this.controller=t,w(this,qt,n,"f")}static fromSSEResponse(e,t,n){let s=!1,o=n?T(n):console;async function*a(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of So(e,t))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let m;try{m=JSON.parse(u.data)}catch(_){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),_}if(m&&m.error)throw new N(void 0,m.error,void 0,e.headers);yield m}else{let m;try{m=JSON.parse(u.data)}catch(_){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),_}if(u.event=="error")throw new N(void 0,m.error,m.message,void 0);yield{event:u.event,data:m}}}c=!0}catch(u){if(Bt(u))return;throw u}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*o(){let c=new Te,u=Xr(e);for await(let m of u)for(let _ of c.decode(m))yield _;for(let m of c.flush())yield m}async function*a(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of o())c||u&&(yield JSON.parse(u));c=!0}catch(u){if(Bt(u))return;throw u}finally{c||t.abort()}}return new r(a,t,n)}[(qt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let a=n.next();e.push(a),t.push(a)}return o.shift()}});return[new r(()=>s(e),this.controller,l(this,qt,"f")),new r(()=>s(t),this.controller,l(this,qt,"f"))]}toReadableStream(){let e=this,t;return Jr({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await t.next();if(o)return n.close();let a=ft(JSON.stringify(s)+`
6
+ `);n.enqueue(a)}catch(s){n.error(s)}},async cancel(){await t.return?.()}})}};async function*So(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new b("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 b("Attempted to iterate over a response with no body");let t=new rn,n=new Te,s=Xr(r.body);for await(let o of Ro(s))for(let a of n.decode(o)){let c=t.decode(a);c&&(yield c)}for(let o of n.flush()){let a=t.decode(o);a&&(yield a)}}async function*Ro(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ft(t):t,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=os(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var rn=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(`
7
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=Eo(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function Eo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function mr(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,a=await(async()=>{if(e.options.stream)return T(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):ne.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let p=await t.json();return nn(p,t)}return await t.text()})();return T(r).debug(`[${n}] response parsed`,ce({retryOfRequestLogID:s,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function nn(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}i();var Gt,ke=class r extends Promise{constructor(e,t,n=mr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,Gt.set(this,void 0),w(this,Gt,e,"f")}_thenUnwrap(e){return new r(l(this,Gt,"f"),this.responsePromise,async(t,n)=>nn(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(l(this,Gt,"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)}};Gt=new WeakMap;var gr,_r=class{constructor(e,t,n,s){gr.set(this,void 0),w(this,gr,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await l(this,gr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Jt=class extends ke{constructor(e,t,n){super(e,t,async(s,o)=>new n(s,o.response,await mr(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},se=class extends _r{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},S=class extends _r{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Fn(this.options.query),after:t}}:null}};i();i();i();var on=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function dt(r,e,t){return on(),new File(r,e??"unknown_file",t)}function Xt(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var an=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var z=async(r,e)=>({...r,body:await Oo(r.body,e)}),as=new WeakMap;function vo(r){let e=typeof r=="function"?r:r.fetch,t=as.get(e);if(t)return t;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return as.set(e,n),n}var Oo=async(r,e)=>{if(!await vo(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(r||{}).map(([n,s])=>sn(t,n,s))),t},To=r=>r instanceof Blob&&"name"in r;var sn=async(r,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")r.append(e,String(t));else if(t instanceof Response)r.append(e,dt([await t.blob()],Xt(t)));else if(an(t))r.append(e,dt([await new Response(cr(t)).blob()],Xt(t)));else if(To(t))r.append(e,t,Xt(t));else if(Array.isArray(t))await Promise.all(t.map(n=>sn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>sn(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var ls=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",ko=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&ls(r),$o=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function br(r,e,t){if(on(),r=await r,ko(r))return r instanceof File?r:dt([await r.arrayBuffer()],r.name);if($o(r)){let s=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),dt(await ln(s),e,t)}let n=await ln(r);if(e||(e=Xt(r)),!t?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return dt(n,e,t)}async function ln(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(ls(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(an(r))for await(let t of r)e.push(...await ln(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Do(r)}`)}return e}function Do(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}i();i();i();i();var h=class{constructor(e){this._client=e}};i();i();i();function us(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var cs=Object.freeze(Object.create(null)),Mo=(r=us)=>function(t,...n){if(t.length===1)return t[0];let s=!1,o=[],a=t.reduce((_,p,y)=>{/[?#]/.test(p)&&(s=!0);let f=n[y],P=(s?encodeURIComponent:r)(""+f);return y!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??cs)??cs)?.toString)&&(P=f+"",o.push({start:_.length+p.length,length:P.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),_+p+(y===n.length?"":P)},""),c=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,m;for(;(m=u.exec(c))!==null;)o.push({start:m.index,length:m[0].length,error:`Value "${m[0]}" can't be safely passed as a path parameter`});if(o.sort((_,p)=>_.start-p.start),o.length>0){let _=0,p=o.reduce((y,f)=>{let P=" ".repeat(f.start-_),A="^".repeat(f.length);return _=f.start+f.length,y+P+A},"");throw new b(`Path parameters result in path with invalid segments:
8
8
  ${o.map(y=>y.error).join(`
9
9
  `)}
10
10
  ${a}
11
- ${p}`)}return a},d=Mo(us);var $e=class extends h{list(e,t={},n){return this._client.getAPIList(d`/chat/completions/${e}/messages`,S,{query:t,...n})}};i();i();i();i();function fs(r){return typeof r.parse=="function"}i();var pt=r=>r?.role==="assistant",cn=r=>r?.role==="tool";i();var un,yr,wr,Vt,zt,xr,Kt,ue,Qt,Ar,Ir,ht,ds,be=class{constructor(){un.add(this),this.controller=new AbortController,yr.set(this,void 0),wr.set(this,()=>{}),Vt.set(this,()=>{}),zt.set(this,void 0),xr.set(this,()=>{}),Kt.set(this,()=>{}),ue.set(this,{}),Qt.set(this,!1),Ar.set(this,!1),Ir.set(this,!1),ht.set(this,!1),w(this,yr,new Promise((e,t)=>{w(this,wr,e,"f"),w(this,Vt,t,"f")}),"f"),w(this,zt,new Promise((e,t)=>{w(this,xr,e,"f"),w(this,Kt,t,"f")}),"f"),l(this,yr,"f").catch(()=>{}),l(this,zt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},l(this,un,"m",ds).bind(this))},0)}_connected(){this.ended||(l(this,wr,"f").call(this),this._emit("connect"))}get ended(){return l(this,Qt,"f")}get errored(){return l(this,Ar,"f")}get aborted(){return l(this,Ir,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,ue,"f")[e]||(l(this,ue,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=l(this,ue,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(l(this,ue,"f")[e]||(l(this,ue,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,ht,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){w(this,ht,!0,"f"),await l(this,zt,"f")}_emit(e,...t){if(l(this,Qt,"f"))return;e==="end"&&(w(this,Qt,!0,"f"),l(this,xr,"f").call(this));let n=l(this,ue,"f")[e];if(n&&(l(this,ue,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!l(this,ht,"f")&&!n?.length&&Promise.reject(s),l(this,Vt,"f").call(this,s),l(this,Kt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!l(this,ht,"f")&&!n?.length&&Promise.reject(s),l(this,Vt,"f").call(this,s),l(this,Kt,"f").call(this,s),this._emit("end")}}_emitFinal(){}};yr=new WeakMap,wr=new WeakMap,Vt=new WeakMap,zt=new WeakMap,xr=new WeakMap,Kt=new WeakMap,ue=new WeakMap,Qt=new WeakMap,Ar=new WeakMap,Ir=new WeakMap,ht=new WeakMap,un=new WeakSet,ds=function(e){if(w(this,Ar,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new v),e instanceof v)return w(this,Ir,!0,"f"),this._emit("abort",e);if(e instanceof b)return this._emit("error",e);if(e instanceof Error){let t=new b(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new b(String(e)))};i();function Yt(r){return r?.$brand==="auto-parseable-response-format"}function De(r){return r?.$brand==="auto-parseable-tool"}function ps(r,e){return!e||!fn(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Zt(r,e)}function Zt(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new ct;if(n.finish_reason==="content_filter")throw new ut;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>Bo(e,s))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Lo(e,n.message.content):null}}});return{...r,choices:t}}function Lo(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function Bo(r,e){let t=r.tools?.find(n=>n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:De(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function hs(r,e){if(!r)return!1;let t=r.tools?.find(n=>n.function?.name===e.function.name);return De(t)||t?.function.strict||!1}function fn(r){return Yt(r.response_format)?!0:r.tools?.some(e=>De(e)||e.type==="function"&&e.function.strict===!0)??!1}function ms(r){for(let e of r??[]){if(e.type!=="function")throw new b(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new b(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var G,dn,Pr,pn,hn,mn,gs,_s,Uo=10,mt=class extends be{constructor(){super(...arguments),G.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(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),cn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(pt(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new b("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),l(this,G,"m",dn).call(this)}async finalMessage(){return await this.done(),l(this,G,"m",Pr).call(this)}async finalFunctionToolCall(){return await this.done(),l(this,G,"m",pn).call(this)}async finalFunctionToolCallResult(){return await this.done(),l(this,G,"m",hn).call(this)}async totalUsage(){return await this.done(),l(this,G,"m",mn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=l(this,G,"m",Pr).call(this);t&&this._emit("finalMessage",t);let n=l(this,G,"m",dn).call(this);n&&this._emit("finalContent",n);let s=l(this,G,"m",pn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=l(this,G,"m",hn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",l(this,G,"m",mn).call(this))}async _createChatCompletion(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,G,"m",gs).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Zt(o,t))}async _runChatCompletion(e,t,n){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){let s="tool",{tool_choice:o="auto",stream:a,...c}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:m=Uo}=n||{},_=t.tools.map(f=>{if(De(f)){if(!f.$callback)throw new b("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),p={};for(let f of _)f.type==="function"&&(p[f.function.name||f.function.function.name]=f.function);let y="tools"in t?_.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<m;++f){let A=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:y,messages:[...this.messages]},n)).choices[0]?.message;if(!A)throw new b("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let T of A.tool_calls){if(T.type!=="function")continue;let E=T.id,{name:x,arguments:j}=T.function,C=p[x];if(C){if(u&&u!==x){let L=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:E,content:L});continue}}else{let L=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(p).map(B=>JSON.stringify(B)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:E,content:L});continue}let J;try{J=fs(C)?await C.parse(j):j}catch(L){let B=L instanceof Error?L.message:String(L);this._addMessage({role:s,tool_call_id:E,content:B});continue}let q=await C.function(J,this),O=l(this,G,"m",_s).call(this,q);if(this._addMessage({role:s,tool_call_id:E,content:O}),u)return}}}};G=new WeakSet,dn=function(){return l(this,G,"m",Pr).call(this).content??null},Pr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(pt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new b("stream ended without producing a ChatCompletionMessage with role=assistant")},pn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(pt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},hn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(cn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},mn=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},gs=function(e){if(e.n!=null&&e.n>1)throw new b("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_s=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var er=class r extends mt{static runTools(e,t,n){let s=new r,o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),pt(e)&&e.content&&this._emit("content",e.content)}};i();i();i();i();var U={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},gn=class extends Error{},_n=class extends Error{};function Wo(r,e=U.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Ho(r.trim(),e)}var Ho=(r,e)=>{let t=r.length,n=0,s=y=>{throw new gn(`${y} at position ${n}`)},o=y=>{throw new _n(`${y} at position ${n}`)},a=()=>(p(),n>=t&&s("Unexpected end of input"),r[n]==='"'?c():r[n]==="{"?u():r[n]==="["?m():r.substring(n,n+4)==="null"||U.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||U.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||U.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||U.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||U.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||U.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):_()),c=()=>{let y=n,f=!1;for(n++;n<t&&(r[n]!=='"'||f&&r[n-1]==="\\");)f=r[n]==="\\"?!f:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(y,++n-Number(f)))}catch(P){o(String(P))}else if(U.STR&e)try{return JSON.parse(r.substring(y,n-Number(f))+'"')}catch{return JSON.parse(r.substring(y,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,p();let y={};try{for(;r[n]!=="}";){if(p(),n>=t&&U.OBJ&e)return y;let f=c();p(),n++;try{let P=a();Object.defineProperty(y,f,{value:P,writable:!0,enumerable:!0,configurable:!0})}catch(P){if(U.OBJ&e)return y;throw P}p(),r[n]===","&&n++}}catch{if(U.OBJ&e)return y;s("Expected '}' at end of object")}return n++,y},m=()=>{n++;let y=[];try{for(;r[n]!=="]";)y.push(a()),p(),r[n]===","&&n++}catch{if(U.ARR&e)return y;s("Expected ']' at end of array")}return n++,y},_=()=>{if(n===0){r==="-"&&U.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(f){if(U.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(f))}}let y=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(U.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(y,n))}catch{r.substring(y,n)==="-"&&U.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(y,r.lastIndexOf("e")))}catch(P){o(String(P))}}},p=()=>{for(;n<t&&`
12
- \r `.includes(r[n]);)n++};return a()},bn=r=>Wo(r,U.ALL^U.NUM);var F,fe,gt,ye,yn,Sr,wn,xn,An,Rr,In,bs,Ne=class r extends mt{constructor(e){super(),F.add(this),fe.set(this,void 0),gt.set(this,void 0),ye.set(this,void 0),w(this,fe,e,"f"),w(this,gt,[],"f")}get currentChatCompletionSnapshot(){return l(this,ye,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new r(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,F,"m",yn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of o)l(this,F,"m",wn).call(this,a);if(o.controller.signal?.aborted)throw new v;return this._addChatCompletion(l(this,F,"m",Rr).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,F,"m",yn).call(this),this._connected();let s=ne.fromReadableStream(e,this.controller),o;for await(let a of s)o&&o!==a.id&&this._addChatCompletion(l(this,F,"m",Rr).call(this)),l(this,F,"m",wn).call(this,a),o=a.id;if(s.controller.signal?.aborted)throw new v;return this._addChatCompletion(l(this,F,"m",Rr).call(this))}[(fe=new WeakMap,gt=new WeakMap,ye=new WeakMap,F=new WeakSet,yn=function(){this.ended||w(this,ye,void 0,"f")},Sr=function(t){let n=l(this,gt,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},l(this,gt,"f")[t.index]=n,n)},wn=function(t){if(this.ended)return;let n=l(this,F,"m",bs).call(this,t);this._emit("chunk",t,n);for(let s of t.choices){let o=n.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let a=l(this,F,"m",Sr).call(this,o);o.finish_reason&&(l(this,F,"m",An).call(this,o),a.current_tool_call_index!=null&&l(this,F,"m",xn).call(this,o,a.current_tool_call_index));for(let c of s.delta.tool_calls??[])a.current_tool_call_index!==c.index&&(l(this,F,"m",An).call(this,o),a.current_tool_call_index!=null&&l(this,F,"m",xn).call(this,o,a.current_tool_call_index)),a.current_tool_call_index=c.index;for(let c of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[c.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:c.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:c.function?.arguments??""}):(u?.type,void 0))}}},xn=function(t,n){if(l(this,F,"m",Sr).call(this,t).done_tool_calls.has(n))return;let o=t.message.tool_calls?.[n];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=l(this,fe,"f")?.tools?.find(c=>c.type==="function"&&c.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:De(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},An=function(t){let n=l(this,F,"m",Sr).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;let s=l(this,F,"m",In).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Rr=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=l(this,ye,"f");if(!t)throw new b("request ended without sending any chunks");return w(this,ye,void 0,"f"),w(this,gt,[],"f"),qo(t,l(this,fe,"f"))},In=function(){let t=l(this,fe,"f")?.response_format;return Yt(t)?t:null},bs=function(t){var n,s,o,a;let c=l(this,ye,"f"),{choices:u,...m}=t;c?Object.assign(c,m):c=w(this,ye,{...m,choices:[]},"f");for(let{delta:_,finish_reason:p,index:y,logprobs:f=null,...P}of t.choices){let A=c.choices[y];if(A||(A=c.choices[y]={finish_reason:p,index:y,message:{},logprobs:f,...P}),f)if(!A.logprobs)A.logprobs=Object.assign({},f);else{let{content:q,refusal:O,...L}=f;Object.assign(A.logprobs,L),q&&((n=A.logprobs).content??(n.content=[]),A.logprobs.content.push(...q)),O&&((s=A.logprobs).refusal??(s.refusal=[]),A.logprobs.refusal.push(...O))}if(p&&(A.finish_reason=p,l(this,fe,"f")&&fn(l(this,fe,"f")))){if(p==="length")throw new ct;if(p==="content_filter")throw new ut}if(Object.assign(A,P),!_)continue;let{content:T,refusal:E,function_call:x,role:j,tool_calls:C,...J}=_;if(Object.assign(A.message,J),E&&(A.message.refusal=(A.message.refusal||"")+E),j&&(A.message.role=j),x&&(A.message.function_call?(x.name&&(A.message.function_call.name=x.name),x.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=x.arguments)):A.message.function_call=x),T&&(A.message.content=(A.message.content||"")+T,!A.message.refusal&&l(this,F,"m",In).call(this)&&(A.message.parsed=bn(A.message.content))),C){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:q,id:O,type:L,function:B,...$}of C){let D=(a=A.message.tool_calls)[q]??(a[q]={});Object.assign(D,$),O&&(D.id=O),L&&(D.type=L),B&&(D.function??(D.function={name:B.name??"",arguments:""})),B?.name&&(D.function.name=B.name),B?.arguments&&(D.function.arguments+=B.arguments,hs(l(this,fe,"f"),D)&&(D.function.parsed_arguments=bn(D.function.arguments)))}}}return c},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{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 ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function qo(r,e){let{id:t,choices:n,created:s,model:o,system_fingerprint:a,...c}=r,u={...c,id:t,choices:n.map(({message:m,finish_reason:_,index:p,logprobs:y,...f})=>{if(!_)throw new b(`missing finish_reason for choice ${p}`);let{content:P=null,function_call:A,tool_calls:T,...E}=m,x=m.role;if(!x)throw new b(`missing role for choice ${p}`);if(A){let{arguments:j,name:C}=A;if(j==null)throw new b(`missing function_call.arguments for choice ${p}`);if(!C)throw new b(`missing function_call.name for choice ${p}`);return{...f,message:{content:P,function_call:{arguments:j,name:C},role:x,refusal:m.refusal??null},finish_reason:_,index:p,logprobs:y}}return T?{...f,index:p,finish_reason:_,logprobs:y,message:{...E,role:x,content:P,refusal:m.refusal??null,tool_calls:T.map((j,C)=>{let{function:J,type:q,id:O,...L}=j,{arguments:B,name:$,...D}=J||{};if(O==null)throw new b(`missing choices[${p}].tool_calls[${C}].id
11
+ ${p}`)}return a},d=Mo(us);var $e=class extends h{list(e,t={},n){return this._client.getAPIList(d`/chat/completions/${e}/messages`,S,{query:t,...n})}};i();i();i();i();function fs(r){return typeof r.parse=="function"}i();var pt=r=>r?.role==="assistant",cn=r=>r?.role==="tool";i();var un,yr,wr,Vt,zt,xr,Kt,ue,Qt,Ar,Ir,ht,ds,be=class{constructor(){un.add(this),this.controller=new AbortController,yr.set(this,void 0),wr.set(this,()=>{}),Vt.set(this,()=>{}),zt.set(this,void 0),xr.set(this,()=>{}),Kt.set(this,()=>{}),ue.set(this,{}),Qt.set(this,!1),Ar.set(this,!1),Ir.set(this,!1),ht.set(this,!1),w(this,yr,new Promise((e,t)=>{w(this,wr,e,"f"),w(this,Vt,t,"f")}),"f"),w(this,zt,new Promise((e,t)=>{w(this,xr,e,"f"),w(this,Kt,t,"f")}),"f"),l(this,yr,"f").catch(()=>{}),l(this,zt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},l(this,un,"m",ds).bind(this))},0)}_connected(){this.ended||(l(this,wr,"f").call(this),this._emit("connect"))}get ended(){return l(this,Qt,"f")}get errored(){return l(this,Ar,"f")}get aborted(){return l(this,Ir,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,ue,"f")[e]||(l(this,ue,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=l(this,ue,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(l(this,ue,"f")[e]||(l(this,ue,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,ht,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){w(this,ht,!0,"f"),await l(this,zt,"f")}_emit(e,...t){if(l(this,Qt,"f"))return;e==="end"&&(w(this,Qt,!0,"f"),l(this,xr,"f").call(this));let n=l(this,ue,"f")[e];if(n&&(l(this,ue,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!l(this,ht,"f")&&!n?.length&&Promise.reject(s),l(this,Vt,"f").call(this,s),l(this,Kt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!l(this,ht,"f")&&!n?.length&&Promise.reject(s),l(this,Vt,"f").call(this,s),l(this,Kt,"f").call(this,s),this._emit("end")}}_emitFinal(){}};yr=new WeakMap,wr=new WeakMap,Vt=new WeakMap,zt=new WeakMap,xr=new WeakMap,Kt=new WeakMap,ue=new WeakMap,Qt=new WeakMap,Ar=new WeakMap,Ir=new WeakMap,ht=new WeakMap,un=new WeakSet,ds=function(e){if(w(this,Ar,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new v),e instanceof v)return w(this,Ir,!0,"f"),this._emit("abort",e);if(e instanceof b)return this._emit("error",e);if(e instanceof Error){let t=new b(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new b(String(e)))};i();function Yt(r){return r?.$brand==="auto-parseable-response-format"}function De(r){return r?.$brand==="auto-parseable-tool"}function ps(r,e){return!e||!fn(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Zt(r,e)}function Zt(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new ct;if(n.finish_reason==="content_filter")throw new ut;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>Bo(e,s))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Lo(e,n.message.content):null}}});return{...r,choices:t}}function Lo(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function Bo(r,e){let t=r.tools?.find(n=>n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:De(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function hs(r,e){if(!r)return!1;let t=r.tools?.find(n=>n.function?.name===e.function.name);return De(t)||t?.function.strict||!1}function fn(r){return Yt(r.response_format)?!0:r.tools?.some(e=>De(e)||e.type==="function"&&e.function.strict===!0)??!1}function ms(r){for(let e of r??[]){if(e.type!=="function")throw new b(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new b(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var G,dn,Pr,pn,hn,mn,gs,_s,Uo=10,mt=class extends be{constructor(){super(...arguments),G.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(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),cn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(pt(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new b("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),l(this,G,"m",dn).call(this)}async finalMessage(){return await this.done(),l(this,G,"m",Pr).call(this)}async finalFunctionToolCall(){return await this.done(),l(this,G,"m",pn).call(this)}async finalFunctionToolCallResult(){return await this.done(),l(this,G,"m",hn).call(this)}async totalUsage(){return await this.done(),l(this,G,"m",mn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=l(this,G,"m",Pr).call(this);t&&this._emit("finalMessage",t);let n=l(this,G,"m",dn).call(this);n&&this._emit("finalContent",n);let s=l(this,G,"m",pn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=l(this,G,"m",hn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",l(this,G,"m",mn).call(this))}async _createChatCompletion(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,G,"m",gs).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Zt(o,t))}async _runChatCompletion(e,t,n){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){let s="tool",{tool_choice:o="auto",stream:a,...c}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:m=Uo}=n||{},_=t.tools.map(f=>{if(De(f)){if(!f.$callback)throw new b("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),p={};for(let f of _)f.type==="function"&&(p[f.function.name||f.function.function.name]=f.function);let y="tools"in t?_.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<m;++f){let A=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:y,messages:[...this.messages]},n)).choices[0]?.message;if(!A)throw new b("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let k of A.tool_calls){if(k.type!=="function")continue;let E=k.id,{name:x,arguments:j}=k.function,C=p[x];if(C){if(u&&u!==x){let L=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:E,content:L});continue}}else{let L=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(p).map(B=>JSON.stringify(B)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:E,content:L});continue}let J;try{J=fs(C)?await C.parse(j):j}catch(L){let B=L instanceof Error?L.message:String(L);this._addMessage({role:s,tool_call_id:E,content:B});continue}let q=await C.function(J,this),O=l(this,G,"m",_s).call(this,q);if(this._addMessage({role:s,tool_call_id:E,content:O}),u)return}}}};G=new WeakSet,dn=function(){return l(this,G,"m",Pr).call(this).content??null},Pr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(pt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new b("stream ended without producing a ChatCompletionMessage with role=assistant")},pn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(pt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},hn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(cn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},mn=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},gs=function(e){if(e.n!=null&&e.n>1)throw new b("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_s=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var er=class r extends mt{static runTools(e,t,n){let s=new r,o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),pt(e)&&e.content&&this._emit("content",e.content)}};i();i();i();i();var U={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},gn=class extends Error{},_n=class extends Error{};function Wo(r,e=U.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Ho(r.trim(),e)}var Ho=(r,e)=>{let t=r.length,n=0,s=y=>{throw new gn(`${y} at position ${n}`)},o=y=>{throw new _n(`${y} at position ${n}`)},a=()=>(p(),n>=t&&s("Unexpected end of input"),r[n]==='"'?c():r[n]==="{"?u():r[n]==="["?m():r.substring(n,n+4)==="null"||U.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||U.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||U.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||U.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||U.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||U.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):_()),c=()=>{let y=n,f=!1;for(n++;n<t&&(r[n]!=='"'||f&&r[n-1]==="\\");)f=r[n]==="\\"?!f:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(y,++n-Number(f)))}catch(P){o(String(P))}else if(U.STR&e)try{return JSON.parse(r.substring(y,n-Number(f))+'"')}catch{return JSON.parse(r.substring(y,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,p();let y={};try{for(;r[n]!=="}";){if(p(),n>=t&&U.OBJ&e)return y;let f=c();p(),n++;try{let P=a();Object.defineProperty(y,f,{value:P,writable:!0,enumerable:!0,configurable:!0})}catch(P){if(U.OBJ&e)return y;throw P}p(),r[n]===","&&n++}}catch{if(U.OBJ&e)return y;s("Expected '}' at end of object")}return n++,y},m=()=>{n++;let y=[];try{for(;r[n]!=="]";)y.push(a()),p(),r[n]===","&&n++}catch{if(U.ARR&e)return y;s("Expected ']' at end of array")}return n++,y},_=()=>{if(n===0){r==="-"&&U.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(f){if(U.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(f))}}let y=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(U.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(y,n))}catch{r.substring(y,n)==="-"&&U.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(y,r.lastIndexOf("e")))}catch(P){o(String(P))}}},p=()=>{for(;n<t&&`
12
+ \r `.includes(r[n]);)n++};return a()},bn=r=>Wo(r,U.ALL^U.NUM);var F,fe,gt,ye,yn,Sr,wn,xn,An,Rr,In,bs,Ne=class r extends mt{constructor(e){super(),F.add(this),fe.set(this,void 0),gt.set(this,void 0),ye.set(this,void 0),w(this,fe,e,"f"),w(this,gt,[],"f")}get currentChatCompletionSnapshot(){return l(this,ye,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new r(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,F,"m",yn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of o)l(this,F,"m",wn).call(this,a);if(o.controller.signal?.aborted)throw new v;return this._addChatCompletion(l(this,F,"m",Rr).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,F,"m",yn).call(this),this._connected();let s=ne.fromReadableStream(e,this.controller),o;for await(let a of s)o&&o!==a.id&&this._addChatCompletion(l(this,F,"m",Rr).call(this)),l(this,F,"m",wn).call(this,a),o=a.id;if(s.controller.signal?.aborted)throw new v;return this._addChatCompletion(l(this,F,"m",Rr).call(this))}[(fe=new WeakMap,gt=new WeakMap,ye=new WeakMap,F=new WeakSet,yn=function(){this.ended||w(this,ye,void 0,"f")},Sr=function(t){let n=l(this,gt,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},l(this,gt,"f")[t.index]=n,n)},wn=function(t){if(this.ended)return;let n=l(this,F,"m",bs).call(this,t);this._emit("chunk",t,n);for(let s of t.choices){let o=n.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let a=l(this,F,"m",Sr).call(this,o);o.finish_reason&&(l(this,F,"m",An).call(this,o),a.current_tool_call_index!=null&&l(this,F,"m",xn).call(this,o,a.current_tool_call_index));for(let c of s.delta.tool_calls??[])a.current_tool_call_index!==c.index&&(l(this,F,"m",An).call(this,o),a.current_tool_call_index!=null&&l(this,F,"m",xn).call(this,o,a.current_tool_call_index)),a.current_tool_call_index=c.index;for(let c of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[c.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:c.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:c.function?.arguments??""}):(u?.type,void 0))}}},xn=function(t,n){if(l(this,F,"m",Sr).call(this,t).done_tool_calls.has(n))return;let o=t.message.tool_calls?.[n];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=l(this,fe,"f")?.tools?.find(c=>c.type==="function"&&c.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:De(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},An=function(t){let n=l(this,F,"m",Sr).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;let s=l(this,F,"m",In).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Rr=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=l(this,ye,"f");if(!t)throw new b("request ended without sending any chunks");return w(this,ye,void 0,"f"),w(this,gt,[],"f"),qo(t,l(this,fe,"f"))},In=function(){let t=l(this,fe,"f")?.response_format;return Yt(t)?t:null},bs=function(t){var n,s,o,a;let c=l(this,ye,"f"),{choices:u,...m}=t;c?Object.assign(c,m):c=w(this,ye,{...m,choices:[]},"f");for(let{delta:_,finish_reason:p,index:y,logprobs:f=null,...P}of t.choices){let A=c.choices[y];if(A||(A=c.choices[y]={finish_reason:p,index:y,message:{},logprobs:f,...P}),f)if(!A.logprobs)A.logprobs=Object.assign({},f);else{let{content:q,refusal:O,...L}=f;Object.assign(A.logprobs,L),q&&((n=A.logprobs).content??(n.content=[]),A.logprobs.content.push(...q)),O&&((s=A.logprobs).refusal??(s.refusal=[]),A.logprobs.refusal.push(...O))}if(p&&(A.finish_reason=p,l(this,fe,"f")&&fn(l(this,fe,"f")))){if(p==="length")throw new ct;if(p==="content_filter")throw new ut}if(Object.assign(A,P),!_)continue;let{content:k,refusal:E,function_call:x,role:j,tool_calls:C,...J}=_;if(Object.assign(A.message,J),E&&(A.message.refusal=(A.message.refusal||"")+E),j&&(A.message.role=j),x&&(A.message.function_call?(x.name&&(A.message.function_call.name=x.name),x.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=x.arguments)):A.message.function_call=x),k&&(A.message.content=(A.message.content||"")+k,!A.message.refusal&&l(this,F,"m",In).call(this)&&(A.message.parsed=bn(A.message.content))),C){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:q,id:O,type:L,function:B,...$}of C){let D=(a=A.message.tool_calls)[q]??(a[q]={});Object.assign(D,$),O&&(D.id=O),L&&(D.type=L),B&&(D.function??(D.function={name:B.name??"",arguments:""})),B?.name&&(D.function.name=B.name),B?.arguments&&(D.function.arguments+=B.arguments,hs(l(this,fe,"f"),D)&&(D.function.parsed_arguments=bn(D.function.arguments)))}}}return c},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{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 ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function qo(r,e){let{id:t,choices:n,created:s,model:o,system_fingerprint:a,...c}=r,u={...c,id:t,choices:n.map(({message:m,finish_reason:_,index:p,logprobs:y,...f})=>{if(!_)throw new b(`missing finish_reason for choice ${p}`);let{content:P=null,function_call:A,tool_calls:k,...E}=m,x=m.role;if(!x)throw new b(`missing role for choice ${p}`);if(A){let{arguments:j,name:C}=A;if(j==null)throw new b(`missing function_call.arguments for choice ${p}`);if(!C)throw new b(`missing function_call.name for choice ${p}`);return{...f,message:{content:P,function_call:{arguments:j,name:C},role:x,refusal:m.refusal??null},finish_reason:_,index:p,logprobs:y}}return k?{...f,index:p,finish_reason:_,logprobs:y,message:{...E,role:x,content:P,refusal:m.refusal??null,tool_calls:k.map((j,C)=>{let{function:J,type:q,id:O,...L}=j,{arguments:B,name:$,...D}=J||{};if(O==null)throw new b(`missing choices[${p}].tool_calls[${C}].id
13
13
  ${Er(r)}`);if(q==null)throw new b(`missing choices[${p}].tool_calls[${C}].type
14
14
  ${Er(r)}`);if($==null)throw new b(`missing choices[${p}].tool_calls[${C}].function.name
15
15
  ${Er(r)}`);if(B==null)throw new b(`missing choices[${p}].tool_calls[${C}].function.arguments
16
- ${Er(r)}`);return{...L,id:O,type:q,function:{...D,name:$,arguments:B}}})}}:{...f,message:{...E,content:P,role:x,refusal:m.refusal??null},finish_reason:_,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ps(u,e)}function Er(r){return JSON.stringify(r)}var tr=class r extends Ne{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let s=new r(t),o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var de=class extends h{constructor(){super(...arguments),this.messages=new $e(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(d`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(d`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/chat/completions/${e}`,t)}parse(e,t){return ms(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Zt(n,e))}runTools(e,t){return e.stream?tr.runTools(this._client,e,t):er.runTools(this._client,e,t)}stream(e,t){return Ne.createChatCompletion(this._client,e,t)}};de.Messages=$e;var we=class extends h{constructor(){super(...arguments),this.completions=new de(this._client)}};we.Completions=de;i();i();i();i();i();var ys=Symbol("brand.privateNullableHeaders");function*Jo(r){if(!r)return;if(ys in r){let{values:n,nulls:s}=r;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Gr(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Gr(n[1])?n[1]:[n[1]],a=!1;for(let c of o)c!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,c])}}var g=r=>{let e=new Headers,t=new Set;for(let n of r){let s=new Set;for(let[o,a]of Jo(n)){let c=o.toLowerCase();s.has(c)||(e.delete(o),s.add(c)),a===null?(e.delete(o),t.add(c)):(e.append(o,a),t.delete(c))}}return{[ys]:!0,values:e,nulls:t}};var _t=class extends h{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:g([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};i();var bt=class extends h{create(e,t){return this._client.post("/audio/transcriptions",z({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};i();var yt=class extends h{create(e,t){return this._client.post("/audio/translations",z({body:e,...t,__metadata:{model:e.model}},this._client))}};var oe=class extends h{constructor(){super(...arguments),this.transcriptions=new bt(this._client),this.translations=new yt(this._client),this.speech=new _t(this._client)}};oe.Transcriptions=bt;oe.Translations=yt;oe.Speech=_t;i();var Me=class extends h{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t})}cancel(e,t){return this._client.post(d`/batches/${e}/cancel`,t)}};i();i();var wt=class extends h{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/assistants/${e}`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};i();i();var xt=class extends h{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};i();var At=class extends h{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var xe=class extends h{constructor(){super(...arguments),this.sessions=new xt(this._client),this.transcriptionSessions=new At(this._client)}};xe.Sessions=xt;xe.TranscriptionSessions=At;i();i();var It=class extends h{create(e,t,n){return this._client.post(d`/threads/${e}/messages`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/messages/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/messages/${e}`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/messages`,S,{query:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(d`/threads/${s}/messages/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};i();i();var Pt=class extends h{retrieve(e,t,n){let{thread_id:s,run_id:o,...a}=t;return this._client.get(d`/threads/${s}/runs/${o}/steps/${e}`,{query:a,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:s,...o}=t;return this._client.getAPIList(d`/threads/${s}/runs/${e}/steps`,S,{query:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};i();i();i();var ws=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};i();var Ae=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var W,je,Pn,ie,Cr,Q,Le,St,Fe,kr,K,vr,Or,sr,rr,nr,xs,As,Is,Ps,Ss,Rs,Es,pe=class extends be{constructor(){super(...arguments),W.add(this),Pn.set(this,[]),ie.set(this,{}),Cr.set(this,{}),Q.set(this,void 0),Le.set(this,void 0),St.set(this,void 0),Fe.set(this,void 0),kr.set(this,void 0),K.set(this,void 0),vr.set(this,void 0),Or.set(this,void 0),sr.set(this,void 0)}[(Pn=new WeakMap,ie=new WeakMap,Cr=new WeakMap,Q=new WeakMap,Le=new WeakMap,St=new WeakMap,Fe=new WeakMap,kr=new WeakMap,K=new WeakMap,vr=new WeakMap,Or=new WeakMap,sr=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{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 je;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=ne.fromReadableStream(e,this.controller);for await(let o of s)l(this,W,"m",rr).call(this,o);if(s.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let o=new je;return o._run(()=>o._runToolAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.submitToolOutputs(t,a,{...s,signal:this.controller.signal});this._connected();for await(let u of c)l(this,W,"m",rr).call(this,u);if(c.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}static createThreadAssistantStream(e,t,n){let s=new je;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){let o=new je;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return l(this,vr,"f")}currentRun(){return l(this,Or,"f")}currentMessageSnapshot(){return l(this,Q,"f")}currentRunStepSnapshot(){return l(this,sr,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,ie,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,Cr,"f"))}async finalRun(){if(await this.done(),!l(this,Le,"f"))throw Error("Final run was not received.");return l(this,Le,"f")}async _createThreadAssistantStream(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},a=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let c of a)l(this,W,"m",rr).call(this,c);if(a.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}async _createAssistantStream(e,t,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.create(t,a,{...s,signal:this.controller.signal});this._connected();for await(let u of c)l(this,W,"m",rr).call(this,u);if(c.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}static accumulateDelta(e,t){for(let[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Wt(o)&&Wt(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...s);continue}for(let a of s){if(!Wt(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let c=a.index;if(c==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof c!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${c}`);let u=o[c];u==null?o.push(a):o[c]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}};je=pe,rr=function(e){if(!this.ended)switch(w(this,vr,e,"f"),l(this,W,"m",Is).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":l(this,W,"m",Es).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":l(this,W,"m",As).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":l(this,W,"m",xs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},nr=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");if(!l(this,Le,"f"))throw Error("Final run has not been received");return l(this,Le,"f")},xs=function(e){let[t,n]=l(this,W,"m",Ss).call(this,e,l(this,Q,"f"));w(this,Q,t,"f"),l(this,Cr,"f")[t.id]=t;for(let s of n){let o=t.content[s.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 s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,a=t.content[s.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(s.index!=l(this,St,"f")){if(l(this,Fe,"f"))switch(l(this,Fe,"f").type){case"text":this._emit("textDone",l(this,Fe,"f").text,l(this,Q,"f"));break;case"image_file":this._emit("imageFileDone",l(this,Fe,"f").image_file,l(this,Q,"f"));break}w(this,St,s.index,"f")}w(this,Fe,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,St,"f")!==void 0){let s=e.data.content[l(this,St,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,l(this,Q,"f"));break;case"text":this._emit("textDone",s.text,l(this,Q,"f"));break}}l(this,Q,"f")&&this._emit("messageDone",e.data),w(this,Q,void 0,"f")}},As=function(e){let t=l(this,W,"m",Ps).call(this,e);switch(w(this,sr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==l(this,kr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(l(this,K,"f")&&this._emit("toolCallDone",l(this,K,"f")),w(this,kr,o.index,"f"),w(this,K,t.step_details.tool_calls[o.index],"f"),l(this,K,"f")&&this._emit("toolCallCreated",l(this,K,"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,sr,void 0,"f"),e.data.step_details.type=="tool_calls"&&l(this,K,"f")&&(this._emit("toolCallDone",l(this,K,"f")),w(this,K,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Is=function(e){l(this,Pn,"f").push(e),this._emit("event",e)},Ps=function(e){switch(e.event){case"thread.run.step.created":return l(this,ie,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=l(this,ie,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let s=je.accumulateDelta(t,n.delta);l(this,ie,"f")[e.data.id]=s}return l(this,ie,"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":l(this,ie,"f")[e.data.id]=e.data;break}if(l(this,ie,"f")[e.data.id])return l(this,ie,"f")[e.data.id];throw new Error("No snapshot available")},Ss=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=l(this,W,"m",Rs).call(this,o,a)}else t.content[o.index]=o,n.push(o);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Rs=function(e,t){return je.accumulateDelta(t,e)},Es=function(e){switch(w(this,Or,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,Le,e.data,"f"),l(this,K,"f")&&(this._emit("toolCallDone",l(this,K,"f")),w(this,K,void 0,"f"));break;case"thread.run.cancelling":break}};var Be=class extends h{constructor(){super(...arguments),this.steps=new Pt(this._client)}create(e,t,n){let{include:s,...o}=t;return this._client.post(d`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/runs/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/runs`,S,{query:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(d`/threads/${s}/runs/${e}/cancel`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let s=g([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let m=parseInt(u);isNaN(m)||(c=m)}}await te(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Be.Steps=Pt;var Ie=class extends h{constructor(){super(...arguments),this.runs=new Be(this._client),this.messages=new It(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/threads/${e}`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(d`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ie.Runs=Be;Ie.Messages=It;var ae=class extends h{constructor(){super(...arguments),this.realtime=new xe(this._client),this.assistants=new wt(this._client),this.threads=new Ie(this._client)}};ae.Realtime=xe;ae.Assistants=wt;ae.Threads=Ie;i();var Ue=class extends h{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};i();i();i();var Rt=class extends h{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}/content`,{...n,headers:g([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var We=class extends h{constructor(){super(...arguments),this.content=new Rt(this._client)}create(e,t,n){return this._client.post(d`/containers/${e}/files`,z({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(d`/containers/${e}/files`,S,{query:t,...n})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(d`/containers/${s}/files/${e}`,{...n,headers:g([{Accept:"*/*"},n?.headers])})}};We.Content=Rt;var Pe=class extends h{constructor(){super(...arguments),this.files=new We(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(d`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/containers/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}};Pe.Files=We;i();var He=class extends h{create(e,t){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&k(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(k(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(c=>{let u=c.embedding;c.embedding=ws(u)}),a)))}};i();i();i();var Et=class extends h{retrieve(e,t,n){let{eval_id:s,run_id:o}=t;return this._client.get(d`/evals/${s}/runs/${o}/output_items/${e}`,n)}list(e,t,n){let{eval_id:s,...o}=t;return this._client.getAPIList(d`/evals/${s}/runs/${e}/output_items`,S,{query:o,...n})}};var qe=class extends h{constructor(){super(...arguments),this.outputItems=new Et(this._client)}create(e,t,n){return this._client.post(d`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(d`/evals/${s}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(d`/evals/${e}/runs`,S,{query:t,...n})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(d`/evals/${s}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(d`/evals/${s}/runs/${e}`,n)}};qe.OutputItems=Et;var Se=class extends h{constructor(){super(...arguments),this.runs=new qe(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(d`/evals/${e}`,t)}update(e,t,n){return this._client.post(d`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/evals/${e}`,t)}};Se.Runs=qe;i();var Ge=class extends h{create(e,t){return this._client.post("/files",z({body:e,...t},this._client))}retrieve(e,t){return this._client.get(d`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/files/${e}`,t)}content(e,t){return this._client.get(d`/files/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!s.has(a.status);)if(await te(t),a=await this.retrieve(e),Date.now()-o>n)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};i();i();var Ct=class extends h{};i();i();var vt=class extends h{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Je=class extends h{constructor(){super(...arguments),this.graders=new vt(this._client)}};Je.Graders=vt;i();i();var Ot=class extends h{create(e,t,n){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,se,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(d`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(d`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}};var Xe=class extends h{constructor(){super(...arguments),this.permissions=new Ot(this._client)}};Xe.Permissions=Ot;i();i();var kt=class extends h{list(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...n})}};var Ve=class extends h{constructor(){super(...arguments),this.checkpoints=new kt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(d`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t})}cancel(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/events`,S,{query:t,...n})}pause(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/resume`,t)}};Ve.Checkpoints=kt;var Y=class extends h{constructor(){super(...arguments),this.methods=new Ct(this._client),this.jobs=new Ve(this._client),this.checkpoints=new Xe(this._client),this.alpha=new Je(this._client)}};Y.Methods=Ct;Y.Jobs=Ve;Y.Checkpoints=Xe;Y.Alpha=Je;i();i();var Tt=class extends h{};var Re=class extends h{constructor(){super(...arguments),this.graderModels=new Tt(this._client)}};Re.GraderModels=Tt;i();var ze=class extends h{createVariation(e,t){return this._client.post("/images/variations",z({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",z({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};i();var Ke=class extends h{retrieve(e,t){return this._client.get(d`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",se,e)}delete(e,t){return this._client.delete(d`/models/${e}`,t)}};i();var Qe=class extends h{create(e,t){return this._client.post("/moderations",{body:e,...t})}};i();i();function Cs(r,e){return!e||!_i(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:Sn(r,e)}function Sn(r,e){let t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:wi(e,s)};if(s.type==="message"){let o=s.content.map(a=>a.type==="output_text"?{...a,parsed:gi(e,a.text)}:a);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||Tr(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function gi(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function _i(r){return!!Yt(r.text?.format)}function bi(r){return r?.$brand==="auto-parseable-tool"}function yi(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function wi(r,e){let t=yi(r.tools??[],e.name);return{...e,...e,parsed_arguments:bi(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Tr(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}i();var $t,$r,Ee,Dr,vs,Os,ks,Ts,Nr=class r extends be{constructor(e){super(),$t.add(this),$r.set(this,void 0),Ee.set(this,void 0),Dr.set(this,void 0),w(this,$r,e,"f")}static createResponse(e,t,n){let s=new r(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,$t,"m",vs).call(this);let o,a=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let c of o)l(this,$t,"m",Os).call(this,c,a);if(o.controller.signal?.aborted)throw new v;return l(this,$t,"m",ks).call(this)}[($r=new WeakMap,Ee=new WeakMap,Dr=new WeakMap,$t=new WeakSet,vs=function(){this.ended||w(this,Ee,void 0,"f")},Os=function(t,n){if(this.ended)return;let s=(a,c)=>{(n==null||c.sequence_number>n)&&this._emit(a,c)},o=l(this,$t,"m",Ts).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new b(`missing output at index ${t.output_index}`);if(a.type==="message"){let c=a.content[t.content_index];if(!c)throw new b(`missing content at index ${t.content_index}`);if(c.type!=="output_text")throw new b(`expected content to be 'output_text', got ${c.type}`);s("response.output_text.delta",{...t,snapshot:c.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new b(`missing output at index ${t.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:s(t.type,t);break}},ks=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=l(this,Ee,"f");if(!t)throw new b("request ended without sending any events");w(this,Ee,void 0,"f");let n=xi(t,l(this,$r,"f"));return w(this,Dr,n,"f"),n},Ts=function(t){let n=l(this,Ee,"f");if(!n){if(t.type!=="response.created")throw new b(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=w(this,Ee,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let s=n.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=n.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new b(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new b(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=n.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{w(this,Ee,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{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=l(this,Dr,"f");if(!e)throw new b("stream ended without producing a ChatCompletion");return e}};function xi(r,e){return Cs(r,e)}i();var Dt=class extends h{list(e,t={},n){return this._client.getAPIList(d`/responses/${e}/input_items`,S,{query:t,...n})}};var Ce=class extends h{constructor(){super(...arguments),this.inputItems=new Dt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Tr(n),n))}retrieve(e,t={},n){return this._client.get(d`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Tr(s),s))}delete(e,t){return this._client.delete(d`/responses/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>Sn(n,e))}stream(e,t){return Nr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d`/responses/${e}/cancel`,t)}};Ce.InputItems=Dt;i();i();var Nt=class extends h{create(e,t,n){return this._client.post(d`/uploads/${e}/parts`,z({body:t,...n},this._client))}};var ve=class extends h{constructor(){super(...arguments),this.parts=new Nt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(d`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(d`/uploads/${e}/complete`,{body:t,...n})}};ve.Parts=Nt;i();i();i();var $s=async r=>{let e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};var Mt=class extends h{create(e,t,n){return this._client.post(d`/vector_stores/${e}/file_batches`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/file_batches/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(d`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...o}=t;return this._client.getAPIList(d`/vector_stores/${s}/file_batches/${e}/files`,S,{query:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let s=g([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let m=parseInt(u);isNaN(m)||(c=m)}}await te(c);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){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=s?.maxConcurrency??5,a=Math.min(o,t.length),c=this._client,u=t.values(),m=[...n];async function _(y){for(let f of y){let P=await c.files.create({file:f,purpose:"assistants"},s);m.push(P.id)}}let p=Array(a).fill(u).map(_);return await $s(p),await this.createAndPoll(e,{file_ids:m})}};i();var Ft=class extends h{create(e,t,n){return this._client.post(d`/vector_stores/${e}/files`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/files/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:s,...o}=t;return this._client.post(d`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/vector_stores/${e}/files`,S,{query:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(d`/vector_stores/${s}/files/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){let s=g([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse(),a=o.data;switch(a.status){case"in_progress":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let m=parseInt(u);isNaN(m)||(c=m)}}await te(c);break;case"failed":case"completed":return a}}}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(d`/vector_stores/${s}/files/${e}/content`,se,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var he=class extends h{constructor(){super(...arguments),this.files=new Ft(this._client),this.fileBatches=new Mt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/vector_stores/${e}`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(d`/vector_stores/${e}/search`,se,{body:t,method:"post",...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};he.Files=Ft;he.FileBatches=Mt;i();var jt,Ds,Mr,Ye=class extends h{constructor(){super(...arguments),jt.add(this)}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");l(this,jt,"m",Ds).call(this,n);let o=g([t]).values,a=l(this,jt,"m",Mr).call(this,o,"webhook-signature"),c=l(this,jt,"m",Mr).call(this,o,"webhook-timestamp"),u=l(this,jt,"m",Mr).call(this,o,"webhook-id"),m=parseInt(c,10);if(isNaN(m))throw new ee("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1e3);if(_-m>s)throw new ee("Webhook timestamp is too old");if(m>_+s)throw new ee("Webhook timestamp is too new");let p=a.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),y=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),f=u?`${u}.${c}.${e}`:`${c}.${e}`,P=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of p)try{let T=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",P,T,new TextEncoder().encode(f)))return}catch{continue}throw new ee("The given webhook signature does not match the expected signature")}};jt=new WeakSet,Ds=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")},Mr=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var Rn,En,Fr,Ns,R=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:n=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(Rn.add(this),Fr.set(this,void 0),this.completions=new Ue(this),this.chat=new we(this),this.embeddings=new He(this),this.files=new Ge(this),this.images=new ze(this),this.audio=new oe(this),this.moderations=new Qe(this),this.models=new Ke(this),this.fineTuning=new Y(this),this.graders=new Re(this),this.vectorStores=new he(this),this.webhooks=new Ye(this),this.beta=new ae(this),this.batches=new Me(this),this.uploads=new ve(this),this.responses=new Ce(this),this.evals=new Se(this),this.containers=new Pe(this),t===void 0)throw new b("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let c={apiKey:t,organization:n,project:s,webhookSecret:o,...a,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&Gn())throw new b(`It looks like you're running in a browser-like environment.
16
+ ${Er(r)}`);return{...L,id:O,type:q,function:{...D,name:$,arguments:B}}})}}:{...f,message:{...E,content:P,role:x,refusal:m.refusal??null},finish_reason:_,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ps(u,e)}function Er(r){return JSON.stringify(r)}var tr=class r extends Ne{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let s=new r(t),o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var de=class extends h{constructor(){super(...arguments),this.messages=new $e(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(d`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(d`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/chat/completions/${e}`,t)}parse(e,t){return ms(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Zt(n,e))}runTools(e,t){return e.stream?tr.runTools(this._client,e,t):er.runTools(this._client,e,t)}stream(e,t){return Ne.createChatCompletion(this._client,e,t)}};de.Messages=$e;var we=class extends h{constructor(){super(...arguments),this.completions=new de(this._client)}};we.Completions=de;i();i();i();i();i();var ys=Symbol("brand.privateNullableHeaders");function*Jo(r){if(!r)return;if(ys in r){let{values:n,nulls:s}=r;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Gr(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Gr(n[1])?n[1]:[n[1]],a=!1;for(let c of o)c!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,c])}}var g=r=>{let e=new Headers,t=new Set;for(let n of r){let s=new Set;for(let[o,a]of Jo(n)){let c=o.toLowerCase();s.has(c)||(e.delete(o),s.add(c)),a===null?(e.delete(o),t.add(c)):(e.append(o,a),t.delete(c))}}return{[ys]:!0,values:e,nulls:t}};var _t=class extends h{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:g([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};i();var bt=class extends h{create(e,t){return this._client.post("/audio/transcriptions",z({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};i();var yt=class extends h{create(e,t){return this._client.post("/audio/translations",z({body:e,...t,__metadata:{model:e.model}},this._client))}};var oe=class extends h{constructor(){super(...arguments),this.transcriptions=new bt(this._client),this.translations=new yt(this._client),this.speech=new _t(this._client)}};oe.Transcriptions=bt;oe.Translations=yt;oe.Speech=_t;i();var Me=class extends h{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t})}cancel(e,t){return this._client.post(d`/batches/${e}/cancel`,t)}};i();i();var wt=class extends h{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/assistants/${e}`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};i();i();var xt=class extends h{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};i();var At=class extends h{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var xe=class extends h{constructor(){super(...arguments),this.sessions=new xt(this._client),this.transcriptionSessions=new At(this._client)}};xe.Sessions=xt;xe.TranscriptionSessions=At;i();i();var It=class extends h{create(e,t,n){return this._client.post(d`/threads/${e}/messages`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/messages/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/messages/${e}`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/messages`,S,{query:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(d`/threads/${s}/messages/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};i();i();var Pt=class extends h{retrieve(e,t,n){let{thread_id:s,run_id:o,...a}=t;return this._client.get(d`/threads/${s}/runs/${o}/steps/${e}`,{query:a,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:s,...o}=t;return this._client.getAPIList(d`/threads/${s}/runs/${e}/steps`,S,{query:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};i();i();i();var ws=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};i();var Ae=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var W,je,Pn,ie,Cr,Y,Le,St,Fe,Tr,K,vr,Or,sr,rr,nr,xs,As,Is,Ps,Ss,Rs,Es,pe=class extends be{constructor(){super(...arguments),W.add(this),Pn.set(this,[]),ie.set(this,{}),Cr.set(this,{}),Y.set(this,void 0),Le.set(this,void 0),St.set(this,void 0),Fe.set(this,void 0),Tr.set(this,void 0),K.set(this,void 0),vr.set(this,void 0),Or.set(this,void 0),sr.set(this,void 0)}[(Pn=new WeakMap,ie=new WeakMap,Cr=new WeakMap,Y=new WeakMap,Le=new WeakMap,St=new WeakMap,Fe=new WeakMap,Tr=new WeakMap,K=new WeakMap,vr=new WeakMap,Or=new WeakMap,sr=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{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 je;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=ne.fromReadableStream(e,this.controller);for await(let o of s)l(this,W,"m",rr).call(this,o);if(s.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let o=new je;return o._run(()=>o._runToolAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.submitToolOutputs(t,a,{...s,signal:this.controller.signal});this._connected();for await(let u of c)l(this,W,"m",rr).call(this,u);if(c.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}static createThreadAssistantStream(e,t,n){let s=new je;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){let o=new je;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return l(this,vr,"f")}currentRun(){return l(this,Or,"f")}currentMessageSnapshot(){return l(this,Y,"f")}currentRunStepSnapshot(){return l(this,sr,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,ie,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,Cr,"f"))}async finalRun(){if(await this.done(),!l(this,Le,"f"))throw Error("Final run was not received.");return l(this,Le,"f")}async _createThreadAssistantStream(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},a=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let c of a)l(this,W,"m",rr).call(this,c);if(a.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}async _createAssistantStream(e,t,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.create(t,a,{...s,signal:this.controller.signal});this._connected();for await(let u of c)l(this,W,"m",rr).call(this,u);if(c.controller.signal?.aborted)throw new v;return this._addRun(l(this,W,"m",nr).call(this))}static accumulateDelta(e,t){for(let[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Wt(o)&&Wt(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...s);continue}for(let a of s){if(!Wt(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let c=a.index;if(c==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof c!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${c}`);let u=o[c];u==null?o.push(a):o[c]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}};je=pe,rr=function(e){if(!this.ended)switch(w(this,vr,e,"f"),l(this,W,"m",Is).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":l(this,W,"m",Es).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":l(this,W,"m",As).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":l(this,W,"m",xs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},nr=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");if(!l(this,Le,"f"))throw Error("Final run has not been received");return l(this,Le,"f")},xs=function(e){let[t,n]=l(this,W,"m",Ss).call(this,e,l(this,Y,"f"));w(this,Y,t,"f"),l(this,Cr,"f")[t.id]=t;for(let s of n){let o=t.content[s.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 s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,a=t.content[s.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(s.index!=l(this,St,"f")){if(l(this,Fe,"f"))switch(l(this,Fe,"f").type){case"text":this._emit("textDone",l(this,Fe,"f").text,l(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",l(this,Fe,"f").image_file,l(this,Y,"f"));break}w(this,St,s.index,"f")}w(this,Fe,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,St,"f")!==void 0){let s=e.data.content[l(this,St,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,l(this,Y,"f"));break;case"text":this._emit("textDone",s.text,l(this,Y,"f"));break}}l(this,Y,"f")&&this._emit("messageDone",e.data),w(this,Y,void 0,"f")}},As=function(e){let t=l(this,W,"m",Ps).call(this,e);switch(w(this,sr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==l(this,Tr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(l(this,K,"f")&&this._emit("toolCallDone",l(this,K,"f")),w(this,Tr,o.index,"f"),w(this,K,t.step_details.tool_calls[o.index],"f"),l(this,K,"f")&&this._emit("toolCallCreated",l(this,K,"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,sr,void 0,"f"),e.data.step_details.type=="tool_calls"&&l(this,K,"f")&&(this._emit("toolCallDone",l(this,K,"f")),w(this,K,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Is=function(e){l(this,Pn,"f").push(e),this._emit("event",e)},Ps=function(e){switch(e.event){case"thread.run.step.created":return l(this,ie,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=l(this,ie,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let s=je.accumulateDelta(t,n.delta);l(this,ie,"f")[e.data.id]=s}return l(this,ie,"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":l(this,ie,"f")[e.data.id]=e.data;break}if(l(this,ie,"f")[e.data.id])return l(this,ie,"f")[e.data.id];throw new Error("No snapshot available")},Ss=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=l(this,W,"m",Rs).call(this,o,a)}else t.content[o.index]=o,n.push(o);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Rs=function(e,t){return je.accumulateDelta(t,e)},Es=function(e){switch(w(this,Or,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,Le,e.data,"f"),l(this,K,"f")&&(this._emit("toolCallDone",l(this,K,"f")),w(this,K,void 0,"f"));break;case"thread.run.cancelling":break}};var Be=class extends h{constructor(){super(...arguments),this.steps=new Pt(this._client)}create(e,t,n){let{include:s,...o}=t;return this._client.post(d`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/runs/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/runs`,S,{query:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(d`/threads/${s}/runs/${e}/cancel`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let s=g([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let m=parseInt(u);isNaN(m)||(c=m)}}await te(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Be.Steps=Pt;var Ie=class extends h{constructor(){super(...arguments),this.runs=new Be(this._client),this.messages=new It(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/threads/${e}`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(d`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ie.Runs=Be;Ie.Messages=It;var ae=class extends h{constructor(){super(...arguments),this.realtime=new xe(this._client),this.assistants=new wt(this._client),this.threads=new Ie(this._client)}};ae.Realtime=xe;ae.Assistants=wt;ae.Threads=Ie;i();var Ue=class extends h{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};i();i();i();var Rt=class extends h{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}/content`,{...n,headers:g([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var We=class extends h{constructor(){super(...arguments),this.content=new Rt(this._client)}create(e,t,n){return this._client.post(d`/containers/${e}/files`,z({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(d`/containers/${e}/files`,S,{query:t,...n})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(d`/containers/${s}/files/${e}`,{...n,headers:g([{Accept:"*/*"},n?.headers])})}};We.Content=Rt;var Pe=class extends h{constructor(){super(...arguments),this.files=new We(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(d`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/containers/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}};Pe.Files=We;i();var He=class extends h{create(e,t){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&T(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(T(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(c=>{let u=c.embedding;c.embedding=ws(u)}),a)))}};i();i();i();var Et=class extends h{retrieve(e,t,n){let{eval_id:s,run_id:o}=t;return this._client.get(d`/evals/${s}/runs/${o}/output_items/${e}`,n)}list(e,t,n){let{eval_id:s,...o}=t;return this._client.getAPIList(d`/evals/${s}/runs/${e}/output_items`,S,{query:o,...n})}};var qe=class extends h{constructor(){super(...arguments),this.outputItems=new Et(this._client)}create(e,t,n){return this._client.post(d`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(d`/evals/${s}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(d`/evals/${e}/runs`,S,{query:t,...n})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(d`/evals/${s}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(d`/evals/${s}/runs/${e}`,n)}};qe.OutputItems=Et;var Se=class extends h{constructor(){super(...arguments),this.runs=new qe(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(d`/evals/${e}`,t)}update(e,t,n){return this._client.post(d`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/evals/${e}`,t)}};Se.Runs=qe;i();var Ge=class extends h{create(e,t){return this._client.post("/files",z({body:e,...t},this._client))}retrieve(e,t){return this._client.get(d`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t})}delete(e,t){return this._client.delete(d`/files/${e}`,t)}content(e,t){return this._client.get(d`/files/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!s.has(a.status);)if(await te(t),a=await this.retrieve(e),Date.now()-o>n)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};i();i();var Ct=class extends h{};i();i();var vt=class extends h{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Je=class extends h{constructor(){super(...arguments),this.graders=new vt(this._client)}};Je.Graders=vt;i();i();var Ot=class extends h{create(e,t,n){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,se,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(d`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(d`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}};var Xe=class extends h{constructor(){super(...arguments),this.permissions=new Ot(this._client)}};Xe.Permissions=Ot;i();i();var Tt=class extends h{list(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...n})}};var Ve=class extends h{constructor(){super(...arguments),this.checkpoints=new Tt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(d`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t})}cancel(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/events`,S,{query:t,...n})}pause(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/resume`,t)}};Ve.Checkpoints=Tt;var Z=class extends h{constructor(){super(...arguments),this.methods=new Ct(this._client),this.jobs=new Ve(this._client),this.checkpoints=new Xe(this._client),this.alpha=new Je(this._client)}};Z.Methods=Ct;Z.Jobs=Ve;Z.Checkpoints=Xe;Z.Alpha=Je;i();i();var kt=class extends h{};var Re=class extends h{constructor(){super(...arguments),this.graderModels=new kt(this._client)}};Re.GraderModels=kt;i();var ze=class extends h{createVariation(e,t){return this._client.post("/images/variations",z({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",z({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};i();var Ke=class extends h{retrieve(e,t){return this._client.get(d`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",se,e)}delete(e,t){return this._client.delete(d`/models/${e}`,t)}};i();var Qe=class extends h{create(e,t){return this._client.post("/moderations",{body:e,...t})}};i();i();function Cs(r,e){return!e||!_i(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:Sn(r,e)}function Sn(r,e){let t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:wi(e,s)};if(s.type==="message"){let o=s.content.map(a=>a.type==="output_text"?{...a,parsed:gi(e,a.text)}:a);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||kr(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function gi(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function _i(r){return!!Yt(r.text?.format)}function bi(r){return r?.$brand==="auto-parseable-tool"}function yi(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function wi(r,e){let t=yi(r.tools??[],e.name);return{...e,...e,parsed_arguments:bi(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function kr(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}i();var $t,$r,Ee,Dr,vs,Os,Ts,ks,Nr=class r extends be{constructor(e){super(),$t.add(this),$r.set(this,void 0),Ee.set(this,void 0),Dr.set(this,void 0),w(this,$r,e,"f")}static createResponse(e,t,n){let s=new r(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,$t,"m",vs).call(this);let o,a=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let c of o)l(this,$t,"m",Os).call(this,c,a);if(o.controller.signal?.aborted)throw new v;return l(this,$t,"m",Ts).call(this)}[($r=new WeakMap,Ee=new WeakMap,Dr=new WeakMap,$t=new WeakSet,vs=function(){this.ended||w(this,Ee,void 0,"f")},Os=function(t,n){if(this.ended)return;let s=(a,c)=>{(n==null||c.sequence_number>n)&&this._emit(a,c)},o=l(this,$t,"m",ks).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new b(`missing output at index ${t.output_index}`);if(a.type==="message"){let c=a.content[t.content_index];if(!c)throw new b(`missing content at index ${t.content_index}`);if(c.type!=="output_text")throw new b(`expected content to be 'output_text', got ${c.type}`);s("response.output_text.delta",{...t,snapshot:c.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new b(`missing output at index ${t.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:s(t.type,t);break}},Ts=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=l(this,Ee,"f");if(!t)throw new b("request ended without sending any events");w(this,Ee,void 0,"f");let n=xi(t,l(this,$r,"f"));return w(this,Dr,n,"f"),n},ks=function(t){let n=l(this,Ee,"f");if(!n){if(t.type!=="response.created")throw new b(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=w(this,Ee,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let s=n.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=n.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new b(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new b(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=n.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{w(this,Ee,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{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=l(this,Dr,"f");if(!e)throw new b("stream ended without producing a ChatCompletion");return e}};function xi(r,e){return Cs(r,e)}i();var Dt=class extends h{list(e,t={},n){return this._client.getAPIList(d`/responses/${e}/input_items`,S,{query:t,...n})}};var Ce=class extends h{constructor(){super(...arguments),this.inputItems=new Dt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&kr(n),n))}retrieve(e,t={},n){return this._client.get(d`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&kr(s),s))}delete(e,t){return this._client.delete(d`/responses/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>Sn(n,e))}stream(e,t){return Nr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d`/responses/${e}/cancel`,t)}};Ce.InputItems=Dt;i();i();var Nt=class extends h{create(e,t,n){return this._client.post(d`/uploads/${e}/parts`,z({body:t,...n},this._client))}};var ve=class extends h{constructor(){super(...arguments),this.parts=new Nt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(d`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(d`/uploads/${e}/complete`,{body:t,...n})}};ve.Parts=Nt;i();i();i();var $s=async r=>{let e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};var Mt=class extends h{create(e,t,n){return this._client.post(d`/vector_stores/${e}/file_batches`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/file_batches/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(d`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...o}=t;return this._client.getAPIList(d`/vector_stores/${s}/file_batches/${e}/files`,S,{query:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let s=g([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let m=parseInt(u);isNaN(m)||(c=m)}}await te(c);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){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=s?.maxConcurrency??5,a=Math.min(o,t.length),c=this._client,u=t.values(),m=[...n];async function _(y){for(let f of y){let P=await c.files.create({file:f,purpose:"assistants"},s);m.push(P.id)}}let p=Array(a).fill(u).map(_);return await $s(p),await this.createAndPoll(e,{file_ids:m})}};i();var Ft=class extends h{create(e,t,n){return this._client.post(d`/vector_stores/${e}/files`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/files/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:s,...o}=t;return this._client.post(d`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/vector_stores/${e}/files`,S,{query:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(d`/vector_stores/${s}/files/${e}`,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){let s=g([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse(),a=o.data;switch(a.status){case"in_progress":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let m=parseInt(u);isNaN(m)||(c=m)}}await te(c);break;case"failed":case"completed":return a}}}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(d`/vector_stores/${s}/files/${e}/content`,se,{...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var he=class extends h{constructor(){super(...arguments),this.files=new Ft(this._client),this.fileBatches=new Mt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/vector_stores/${e}`,{body:t,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(d`/vector_stores/${e}/search`,se,{body:t,method:"post",...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};he.Files=Ft;he.FileBatches=Mt;i();var jt,Ds,Mr,Ye=class extends h{constructor(){super(...arguments),jt.add(this)}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");l(this,jt,"m",Ds).call(this,n);let o=g([t]).values,a=l(this,jt,"m",Mr).call(this,o,"webhook-signature"),c=l(this,jt,"m",Mr).call(this,o,"webhook-timestamp"),u=l(this,jt,"m",Mr).call(this,o,"webhook-id"),m=parseInt(c,10);if(isNaN(m))throw new ee("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1e3);if(_-m>s)throw new ee("Webhook timestamp is too old");if(m>_+s)throw new ee("Webhook timestamp is too new");let p=a.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),y=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),f=u?`${u}.${c}.${e}`:`${c}.${e}`,P=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of p)try{let k=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",P,k,new TextEncoder().encode(f)))return}catch{continue}throw new ee("The given webhook signature does not match the expected signature")}};jt=new WeakSet,Ds=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")},Mr=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var Rn,En,Fr,Ns,R=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:n=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(Rn.add(this),Fr.set(this,void 0),this.completions=new Ue(this),this.chat=new we(this),this.embeddings=new He(this),this.files=new Ge(this),this.images=new ze(this),this.audio=new oe(this),this.moderations=new Qe(this),this.models=new Ke(this),this.fineTuning=new Z(this),this.graders=new Re(this),this.vectorStores=new he(this),this.webhooks=new Ye(this),this.beta=new ae(this),this.batches=new Me(this),this.uploads=new ve(this),this.responses=new Ce(this),this.evals=new Se(this),this.containers=new Pe(this),t===void 0)throw new b("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let c={apiKey:t,organization:n,project:s,webhookSecret:o,...a,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&Gn())throw new b(`It looks like you're running in a browser-like environment.
17
17
 
18
18
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
19
19
  If you understand the risks and have appropriate mitigations in place,
@@ -22,8 +22,8 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
22
22
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
23
23
 
24
24
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
25
- `);this.baseURL=c.baseURL,this.timeout=c.timeout??En.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u="warn";this.logLevel=u,this.logLevel=tn(c.logLevel,"ClientOptions.logLevel",this)??tn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??Xn(),w(this,Fr,zn,"f"),this._options=c,this.apiKey=t,this.organization=n,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...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.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Zr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${qr()}`}makeStatusError(e,t,n,s){return N.generate(e,t,n,s)}buildURL(e,t,n){let s=!l(this,Rn,"m",Ns).call(this)&&n||this.baseURL,o=Mn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return jn(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Te(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:a,url:c,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:s});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),_=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(k(this).debug(`[${m}] sending request`,ce({retryOfRequestLogID:n,method:s.method,url:c,options:s,headers:a.headers})),s.signal?.aborted)throw new v;let y=new AbortController,f=await this.fetchWithTimeout(c,a,u,y).catch(Ut),P=Date.now();if(f instanceof Error){let E=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new v;let x=Bt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return k(this).info(`[${m}] connection ${x?"timed out":"failed"} - ${E}`),k(this).debug(`[${m}] connection ${x?"timed out":"failed"} (${E})`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),this.retryRequest(s,t,n??m);throw k(this).info(`[${m}] connection ${x?"timed out":"failed"} - error; no more retries left`),k(this).debug(`[${m}] connection ${x?"timed out":"failed"} (error; no more retries left)`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),x?new ge:new me({cause:f})}let A=[...f.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,x])=>", "+E+": "+JSON.stringify(x)).join(""),T=`[${m}${_}${A}] ${a.method} ${c} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${P-p}ms`;if(!f.ok){let E=await this.shouldRetry(f);if(t&&E){let O=`retrying, ${t} attempts remaining`;return await Vn(f.body),k(this).info(`${T} - ${O}`),k(this).debug(`[${m}] response error (${O})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),this.retryRequest(s,t,n??m,f.headers)}let x=E?"error; no more retries left":"error; not retryable";k(this).info(`${T} - ${x}`);let j=await f.text().catch(O=>Ut(O).message),C=Un(j),J=C?void 0:j;throw k(this).debug(`[${m}] response error (${x})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,C,J,f.headers)}return k(this).info(T),k(this).debug(`[${m}] response start`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),{response:f,options:s,controller:y,requestLogID:m,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Jt(this,n,e)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:a,...c}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,_={signal:s.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(_.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,_)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s){let o,a=s?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(o=u)}let c=s?.get("retry-after");if(c&&!o){let u=parseFloat(c);Number.isNaN(u)?o=Date.parse(c)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await te(o),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:s,path:o,query:a,defaultBaseURL:c}=n,u=this.buildURL(o,a,c);"timeout"in n&&Bn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:m,body:_}=this.buildBody({options:n}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:m,retryCount:t});return{req:{method:s,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=g([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Jn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:cr(e)}:l(this,Fr,"f").call(this,{body:e,headers:n})}};En=R,Fr=new WeakMap,Rn=new WeakSet,Ns=function(){return this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=En;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=b;R.APIError=N;R.APIConnectionError=me;R.APIConnectionTimeoutError=ge;R.APIUserAbortError=v;R.NotFoundError=st;R.ConflictError=ot;R.RateLimitError=at;R.BadRequestError=tt;R.AuthenticationError=rt;R.InternalServerError=lt;R.PermissionDeniedError=nt;R.UnprocessableEntityError=it;R.InvalidWebhookSignatureError=ee;R.toFile=br;R.Completions=Ue;R.Chat=we;R.Embeddings=He;R.Files=Ge;R.Images=ze;R.Audio=oe;R.Moderations=Qe;R.Models=Ke;R.FineTuning=Y;R.Graders=Re;R.VectorStores=he;R.Webhooks=Ye;R.Beta=ae;R.Batches=Me;R.Uploads=ve;R.Responses=Ce;R.Evals=Se;R.Containers=Pe;i();function kn(r){return r instanceof Error&&"code"in r}function Lm(r){return!r||typeof r!="object"?!1:!!(r instanceof v||r instanceof Error&&r.name==="AbortError"||kn(r)&&r.code==="ABORT_ERR")}function Bm(r){if(r instanceof Error){let e=r.cause;return e instanceof Error&&e.message!==r.message?`${r.message} (cause: ${e.message})`:r.message}try{return String(r)}catch{return"Failed to get error details"}}function Um(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status??e.statusCode??e.response?.status??e.error?.code;if(typeof t=="number"&&t>=100&&t<=599)return t;if(typeof e.message=="string"){let n=e.message.match(/HTTP_STATUS\/(\d{3})\b/);if(n){let s=Number(n[1]);if(s>=100&&s<=599)return s}}}function Wm(r){if(typeof r!="object"||r===null)return"unknown";let e=r instanceof Error&&r.constructor.name!=="Error"?r.constructor.name:void 0,t=r.type,n=e??t??(r instanceof Error?r.name:"unknown"),s=r instanceof Error?r.cause:void 0,o=s&&typeof s=="object"&&"code"in s?s.code:void 0;return o?`${n}:${o}`:n}var le=class extends Error{constructor(t,n){super(t);this.exitCode=n}},Ms=class extends le{constructor(e){super(e,41)}},Fs=class extends le{constructor(e){super(e,42)}},js=class extends le{constructor(e){super(e,44)}},or=class extends le{constructor(e){super(e,52)}},Ls=class extends le{constructor(e){super(e,53)}},Bs=class extends le{constructor(e){super(e,54)}},Us=class extends le{constructor(e){super(e,55)}},Ws=class extends le{constructor(e){super(e,130)}},Cn=class extends Error{},vn=class extends Error{},On=class extends Error{},Hs=class extends Error{status=403;code="ACCOUNT_INACTIVE";title="Account access restricted";constructor(){super("Your account is suspended or restricted from sending messages. Contact Matilda support to review your access. Signing in again will not remove this restriction."),this.name="AccountRestrictedError"}};function Hm(r){if(!r||typeof r!="object")return!1;let e=r;if(e.status!==void 0&&Number(e.status)!==403)return!1;let t=e.error;return e.code==="ACCOUNT_INACTIVE"||t==="account_inactive"||typeof t=="object"&&t!==null&&"code"in t&&t.code==="ACCOUNT_INACTIVE"}var qs=class extends Error{constructor(t,n,s,o){super(t);this.categories=n;this.severity=s;this.assistantMessage=o;this.name="ContentBlockedError"}};function qm(r){if(r&&typeof r=="object"&&"response"in r){let t=Ei(r);if(t.error&&t.error.message&&t.error.code)switch(t.error.code){case 400:return new On(t.error.message);case 401:return new vn(t.error.message);case 403:return new Cn(t.error.message);default:}}return r}function Ei(r){return typeof r.response?.data=="string"?JSON.parse(r.response?.data):r.response?.data}i();import Ci from"node:fs";import Z from"node:path";import Oe from"node:os";import*as Gs from"node:crypto";var ir=".matilda",Qm="google_accounts.json",Lt=new Map,vi=1024;function Ym(){Lt.clear()}var Js=/[ \t()[\]{};|*?$`'"#&<>!~,]/,Zm=["file_path","path","filePath","notebook_path"],Oi=(()=>{let r=Js.source.slice(1,-1);return new RegExp(`\\\\([${r}])`,"g")})();function eg(r){let e=Oe.homedir();return r.startsWith(e)?r.replace(e,"~"):r}function tg(r){if(!r)return"";let e=r;return r.toLowerCase().startsWith("%userprofile%")?e=Oe.homedir()+r.substring(13):(r==="~"||r.startsWith("~/"))&&(e=Oe.homedir()+r.substring(1)),Z.normalize(e)}function rg(r,e=80){if(r.length<=e)return r;let t=Z.sep,n="...";if(e<10)return r.substring(0,e-3)+n;let o=Z.parse(r).root,c=r.substring(o.length).split(t).filter(_=>_!=="");if(c.length===0)return o.length<=e?o:o.substring(0,e-3)+n;if(c.length===1){let _=o+c[0];if(_.length<=e)return _;let p=Math.floor((e-3)/2),y=_.substring(0,p),f=_.substring(_.length-p);return`${y}${n}${f}`}let u=o+c[0],m=[];for(let _=c.length-1;_>=1;_--){let p=c[_],y=[p,...m].join(t),f=_>1,P;if(f?P=u+t+n+t+y:P=u+t+y,P.length<=e){if(m.unshift(p),_===1)return P}else break}if(m.length===0){let _=Math.floor((e-3)/2),p=r.substring(0,_),y=r.substring(r.length-_);return`${p}${n}${y}`}return u+t+n+t+m.join(t)}function ng(r,e){let t=Z.resolve(r),n=Z.resolve(e);return zs(n,t)?Z.relative(n,t)||".":t}function sg(r){let e="";for(let t=0;t<r.length;t++){let n=r[t],s=0;for(let a=t-1;a>=0&&r[a]==="\\";a--)s++;!(s%2===1)&&Js.test(n)?e+="\\"+n:e+=n}return e}function og(r){return Oe.platform()==="win32"?r:r.replace(Oi,"$1")}function Xs(r){let e=Oe.platform()==="win32"?r.toLowerCase():r;return Gs.createHash("sha256").update(e).digest("hex")}function Vs(r){return(Oe.platform()==="win32"?r.toLowerCase():r).replace(/[^a-zA-Z0-9]/g,"-")}function zs(r,e){let n=Oe.platform()==="win32"?Z.win32:Z,s=n.relative(r,e);return!s.startsWith(`..${n.sep}`)&&s!==".."&&!n.isAbsolute(s)}function ig(r,e){return r.some(t=>zs(t,e))}function ki(r=process.cwd(),e){let t=Oe.homedir();return e==="~"?t:e.startsWith("~/")?Z.join(t,e.slice(2)):Z.isAbsolute(e)?e:Z.resolve(r,e)}function Ti(r,e,t={}){let{allowFiles:n=!1,allowExternalPaths:s=!1}=t,a=r.getWorkspaceContext().isPathWithinWorkspace(e);if(!s&&!a)throw new Error("Path is not within workspace");if(s&&!a)return;let c=Lt.get(e);if(c===void 0){try{c=Ci.statSync(e).isDirectory()}catch(u){throw kn(u)&&u.code==="ENOENT"?new Error(`Path does not exist: ${e}`):u}if(Lt.size>=vi){let u=Lt.keys().next().value;u!==void 0&&Lt.delete(u)}Lt.set(e,c)}if(!n&&!c)throw new Error(`Path is not a directory: ${e}`)}function ag(r,e,t={}){let n=r.getTargetDir();if(!e)return n;let s=ki(n,e);return Ti(r,s,t),s}i();import*as I from"node:path";import*as Ze from"node:os";import*as jr from"node:fs";import{AsyncLocalStorage as $i}from"node:async_hooks";var Di="google_accounts.json",Ni="oauth_creds.json",Mi=[".matilda",".agents"],Ks="tmp",Fi="bin",ji="projects",Li="ide",Bi="plans",Ui="debug",Wi="arena",et=class r{targetDir;pinnedRuntimeBaseDir;static runtimeBaseDir=null;static runtimeBaseDirContext=new $i;constructor(e,t){this.targetDir=e,this.pinnedRuntimeBaseDir=t?r.resolvePath(t):void 0}getRuntimeBaseDir(){return this.pinnedRuntimeBaseDir??r.getRuntimeBaseDir()}static resolvePath(e,t){let n=e;if(n==="~"||n.startsWith("~/")||n.startsWith("~\\")){let s=n==="~"?[]:n.slice(2).split(/[/\\]+/).filter(Boolean);n=I.join(Ze.homedir(),...s)}return I.isAbsolute(n)||(n=t?I.resolve(t,n):I.resolve(n)),n}static sanitizePlanSessionId(e){return I.basename(e.replace(/\\/g,"/")).replace(/^\.+/g,"_").replace(/[<>:"|?*\x00-\x1F]/g,"_")||"_"}static resolveRuntimeBaseDir(e,t){return e?r.resolvePath(e,t):null}static setRuntimeBaseDir(e,t){r.runtimeBaseDir=r.resolveRuntimeBaseDir(e,t)}static runWithRuntimeBaseDir(e,t,n){let s=r.resolveRuntimeBaseDir(e,t);return r.runtimeBaseDirContext.run(s,n)}static getRuntimeBaseDir(){let e=process.env.MATILDA_RUNTIME_DIR;if(e)return r.resolveRuntimeBaseDir(e)??r.getGlobalMatildaDir();let t=r.runtimeBaseDirContext.getStore();return t!==void 0?t??r.getGlobalMatildaDir():r.runtimeBaseDir?r.runtimeBaseDir:r.getGlobalMatildaDir()}static getGlobalMatildaDir(){let e=process.env.MATILDA_HOME;if(e)return r.resolvePath(e);let t=Ze.homedir();return t?I.join(t,ir):I.join(Ze.tmpdir(),".matilda")}static getMcpOAuthTokensPath(){return I.join(r.getGlobalMatildaDir(),"mcp-oauth-tokens.json")}static getGlobalSettingsPath(){return I.join(r.getGlobalMatildaDir(),"settings.json")}static getInstallationIdPath(){return I.join(r.getGlobalMatildaDir(),"installation_id")}static getGoogleAccountsPath(){return I.join(r.getGlobalMatildaDir(),Di)}static getUserCommandsDir(){return I.join(r.getGlobalMatildaDir(),"commands")}static getGlobalMemoryFilePath(){return I.join(r.getGlobalMatildaDir(),"memory.md")}static getGlobalTempDir(){return I.join(r.getRuntimeBaseDir(),Ks)}static getGlobalDebugDir(){return I.join(r.getRuntimeBaseDir(),Ui)}static getDebugLogPath(e){return I.join(r.getGlobalDebugDir(),`${e}.txt`)}static getGlobalIdeDir(){return I.join(r.getGlobalMatildaDir(),Li)}static resolvePathThroughExistingAncestor(e){let t=e;for(;;)try{let n=jr.realpathSync(t),s=I.relative(t,e);return I.join(n,s)}catch(n){if(n.code!=="ENOENT")throw n;let s=I.dirname(t);if(s===t)return e;t=s}}static isPathWithinDirectory(e,t){let n=r.resolvePathThroughExistingAncestor(t),s=r.resolvePathThroughExistingAncestor(e),o=I.relative(n,s);return o===""||!o.startsWith("..")&&!I.isAbsolute(o)}static assertPathWithinDirectory(e,t,n){if(!r.isPathWithinDirectory(e,t))throw new or(n)}static getPlansDir(e,t){let n=t?.trim();if(n){if(!e)throw new or("projectRoot is required when plansDirectory is configured.");let s=I.resolve(e),o=r.resolvePath(n,s);return r.assertPathWithinDirectory(o,s,"plansDirectory must resolve within the project root."),o}return I.join(r.getGlobalMatildaDir(),Bi)}static getPlanFilePath(e,t,n){return I.join(r.getPlansDir(t,n),`${r.sanitizePlanSessionId(e)}.md`)}static getGlobalBinDir(){return I.join(r.getGlobalMatildaDir(),Fi)}static getGlobalArenaDir(){return I.join(r.getGlobalMatildaDir(),Wi)}getMatildaDir(){return I.join(this.targetDir,ir)}getProjectDir(){let e=Vs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),ji);return I.join(t,e)}getProjectTempDir(){let e=Xs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),Ks);return I.join(t,e)}getToolResultsDir(){return I.join(this.getProjectTempDir(),"tool-results")}ensureProjectTempDirExists(){jr.mkdirSync(this.getProjectTempDir(),{recursive:!0})}static getOAuthCredsPath(){return I.join(r.getGlobalMatildaDir(),Ni)}getProjectRoot(){return this.targetDir}getWorkspaceSettingsPath(){return I.join(this.getMatildaDir(),"settings.json")}getProjectCommandsDir(){return I.join(this.getMatildaDir(),"commands")}getRuntimeStatusPath(e){return I.join(this.getProjectDir(),"chats",`${e}.runtime.json`)}getProjectTempCheckpointsDir(){return I.join(this.getProjectTempDir(),"checkpoints")}getExtensionsDir(){return I.join(this.getMatildaDir(),"extensions")}getExtensionsConfigPath(){return I.join(this.getExtensionsDir(),"matilda-extension.json")}getUserSkillsDirs(){let e=Ze.homedir()||Ze.tmpdir();return Mi.map(t=>t===ir?I.join(r.getGlobalMatildaDir(),"skills"):I.join(e,t,"skills"))}static getUserExtensionsDir(){return I.join(r.getGlobalMatildaDir(),"extensions")}getHistoryFilePath(){return I.join(this.getProjectTempDir(),"shell_history")}};i();import{promises as Tn}from"node:fs";import Qs from"node:path";async function Ys(r,e,t){let{fallbackCopy:n=!0}=t??{},s=Qs.dirname(r),o=Qs.relative(s,e);try{await Tn.unlink(r)}catch{}try{await Tn.symlink(o,r);return}catch{}if(n)try{await Tn.copyFile(e,r)}catch{}}i();fo();i();var Zs,eo;function wg(r,e){Zs=r,eo=e}function to(){return Zs}function xg(){return eo}function ro(r){let e=r?.spanContext();return e&&Nn(e)?{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}:null}function Hi(){try{return ro(Hr.getActiveSpan())}catch{return null}}function qi(){try{let r=to();return ro(r?Hr.getSpan(r):void 0)}catch{return null}}function no(){return Hi()??qi()}function Eg(r){let e=(r.traceFlags&255).toString(16).padStart(2,"0");return`00-${r.traceId}-${r.spanId}-${e}`}var so=!1;function Cg(r){so=r}function vg(){return so}i();import{promises as oo}from"node:fs";import Gi from"node:path";import{AsyncLocalStorage as Ji}from"node:async_hooks";import Xi from"node:util";var lr=null,Br=null,Ur=!1,io=null,ao=new Ji;function lo(){let r=process.env.MATILDA_DEBUG_LOG_FILE;if(!r)return!1;let e=r.trim().toLowerCase();return!["","0","false","off","no"].includes(e)}function ar(){return ao.getStore()??io}function co(){let r=et.getGlobalDebugDir();return(!lr||Br!==r)&&(Br=r,lr=oo.mkdir(r,{recursive:!0}).then(()=>{}).catch(()=>{Ur=!0,lr=null,Br=null})),lr??Promise.resolve()}function Vi(r){return r.map(e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:e).map(e=>typeof e=="string"?e:Xi.inspect(e)).join(" ")}function zi(r,e,t,n){let s=new Date().toISOString(),o=t?` [${t}]`:"",a=n?` [trace_id=${n.traceId} span_id=${n.spanId}]`:"";return`${s} [${r}]${o}${a} ${e}
26
- `}function Lr(r,e,t,n){if(!lo())return;let s=r.getSessionId(),o=et.getDebugLogPath(s),a=Vi(n),c=no(),u=zi(e,a,t,c);co().then(()=>oo.appendFile(o,u,"utf8")).catch(()=>{Ur=!0})}function Lg(){return Ur}function Bg(){Ur=!1,lr=null,Br=null}var Ki="latest";function Qi(r){if(!lo())return;let e=Gi.join(et.getGlobalDebugDir(),Ki),t=et.getDebugLogPath(r);co().then(()=>Ys(e,t,{fallbackCopy:!1})).catch(()=>{})}function Ug(r){io=r??null,r&&Qi(r.getSessionId())}function Wg(r,e){return ao.run(r,e)}function Hg(r){return{isEnabled:()=>ar()!==null,debug:(...e)=>{let t=ar();t&&Lr(t,"DEBUG",r,e)},info:(...e)=>{let t=ar();t&&Lr(t,"INFO",r,e)},warn:(...e)=>{let t=ar();t&&Lr(t,"WARN",r,e)},error:(...e)=>{let t=ar();t&&Lr(t,"ERROR",r,e)}}}export{R as a,kn as b,Lm as c,Bm as d,Um as e,Wm as f,le as g,Ms as h,Fs as i,js as j,or as k,Ls as l,Bs as m,Us as n,Ws as o,Cn as p,vn as q,On as r,Hs as s,Hm as t,qs as u,qm as v,ir as w,Qm as x,Ym as y,Js as z,Zm as A,eg as B,tg as C,rg as D,ng as E,sg as F,og as G,Xs as H,Vs as I,zs as J,ig as K,ki as L,Ti as M,ag as N,Mi as O,et as P,Ys as Q,wg as R,xg as S,Hi as T,no as U,Eg as V,Cg as W,vg as X,Lg as Y,Bg as Z,Ug as _,Wg as $,Hg as aa};
25
+ `);this.baseURL=c.baseURL,this.timeout=c.timeout??En.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u="warn";this.logLevel=u,this.logLevel=tn(c.logLevel,"ClientOptions.logLevel",this)??tn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??Xn(),w(this,Fr,zn,"f"),this._options=c,this.apiKey=t,this.organization=n,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...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.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Zr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${qr()}`}makeStatusError(e,t,n,s){return N.generate(e,t,n,s)}buildURL(e,t,n){let s=!l(this,Rn,"m",Ns).call(this)&&n||this.baseURL,o=Mn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return jn(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:a,url:c,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:s});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),_=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(T(this).debug(`[${m}] sending request`,ce({retryOfRequestLogID:n,method:s.method,url:c,options:s,headers:a.headers})),s.signal?.aborted)throw new v;let y=new AbortController,f=await this.fetchWithTimeout(c,a,u,y).catch(Ut),P=Date.now();if(f instanceof Error){let E=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new v;let x=Bt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return T(this).info(`[${m}] connection ${x?"timed out":"failed"} - ${E}`),T(this).debug(`[${m}] connection ${x?"timed out":"failed"} (${E})`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),this.retryRequest(s,t,n??m);throw T(this).info(`[${m}] connection ${x?"timed out":"failed"} - error; no more retries left`),T(this).debug(`[${m}] connection ${x?"timed out":"failed"} (error; no more retries left)`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),x?new ge:new me({cause:f})}let A=[...f.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,x])=>", "+E+": "+JSON.stringify(x)).join(""),k=`[${m}${_}${A}] ${a.method} ${c} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${P-p}ms`;if(!f.ok){let E=await this.shouldRetry(f);if(t&&E){let O=`retrying, ${t} attempts remaining`;return await Vn(f.body),T(this).info(`${k} - ${O}`),T(this).debug(`[${m}] response error (${O})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),this.retryRequest(s,t,n??m,f.headers)}let x=E?"error; no more retries left":"error; not retryable";T(this).info(`${k} - ${x}`);let j=await f.text().catch(O=>Ut(O).message),C=Un(j),J=C?void 0:j;throw T(this).debug(`[${m}] response error (${x})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,C,J,f.headers)}return T(this).info(k),T(this).debug(`[${m}] response start`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),{response:f,options:s,controller:y,requestLogID:m,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Jt(this,n,e)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:a,...c}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,_={signal:s.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(_.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,_)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s){let o,a=s?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(o=u)}let c=s?.get("retry-after");if(c&&!o){let u=parseFloat(c);Number.isNaN(u)?o=Date.parse(c)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await te(o),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:s,path:o,query:a,defaultBaseURL:c}=n,u=this.buildURL(o,a,c);"timeout"in n&&Bn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:m,body:_}=this.buildBody({options:n}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:m,retryCount:t});return{req:{method:s,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=g([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Jn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:cr(e)}:l(this,Fr,"f").call(this,{body:e,headers:n})}};En=R,Fr=new WeakMap,Rn=new WeakSet,Ns=function(){return this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=En;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=b;R.APIError=N;R.APIConnectionError=me;R.APIConnectionTimeoutError=ge;R.APIUserAbortError=v;R.NotFoundError=st;R.ConflictError=ot;R.RateLimitError=at;R.BadRequestError=tt;R.AuthenticationError=rt;R.InternalServerError=lt;R.PermissionDeniedError=nt;R.UnprocessableEntityError=it;R.InvalidWebhookSignatureError=ee;R.toFile=br;R.Completions=Ue;R.Chat=we;R.Embeddings=He;R.Files=Ge;R.Images=ze;R.Audio=oe;R.Moderations=Qe;R.Models=Ke;R.FineTuning=Z;R.Graders=Re;R.VectorStores=he;R.Webhooks=Ye;R.Beta=ae;R.Batches=Me;R.Uploads=ve;R.Responses=Ce;R.Evals=Se;R.Containers=Pe;i();function Tn(r){return r instanceof Error&&"code"in r}function Lm(r){return!r||typeof r!="object"?!1:!!(r instanceof v||r instanceof Error&&r.name==="AbortError"||Tn(r)&&r.code==="ABORT_ERR")}function Bm(r){if(r instanceof Error){let e=r.cause;return e instanceof Error&&e.message!==r.message?`${r.message} (cause: ${e.message})`:r.message}try{return String(r)}catch{return"Failed to get error details"}}function Um(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status??e.statusCode??e.response?.status??e.error?.code;if(typeof t=="number"&&t>=100&&t<=599)return t;if(typeof e.message=="string"){let n=e.message.match(/HTTP_STATUS\/(\d{3})\b/);if(n){let s=Number(n[1]);if(s>=100&&s<=599)return s}}}function Wm(r){if(typeof r!="object"||r===null)return"unknown";let e=r instanceof Error&&r.constructor.name!=="Error"?r.constructor.name:void 0,t=r.type,n=e??t??(r instanceof Error?r.name:"unknown"),s=r instanceof Error?r.cause:void 0,o=s&&typeof s=="object"&&"code"in s?s.code:void 0;return o?`${n}:${o}`:n}var le=class extends Error{constructor(t,n){super(t);this.exitCode=n}},Ms=class extends le{constructor(e){super(e,41)}},Fs=class extends le{constructor(e){super(e,42)}},js=class extends le{constructor(e){super(e,44)}},or=class extends le{constructor(e){super(e,52)}},Ls=class extends le{constructor(e){super(e,53)}},Bs=class extends le{constructor(e){super(e,54)}},Us=class extends le{constructor(e){super(e,55)}},Ws=class extends le{constructor(e){super(e,130)}},Cn=class extends Error{},vn=class extends Error{},On=class extends Error{},Hs=class extends Error{status=403;code="ACCOUNT_INACTIVE";title="Account access restricted";constructor(){super("Your account is suspended or restricted from sending messages. Contact Matilda support to review your access. Signing in again will not remove this restriction."),this.name="AccountRestrictedError"}};function Hm(r){if(!r||typeof r!="object")return!1;let e=r;if(e.status!==void 0&&Number(e.status)!==403)return!1;let t=e.error;return e.code==="ACCOUNT_INACTIVE"||t==="account_inactive"||typeof t=="object"&&t!==null&&"code"in t&&t.code==="ACCOUNT_INACTIVE"}var qs=class extends Error{constructor(t,n,s,o){super(t);this.categories=n;this.severity=s;this.assistantMessage=o;this.name="ContentBlockedError"}};function qm(r){if(r&&typeof r=="object"&&"response"in r){let t=Ei(r);if(t.error&&t.error.message&&t.error.code)switch(t.error.code){case 400:return new On(t.error.message);case 401:return new vn(t.error.message);case 403:return new Cn(t.error.message);default:}}return r}function Ei(r){return typeof r.response?.data=="string"?JSON.parse(r.response?.data):r.response?.data}i();import Ci from"node:fs";import Q from"node:path";import Oe from"node:os";import*as Gs from"node:crypto";var ir=".matilda",Qm="google_accounts.json",Lt=new Map,vi=1024;function Ym(){Lt.clear()}var Js=/[ \t()[\]{};|*?$`'"#&<>!~,]/,Zm=["file_path","path","filePath","notebook_path"],Oi=(()=>{let r=Js.source.slice(1,-1);return new RegExp(`\\\\([${r}])`,"g")})();function eg(r){let e=Oe.homedir();return r.startsWith(e)?r.replace(e,"~"):r}function tg(r){if(!r)return"";let e=r;return r.toLowerCase().startsWith("%userprofile%")?e=Oe.homedir()+r.substring(13):(r==="~"||r.startsWith("~/"))&&(e=Oe.homedir()+r.substring(1)),Q.normalize(e)}function rg(r,e=80){if(r.length<=e)return r;let t=Q.sep,n="...";if(e<10)return r.substring(0,e-3)+n;let o=Q.parse(r).root,c=r.substring(o.length).split(t).filter(_=>_!=="");if(c.length===0)return o.length<=e?o:o.substring(0,e-3)+n;if(c.length===1){let _=o+c[0];if(_.length<=e)return _;let p=Math.floor((e-3)/2),y=_.substring(0,p),f=_.substring(_.length-p);return`${y}${n}${f}`}let u=o+c[0],m=[];for(let _=c.length-1;_>=1;_--){let p=c[_],y=[p,...m].join(t),f=_>1,P;if(f?P=u+t+n+t+y:P=u+t+y,P.length<=e){if(m.unshift(p),_===1)return P}else break}if(m.length===0){let _=Math.floor((e-3)/2),p=r.substring(0,_),y=r.substring(r.length-_);return`${p}${n}${y}`}return u+t+n+t+m.join(t)}function ng(r,e){let t=Q.resolve(r),n=Q.resolve(e);return zs(n,t)?Q.relative(n,t)||".":t}function sg(r){let e="";for(let t=0;t<r.length;t++){let n=r[t],s=0;for(let a=t-1;a>=0&&r[a]==="\\";a--)s++;!(s%2===1)&&Js.test(n)?e+="\\"+n:e+=n}return e}function og(r){return Oe.platform()==="win32"?r:r.replace(Oi,"$1")}function Xs(r){let e=Oe.platform()==="win32"?r.toLowerCase():r;return Gs.createHash("sha256").update(e).digest("hex")}function Vs(r){return(Oe.platform()==="win32"?r.toLowerCase():r).replace(/[^a-zA-Z0-9]/g,"-")}function zs(r,e){let n=Oe.platform()==="win32"?Q.win32:Q,s=n.relative(r,e);return!s.startsWith(`..${n.sep}`)&&s!==".."&&!n.isAbsolute(s)}function ig(r,e){return r.some(t=>zs(t,e))}function Ti(r=process.cwd(),e){let t=Oe.homedir();return e==="~"?t:e.startsWith("~/")?Q.join(t,e.slice(2)):Q.isAbsolute(e)?e:Q.resolve(r,e)}function ki(r,e,t={}){let{allowFiles:n=!1,allowExternalPaths:s=!1}=t,a=r.getWorkspaceContext().isPathWithinWorkspace(e);if(!s&&!a)throw new Error("Path is not within workspace");if(s&&!a)return;let c=Lt.get(e);if(c===void 0){try{c=Ci.statSync(e).isDirectory()}catch(u){throw Tn(u)&&u.code==="ENOENT"?new Error(`Path does not exist: ${e}`):u}if(Lt.size>=vi){let u=Lt.keys().next().value;u!==void 0&&Lt.delete(u)}Lt.set(e,c)}if(!n&&!c)throw new Error(`Path is not a directory: ${e}`)}function ag(r,e){let t=r.getTranscriptPath?.();return!!t&&Q.resolve(e)===Q.resolve(t)}function lg(r,e,t={}){let n=r.getTargetDir();if(!e)return n;let s=Ti(n,e);return ki(r,s,t),s}i();import*as I from"node:path";import*as Ze from"node:os";import*as jr from"node:fs";import{AsyncLocalStorage as $i}from"node:async_hooks";var Di="google_accounts.json",Ni="oauth_creds.json",Mi=[".matilda",".agents"],Ks="tmp",Fi="bin",ji="projects",Li="ide",Bi="plans",Ui="debug",Wi="arena",et=class r{targetDir;pinnedRuntimeBaseDir;static runtimeBaseDir=null;static runtimeBaseDirContext=new $i;constructor(e,t){this.targetDir=e,this.pinnedRuntimeBaseDir=t?r.resolvePath(t):void 0}getRuntimeBaseDir(){return this.pinnedRuntimeBaseDir??r.getRuntimeBaseDir()}static resolvePath(e,t){let n=e;if(n==="~"||n.startsWith("~/")||n.startsWith("~\\")){let s=n==="~"?[]:n.slice(2).split(/[/\\]+/).filter(Boolean);n=I.join(Ze.homedir(),...s)}return I.isAbsolute(n)||(n=t?I.resolve(t,n):I.resolve(n)),n}static sanitizePlanSessionId(e){return I.basename(e.replace(/\\/g,"/")).replace(/^\.+/g,"_").replace(/[<>:"|?*\x00-\x1F]/g,"_")||"_"}static resolveRuntimeBaseDir(e,t){return e?r.resolvePath(e,t):null}static setRuntimeBaseDir(e,t){r.runtimeBaseDir=r.resolveRuntimeBaseDir(e,t)}static runWithRuntimeBaseDir(e,t,n){let s=r.resolveRuntimeBaseDir(e,t);return r.runtimeBaseDirContext.run(s,n)}static getRuntimeBaseDir(){let e=process.env.MATILDA_RUNTIME_DIR;if(e)return r.resolveRuntimeBaseDir(e)??r.getGlobalMatildaDir();let t=r.runtimeBaseDirContext.getStore();return t!==void 0?t??r.getGlobalMatildaDir():r.runtimeBaseDir?r.runtimeBaseDir:r.getGlobalMatildaDir()}static getGlobalMatildaDir(){let e=process.env.MATILDA_HOME;if(e)return r.resolvePath(e);let t=Ze.homedir();return t?I.join(t,ir):I.join(Ze.tmpdir(),".matilda")}static getMcpOAuthTokensPath(){return I.join(r.getGlobalMatildaDir(),"mcp-oauth-tokens.json")}static getGlobalSettingsPath(){return I.join(r.getGlobalMatildaDir(),"settings.json")}static getInstallationIdPath(){return I.join(r.getGlobalMatildaDir(),"installation_id")}static getGoogleAccountsPath(){return I.join(r.getGlobalMatildaDir(),Di)}static getUserCommandsDir(){return I.join(r.getGlobalMatildaDir(),"commands")}static getGlobalMemoryFilePath(){return I.join(r.getGlobalMatildaDir(),"memory.md")}static getGlobalTempDir(){return I.join(r.getRuntimeBaseDir(),Ks)}static getGlobalDebugDir(){return I.join(r.getRuntimeBaseDir(),Ui)}static getDebugLogPath(e){return I.join(r.getGlobalDebugDir(),`${e}.txt`)}static getGlobalIdeDir(){return I.join(r.getGlobalMatildaDir(),Li)}static resolvePathThroughExistingAncestor(e){let t=e;for(;;)try{let n=jr.realpathSync(t),s=I.relative(t,e);return I.join(n,s)}catch(n){if(n.code!=="ENOENT")throw n;let s=I.dirname(t);if(s===t)return e;t=s}}static isPathWithinDirectory(e,t){let n=r.resolvePathThroughExistingAncestor(t),s=r.resolvePathThroughExistingAncestor(e),o=I.relative(n,s);return o===""||!o.startsWith("..")&&!I.isAbsolute(o)}static assertPathWithinDirectory(e,t,n){if(!r.isPathWithinDirectory(e,t))throw new or(n)}static getPlansDir(e,t){let n=t?.trim();if(n){if(!e)throw new or("projectRoot is required when plansDirectory is configured.");let s=I.resolve(e),o=r.resolvePath(n,s);return r.assertPathWithinDirectory(o,s,"plansDirectory must resolve within the project root."),o}return I.join(r.getGlobalMatildaDir(),Bi)}static getPlanFilePath(e,t,n){return I.join(r.getPlansDir(t,n),`${r.sanitizePlanSessionId(e)}.md`)}static getGlobalBinDir(){return I.join(r.getGlobalMatildaDir(),Fi)}static getGlobalArenaDir(){return I.join(r.getGlobalMatildaDir(),Wi)}getMatildaDir(){return I.join(this.targetDir,ir)}getProjectDir(){let e=Vs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),ji);return I.join(t,e)}getProjectTempDir(){let e=Xs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),Ks);return I.join(t,e)}getToolResultsDir(){return I.join(this.getProjectTempDir(),"tool-results")}ensureProjectTempDirExists(){jr.mkdirSync(this.getProjectTempDir(),{recursive:!0})}static getOAuthCredsPath(){return I.join(r.getGlobalMatildaDir(),Ni)}getProjectRoot(){return this.targetDir}getWorkspaceSettingsPath(){return I.join(this.getMatildaDir(),"settings.json")}getProjectCommandsDir(){return I.join(this.getMatildaDir(),"commands")}getRuntimeStatusPath(e){return I.join(this.getProjectDir(),"chats",`${e}.runtime.json`)}getProjectTempCheckpointsDir(){return I.join(this.getProjectTempDir(),"checkpoints")}getExtensionsDir(){return I.join(this.getMatildaDir(),"extensions")}getExtensionsConfigPath(){return I.join(this.getExtensionsDir(),"matilda-extension.json")}getUserSkillsDirs(){let e=Ze.homedir()||Ze.tmpdir();return Mi.map(t=>t===ir?I.join(r.getGlobalMatildaDir(),"skills"):I.join(e,t,"skills"))}static getUserExtensionsDir(){return I.join(r.getGlobalMatildaDir(),"extensions")}getHistoryFilePath(){return I.join(this.getProjectTempDir(),"shell_history")}};i();import{promises as kn}from"node:fs";import Qs from"node:path";async function Ys(r,e,t){let{fallbackCopy:n=!0}=t??{},s=Qs.dirname(r),o=Qs.relative(s,e);try{await kn.unlink(r)}catch{}try{await kn.symlink(o,r);return}catch{}if(n)try{await kn.copyFile(e,r)}catch{}}i();fo();i();var Zs,eo;function xg(r,e){Zs=r,eo=e}function to(){return Zs}function Ag(){return eo}function ro(r){let e=r?.spanContext();return e&&Nn(e)?{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}:null}function Hi(){try{return ro(Hr.getActiveSpan())}catch{return null}}function qi(){try{let r=to();return ro(r?Hr.getSpan(r):void 0)}catch{return null}}function no(){return Hi()??qi()}function Cg(r){let e=(r.traceFlags&255).toString(16).padStart(2,"0");return`00-${r.traceId}-${r.spanId}-${e}`}var so=!1;function vg(r){so=r}function Og(){return so}i();import{promises as oo}from"node:fs";import Gi from"node:path";import{AsyncLocalStorage as Ji}from"node:async_hooks";import Xi from"node:util";var lr=null,Br=null,Ur=!1,io=null,ao=new Ji;function lo(){let r=process.env.MATILDA_DEBUG_LOG_FILE;if(!r)return!1;let e=r.trim().toLowerCase();return!["","0","false","off","no"].includes(e)}function ar(){return ao.getStore()??io}function co(){let r=et.getGlobalDebugDir();return(!lr||Br!==r)&&(Br=r,lr=oo.mkdir(r,{recursive:!0}).then(()=>{}).catch(()=>{Ur=!0,lr=null,Br=null})),lr??Promise.resolve()}function Vi(r){return r.map(e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:e).map(e=>typeof e=="string"?e:Xi.inspect(e)).join(" ")}function zi(r,e,t,n){let s=new Date().toISOString(),o=t?` [${t}]`:"",a=n?` [trace_id=${n.traceId} span_id=${n.spanId}]`:"";return`${s} [${r}]${o}${a} ${e}
26
+ `}function Lr(r,e,t,n){if(!lo())return;let s=r.getSessionId(),o=et.getDebugLogPath(s),a=Vi(n),c=no(),u=zi(e,a,t,c);co().then(()=>oo.appendFile(o,u,"utf8")).catch(()=>{Ur=!0})}function Bg(){return Ur}function Ug(){Ur=!1,lr=null,Br=null}var Ki="latest";function Qi(r){if(!lo())return;let e=Gi.join(et.getGlobalDebugDir(),Ki),t=et.getDebugLogPath(r);co().then(()=>Ys(e,t,{fallbackCopy:!1})).catch(()=>{})}function Wg(r){io=r??null,r&&Qi(r.getSessionId())}function Hg(r,e){return ao.run(r,e)}function qg(r){return{isEnabled:()=>ar()!==null,debug:(...e)=>{let t=ar();t&&Lr(t,"DEBUG",r,e)},info:(...e)=>{let t=ar();t&&Lr(t,"INFO",r,e)},warn:(...e)=>{let t=ar();t&&Lr(t,"WARN",r,e)},error:(...e)=>{let t=ar();t&&Lr(t,"ERROR",r,e)}}}export{R as a,Tn as b,Lm as c,Bm as d,Um as e,Wm as f,le as g,Ms as h,Fs as i,js as j,or as k,Ls as l,Bs as m,Us as n,Ws as o,Cn as p,vn as q,On as r,Hs as s,Hm as t,qs as u,qm as v,ir as w,Qm as x,Ym as y,Js as z,Zm as A,eg as B,tg as C,rg as D,ng as E,sg as F,og as G,Xs as H,Vs as I,zs as J,ig as K,Ti as L,ki as M,ag as N,lg as O,Mi as P,et as Q,Ys as R,xg as S,Ag as T,Hi as U,no as V,Cg as W,vg as X,Og as Y,Bg as Z,Ug as _,Wg as $,Hg as aa,qg as ba};
27
27
  /**
28
28
  * @license
29
29
  * Copyright 2025 Google LLC