eser 4.1.13 → 4.1.22

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 (191) hide show
  1. package/README.md +152 -3
  2. package/chunks/add-4LRHVBEC.js +7 -0
  3. package/chunks/anthropic-GBDSASP5.js +1 -0
  4. package/chunks/approve-364KOMLB.js +1 -0
  5. package/chunks/ask-752YJEHO.js +2 -0
  6. package/chunks/block-JVJQU723.js +1 -0
  7. package/chunks/browser-6UKLTPJO.js +1 -0
  8. package/chunks/build-VKOO2WEA.js +6 -0
  9. package/chunks/bun-N3TIWBPP.js +1 -0
  10. package/chunks/changelog-gen-ZCNNOY7G.js +7 -0
  11. package/chunks/chunk-2R4MK2KR.js +2 -0
  12. package/chunks/chunk-2TRQKCFC.js +1 -0
  13. package/chunks/chunk-34GCQZ3Z.js +3 -0
  14. package/chunks/chunk-3APERFKY.js +18 -0
  15. package/chunks/chunk-3DMTTLUJ.js +1 -0
  16. package/chunks/chunk-3TYZYY77.js +1 -0
  17. package/chunks/chunk-4HMEWMWL.js +1 -0
  18. package/chunks/chunk-4HNB3UTC.js +1 -0
  19. package/chunks/chunk-4OIKB2P5.js +1 -0
  20. package/chunks/chunk-4Q3SEHPE.js +1 -0
  21. package/chunks/chunk-4S7QYPS6.js +1 -0
  22. package/chunks/chunk-5C7ZQN6X.js +3 -0
  23. package/chunks/chunk-5O7V5P53.js +1 -0
  24. package/chunks/chunk-5UGVJVIQ.js +1 -0
  25. package/chunks/chunk-6FMPNAZ3.js +1 -0
  26. package/chunks/chunk-6U2VEZEM.js +1 -0
  27. package/chunks/chunk-6YRN6OJC.js +2 -0
  28. package/chunks/chunk-7GS5KPVF.js +1 -0
  29. package/chunks/chunk-7M3ONEMO.js +32 -0
  30. package/chunks/chunk-7QNRH7OR.js +3 -0
  31. package/chunks/chunk-A2GDVOQP.js +1 -0
  32. package/chunks/chunk-AK3OJD4W.js +1 -0
  33. package/chunks/chunk-ATLUGTI7.js +2 -0
  34. package/chunks/chunk-BK2BDHKB.js +1 -0
  35. package/chunks/chunk-BKVQBSFV.js +6 -0
  36. package/chunks/chunk-BP2MZX2P.js +2 -0
  37. package/chunks/chunk-C3OSYHJY.js +2 -0
  38. package/chunks/chunk-CDLEA2PD.js +1 -0
  39. package/chunks/chunk-DDLQMSA7.js +0 -0
  40. package/chunks/chunk-DLVQNMNV.js +1 -0
  41. package/chunks/chunk-DOV5776P.js +3 -0
  42. package/chunks/chunk-DQAEQEXD.js +1 -0
  43. package/chunks/chunk-DRQWYJMH.js +1 -0
  44. package/chunks/chunk-DXB73IDG.js +1 -0
  45. package/chunks/chunk-DZD6MI45.js +5 -0
  46. package/chunks/chunk-EW5NCPPE.js +3 -0
  47. package/chunks/chunk-FGDJVQG3.js +32 -0
  48. package/chunks/chunk-FKF2SWQM.js +18 -0
  49. package/chunks/chunk-GETSWLMF.js +4 -0
  50. package/chunks/chunk-GLSCZGXA.js +1 -0
  51. package/chunks/chunk-GRTR6TNJ.js +1 -0
  52. package/chunks/chunk-GXPLME3K.js +14 -0
  53. package/chunks/chunk-H2JGLZIR.js +1 -0
  54. package/chunks/chunk-HGNGFAAY.js +60 -0
  55. package/chunks/chunk-HPPFA3XU.js +1 -0
  56. package/chunks/chunk-HPVL4BVQ.js +2 -0
  57. package/chunks/chunk-HVMMNGY5.js +7 -0
  58. package/chunks/chunk-IA7GIU76.js +14 -0
  59. package/chunks/chunk-IAWIWTDY.js +1 -0
  60. package/chunks/chunk-JQHMDTPL.js +1 -0
  61. package/chunks/chunk-L2BYHWDC.js +1 -0
  62. package/chunks/chunk-LRL56YFE.js +1 -0
  63. package/chunks/chunk-LU3DHXOC.js +2 -0
  64. package/chunks/chunk-LXVBR775.js +1 -0
  65. package/chunks/chunk-M5TBBQQC.js +21 -0
  66. package/chunks/chunk-MQH4XBFN.js +1 -0
  67. package/chunks/chunk-NADES3GN.js +1 -0
  68. package/chunks/chunk-NIX3WX3O.js +1 -0
  69. package/chunks/chunk-NSZ4HGDI.js +1 -0
  70. package/chunks/chunk-NUSNMQPL.js +1 -0
  71. package/chunks/chunk-NZFUFGOC.js +1 -0
  72. package/chunks/chunk-OBIEQJDE.js +4 -0
  73. package/chunks/chunk-OLM5RTFK.js +1 -0
  74. package/chunks/chunk-PBSR4XR2.js +335 -0
  75. package/chunks/chunk-PLJNPQFC.js +1 -0
  76. package/chunks/chunk-PLRSDG6G.js +2 -0
  77. package/chunks/chunk-Q7QMINSQ.js +0 -0
  78. package/chunks/chunk-QIUIPRJP.js +1 -0
  79. package/chunks/chunk-QXTK62N4.js +1 -0
  80. package/chunks/chunk-R6F4EK2B.js +4 -0
  81. package/chunks/chunk-RGUC6KAZ.js +1 -0
  82. package/chunks/chunk-SCCNNGD4.js +2 -0
  83. package/chunks/chunk-SCULX2ND.js +1 -0
  84. package/chunks/chunk-SJQWPBMJ.js +1 -0
  85. package/chunks/chunk-TMFPDVYN.js +127 -0
  86. package/chunks/chunk-UJX2S56V.js +1 -0
  87. package/chunks/chunk-USCAYIWL.js +1 -0
  88. package/chunks/chunk-V5HTJPFW.js +3 -0
  89. package/chunks/chunk-VFMYWG2I.js +3 -0
  90. package/chunks/chunk-VGFZXQMW.js +1 -0
  91. package/chunks/chunk-VTQ72OK7.js +1 -0
  92. package/chunks/chunk-WE7PSSAQ.js +91 -0
  93. package/chunks/chunk-WUJUQPHI.js +1 -0
  94. package/chunks/chunk-X4ZCYXOT.js +1 -0
  95. package/chunks/chunk-XJ3VEVYL.js +3 -0
  96. package/chunks/chunk-XMTGT2NJ.js +10 -0
  97. package/chunks/chunk-XWYLEYLY.js +1 -0
  98. package/chunks/chunk-Y6DLCHJN.js +1 -0
  99. package/chunks/chunk-Y6DZEK4W.js +1 -0
  100. package/chunks/chunk-YUXQ7JNG.js +1 -0
  101. package/chunks/chunk-Z7742D7Q.js +1 -0
  102. package/chunks/chunk-ZE5T64HQ.js +1 -0
  103. package/chunks/chunk-ZF2XYULB.js +1 -0
  104. package/chunks/chunk-ZOZYBQX2.js +0 -0
  105. package/chunks/chunk-ZTLJ775S.js +1 -0
  106. package/chunks/chunk-ZY72QNKZ.js +3 -0
  107. package/chunks/claude-code-PWTLM554.js +1 -0
  108. package/chunks/clone-DASXIL35.js +5 -0
  109. package/chunks/commitmsg-SQRQONCS.js +10 -0
  110. package/chunks/deno-PZXN5K3J.js +1 -0
  111. package/chunks/dev-FLO2KEPZ.js +3 -0
  112. package/chunks/file-tools-shared-ESMPLZVJ.js +1 -0
  113. package/chunks/fileFromPath-4UEDFJ4U.js +6 -0
  114. package/chunks/gemini-I6F5N7PS.js +1 -0
  115. package/chunks/gh-Y4BXDXR5.js +4 -0
  116. package/chunks/gh-contributors-5SHGJHAQ.js +11 -0
  117. package/chunks/init-GXBXQGGV.js +1 -0
  118. package/chunks/init-UFJL24PW.js +12 -0
  119. package/chunks/install-Q2KQZM62.js +2 -0
  120. package/chunks/kiro-NMTIFMT4.js +1 -0
  121. package/chunks/list-B7L4FZKG.js +2 -0
  122. package/chunks/list-MN7OUE52.js +1 -0
  123. package/chunks/list-UZKWSA4S.js +1 -0
  124. package/chunks/load-config-TSM3AAQ6.js +1 -0
  125. package/chunks/main-WVXCURBF.js +5 -0
  126. package/chunks/manifest-VJQJG2LS.js +1 -0
  127. package/chunks/mod-3PJAIZ2O.js +1 -0
  128. package/chunks/mod-6P2JPEHC.js +1 -0
  129. package/chunks/mod-7X3BOO5H.js +1 -0
  130. package/chunks/mod-CI56JMO4.js +43 -0
  131. package/chunks/mod-FKPTF5D5.js +1 -0
  132. package/chunks/mod-GZ6BSK2P.js +1 -0
  133. package/chunks/mod-JTBNNSZZ.js +1 -0
  134. package/chunks/mod-MKMQWZ6G.js +1 -0
  135. package/chunks/mod-PEAFMI6F.js +1 -0
  136. package/chunks/mod-QODEWK3G.js +9 -0
  137. package/chunks/mod-STKIZYZ3.js +27 -0
  138. package/chunks/new-W5YBJFGW.js +4 -0
  139. package/chunks/next-773GX25N.js +3 -0
  140. package/chunks/node-RWYXITVV.js +59 -0
  141. package/chunks/node-VPHAK3FD.js +1 -0
  142. package/chunks/ollama-DQ5VM4HI.js +1 -0
  143. package/chunks/openai-EKIA3VP3.js +19 -0
  144. package/chunks/openai-XMIVMDDL.js +1 -0
  145. package/chunks/opencode-IZMQZ4ZK.js +1 -0
  146. package/chunks/recipe-applier-F2REROYS.js +1 -0
  147. package/chunks/registry-fetcher-ZJ76EHBA.js +1 -0
  148. package/chunks/release-YJOLKWDT.js +8 -0
  149. package/chunks/release-notes-Z53AFCII.js +3 -0
  150. package/chunks/release-tag-QRIKYVQB.js +1 -0
  151. package/chunks/reset-5LQGIOGB.js +1 -0
  152. package/chunks/rule-K42YEAMO.js +2 -0
  153. package/chunks/run-7JXDS75G.js +4 -0
  154. package/chunks/scripts-RSK5XDRW.js +1 -0
  155. package/chunks/sdk-5JGXLIO5.js +18 -0
  156. package/chunks/serve-U6IXMGXQ.js +3 -0
  157. package/chunks/server-PXE4DB3V.js +69 -0
  158. package/chunks/spec-5446CSQC.js +1 -0
  159. package/chunks/status-HK3P6J6G.js +1 -0
  160. package/chunks/sync-4FSA5257.js +1 -0
  161. package/chunks/system-3MH6OCP6.js +1 -0
  162. package/chunks/system-KWFBSQYQ.js +1 -0
  163. package/chunks/unstable_chmod-WRDBWEC2.js +1 -0
  164. package/chunks/update-QD5S73WT.js +5 -0
  165. package/chunks/validate-bom-IVALGNGE.js +1 -0
  166. package/chunks/validate-case-conflict-LKECKLD5.js +1 -0
  167. package/chunks/validate-circular-deps-PXFPCBXA.js +1 -0
  168. package/chunks/validate-commit-msg-77CBKGOF.js +1 -0
  169. package/chunks/validate-docs-3UGB7LN7.js +1 -0
  170. package/chunks/validate-eof-ZSIYNHO5.js +1 -0
  171. package/chunks/validate-export-names-BPSCBX7B.js +1 -0
  172. package/chunks/validate-filenames-G4XJ2LHN.js +1 -0
  173. package/chunks/validate-json-YRCFW2O7.js +1 -0
  174. package/chunks/validate-large-files-MWWSFDOE.js +1 -0
  175. package/chunks/validate-licenses-Q2YA2MND.js +1 -0
  176. package/chunks/validate-line-endings-C6NHWHGI.js +1 -0
  177. package/chunks/validate-merge-conflict-KTBL4FUY.js +1 -0
  178. package/chunks/validate-mod-exports-LQIIQRIS.js +1 -0
  179. package/chunks/validate-package-configs-36PYXIWC.js +1 -0
  180. package/chunks/validate-secrets-UFDJ7ITY.js +1 -0
  181. package/chunks/validate-shebangs-3UO4MDMZ.js +1 -0
  182. package/chunks/validate-submodules-YA654D3B.js +1 -0
  183. package/chunks/validate-symlinks-R2PNE5TG.js +1 -0
  184. package/chunks/validate-toml-7H2N5AKI.js +1 -0
  185. package/chunks/validate-trailing-whitespace-HXO7M3ED.js +1 -0
  186. package/chunks/validate-yaml-ZJJCQVBB.js +1 -0
  187. package/chunks/versions-CWT5S7G4.js +1 -0
  188. package/chunks/vertexai-2SMP54AR.js +1 -0
  189. package/chunks/workerd-NXKZMQPV.js +1 -0
  190. package/eser.js +1 -986
  191. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ import{b as F}from"./chunk-4OIKB2P5.js";import{b as v,d as E}from"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";import*as s from"node:fs/promises";import*as x from"node:fs";import*as i from"node:path";import*as g from"node:os";import*as b from"node:child_process";import d from"node:process";import{Buffer as w}from"node:buffer";import{Readable as k,Writable as O}from"node:stream";var S={fs:!0,fsSync:!0,exec:!0,process:!0,env:!0,stdin:!0,stdout:!0,kv:!1},R=()=>{let n=e=>({isFile:e.isFile(),isDirectory:e.isDirectory(),isSymlink:e.isSymbolicLink(),size:e.size,mtime:e.mtime,atime:e.atime,birthtime:e.birthtime}),a=(e,t)=>{throw e instanceof Error&&"code"in e&&e.code==="ENOENT"?new v(t):e};return{async readFile(e,t){try{let r=await s.readFile(e,{signal:t?.signal});return new Uint8Array(r)}catch(r){return a(r,e)}},async readTextFile(e,t){try{return await s.readFile(e,{encoding:"utf-8",signal:t?.signal})}catch(r){return a(r,e)}},async writeFile(e,t,r){let c=r?.append?"a":"w";await s.writeFile(e,t,{signal:r?.signal,mode:r?.mode,flag:c})},async writeTextFile(e,t,r){let c=r?.append?"a":"w";await s.writeFile(e,t,{encoding:"utf-8",signal:r?.signal,mode:r?.mode,flag:c})},async exists(e){try{return await s.access(e),!0}catch{return!1}},async stat(e){try{let t=await s.stat(e);return n(t)}catch(t){return a(t,e)}},async lstat(e){try{let t=await s.lstat(e);return n(t)}catch(t){return a(t,e)}},async mkdir(e,t){await s.mkdir(e,{recursive:t?.recursive??!1,mode:t?.mode})},async ensureDir(e){await s.mkdir(e,{recursive:!0})},async remove(e,t){try{await s.rm(e,{recursive:t?.recursive??!1,force:!1})}catch(r){a(r,e)}},async*readDir(e){try{let t=await s.readdir(e,{withFileTypes:!0});for(let r of t)yield{name:r.name,isFile:r.isFile(),isDirectory:r.isDirectory(),isSymlink:r.isSymbolicLink()}}catch(t){a(t,e)}},async copyFile(e,t){await s.copyFile(e,t)},async rename(e,t){await s.rename(e,t)},async makeTempDir(e){let t=e?.dir??g.tmpdir(),r=e?.prefix??"",c=e?.suffix??"",u=await s.mkdtemp(i.join(t,r));if(c){let o=u+c;return await s.rename(u,o),o}return u},async realPath(e){try{return await s.realpath(e)}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ENOENT"?new v(e):t}},watch(e,t){let r=t?.recursive??!0,c=[],u=[],o=[],l=!1,P=m=>{l||(o.length>0?o.shift()({value:m,done:!1}):u.push(m))};for(let m of e)try{let f=x.watch(m,{recursive:r},(h,y)=>{y!==null&&P({kind:h==="rename"?"create":"modify",paths:[i.join(m,y)]})});c.push(f)}catch{}return{close:()=>{l=!0;for(let m of c)m.close();for(let m of o)m({value:void 0,done:!0});o=[]},[Symbol.asyncIterator]:()=>({next:()=>l?Promise.resolve({value:void 0,done:!0}):u.length>0?Promise.resolve({value:u.shift(),done:!1}):new Promise(m=>{o.push(m)})})}},async chmod(e,t){await s.chmod(e,t)},async*walk(e,t){let r=t?.includeDirs??!0,c=t?.includeFiles??!0,u=t?.exts,o=t?.skip,l=async function*(P){let m=await s.readdir(P,{withFileTypes:!0});for(let f of m){let h=i.join(P,f.name);if(o?.some(p=>p.test(h)))continue;let y=f.isSymbolicLink();if(f.isDirectory())r&&(yield{path:h,name:f.name,isFile:!1,isDirectory:!0,isSymlink:y}),yield*l(h);else if(f.isFile()||y){if(!c||u&&!u.some(p=>f.name.endsWith(p.startsWith(".")?p:`.${p}`)))continue;yield{path:h,name:f.name,isFile:f.isFile(),isDirectory:!1,isSymlink:y}}}};yield*l(e)}}},W=()=>({join:i.join,resolve:i.resolve,dirname:i.dirname,basename:i.basename,extname:i.extname,normalize:i.normalize,isAbsolute:i.isAbsolute,relative:i.relative,parse:i.parse,format:i.format,sep:i.sep,delimiter:i.delimiter}),A=()=>({spawn(n,a=[],e){return new Promise((t,r)=>{let c=b.spawn(n,a,{cwd:e?.cwd,env:e?.env?{...d.env,...e.env}:void 0,stdio:F(e),signal:e?.signal}),u=[],o=[];c.stdout?.on("data",l=>u.push(l)),c.stderr?.on("data",l=>o.push(l)),c.on("error",r),c.on("close",l=>{t({success:l===0,code:l??1,stdout:new Uint8Array(w.concat(u)),stderr:new Uint8Array(w.concat(o))})})})},async exec(n,a=[],e){let t=await this.spawn(n,a,e);if(!t.success){let r=new TextDecoder().decode(t.stderr);throw new E(n,t.code,r)}return new TextDecoder().decode(t.stdout).trim()},async execJson(n,a=[],e){let t=await this.exec(n,a,e);return JSON.parse(t)},spawnChild(n,a=[],e){let t=b.spawn(n,a,{cwd:e?.cwd,env:e?.env?{...d.env,...e.env}:void 0,stdio:F(e),signal:e?.signal}),r=[],c=[];t.stdout?.on("data",o=>r.push(o)),t.stderr?.on("data",o=>c.push(o));let u=new Promise((o,l)=>{t.on("error",l),t.on("close",(P,m)=>{o({success:P===0,code:P??1,signal:m??void 0})})});return{pid:t.pid,stdin:t.stdin?O.toWeb(t.stdin):null,stdout:t.stdout?k.toWeb(t.stdout):null,stderr:t.stderr?k.toWeb(t.stderr):null,status:u,output:async()=>{let o=await u;return{success:o.success,code:o.code,stdout:new Uint8Array(w.concat(r)),stderr:new Uint8Array(w.concat(c))}},kill:o=>{t.kill(o)}}}}),D=()=>({get(n){return d.env[n]},set(n,a){d.env[n]=a},delete(n){delete d.env[n]},has(n){return n in d.env},toObject(){let n={};for(let[a,e]of Object.entries(d.env))e!==void 0&&(n[a]=e);return n}}),C=()=>({exit(n){d.exit(n)},setExitCode(n){d.exitCode=n},cwd(){return d.cwd()},chdir(n){d.chdir(n)},hostname(){return g.hostname()},execPath(){return d.execPath},args:d.argv.slice(2),pid:d.pid,stdin:k.toWeb(d.stdin),stdout:O.toWeb(d.stdout),stderr:O.toWeb(d.stderr)}),j=()=>{let n=R(),a=W(),e=A(),t=D(),r=C();return{name:"node",version:d.versions.node,capabilities:S,fs:n,path:a,exec:e,env:t,process:r}};export{S as NODE_CAPABILITIES,j as createNodeRuntime};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-ZY72QNKZ.js";import"./chunk-7QNRH7OR.js";import"./chunk-OLM5RTFK.js";import"./chunk-DOV5776P.js";import"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";export{a as OllamaModel,b as ollamaFactory};
@@ -0,0 +1,19 @@
1
+ import{a as Ds,b as Dn,c as jn,d as js}from"./chunk-IA7GIU76.js";import{a as Ln}from"./chunk-AK3OJD4W.js";import{b as Bs,c as Ls}from"./chunk-FKF2SWQM.js";import{e as Xr}from"./chunk-DXB73IDG.js";var gr="RFC3986",wr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:s=>String(s)},Us="RFC1738";var Un=Array.isArray,Z=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Gr=1024,qs=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Gr){let c=o.length>=Gr?o.slice(a,a+Gr):o,d=[];for(let b=0;b<c.length;++b){let u=c.charCodeAt(b);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||n===Us&&(u===40||u===41)){d[d.length]=c.charAt(b);continue}if(u<128){d[d.length]=Z[u];continue}if(u<2048){d[d.length]=Z[192|u>>6]+Z[128|u&63];continue}if(u<55296||u>=57344){d[d.length]=Z[224|u>>12]+Z[128|u>>6&63]+Z[128|u&63];continue}b+=1,u=65536+((u&1023)<<10|c.charCodeAt(b)&1023),d[d.length]=Z[240|u>>18]+Z[128|u>>12&63]+Z[128|u>>6&63]+Z[128|u&63]}i+=d.join("")}return i};function Ws(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Kr(s,e){if(Un(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var qn=Object.prototype.hasOwnProperty,Hs={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},ee=Array.isArray,Wn=Array.prototype.push,Js=function(s,e){Wn.apply(s,ee(e)?e:[e])},Hn=Date.prototype.toISOString,T={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:qs,encodeValuesOnly:!1,format:gr,formatter:wr[gr],indices:!1,serializeDate(s){return Hn.call(s)},skipNulls:!1,strictNullHandling:!1};function Jn(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var zr={};function Vs(s,e,t,r,n,o,i,a,c,d,b,u,p,h,A,_,C,v){let g=s,L=v,R=0,k=!1;for(;(L=L.get(zr))!==void 0&&!k;){let E=L.get(s);if(R+=1,typeof E<"u"){if(E===R)throw new RangeError("Cyclic object value");k=!0}typeof L.get(zr)>"u"&&(R=0)}if(typeof d=="function"?g=d(e,g):g instanceof Date?g=p?.(g):t==="comma"&&ee(g)&&(g=Kr(g,function(E){return E instanceof Date?p?.(E):E})),g===null){if(o)return c&&!_?c(e,T.encoder,C,"key",h):e;g=""}if(Jn(g)||Ws(g)){if(c){let E=_?e:c(e,T.encoder,C,"key",h);return[A?.(E)+"="+A?.(c(g,T.encoder,C,"value",h))]}return[A?.(e)+"="+A?.(String(g))]}let j=[];if(typeof g>"u")return j;let U;if(t==="comma"&&ee(g))_&&c&&(g=Kr(g,c)),U=[{value:g.length>0?g.join(",")||null:void 0}];else if(ee(d))U=d;else{let E=Object.keys(g);U=b?E.sort(b):E}let M=a?String(e).replace(/\./g,"%2E"):String(e),N=r&&ee(g)&&g.length===1?M+"[]":M;if(n&&ee(g)&&g.length===0)return N+"[]";for(let E=0;E<U.length;++E){let $=U[E],Ms=typeof $=="object"&&typeof $.value<"u"?$.value:g[$];if(i&&Ms===null)continue;let Vr=u&&a?$.replace(/\./g,"%2E"):$,Bn=ee(g)?typeof t=="function"?t(N,Vr):N:N+(u?"."+Vr:"["+Vr+"]");v.set(s,R);let Ns=new WeakMap;Ns.set(zr,v),Js(j,Vs(Ms,Bn,t,r,n,o,i,a,t==="comma"&&_&&ee(g)?null:c,d,b,u,p,h,A,_,C,Ns))}return j}function Vn(s=T){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||T.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=gr;if(typeof s.format<"u"){if(!qn.call(wr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=wr[t],n=T.filter;(typeof s.filter=="function"||ee(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Hs?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=T.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:T.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:T.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:T.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:T.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?T.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:T.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:T.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:T.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:T.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:T.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:T.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:T.strictNullHandling}}function Qr(s,e={}){let t=s,r=Vn(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):ee(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let a=Hs[r.arrayFormat],c=a==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let d=new WeakMap;for(let p=0;p<n.length;++p){let h=n[p];r.skipNulls&&t[h]===null||Js(i,Vs(t[h],h,a,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let b=i.join(r.delimiter),u=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),b.length>0?u+b:""}var je="4.104.0";var Xs=!1,Ue,Yr,Gn,Kn,zn,Zr,Qn,yr,es,ts,rs,rr,ss;function Gs(s,e={auto:!1}){if(Xs)throw new Error(`you must \`import 'openai/shims/${s.kind}'\` before importing anything else from openai`);if(Ue)throw new Error(`can't \`import 'openai/shims/${s.kind}'\` after \`import 'openai/shims/${Ue}'\``);Xs=e.auto,Ue=s.kind,Yr=s.fetch,Gn=s.Request,Kn=s.Response,zn=s.Headers,Zr=s.FormData,Qn=s.Blob,yr=s.File,es=s.ReadableStream,ts=s.getMultipartRequestOptions,rs=s.getDefaultAgent,rr=s.fileFromPath,ss=s.isFsReadStream}var be=Xr(Ln(),1);var ns=Xr(Dn(),1),zs=Xr(jn(),1);import{ReadStream as Zn}from"node:fs";import{Readable as eo}from"node:stream";var br=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};import{ReadableStream as to}from"node:stream/web";var Ks=!1;async function ro(s,...e){let{fileFromPath:t}=await import("./fileFromPath-4UEDFJ4U.js");return Ks||(console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(s)}) instead`),Ks=!0),await t(s,...e)}var so=new ns.default({keepAlive:!0,timeout:5*60*1e3}),no=new ns.default.HttpsAgent({keepAlive:!0,timeout:5*60*1e3});async function oo(s,e){let t=new js(s),r=eo.from(t),n=new br(r),o={...e.headers,...t.headers,"Content-Length":t.contentLength};return{...e,body:n,headers:o}}function Qs(){return typeof AbortController>"u"&&(globalThis.AbortController=zs.AbortController),{kind:"node",fetch:be.default,Request:be.Request,Response:be.Response,Headers:be.Headers,FormData:Ds,Blob:Bs,File:Ls,ReadableStream:to,getMultipartRequestOptions:oo,getDefaultAgent:s=>s.startsWith("https")?no:so,fileFromPath:ro,isFsReadStream:s=>s instanceof Zn}}var os=()=>{Ue||Gs(Qs(),{auto:!0})};os();var f=class extends Error{},O=class s extends f{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["x-request-id"],this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new ue({message:r,cause:xr(t)});let o=t?.error;return e===400?new ft(e,o,r,n):e===401?new ht(e,o,r,n):e===403?new dt(e,o,r,n):e===404?new pt(e,o,r,n):e===409?new mt(e,o,r,n):e===422?new _t(e,o,r,n):e===429?new gt(e,o,r,n):e>=500?new wt(e,o,r,n):new s(e,o,r,n)}},S=class extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ue=class extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},fe=class extends ue{constructor({message:e}={}){super({message:e??"Request timed out."})}},ft=class extends O{},ht=class extends O{},dt=class extends O{},pt=class extends O{},mt=class extends O{},_t=class extends O{},gt=class extends O{},wt=class extends O{},yt=class extends f{constructor(){super("Could not parse response content as the length limit was reached")}},bt=class extends f{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};var Ar=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},qe=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},J,We=class{constructor(){J.set(this,void 0),this.buffer=new Uint8Array,Ar(this,J,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;let n=[],o;for(;(o=ao(this.buffer,qe(this,J,"f")))!=null;){if(o.carriage&&qe(this,J,"f")==null){Ar(this,J,o.index,"f");continue}if(qe(this,J,"f")!=null&&(o.index!==qe(this,J,"f")+1||o.carriage)){n.push(this.decodeText(this.buffer.slice(0,qe(this,J,"f")-1))),this.buffer=this.buffer.slice(qe(this,J,"f")),Ar(this,J,null,"f");continue}let i=qe(this,J,"f")!==null?o.preceding-1:o.preceding,a=this.decodeText(this.buffer.slice(0,i));n.push(a),this.buffer=this.buffer.slice(o.index),Ar(this,J,null,"f")}return n}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new f(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new f(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new f("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
2
+ `):[]}};J=new WeakMap;We.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);We.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ao(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ys(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}function is(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var te=class s{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*n(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(let i of lo(e,t))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(a&&a.error)throw new O(void 0,a.error,void 0,ls(e.headers));yield a}else{let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(i.event=="error")throw new O(void 0,a.error,a.message,void 0);yield{event:i.event,data:a}}}o=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{o||t.abort()}}return new s(n,t)}static fromReadableStream(e,t){let r=!1;async function*n(){let i=new We,a=is(e);for await(let c of a)for(let d of i.decode(c))yield d;for(let c of i.flush())yield c}async function*o(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(let a of n())i||a&&(yield JSON.parse(a));i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||t.abort()}}return new s(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller),new s(()=>n(t),this.controller)]}toReadableStream(){let e=this,t,r=new TextEncoder;return new es({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:i}=await t.next();if(i)return n.close();let a=r.encode(JSON.stringify(o)+`
4
+ `);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*lo(s,e){if(!s.body)throw e.abort(),new f("Attempted to iterate over a response with no body");let t=new as,r=new We,n=is(s.body);for await(let o of co(n))for(let i of r.decode(o)){let a=t.decode(i);a&&(yield a)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*co(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Ys(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var as=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=uo(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function uo(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}var Zs=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",en=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&sr(s),sr=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",fo=s=>en(s)||Zs(s)||ss(s);async function Pr(s,e,t){if(s=await s,en(s))return s;if(Zs(s)){let n=await s.blob();e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=sr(n)?[await n.arrayBuffer()]:[n];return new yr(o,e,t)}let r=await ho(s);if(e||(e=mo(s)??"unknown_file"),!t?.type){let n=r[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new yr(r,e,t)}async function ho(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(sr(s))e.push(await s.arrayBuffer());else if(_o(s))for await(let t of s)e.push(t);else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${s?.constructor?.name}; props: ${po(s)}`);return e}function po(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function mo(s){return cs(s.name)||cs(s.filename)||cs(s.path)?.split(/[\\/]/).pop()}var cs=s=>{if(typeof s=="string")return s;if(typeof Buffer<"u"&&s instanceof Buffer)return String(s)},_o=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",fs=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody";var W=async s=>{let e=await tn(s.body);return ts(e,s)},tn=async s=>{let e=new Zr;return await Promise.all(Object.entries(s||{}).map(([t,r])=>us(e,t,r))),e};var us=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(fo(t)){let r=await Pr(t);s.append(e,r)}else if(Array.isArray(t))await Promise.all(t.map(r=>us(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>us(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var wo=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},yo=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},Ir;os();async function ln(s){let{response:e}=s;if(s.options.stream)return he("response",e.status,e.url,e.headers,e.body),s.options.__streamClass?s.options.__streamClass.fromSSEResponse(e,s.controller):te.fromSSEResponse(e,s.controller);if(e.status===204)return null;if(s.options.__binaryResponse)return e;let r=e.headers.get("content-type")?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){let i=await e.json();return he("response",e.status,e.url,e.headers,i),cn(i,e)}let o=await e.text();return he("response",e.status,e.url,e.headers,o),o}function cn(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Cr=class s extends Promise{constructor(e,t=ln){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new s(this.responsePromise,async t=>cn(e(await this.parseResponse(t),t),t.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(this.parseResponse)),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)}},Sr=class{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:o}){this.baseURL=e,this.maxRetries=hs("maxRetries",t),this.timeout=hs("timeout",r),this.httpAgent=n,this.fetch=o??Yr}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Po(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${So()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(async n=>{let o=n&&sr(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:o}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,headers:a={}}=r,c=ArrayBuffer.isView(r.body)||r.__binaryRequest&&typeof r.body=="string"?r.body:fs(r.body)?r.body.body:r.body?JSON.stringify(r.body,null,2):null,d=this.calculateContentLength(c),b=this.buildURL(o,i);"timeout"in r&&hs("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let u=r.httpAgent??this.httpAgent??rs(b),p=r.timeout+1e3;typeof u?.options?.timeout=="number"&&p>(u.options.timeout??0)&&(u.options.timeout=p),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let h=this.buildHeaders({options:r,headers:a,contentLength:d,retryCount:t});return{req:{method:n,...c&&{body:c},headers:h,...u&&{agent:u},signal:r.signal??null},url:b,timeout:r.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){let o={};r&&(o["content-length"]=r);let i=this.defaultHeaders(e);return on(o,i),on(o,t),fs(e.body)&&Ue!=="node"&&delete o["content-type"],Rr(i,"x-stainless-retry-count")===void 0&&Rr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(n)),Rr(i,"x-stainless-timeout")===void 0&&Rr(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(o,t),o}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,r,n){return O.generate(e,t,r,n)}request(e,t=null){return new Cr(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,n=r.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(r);let{req:o,url:i,timeout:a}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(o,{url:i,options:r}),he("request",i,r,o.headers),r.signal?.aborted)throw new S;let c=new AbortController,d=await this.fetchWithTimeout(i,o,a,c).catch(xr);if(d instanceof Error){if(r.signal?.aborted)throw new S;if(t)return this.retryRequest(r,t);throw d.name==="AbortError"?new fe:new ue({cause:d})}let b=ls(d.headers);if(!d.ok){if(t&&this.shouldRetry(d)){let C=`retrying, ${t} attempts remaining`;return he(`response (error; ${C})`,d.status,i,b),this.retryRequest(r,t,b)}let u=await d.text().catch(C=>xr(C).message),p=Io(u),h=p?void 0:u;throw he(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,d.status,i,b,h),this.makeStatusError(d.status,p,h,b)}return{response:d,options:r,controller:c}}requestAPIList(e,t){let r=this.makeRequest(t,null);return new ds(this,r,e)}buildURL(e,t){let r=Co(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return un(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new f(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,n){let{signal:o,...i}=t||{};o&&o.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r),c={signal:n.signal,...i};return c.method&&(c.method=c.method.toUpperCase()),this.fetch.call(void 0,e,c).finally(()=>{clearTimeout(a)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r){let n,o=r?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(n=a)}let i=r?.["retry-after"];if(i&&!n){let a=parseFloat(i);Number.isNaN(a)?n=Date.parse(i)-Date.now():n=a*1e3}if(!(n&&0<=n&&n<60*1e3)){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await de(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${je}`}},nr=class{constructor(e,t,r,n){Ir.set(this,void 0),wo(this,Ir,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new f("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,o]of r)e.url.searchParams.set(n,o);t.query=void 0,t.path=e.url.toString()}return await yo(this,Ir,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ir=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ds=class extends Cr{constructor(e,t,r){super(t,async n=>new r(e,n.response,await ln(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ls=s=>new Proxy(Object.fromEntries(s.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),bo={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},y=s=>typeof s=="object"&&s!==null&&!un(s)&&Object.keys(s).every(e=>fn(bo,e)),xo=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":je,"X-Stainless-OS":sn(Deno.build.os),"X-Stainless-Arch":rn(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":je,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":je,"X-Stainless-OS":sn(process.platform),"X-Stainless-Arch":rn(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let s=Ao();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":je,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":je,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ao(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var rn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",sn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),nn,Po=()=>nn??(nn=xo()),Io=s=>{try{return JSON.parse(s)}catch{return}},Ro=/^[a-z][a-z0-9+.-]*:/i,Co=s=>Ro.test(s),de=s=>new Promise(e=>setTimeout(e,s)),hs=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new f(`${s} must be an integer`);if(e<0)throw new f(`${s} must be a positive integer`);return e},xr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null)try{return new Error(JSON.stringify(s))}catch{}return new Error(s)};var xe=s=>{if(typeof process<"u")return process.env?.[s]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(s)?.trim()};function un(s){if(!s)return!0;for(let e in s)return!1;return!0}function fn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function on(s,e){for(let t in e){if(!fn(e,t))continue;let r=t.toLowerCase();if(!r)continue;let n=e[t];n===null?delete s[r]:n!==void 0&&(s[r]=n)}}var an=new Set(["authorization","api-key"]);function he(s,...e){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let t=e.map(r=>{if(!r)return r;if(r.headers){let o={...r,headers:{...r.headers}};for(let i in r.headers)an.has(i.toLowerCase())&&(o.headers[i]="REDACTED");return o}let n=null;for(let o in r)an.has(o.toLowerCase())&&(n??(n={...r}),n[o]="REDACTED");return n??r});console.log(`OpenAI:DEBUG:${s}`,...t)}}var So=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)}),hn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Eo=s=>typeof s?.get=="function";var Rr=(s,e)=>{let t=e.toLowerCase();if(Eo(s)){let r=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,o,i)=>o+i.toUpperCase());for(let n of[e,t,e.toUpperCase(),r]){let o=s.get(n);if(o)return o}}for(let[r,n]of Object.entries(s))if(r.toLowerCase()===t)return Array.isArray(n)?(n.length<=1||console.warn(`Received ${n.length} entries for the ${e} header, using the first entry.`),n[0]):n};var dn=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};function xt(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var re=class extends nr{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}},x=class extends nr{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){let e=this.getPaginatedItems();if(!e.length)return null;let t=e[e.length-1]?.id;return t?{params:{after:t}}:null}};var l=class{constructor(e){this._client=e}};var At=class extends l{list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Er,{query:t,...r})}};var Ae=class extends l{constructor(){super(...arguments),this.messages=new At(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(`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/chat/completions",Pe,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}},Pe=class extends x{},Er=class extends x{};Ae.ChatCompletionsPage=Pe;Ae.Messages=At;var me=class extends l{constructor(){super(...arguments),this.completions=new Ae(this._client)}};me.Completions=Ae;me.ChatCompletionsPage=Pe;var Pt=class extends l{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}};var It=class extends l{create(e,t){return this._client.post("/audio/transcriptions",W({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}};var Rt=class extends l{create(e,t){return this._client.post("/audio/translations",W({body:e,...t,__metadata:{model:e.model}}))}};var se=class extends l{constructor(){super(...arguments),this.transcriptions=new It(this._client),this.translations=new Rt(this._client),this.speech=new Pt(this._client)}};se.Transcriptions=It;se.Translations=Rt;se.Speech=Pt;var Ie=class extends l{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/batches",He,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}},He=class extends x{};Ie.BatchesPage=He;var z=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},I=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},ps,Or,vr,or,ir,$r,ar,_e,lr,Tr,Fr,Ct,pn,Re=class{constructor(){ps.add(this),this.controller=new AbortController,Or.set(this,void 0),vr.set(this,()=>{}),or.set(this,()=>{}),ir.set(this,void 0),$r.set(this,()=>{}),ar.set(this,()=>{}),_e.set(this,{}),lr.set(this,!1),Tr.set(this,!1),Fr.set(this,!1),Ct.set(this,!1),z(this,Or,new Promise((e,t)=>{z(this,vr,e,"f"),z(this,or,t,"f")}),"f"),z(this,ir,new Promise((e,t)=>{z(this,$r,e,"f"),z(this,ar,t,"f")}),"f"),I(this,Or,"f").catch(()=>{}),I(this,ir,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},I(this,ps,"m",pn).bind(this))},0)}_connected(){this.ended||(I(this,vr,"f").call(this),this._emit("connect"))}get ended(){return I(this,lr,"f")}get errored(){return I(this,Tr,"f")}get aborted(){return I(this,Fr,"f")}abort(){this.controller.abort()}on(e,t){return(I(this,_e,"f")[e]||(I(this,_e,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=I(this,_e,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(I(this,_e,"f")[e]||(I(this,_e,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{z(this,Ct,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){z(this,Ct,!0,"f"),await I(this,ir,"f")}_emit(e,...t){if(I(this,lr,"f"))return;e==="end"&&(z(this,lr,!0,"f"),I(this,$r,"f").call(this));let r=I(this,_e,"f")[e];if(r&&(I(this,_e,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!I(this,Ct,"f")&&!r?.length&&Promise.reject(n),I(this,or,"f").call(this,n),I(this,ar,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!I(this,Ct,"f")&&!r?.length&&Promise.reject(n),I(this,or,"f").call(this,n),I(this,ar,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Or=new WeakMap,vr=new WeakMap,or=new WeakMap,ir=new WeakMap,$r=new WeakMap,ar=new WeakMap,_e=new WeakMap,lr=new WeakMap,Tr=new WeakMap,Fr=new WeakMap,Ct=new WeakMap,ps=new WeakSet,pn=function(e){if(z(this,Tr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new S),e instanceof S)return z(this,Fr,!0,"f"),this._emit("abort",e);if(e instanceof f)return this._emit("error",e);if(e instanceof Error){let t=new f(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new f(String(e)))};var m=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},V=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},D,ms,ne,kr,Q,Ve,St,Je,Br,X,Mr,Nr,fr,cr,ur,mn,_n,gn,wn,yn,bn,xn,oe=class s extends Re{constructor(){super(...arguments),D.add(this),ms.set(this,[]),ne.set(this,{}),kr.set(this,{}),Q.set(this,void 0),Ve.set(this,void 0),St.set(this,void 0),Je.set(this,void 0),Br.set(this,void 0),X.set(this,void 0),Mr.set(this,void 0),Nr.set(this,void 0),fr.set(this,void 0)}[(ms=new WeakMap,ne=new WeakMap,kr=new WeakMap,Q=new WeakMap,Ve=new WeakMap,St=new WeakMap,Je=new WeakMap,Br=new WeakMap,X=new WeakMap,Mr=new WeakMap,Nr=new WeakMap,fr=new WeakMap,D=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).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 s;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=te.fromReadableStream(e,this.controller);for await(let o of n)m(this,D,"m",cr).call(this,o);if(n.controller.signal?.aborted)throw new S;return this._addRun(m(this,D,"m",ur).call(this))}toReadableStream(){return new te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n,o){let i=new s;return i._run(()=>i._runToolAssistantStream(e,t,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,r,n,o){let i=o?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.submitToolOutputs(t,r,a,{...o,signal:this.controller.signal});this._connected();for await(let d of c)m(this,D,"m",cr).call(this,d);if(c.controller.signal?.aborted)throw new S;return this._addRun(m(this,D,"m",ur).call(this))}static createThreadAssistantStream(e,t,r){let n=new s;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new s;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return m(this,Mr,"f")}currentRun(){return m(this,Nr,"f")}currentMessageSnapshot(){return m(this,Q,"f")}currentRunStepSnapshot(){return m(this,fr,"f")}async finalRunSteps(){return await this.done(),Object.values(m(this,ne,"f"))}async finalMessages(){return await this.done(),Object.values(m(this,kr,"f"))}async finalRun(){if(await this.done(),!m(this,Ve,"f"))throw Error("Final run was not received.");return m(this,Ve,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let a of i)m(this,D,"m",cr).call(this,a);if(i.controller.signal?.aborted)throw new S;return this._addRun(m(this,D,"m",ur).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let c of a)m(this,D,"m",cr).call(this,c);if(a.controller.signal?.aborted)throw new S;return this._addRun(m(this,D,"m",ur).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(xt(o)&&xt(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!xt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n,o){return await this._createToolAssistantStream(r,e,t,n,o)}};cr=function(e){if(!this.ended)switch(V(this,Mr,e,"f"),m(this,D,"m",gn).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":m(this,D,"m",xn).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":m(this,D,"m",_n).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":m(this,D,"m",mn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ur=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");if(!m(this,Ve,"f"))throw Error("Final run has not been received");return m(this,Ve,"f")},mn=function(e){let[t,r]=m(this,D,"m",yn).call(this,e,m(this,Q,"f"));V(this,Q,t,"f"),m(this,kr,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=m(this,St,"f")){if(m(this,Je,"f"))switch(m(this,Je,"f").type){case"text":this._emit("textDone",m(this,Je,"f").text,m(this,Q,"f"));break;case"image_file":this._emit("imageFileDone",m(this,Je,"f").image_file,m(this,Q,"f"));break}V(this,St,n.index,"f")}V(this,Je,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(m(this,St,"f")!==void 0){let n=e.data.content[m(this,St,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,m(this,Q,"f"));break;case"text":this._emit("textDone",n.text,m(this,Q,"f"));break}}m(this,Q,"f")&&this._emit("messageDone",e.data),V(this,Q,void 0,"f")}},_n=function(e){let t=m(this,D,"m",wn).call(this,e);switch(V(this,fr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==m(this,Br,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(m(this,X,"f")&&this._emit("toolCallDone",m(this,X,"f")),V(this,Br,o.index,"f"),V(this,X,t.step_details.tool_calls[o.index],"f"),m(this,X,"f")&&this._emit("toolCallCreated",m(this,X,"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":V(this,fr,void 0,"f"),e.data.step_details.type=="tool_calls"&&m(this,X,"f")&&(this._emit("toolCallDone",m(this,X,"f")),V(this,X,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},gn=function(e){m(this,ms,"f").push(e),this._emit("event",e)},wn=function(e){switch(e.event){case"thread.run.step.created":return m(this,ne,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=m(this,ne,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=oe.accumulateDelta(t,r.delta);m(this,ne,"f")[e.data.id]=n}return m(this,ne,"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":m(this,ne,"f")[e.data.id]=e.data;break}if(m(this,ne,"f")[e.data.id])return m(this,ne,"f")[e.data.id];throw new Error("No snapshot available")},yn=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=m(this,D,"m",bn).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},bn=function(e,t){return oe.accumulateDelta(t,e)},xn=function(e){switch(V(this,Nr,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":V(this,Ve,e.data,"f"),m(this,X,"f")&&(this._emit("toolCallDone",m(this,X,"f")),V(this,X,void 0,"f"));break;case"thread.run.cancelling":break}};var Xe=class extends l{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/assistants",Et,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}},Et=class extends x{};Xe.AssistantsPage=Et;function _s(s){return typeof s.parse=="function"}var Ce=s=>s?.role==="assistant",gs=s=>s?.role==="function",ws=s=>s?.role==="tool";function hr(s){return s?.$brand==="auto-parseable-response-format"}function Ge(s){return s?.$brand==="auto-parseable-tool"}function An(s,e){return!e||!ys(e)?{...s,choices:s.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:dr(s,e)}function dr(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new yt;if(r.finish_reason==="content_filter")throw new bt;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>No(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Mo(e,r.message.content):null}}});return{...s,choices:t}}function Mo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function No(s,e){let t=s.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ge(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Pn(s,e){if(!s)return!1;let t=s.tools?.find(r=>r.function?.name===e.function.name);return Ge(t)||t?.function.strict||!1}function ys(s){return hr(s.response_format)?!0:s.tools?.some(e=>Ge(e)||e.type==="function"&&e.function.strict===!0)??!1}function In(s){for(let e of s??[]){if(e.type!=="function")throw new f(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new f(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var H=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},q,bs,Lr,xs,As,Ps,Cn,Is,Rn=10,Ot=class extends Re{constructor(){super(...arguments),q.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),(gs(e)||ws(e))&&e.content)this._emit("functionCallResult",e.content);else if(Ce(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Ce(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new f("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),H(this,q,"m",bs).call(this)}async finalMessage(){return await this.done(),H(this,q,"m",Lr).call(this)}async finalFunctionCall(){return await this.done(),H(this,q,"m",xs).call(this)}async finalFunctionCallResult(){return await this.done(),H(this,q,"m",As).call(this)}async totalUsage(){return await this.done(),H(this,q,"m",Ps).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=H(this,q,"m",Lr).call(this);t&&this._emit("finalMessage",t);let r=H(this,q,"m",bs).call(this);r&&this._emit("finalContent",r);let n=H(this,q,"m",xs).call(this);n&&this._emit("finalFunctionCall",n);let o=H(this,q,"m",As).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",H(this,q,"m",Ps).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),H(this,q,"m",Cn).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(dr(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){let n="function",{function_call:o="auto",stream:i,...a}=t,c=typeof o!="string"&&o?.name,{maxChatCompletions:d=Rn}=r||{},b={};for(let p of t.functions)b[p.name||p.function.name]=p;let u=t.functions.map(p=>({name:p.name||p.function.name,parameters:p.parameters,description:p.description}));for(let p of t.messages)this._addMessage(p,!1);for(let p=0;p<d;++p){let A=(await this._createChatCompletion(e,{...a,function_call:o,functions:u,messages:[...this.messages]},r)).choices[0]?.message;if(!A)throw new f("missing message in ChatCompletion response");if(!A.function_call)return;let{name:_,arguments:C}=A.function_call,v=b[_];if(v){if(c&&c!==_){let k=`Invalid function_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:n,name:_,content:k});continue}}else{let k=`Invalid function_call: ${JSON.stringify(_)}. Available options are: ${u.map(j=>JSON.stringify(j.name)).join(", ")}. Please try again`;this._addMessage({role:n,name:_,content:k});continue}let g;try{g=_s(v)?await v.parse(C):C}catch(k){this._addMessage({role:n,name:_,content:k instanceof Error?k.message:String(k)});continue}let L=await v.function(g,this),R=H(this,q,"m",Is).call(this,L);if(this._addMessage({role:n,name:_,content:R}),c)return}}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...a}=t,c=typeof o!="string"&&o?.function?.name,{maxChatCompletions:d=Rn}=r||{},b=t.tools.map(h=>{if(Ge(h)){if(!h.$callback)throw new f("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),u={};for(let h of b)h.type==="function"&&(u[h.function.name||h.function.function.name]=h.function);let p="tools"in t?b.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of t.messages)this._addMessage(h,!1);for(let h=0;h<d;++h){let _=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!_)throw new f("missing message in ChatCompletion response");if(!_.tool_calls?.length)return;for(let C of _.tool_calls){if(C.type!=="function")continue;let v=C.id,{name:g,arguments:L}=C.function,R=u[g];if(R){if(c&&c!==g){let M=`Invalid tool_call: ${JSON.stringify(g)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:n,tool_call_id:v,content:M});continue}}else{let M=`Invalid tool_call: ${JSON.stringify(g)}. Available options are: ${Object.keys(u).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:v,content:M});continue}let k;try{k=_s(R)?await R.parse(L):L}catch(M){let N=M instanceof Error?M.message:String(M);this._addMessage({role:n,tool_call_id:v,content:N});continue}let j=await R.function(k,this),U=H(this,q,"m",Is).call(this,j);if(this._addMessage({role:n,tool_call_id:v,content:U}),c)return}}}};q=new WeakSet,bs=function(){return H(this,q,"m",Lr).call(this).content??null},Lr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Ce(t)){let{function_call:r,...n}=t,o={...n,content:t.content??null,refusal:t.refusal??null};return r&&(o.function_call=r),o}}throw new f("stream ended without producing a ChatCompletionMessage with role=assistant")},xs=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ce(t)&&t?.function_call)return t.function_call;if(Ce(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},As=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(gs(t)&&t.content!=null||ws(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},Ps=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},Cn=function(e){if(e.n!=null&&e.n>1)throw new f("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Is=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var pr=class s extends Ot{static runFunctions(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,o)),n}static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),Ce(e)&&e.content&&this._emit("content",e.content)}};var B={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},Rs=class extends Error{},Cs=class extends Error{};function Bo(s,e=B.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return Lo(s.trim(),e)}var Lo=(s,e)=>{let t=s.length,r=0,n=p=>{throw new Rs(`${p} at position ${r}`)},o=p=>{throw new Cs(`${p} at position ${r}`)},i=()=>(u(),r>=t&&n("Unexpected end of input"),s[r]==='"'?a():s[r]==="{"?c():s[r]==="["?d():s.substring(r,r+4)==="null"||B.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||B.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||B.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||B.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||B.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||B.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):b()),a=()=>{let p=r,h=!1;for(r++;r<t&&(s[r]!=='"'||h&&s[r-1]==="\\");)h=s[r]==="\\"?!h:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(p,++r-Number(h)))}catch(A){o(String(A))}else if(B.STR&e)try{return JSON.parse(s.substring(p,r-Number(h))+'"')}catch{return JSON.parse(s.substring(p,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{r++,u();let p={};try{for(;s[r]!=="}";){if(u(),r>=t&&B.OBJ&e)return p;let h=a();u(),r++;try{let A=i();Object.defineProperty(p,h,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(B.OBJ&e)return p;throw A}u(),s[r]===","&&r++}}catch{if(B.OBJ&e)return p;n("Expected '}' at end of object")}return r++,p},d=()=>{r++;let p=[];try{for(;s[r]!=="]";)p.push(i()),u(),s[r]===","&&r++}catch{if(B.ARR&e)return p;n("Expected ']' at end of array")}return r++,p},b=()=>{if(r===0){s==="-"&&B.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(h){if(B.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(h))}}let p=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(B.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(p,r))}catch{s.substring(p,r)==="-"&&B.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(p,s.lastIndexOf("e")))}catch(A){o(String(A))}}},u=()=>{for(;r<t&&`
6
+ \r `.includes(s[r]);)r++};return i()},Ss=s=>Bo(s,B.ALL^B.NUM);var vt=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},P=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},F,ge,$t,Se,Es,Dr,Os,vs,$s,jr,Ts,Sn,Tt=class s extends Ot{constructor(e){super(),F.add(this),ge.set(this,void 0),$t.set(this,void 0),Se.set(this,void 0),vt(this,ge,e,"f"),vt(this,$t,[],"f")}get currentChatCompletionSnapshot(){return P(this,Se,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),P(this,F,"m",Es).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)P(this,F,"m",Os).call(this,i);if(o.controller.signal?.aborted)throw new S;return this._addChatCompletion(P(this,F,"m",jr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),P(this,F,"m",Es).call(this),this._connected();let n=te.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(P(this,F,"m",jr).call(this)),P(this,F,"m",Os).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new S;return this._addChatCompletion(P(this,F,"m",jr).call(this))}[(ge=new WeakMap,$t=new WeakMap,Se=new WeakMap,F=new WeakSet,Es=function(){this.ended||vt(this,Se,void 0,"f")},Dr=function(t){let r=P(this,$t,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},P(this,$t,"f")[t.index]=r,r)},Os=function(t){if(this.ended)return;let r=P(this,F,"m",Sn).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=P(this,F,"m",Dr).call(this,o);o.finish_reason&&(P(this,F,"m",$s).call(this,o),i.current_tool_call_index!=null&&P(this,F,"m",vs).call(this,o,i.current_tool_call_index));for(let a of n.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(P(this,F,"m",$s).call(this,o),i.current_tool_call_index!=null&&P(this,F,"m",vs).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of n.delta.tool_calls??[]){let c=o.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},vs=function(t,r){if(P(this,F,"m",Dr).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=P(this,ge,"f")?.tools?.find(a=>a.type==="function"&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ge(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},$s=function(t){let r=P(this,F,"m",Dr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=P(this,F,"m",Ts).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},jr=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");let t=P(this,Se,"f");if(!t)throw new f("request ended without sending any chunks");return vt(this,Se,void 0,"f"),vt(this,$t,[],"f"),Do(t,P(this,ge,"f"))},Ts=function(){let t=P(this,ge,"f")?.response_format;return hr(t)?t:null},Sn=function(t){var r,n,o,i;let a=P(this,Se,"f"),{choices:c,...d}=t;a?Object.assign(a,d):a=vt(this,Se,{...d,choices:[]},"f");for(let{delta:b,finish_reason:u,index:p,logprobs:h=null,...A}of t.choices){let _=a.choices[p];if(_||(_=a.choices[p]={finish_reason:u,index:p,message:{},logprobs:h,...A}),h)if(!_.logprobs)_.logprobs=Object.assign({},h);else{let{content:j,refusal:U,...M}=h;Object.assign(_.logprobs,M),j&&((r=_.logprobs).content??(r.content=[]),_.logprobs.content.push(...j)),U&&((n=_.logprobs).refusal??(n.refusal=[]),_.logprobs.refusal.push(...U))}if(u&&(_.finish_reason=u,P(this,ge,"f")&&ys(P(this,ge,"f")))){if(u==="length")throw new yt;if(u==="content_filter")throw new bt}if(Object.assign(_,A),!b)continue;let{content:C,refusal:v,function_call:g,role:L,tool_calls:R,...k}=b;if(Object.assign(_.message,k),v&&(_.message.refusal=(_.message.refusal||"")+v),L&&(_.message.role=L),g&&(_.message.function_call?(g.name&&(_.message.function_call.name=g.name),g.arguments&&((o=_.message.function_call).arguments??(o.arguments=""),_.message.function_call.arguments+=g.arguments)):_.message.function_call=g),C&&(_.message.content=(_.message.content||"")+C,!_.message.refusal&&P(this,F,"m",Ts).call(this)&&(_.message.parsed=Ss(_.message.content))),R){_.message.tool_calls||(_.message.tool_calls=[]);for(let{index:j,id:U,type:M,function:N,...E}of R){let $=(i=_.message.tool_calls)[j]??(i[j]={});Object.assign($,E),U&&($.id=U),M&&($.type=M),N&&($.function??($.function={name:N.name??"",arguments:""})),N?.name&&($.function.name=N.name),N?.arguments&&($.function.arguments+=N.arguments,Pn(P(this,ge,"f"),$)&&($.function.parsed_arguments=Ss($.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Do(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...a}=s,c={...a,id:t,choices:r.map(({message:d,finish_reason:b,index:u,logprobs:p,...h})=>{if(!b)throw new f(`missing finish_reason for choice ${u}`);let{content:A=null,function_call:_,tool_calls:C,...v}=d,g=d.role;if(!g)throw new f(`missing role for choice ${u}`);if(_){let{arguments:L,name:R}=_;if(L==null)throw new f(`missing function_call.arguments for choice ${u}`);if(!R)throw new f(`missing function_call.name for choice ${u}`);return{...h,message:{content:A,function_call:{arguments:L,name:R},role:g,refusal:d.refusal??null},finish_reason:b,index:u,logprobs:p}}return C?{...h,index:u,finish_reason:b,logprobs:p,message:{...v,role:g,content:A,refusal:d.refusal??null,tool_calls:C.map((L,R)=>{let{function:k,type:j,id:U,...M}=L,{arguments:N,name:E,...$}=k||{};if(U==null)throw new f(`missing choices[${u}].tool_calls[${R}].id
7
+ ${Ur(s)}`);if(j==null)throw new f(`missing choices[${u}].tool_calls[${R}].type
8
+ ${Ur(s)}`);if(E==null)throw new f(`missing choices[${u}].tool_calls[${R}].function.name
9
+ ${Ur(s)}`);if(N==null)throw new f(`missing choices[${u}].tool_calls[${R}].function.arguments
10
+ ${Ur(s)}`);return{...M,id:U,type:j,function:{...$,name:E,arguments:N}}})}}:{...h,message:{...v,content:A,role:g,refusal:d.refusal??null},finish_reason:b,index:u,logprobs:p}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return An(c,e)}function Ur(s){return JSON.stringify(s)}var mr=class s extends Tt{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){let n=new s(null),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,o)),n}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var _r=class extends l{parse(e,t){return In(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(r=>dr(r,e))}runFunctions(e,t){return e.stream?mr.runFunctions(this._client,e,t):pr.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?mr.runTools(this._client,e,t):pr.runTools(this._client,e,t)}stream(e,t){return Tt.createChatCompletion(this._client,e,t)}};var Ft=class extends l{constructor(){super(...arguments),this.completions=new _r(this._client)}};(function(s){s.Completions=_r})(Ft||(Ft={}));var kt=class extends l{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}};var Mt=class extends l{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}};var Ee=class extends l{constructor(){super(...arguments),this.sessions=new kt(this._client),this.transcriptionSessions=new Mt(this._client)}};Ee.Sessions=kt;Ee.TranscriptionSessions=Mt;var Ke=class extends l{create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Nt,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}},Nt=class extends x{};Ke.MessagesPage=Nt;var ze=class extends l{retrieve(e,t,r,n={},o){return y(n)?this.retrieve(e,t,r,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:n,...o,headers:{"OpenAI-Beta":"assistants=v2",...o?.headers}})}list(e,t,r={},n){return y(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Bt,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}},Bt=class extends x{};ze.RunStepsPage=Bt;var we=class extends l{constructor(){super(...arguments),this.steps=new ze(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Lt,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}createAndStream(e,t,r){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let d=parseInt(c);isNaN(d)||(a=d)}}await de(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,n){let o=await this.submitToolOutputs(e,t,r,n);return await this.poll(e,o.id,n)}submitToolOutputsStream(e,t,r,n){return oe.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,n)}},Lt=class extends x{};we.RunsPage=Lt;we.Steps=ze;we.RunStepsPage=Bt;var ie=class extends l{constructor(){super(...arguments),this.runs=new we(this._client),this.messages=new Ke(this._client)}create(e={},t){return y(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return oe.createThreadAssistantStream(e,this._client.beta.threads,t)}};ie.Runs=we;ie.RunsPage=Lt;ie.Messages=Ke;ie.MessagesPage=Nt;var Y=class extends l{constructor(){super(...arguments),this.realtime=new Ee(this._client),this.chat=new Ft(this._client),this.assistants=new Xe(this._client),this.threads=new ie(this._client)}};Y.Realtime=Ee;Y.Assistants=Xe;Y.AssistantsPage=Et;Y.Threads=ie;var Qe=class extends l{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var Dt=class extends l{retrieve(e,t,r){return this._client.get(`/containers/${e}/files/${t}/content`,{...r,headers:{Accept:"application/binary",...r?.headers},__binaryResponse:!0})}};var Oe=class extends l{constructor(){super(...arguments),this.content=new Dt(this._client)}create(e,t,r){return this._client.post(`/containers/${e}/files`,W({body:t,...r}))}retrieve(e,t,r){return this._client.get(`/containers/${e}/files/${t}`,r)}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,jt,{query:t,...r})}del(e,t,r){return this._client.delete(`/containers/${e}/files/${t}`,{...r,headers:{Accept:"*/*",...r?.headers}})}},jt=class extends x{};Oe.FileListResponsesPage=jt;Oe.Content=Dt;var ae=class extends l{constructor(){super(...arguments),this.files=new Oe(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/containers",Ye,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}},Ye=class extends x{};ae.ContainerListResponsesPage=Ye;ae.Files=Oe;ae.FileListResponsesPage=jt;var Ze=class extends l{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&he("Request","User defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(he("response","Decoding base64 embeddings to float32 array"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=dn(c)}),i)))}};var et=class extends l{retrieve(e,t,r,n){return this._client.get(`/evals/${e}/runs/${t}/output_items/${r}`,n)}list(e,t,r={},n){return y(r)?this.list(e,t,{},r):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Ut,{query:r,...n})}},Ut=class extends x{};et.OutputItemListResponsesPage=Ut;var ye=class extends l{constructor(){super(...arguments),this.outputItems=new et(this._client)}create(e,t,r){return this._client.post(`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){return this._client.get(`/evals/${e}/runs/${t}`,r)}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,qt,{query:t,...r})}del(e,t,r){return this._client.delete(`/evals/${e}/runs/${t}`,r)}cancel(e,t,r){return this._client.post(`/evals/${e}/runs/${t}`,r)}},qt=class extends x{};ye.RunListResponsesPage=qt;ye.OutputItems=et;ye.OutputItemListResponsesPage=Ut;var le=class extends l{constructor(){super(...arguments),this.runs=new ye(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,r){return this._client.post(`/evals/${e}`,{body:t,...r})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/evals",tt,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}},tt=class extends x{};le.EvalListResponsesPage=tt;le.Runs=ye;le.RunListResponsesPage=qt;var ve=class extends l{create(e,t){return this._client.post("/files",W({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/files",rt,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await de(t),i=await this.retrieve(e),Date.now()-o>r)throw new fe({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}},rt=class extends x{};ve.FileObjectsPage=rt;var Wt=class extends l{};var Ht=class extends l{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 st=class extends l{constructor(){super(...arguments),this.graders=new Ht(this._client)}};st.Graders=Ht;var nt=class extends l{create(e,t,r){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Jt,{body:t,method:"post",...r})}retrieve(e,t={},r){return y(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}del(e,t,r){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,r)}},Jt=class extends re{};nt.PermissionCreateResponsesPage=Jt;var $e=class extends l{constructor(){super(...arguments),this.permissions=new nt(this._client)}};$e.Permissions=nt;$e.PermissionCreateResponsesPage=Jt;var ot=class extends l{list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Vt,{query:t,...r})}},Vt=class extends x{};ot.FineTuningJobCheckpointsPage=Vt;var ce=class extends l{constructor(){super(...arguments),this.checkpoints=new ot(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Xt,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return y(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Gt,{query:t,...r})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}},Xt=class extends x{},Gt=class extends x{};ce.FineTuningJobsPage=Xt;ce.FineTuningJobEventsPage=Gt;ce.Checkpoints=ot;ce.FineTuningJobCheckpointsPage=Vt;var G=class extends l{constructor(){super(...arguments),this.methods=new Wt(this._client),this.jobs=new ce(this._client),this.checkpoints=new $e(this._client),this.alpha=new st(this._client)}};G.Methods=Wt;G.Jobs=ce;G.FineTuningJobsPage=Xt;G.FineTuningJobEventsPage=Gt;G.Checkpoints=$e;G.Alpha=st;var Kt=class extends l{};var Te=class extends l{constructor(){super(...arguments),this.graderModels=new Kt(this._client)}};Te.GraderModels=Kt;var it=class extends l{createVariation(e,t){return this._client.post("/images/variations",W({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",W({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}};var Fe=class extends l{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",at,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}},at=class extends re{};Fe.ModelsPage=at;var lt=class extends l{create(e,t){return this._client.post("/moderations",{body:e,...t})}};function En(s,e){return!e||!li(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Fs(s,e)}function Fs(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:fi(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:ai(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||ks(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function ai(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function li(s){return!!hr(s.text?.format)}function ci(s){return s?.$brand==="auto-parseable-tool"}function ui(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function fi(s,e){let t=ui(s.tools??[],e.name);return{...e,...e,parsed_arguments:ci(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ks(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var zt=class extends l{list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,qr,{query:t,...r})}};var Qt=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},ke=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},Yt,Wr,Me,Hr,On,vn,$n,Tn,Jr=class s extends Re{constructor(e){super(),Yt.add(this),Wr.set(this,void 0),Me.set(this,void 0),Hr.set(this,void 0),Qt(this,Wr,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),ke(this,Yt,"m",On).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of o)ke(this,Yt,"m",vn).call(this,a,i);if(o.controller.signal?.aborted)throw new S;return ke(this,Yt,"m",$n).call(this)}[(Wr=new WeakMap,Me=new WeakMap,Hr=new WeakMap,Yt=new WeakSet,On=function(){this.ended||Qt(this,Me,void 0,"f")},vn=function(t,r){if(this.ended)return;let n=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=ke(this,Yt,"m",Tn).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new f(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new f(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new f(`expected content to be 'output_text', got ${a.type}`);n("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new f(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},$n=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");let t=ke(this,Me,"f");if(!t)throw new f("request ended without sending any events");Qt(this,Me,void 0,"f");let r=di(t,ke(this,Wr,"f"));return Qt(this,Hr,r,"f"),r},Tn=function(t){let r=ke(this,Me,"f");if(!r){if(t.type!=="response.created")throw new f(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=Qt(this,Me,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new f(`missing output at index ${t.output_index}`);n.type==="message"&&n.content.push(t.part);break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new f(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new f(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new f(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new f(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.completed":{Qt(this,Me,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).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=ke(this,Hr,"f");if(!e)throw new f("stream ended without producing a ChatCompletion");return e}};function di(s,e){return En(s,e)}var Ne=class extends l{constructor(){super(...arguments),this.inputItems=new zt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&ks(r),r))}retrieve(e,t={},r){return this._client.get(`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Fs(r,e))}stream(e,t){return Jr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}},qr=class extends x{};Ne.InputItems=zt;var Zt=class extends l{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,W({body:t,...r}))}};var Be=class extends l{constructor(){super(...arguments),this.parts=new Zt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(`/uploads/${e}/complete`,{body:t,...r})}};Be.Parts=Zt;var Fn=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var Le=class extends l{create(e,t,r){return this._client.post(`/vector_stores/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,De,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let o=await this.retrieve(e,t,{...r,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let c=o.response.headers.get("openai-poll-after-ms");if(c){let d=parseInt(c);isNaN(d)||(a=d)}}await de(a);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,er,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}},De=class extends x{},er=class extends re{};Le.VectorStoreFilesPage=De;Le.FileContentResponsesPage=er;var tr=class extends l{create(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r={},n){return y(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,De,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let d=parseInt(c);isNaN(d)||(a=d)}}await de(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,t.length),a=this._client,c=t.values(),d=[...r];async function b(p){for(let h of p){let A=await a.files.create({file:h,purpose:"assistants"},n);d.push(A.id)}}let u=Array(i).fill(c).map(b);return await Fn(u),await this.createAndPoll(e,{file_ids:d})}};var K=class extends l{constructor(){super(...arguments),this.files=new Le(this._client),this.fileBatches=new tr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/vector_stores/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/vector_stores",ct,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/search`,ut,{body:t,method:"post",...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}},ct=class extends x{},ut=class extends re{};K.VectorStoresPage=ct;K.VectorStoreSearchResponsesPage=ut;K.Files=Le;K.VectorStoreFilesPage=De;K.FileContentResponsesPage=er;K.FileBatches=tr;var Nn,w=class extends Sr{constructor({baseURL:e=xe("OPENAI_BASE_URL"),apiKey:t=xe("OPENAI_API_KEY"),organization:r=xe("OPENAI_ORG_ID")??null,project:n=xe("OPENAI_PROJECT_ID")??null,...o}={}){if(t===void 0)throw new f("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 i={apiKey:t,organization:r,project:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&hn())throw new f(`It looks like you're running in a browser-like environment.
11
+
12
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
13
+ If you understand the risks and have appropriate mitigations in place,
14
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
15
+
16
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
17
+
18
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
19
+ `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new Qe(this),this.chat=new me(this),this.embeddings=new Ze(this),this.files=new ve(this),this.images=new it(this),this.audio=new se(this),this.moderations=new lt(this),this.models=new Fe(this),this.fineTuning=new G(this),this.graders=new Te(this),this.vectorStores=new K(this),this.beta=new Y(this),this.batches=new Ie(this),this.uploads=new Be(this),this.responses=new Ne(this),this.evals=new le(this),this.containers=new ae(this),this._options=i,this.apiKey=t,this.organization=r,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Qr(e,{arrayFormat:"brackets"})}};Nn=w;w.OpenAI=Nn;w.DEFAULT_TIMEOUT=6e5;w.OpenAIError=f;w.APIError=O;w.APIConnectionError=ue;w.APIConnectionTimeoutError=fe;w.APIUserAbortError=S;w.NotFoundError=pt;w.ConflictError=mt;w.RateLimitError=gt;w.BadRequestError=ft;w.AuthenticationError=ht;w.InternalServerError=wt;w.PermissionDeniedError=dt;w.UnprocessableEntityError=_t;w.toFile=Pr;w.fileFromPath=rr;w.Completions=Qe;w.Chat=me;w.ChatCompletionsPage=Pe;w.Embeddings=Ze;w.Files=ve;w.FileObjectsPage=rt;w.Images=it;w.Audio=se;w.Moderations=lt;w.Models=Fe;w.ModelsPage=at;w.FineTuning=G;w.Graders=Te;w.VectorStores=K;w.VectorStoresPage=ct;w.VectorStoreSearchResponsesPage=ut;w.Beta=Y;w.Batches=Ie;w.BatchesPage=He;w.Uploads=Be;w.Responses=Ne;w.Evals=le;w.EvalListResponsesPage=tt;w.Containers=ae;w.ContainerListResponsesPage=Ye;var kn=class extends w{constructor({baseURL:e=xe("OPENAI_BASE_URL"),apiKey:t=xe("AZURE_OPENAI_API_KEY"),apiVersion:r=xe("OPENAI_API_VERSION"),endpoint:n,deployment:o,azureADTokenProvider:i,dangerouslyAllowBrowser:a,...c}={}){if(!r)throw new f("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof i=="function"&&(a=!0),!i&&!t)throw new f("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&t)throw new f("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(t??(t=Mn),c.defaultQuery={...c.defaultQuery,"api-version":r},e){if(n)throw new f("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new f("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${n}/openai`}super({apiKey:t,baseURL:e,...c,...a!==void 0?{dangerouslyAllowBrowser:a}:{}}),this.apiVersion="",this._azureADTokenProvider=i,this.apiVersion=r,this.deploymentName=o}buildRequest(e,t={}){if(wi.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!xt(e.body))throw new Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;r!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${r}${e.path}`)}return super.buildRequest(e,t)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){let e=await this._azureADTokenProvider();if(!e||typeof e!="string")throw new f(`Expected 'azureADTokenProvider' argument to return a string but it returned ${e}`);return e}}authHeaders(e){return{}}async prepareOptions(e){if(e.headers?.["api-key"])return super.prepareOptions(e);let t=await this._getAzureADToken();if(e.headers??(e.headers={}),t)e.headers.Authorization=`Bearer ${t}`;else if(this.apiKey!==Mn)e.headers["api-key"]=this.apiKey;else throw new f("Unable to handle auth");return super.prepareOptions(e)}},wi=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/images/edits"]),Mn="<Missing Key>",mf=w;export{ue as APIConnectionError,fe as APIConnectionTimeoutError,O as APIError,S as APIUserAbortError,ht as AuthenticationError,kn as AzureOpenAI,ft as BadRequestError,mt as ConflictError,wt as InternalServerError,pt as NotFoundError,w as OpenAI,f as OpenAIError,dt as PermissionDeniedError,gt as RateLimitError,_t as UnprocessableEntityError,mf as default,rr as fileFromPath,Pr as toFile};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-GETSWLMF.js";import"./chunk-OLM5RTFK.js";import"./chunk-DXB73IDG.js";export{a as OpenAIModel,b as openaiFactory};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-NZFUFGOC.js";import"./chunk-7QNRH7OR.js";import"./chunk-OLM5RTFK.js";import"./chunk-DOV5776P.js";import"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";export{a as OpenCodeModel,b as openCodeFactory};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f}from"./chunk-6YRN6OJC.js";import"./chunk-SCULX2ND.js";import"./chunk-DXB73IDG.js";export{e as applyRecipe,f as applyRecipeChain,b as fileExists,a as isPathSafe,c as processContent,d as runPostInstall};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-SCULX2ND.js";import"./chunk-DXB73IDG.js";export{b as DEFAULT_REGISTRY_URL,a as FETCH_TIMEOUT_MS,c as LOCAL_REGISTRY_PATH,e as detectLocalRegistry,g as fetchRecipeFile,i as fetchRecipeFolder,j as fetchRecipeFromRepo,f as fetchRegistry,h as parseGitHubRawUrl,d as registryFetch};
@@ -0,0 +1,8 @@
1
+ import{a as c}from"./chunk-LU3DHXOC.js";import"./chunk-ATLUGTI7.js";import"./chunk-Y6DZEK4W.js";import"./chunk-34GCQZ3Z.js";import"./chunk-3APERFKY.js";import{a as g}from"./chunk-6U2VEZEM.js";import{a as C,b as v}from"./chunk-JQHMDTPL.js";import"./chunk-2TRQKCFC.js";import"./chunk-ZF2XYULB.js";import"./chunk-5UGVJVIQ.js";import"./chunk-4S7QYPS6.js";import{f as w}from"./chunk-NUSNMQPL.js";import"./chunk-GXPLME3K.js";import"./chunk-FGDJVQG3.js";import"./chunk-USCAYIWL.js";import{b as n,e as h,f,g as y,h as o}from"./chunk-PLJNPQFC.js";import{b as l}from"./chunk-DOV5776P.js";import{a as m}from"./chunk-HPPFA3XU.js";import{g as i}from"./chunk-DQAEQEXD.js";import"./chunk-WUJUQPHI.js";import"./chunk-A2GDVOQP.js";import"./chunk-GLSCZGXA.js";import"./chunk-ZE5T64HQ.js";import"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var t=C(),A=async()=>(await l`git status --porcelain`.noThrow().text()).length===0,b=async()=>{let e=await l`git log @{u}..HEAD --oneline`.noThrow().text();return e.length>0?e.split(`
2
+ `):[]},P=async(e,s)=>{for(let r of s)await l`git add ${r}`.spawn();await l`git commit -m ${e}`.spawn()},O=async()=>{await l`git push origin HEAD`.spawn()},k=async e=>{await l`git tag -d ${e}`.noThrow().spawn();let s=`:refs/tags/${e}`;await l`git push origin ${s}`.noThrow().spawn()},T=async e=>{let s=new TextEncoder,r=new TextDecoder,a=new Uint8Array(256);await Deno.stderr.write(s.encode(`${e} [y/N] `));let p=await Deno.stdin.read(a),d=r.decode(a.subarray(0,p??0)).trim();return d==="y"||d==="Y"},M=async e=>{let{type:s,dryRun:r=!1}=e;if(!await A())throw new Error("Working tree is dirty. Commit or stash changes first.");let a=await b();if(a.length>0&&e.yes!==!0)throw new Error(`You have ${a.length} unpushed commit(s):
3
+ ${a.join(`
4
+ `)}
5
+
6
+ Push first, or re-run with --yes to continue anyway.`);let p=await c()??"0.0.0";s!=="same"&&await(await import("./versions-CWT5S7G4.js")).versions(s,{dryRun:r});let d=await c()??p,u=!1;try{await(await import("./changelog-gen-ZCNNOY7G.js")).generateChangelog({dryRun:r}),u=!0}catch{u=!1}let x=!1,E=!1;if(!r){u&&await l`deno fmt CHANGELOG.md`.noThrow().spawn();let R=["VERSION","CHANGELOG.md","pkg/*/deno.json","pkg/*/package.json","package.json"],$=`chore(codebase): release v${d}`;await P($,R),x=!0,await O(),E=!0}return{version:d,previousVersion:p,changelogGenerated:u,committed:x,pushed:E,dryRun:r}},U=async(e={})=>{let{dryRun:s=!1}=e;if(!await A())throw new Error("Working tree is dirty. Commit and push first.");let r=await b();if(r.length>0)throw new Error(`You have unpushed commits. Push first, then rerelease.
7
+ ${r.join(`
8
+ `)}`);let a=await c();if(a===void 0||!/^\d+\.\d+\.\d+$/.test(a))throw new Error(`Invalid or missing version in VERSION file: "${a}"`);let p=`v${a}`;if(!s){let d=`chore(codebase): release v${a}`;await l`git commit --allow-empty -m ${d}`.spawn(),await l`git push origin HEAD`.spawn()}return{version:a,tag:p,dryRun:s}},H=async(e={})=>{let s=await c();if(s===void 0||!/^\d+\.\d+\.\d+$/.test(s))throw new Error(`Invalid or missing version in VERSION file: "${s}"`);let r=`v${s}`;if(e.yes!==!0)throw new Error(`This will delete tag ${r} locally and remotely. Re-run with --yes to confirm.`);return await k(r),{version:s,tag:r,deleted:!0}},I=e=>w.fromPromise(()=>M(e)),V=e=>w.fromPromise(()=>U(e)),D=e=>w.fromPromise(()=>H(e)),j=e=>{let s=e.args[0];return s===void 0||!["patch","minor","major","same"].includes(s)?i.fail(g.adaptError("Usage: eser codebase release <patch|minor|major|same> [--dry-run] [--yes]")):i.ok({type:s,dryRun:e.flags["dry-run"]===!0,yes:e.flags.yes===!0})},N=e=>i.ok({dryRun:e.flags["dry-run"]===!0}),G=e=>i.ok({yes:e.flags.yes===!0}),S=e=>{if(i.isFail(e)){let r=e.error,a=r instanceof Error?r.message:r.message??String(r);return t.writeln(h("\u2717"),n(" "+a)),i.fail({exitCode:1})}let{value:s}=e;return s.dryRun?(t.writeln(y("\u26A0"),n(" [DRY RUN] Release preview:")),t.writeln(o("\u2139"),n(` Version: ${s.previousVersion} -> ${s.version}`)),t.writeln(o("\u2139"),n(` Changelog: ${s.changelogGenerated?"generated":"no user-facing changes"}`)),t.writeln(o("\u2139"),n(" No changes were made."))):(t.writeln(f("\u2713"),n(` Released v${s.version}`)),t.writeln(o("\u2139"),n(` Version: ${s.previousVersion} -> ${s.version}`)),t.writeln(o("\u2139"),n(` Changelog: ${s.changelogGenerated?"updated":"no user-facing changes"}`)),t.writeln(o("\u2139"),n(` Committed: ${s.committed}`)),t.writeln(o("\u2139"),n(` Pushed: ${s.pushed}`)),t.writeln(o("\u2139"),n(" CI will validate, tag, and publish.")),t.writeln(o("\u2139"),n(" Watch: https://github.com/eser/stack/actions"))),i.ok(void 0)},Y=e=>{if(i.isFail(e)){let r=e.error,a=r instanceof Error?r.message:r.message??String(r);return t.writeln(h("\u2717"),n(" "+a)),i.fail({exitCode:1})}let{value:s}=e;return s.dryRun?t.writeln(y("\u26A0"),n(` [DRY RUN] Would delete and recreate tag ${s.tag}`)):(t.writeln(f("\u2713"),n(` Re-tagged ${s.tag}`)),t.writeln(o("\u2139"),n(" CI will validate and publish."))),i.ok(void 0)},F=e=>{if(i.isFail(e)){let r=e.error,a=r instanceof Error?r.message:r.message??String(r);return t.writeln(h("\u2717"),n(" "+a)),i.fail({exitCode:1})}let{value:s}=e;return s.deleted&&t.writeln(f("\u2713"),n(` Deleted tag v${s.version} (local + remote).`)),i.ok(void 0)},W=g.createTrigger({handler:I,adaptInput:j,adaptOutput:S}),L=g.createTrigger({handler:V,adaptInput:N,adaptOutput:Y}),B=g.createTrigger({handler:D,adaptInput:G,adaptOutput:F}),re=async e=>{let s=m(e??[],{boolean:["dry-run","yes"],alias:{n:"dry-run",y:"yes"}}),r=s._[0],a=s["dry-run"]===!0,p=s.yes===!0;if(r!==void 0&&!a&&!p&&["patch","minor","major","same"].includes(r)){let u=await c()??"0.0.0";if(t.writeln(o("\u2139"),n(` Current version: ${u}`)),t.writeln(o("\u2139"),n(` Bump type: ${r}`)),t.writeln(o("\u2139"),n(" This will bump version, generate changelog, commit, and push.")),await t.flush(),!await T("Proceed?"))return t.writeln(y("\u26A0"),n(" Aborted.")),i.ok(void 0);s.yes=!0}let d=v("release",s);return await W(d)},ne=async e=>{let s=m(e??[],{boolean:["dry-run"],alias:{n:"dry-run"}}),r=v("rerelease",s);return await L(r)},te=async e=>{let s=m(e??[],{boolean:["yes"],alias:{y:"yes"}}),r=v("unrelease",s);return await B(r)};export{W as handleReleaseCli,L as handleRereleaseCli,B as handleUnreleaseCli,re as main,M as release,I as releaseHandler,U as rerelease,V as rereleaseHandler,ne as rereleaseMain,H as unrelease,D as unreleaseHandler,te as unreleaseMain};
@@ -0,0 +1,3 @@
1
+ import"./chunk-DDLQMSA7.js";import{a as y}from"./chunk-6U2VEZEM.js";import{a as E,b as A}from"./chunk-JQHMDTPL.js";import"./chunk-2TRQKCFC.js";import"./chunk-ZF2XYULB.js";import"./chunk-5UGVJVIQ.js";import"./chunk-4S7QYPS6.js";import{f as $}from"./chunk-NUSNMQPL.js";import"./chunk-FGDJVQG3.js";import"./chunk-USCAYIWL.js";import{b as p,e as P,f as m,g as C}from"./chunk-PLJNPQFC.js";import{c as u}from"./chunk-DOV5776P.js";import"./chunk-ZOZYBQX2.js";import"./chunk-DRQWYJMH.js";import"./chunk-WE7PSSAQ.js";import{a as v}from"./chunk-HPPFA3XU.js";import{g as l}from"./chunk-DQAEQEXD.js";import"./chunk-WUJUQPHI.js";import"./chunk-A2GDVOQP.js";import{j as w,n as R}from"./chunk-GLSCZGXA.js";import"./chunk-ZE5T64HQ.js";import{u as c}from"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var h=E(),O=/^##\s+\[?([^\]\s]+)\]?\s*-?\s*([0-9]{4}-[0-9]{2}-[0-9]{2})?\s*$/,T=t=>{let e=t.trim().replace(/^refs\/tags\//,"");return e.startsWith("v")?e:`v${e}`},k=t=>{let e=t.split(/\r?\n/),n=[];for(let s=0;s<e.length;s+=1){let i=e[s].match(O);i!==null&&/^\d/.test(i[1])&&n.push({version:i[1],date:i[2]??"",headingLineIndex:s})}return n.length===0?[]:n.map((s,o)=>{let i=n[o+1],g=s.headingLineIndex+1,a=i!==void 0?i.headingLineIndex:e.length,r=e.slice(g,a);for(;r.length>0&&r[0].trim()==="";)r.shift();for(;r.length>0&&r[r.length-1].trim()==="";)r.pop();let d=[`## ${s.version}${s.date!==""?` - ${s.date}`:""}`];return r.length>0&&d.push("",...r),{version:s.version,date:s.date,tag:`v${s.version}`,notes:`${d.join(`
2
+ `).trim()}
3
+ `}})},I=async(t={})=>{let{changelogPath:e="CHANGELOG.md",root:n="."}=t,s=R(n,e),o=await c.current.fs.readTextFile(s);return{entries:k(o)}},S=async(t,e)=>{try{return await u.exec`gh release view ${t} --repo ${e}`.quiet().text(),!0}catch{return!1}},b=async t=>{let{repo:e,createIfMissing:n=!1,changelogPath:s="CHANGELOG.md",root:o=".",releaseTitle:i="eserstack {tag}"}=t,{entries:g}=await I({changelogPath:s,root:o});if(g.length===0)throw new Error("No release headings found in CHANGELOG.md.");let a=t.tag!==void 0?T(t.tag):g[0].tag,r=g.find(x=>x.tag===a);if(r===void 0)throw new Error(`No matching changelog section found for ${a}.`);let d=await c.current.fs.makeTempDir({prefix:"eserstack-release-"}),f=w(d,`${a}-notes.md`);await c.current.fs.writeTextFile(f,r.notes);try{if(await S(a,e))return await u.exec`gh release edit ${a} --repo ${e} --notes-file ${f}`.spawn(),{tag:a,entry:r,action:"updated"};if(!n)return{tag:a,entry:r,action:"skipped"};let N=i.replace("{tag}",a);try{return await u.exec`gh release create ${a} --repo ${e} --title ${N} --notes-file ${f}`.spawn(),{tag:a,entry:r,action:"created"}}catch{return await u.exec`gh release edit ${a} --repo ${e} --notes-file ${f}`.spawn(),{tag:a,entry:r,action:"updated"}}}finally{await c.current.fs.remove(d,{recursive:!0})}},G=t=>$.fromPromise(()=>b(t)),H=t=>{let e=t.flags.repo??c.current.env.get("GITHUB_REPOSITORY")??"";return e===""?l.fail(y.adaptError("Missing repository. Pass --repo or set GITHUB_REPOSITORY.")):l.ok({repo:e,tag:t.flags.tag??void 0,createIfMissing:t.flags["create-if-missing"]===!0})},L=t=>{if(l.isFail(t)){let n=t.error,s=n instanceof Error?n.message:n.message??String(n);return h.writeln(P("\u2717"),p(" "+s)),l.fail({exitCode:1})}let{value:e}=t;switch(e.action){case"created":h.writeln(m("\u2713"),p(` Created release ${e.tag} with changelog notes.`));break;case"updated":h.writeln(m("\u2713"),p(` Updated release notes for ${e.tag}.`));break;case"skipped":h.writeln(C("\u26A0"),p(` Release ${e.tag} not found. Skipping (pass --create-if-missing to create).`));break}return l.ok(void 0)},M=y.createTrigger({handler:G,adaptInput:H,adaptOutput:L}),W=async t=>{let e=v(t??[],{string:["repo","tag"],boolean:["create-if-missing"],alias:{h:"help"}}),n=A("release-notes",e);return await M(n)};export{M as handleCli,S as hasGitHubRelease,W as main,T as normalizeTag,I as parseChangelog,k as parseChangelogText,b as syncReleaseNotes,G as syncReleaseNotesHandler};
@@ -0,0 +1 @@
1
+ import{c as y,d as v}from"./chunk-BP2MZX2P.js";import{a as P}from"./chunk-LU3DHXOC.js";import"./chunk-ATLUGTI7.js";import"./chunk-Y6DZEK4W.js";import"./chunk-34GCQZ3Z.js";import"./chunk-3APERFKY.js";import{a as h}from"./chunk-6U2VEZEM.js";import{a as f,b as R}from"./chunk-JQHMDTPL.js";import"./chunk-2TRQKCFC.js";import"./chunk-ZF2XYULB.js";import"./chunk-5UGVJVIQ.js";import"./chunk-4S7QYPS6.js";import{f as c}from"./chunk-NUSNMQPL.js";import"./chunk-GXPLME3K.js";import"./chunk-FGDJVQG3.js";import"./chunk-USCAYIWL.js";import{b as a,e as g,f as u,g as d,h as m}from"./chunk-PLJNPQFC.js";import"./chunk-DOV5776P.js";import{a as p}from"./chunk-HPPFA3XU.js";import{g as t}from"./chunk-DQAEQEXD.js";import"./chunk-WUJUQPHI.js";import"./chunk-A2GDVOQP.js";import"./chunk-GLSCZGXA.js";import"./chunk-ZE5T64HQ.js";import"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var o=f(),C=async(e={})=>{let{root:r=".",remote:n="origin",tagPrefix:T="v",messageTemplate:x="Release {tag}",dryRun:l=!1}=e,s=await P({root:r});if(s===void 0||!/^\d+\.\d+\.\d+$/.test(s))throw new Error(`Invalid or missing version in VERSION file: "${s}"`);let i=`${T}${s}`,w=x.replace("{tag}",i).replace("{version}",s);return l||(await y(i,w),await v(n,i)),{version:s,tag:i,remote:n,dryRun:l}},A=e=>c.fromPromise(()=>C(e)),E=e=>t.ok({dryRun:e.flags["dry-run"]===!0}),$=e=>{if(t.isFail(e))return o.writeln(g("\u2717"),a(" "+(e.error instanceof Error?e.error.message:String(e.error)))),t.fail({exitCode:1});let{value:r}=e;return r.dryRun?o.writeln(d("\u26A0"),a(` [DRY RUN] Would create and push tag ${r.tag}`)):(o.writeln(u("\u2713"),a(` Created tag ${r.tag}`)),o.writeln(m("\u2139"),a(` Pushed tag ${r.tag} to ${r.remote}`))),t.ok(void 0)},O=h.createTrigger({handler:A,adaptInput:E,adaptOutput:$}),U=async e=>{let r=p(e??[],{boolean:["dry-run"],alias:{n:"dry-run"}}),n=R("release-tag",r);return await O(n)};export{O as handleCli,U as main,C as pushReleaseTag,A as pushReleaseTagHandler};
@@ -0,0 +1 @@
1
+ import{h as d}from"./chunk-LXVBR775.js";import{d as p,e as c}from"./chunk-BKVQBSFV.js";import{f as o,h as l,k as m}from"./chunk-FGDJVQG3.js";import{d as a,f as i}from"./chunk-PLJNPQFC.js";import{a as r}from"./chunk-DQAEQEXD.js";import"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var y=async f=>{let e=o({renderer:m.ansi(),sink:l.stdout()}),n=Deno.cwd(),s=await p(n);if(s.phase==="IDLE"||s.phase==="UNINITIALIZED")return e.writeln(a("Already idle. Nothing to reset.")),await e.close(),r(void 0);let t=s.spec,u=d(s);return await c(n,u),e.writeln(i("\u2714")," Reset to IDLE."),t!==null&&e.writeln(a(`Spec "${t}" state cleared. Files in .nos/specs/${t}/ preserved.`)),await e.close(),r(void 0)};export{y as main};
@@ -0,0 +1,2 @@
1
+ import{a as g,b as h}from"./chunk-XMTGT2NJ.js";import{c as p,f}from"./chunk-BKVQBSFV.js";import{f as i,h as o,k as l}from"./chunk-FGDJVQG3.js";import{c,d as n,e as m,f as w}from"./chunk-PLJNPQFC.js";import{a,b as u}from"./chunk-DQAEQEXD.js";import"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var T=async s=>{let e=s?.[0];if(e==="add")return await k(s?.slice(1));if(e==="list")return await x();if(e==="promote")return await A(s?.slice(1));let t=i({renderer:l.ansi(),sink:o.stdout()});return t.writeln('Usage: noskills rule <add "rule text" | list | promote "decision">'),await t.close(),a(void 0)},k=async s=>{let e=i({renderer:l.ansi(),sink:o.stdout()}),t=Deno.cwd(),r=s?.join(" ");if(r===void 0||r.length===0)return e.writeln(m("Please provide a rule: "),c('noskills rule add "Use Vitest for all tests"')),await e.close(),u({exitCode:1});let y=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),P=`${t}/${p.rulesDir}/${y}.md`;await Deno.mkdir(`${t}/${p.rulesDir}`,{recursive:!0}),await Deno.writeTextFile(P,r+`
2
+ `),e.writeln(w("\u2714")," Rule added: ",n(r));let d=await f(t);return d!==null&&d.tools.length>0&&(await h(t,d.tools),e.writeln(n(" Tool files synced."))),await e.close(),a(void 0)},x=async()=>{let s=i({renderer:l.ansi(),sink:o.stdout()}),e=Deno.cwd(),t=await g(e);if(s.writeln(c("Rules")),s.writeln(""),t.length===0)s.writeln(n(' No rules yet. Add one with: noskills rule add "..."'));else for(let r of t)s.writeln(" ",n("\u2022"),` ${r}`);return await s.close(),a(void 0)},A=async s=>{let e=i({renderer:l.ansi(),sink:o.stdout()}),t=s?.join(" ");return t===void 0||t.length===0?(e.writeln(m("Please provide the decision text to promote.")),await e.close(),u({exitCode:1})):(e.writeln(n("Promoting decision to rule...")),await e.close(),await k(s))};export{T as main};
@@ -0,0 +1,4 @@
1
+ import{a as V,b as q,c as z}from"./chunk-2R4MK2KR.js";import"./chunk-7GS5KPVF.js";import{a as A,c as J,d as k,e as L}from"./chunk-NUSNMQPL.js";import"./chunk-GXPLME3K.js";import{f as N,h as U,k as B}from"./chunk-FGDJVQG3.js";import{e as x,f as C,g as F}from"./chunk-PLJNPQFC.js";import{b as H}from"./chunk-DOV5776P.js";import{a as I}from"./chunk-HPPFA3XU.js";import{a as W,b as c,c as P,d as S}from"./chunk-DQAEQEXD.js";import{t as _}from"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var O=s=>({_tag:"WorkflowError",message:s}),Z=s=>{if(typeof s=="string")return{name:s,options:{},continueOnError:!1};let o=Object.entries(s);if(o.length!==1)throw new Error(`Invalid step config: expected exactly one key, got ${o.length}`);let[e,n]=o[0],r={},i=!1,l;for(let[a,t]of Object.entries(n))a==="continueOnError"?i=t===!0:a==="timeout"?l=t*1e3:r[a]=t;return{name:e,options:r,continueOnError:i,timeout:l}},ee=(s,o,e)=>L(J(s,n=>O(n instanceof Error?n.message:String(n))),o,O(`Step '${e}' timed out after ${(o/1e3).toFixed(0)}s`)),G=(s,o,e={})=>A(async()=>{let n=performance.now(),r=[],i=e.defaultTimeout??6e4;for(let a of s.steps){let t=Z(a);if(e.only!==void 0&&t.name!==e.only)continue;let T=o.get(t.name);if(T===void 0)return c(O(`Unknown tool '${t.name}' in workflow '${s.id}'. Registered tools: ${o.names().join(", ")||"(none)"}`));let v={...t.options,root:e.root??".",fix:e.fix??!1,_args:e.args??[]};e.changedFiles!==void 0&&(v._changedFiles=e.changedFiles),e.onStepStart?.(t.name);let g=performance.now(),j=t.timeout??i,h=ee(()=>T.run(v),j,t.name),p=await k(h),d;if(P(p))d=p.value;else if(t.continueOnError)d={name:t.name,passed:!1,issues:[{message:p.error.message}],mutations:[],stats:{}};else return p;let b=performance.now()-g,y={...d,durationMs:b};r.push(y),d.mutations.length>0&&e.onMutations!==void 0&&await e.onMutations(d.mutations),e.onStepEnd?.(y)}let l=performance.now()-n;return W({workflowId:s.id,passed:r.every(a=>a.passed),steps:r,totalDurationMs:l})}),D=(s,o,e=new Set)=>{if(s.includes===void 0||s.includes.length===0)return s;let n=new Set(e);n.add(s.id);let r=[];for(let i of s.includes){if(n.has(i))throw new Error(`Circular include detected: workflow '${s.id}' includes '${i}' which is already in the include chain: ${[...n].join(" \u2192 ")}`);let l=o.find(t=>t.id===i);if(l===void 0)throw new Error(`Workflow '${s.id}' includes '${i}' but no workflow with that id exists. Available: ${o.map(t=>t.id).join(", ")||"(none)"}`);let a=D(l,o,n);r.push(...a.steps)}return{...s,steps:[...r,...s.steps],includes:void 0}},K=(s,o,e,n={})=>A(async()=>{let r=o.workflows.find(l=>l.id===s);if(r===void 0)return c(O(`Workflow '${s}' not found. Available: ${o.workflows.map(l=>l.id).join(", ")||"(none)"}`));let i=D(r,o.workflows);return await k(G(i,e,n))}),Q=(s,o,e,n={})=>A(async()=>{let r=o.filter(l=>l.on.includes(s));if(r.length===0)return c(O(`No workflows found for event '${s}'. Available: ${o.map(l=>`${l.id} (${l.on.join(", ")})`).join("; ")||"(none)"}`));let i=[];for(let l of r){let a=D(l,o),t=await k(G(a,e,n));if(S(t))return t;i.push(t.value)}return W(i)});var oe=50,$=B.ansi(),se=(s,o,e)=>{let n=".".repeat(Math.max(1,oe-s.length)),r=`${(o.durationMs/1e3).toFixed(1)}s`,i;if(o.passed&&o.mutations.length>0)i=$.render([F(`Fixed (${o.mutations.length} file${o.mutations.length===1?"":"s"}, ${r})`)]);else if(o.passed)if(e&&Object.keys(o.stats).length>0){let l=Object.entries(o.stats).map(([a,t])=>`${t} ${a}`).join(", ");i=$.render([C(`Passed (${l}, ${r})`)])}else i=$.render([C(`Passed (${r})`)]);else i=$.render([x(`Failed (${r})`)]);return`${s}${n}${i}`},pe=async(s,o)=>{let e=I(s??[],{string:["event","workflow","only","config"],boolean:["fix","dry-run","help","verbose","json","changed"],alias:{e:"event",w:"workflow",h:"help",v:"verbose"}});if(e.help)return console.log(`eser workflows run \u2014 Run workflow pipelines
2
+ `),console.log("Usage:"),console.log(" eser workflows run -e <event> Run by event"),console.log(" eser workflows run -w <workflow-id> Run by workflow id"),console.log(),console.log("Options:"),console.log(" -e, --event <name> Event to trigger (precommit, commitmsg, prepush)"),console.log(" -w, --workflow <id> Workflow id to run"),console.log(" --fix Auto-fix issues where supported"),console.log(" --dry-run Preview mutations without writing"),console.log(" --only <step> Run only a specific step"),console.log(" --config <path> Config directory (default: .)"),console.log(" -v, --verbose Show stats and issues for all steps"),console.log(" --json Output results as JSON"),console.log(" --changed Only check files changed in git"),console.log(" -h, --help Show this help"),W(void 0);let n=N({renderer:$,sink:U.stdout()}),r=e.event,i=e.workflow,l=e.fix??!1,a=e["dry-run"]??!1,t=e.only,T=e._,v=e.verbose??!1,g=e.json??!1,j=e.changed??!1;if(r===void 0&&i===void 0)return console.error("Error: specify -e <event> or -w <workflow-id>. Use --help for usage."),await n.close(),c({exitCode:1});let h=V();h.register(z),o?.tools!==void 0&&h.registerAll(o.tools);let p=e.config??".",d=await q(p);if(d===null)return console.error("Error: no .manifest.yml found in current directory."),await n.close(),c({exitCode:1});let b;if(j)try{b=await H`git diff --name-only HEAD`.cwd(p).noThrow().lines()}catch{n.writeln(F("Warning: could not run git, running without file filtering."))}let y=[],M={root:p,fix:l,dryRun:a,only:t,args:T,changedFiles:b,onStepStart:void 0,onStepEnd:g?void 0:f=>{if(console.log(se(f.name,f,v)),!f.passed||v)for(let u of f.issues){let R=u.path!==void 0?u.line!==void 0?`${u.path}:${u.line}`:u.path:"";console.log(` ${$.render([x("\u2717")])} ${R}${R.length>0?": ":""}${u.message}`)}},onMutations:async f=>{if(!a)for(let u of f)u.oldContent!==u.newContent&&await _.fs.writeTextFile(u.path,u.newContent)}};try{let f=!0,u=0,R=0;if(r!==void 0){let w=await k(Q(r,d.workflows,h,M));if(S(w))throw new Error(w.error.message);for(let m of w.value){y.push(m),m.passed||(f=!1);for(let E of m.steps)E.passed||(R++,u+=E.issues.length)}}else{let w=await k(K(i,d,h,M));if(S(w))throw new Error(w.error.message);let m=w.value;y.push(m),f=m.passed;for(let E of m.steps)E.passed||(R++,u+=E.issues.length)}return g&&console.log(JSON.stringify(y,null,2)),f?(g||n.writeln(C(`
3
+ All checks passed!`)),await n.close(),W(void 0)):(g||n.writeln(x(`
4
+ ${R} check(s) failed with ${u} issue(s)`)),await n.close(),c({exitCode:1}))}catch(f){return n.writeln(x(`Error: ${f instanceof Error?f.message:String(f)}`)),await n.close(),c({exitCode:1})}};export{pe as main};
@@ -0,0 +1 @@
1
+ import{f as w,h as g,k as y}from"./chunk-FGDJVQG3.js";import{b as m,d as p,e as C}from"./chunk-PLJNPQFC.js";import{a as x}from"./chunk-DOV5776P.js";import{a as h,b as f}from"./chunk-DQAEQEXD.js";import{t as S}from"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var l=(e,r)=>typeof r=="string"?{command:r,description:e,workingDirectory:void 0,depends:[]}:{command:r.command,description:r.description??e,workingDirectory:r.workingDirectory,depends:r.depends??[]},k=(e,r,t=new Set,s=new Set)=>{if(s.has(e))return[];if(t.has(e))throw new Error(`Circular dependency detected: ${e} depends on itself (cycle in dependency chain)`);let n=r[e];if(n===void 0)throw new Error(`Unknown script dependency: "${e}"`);t.add(e);let c=l(e,n),o=[];for(let a of c.depends){let i=k(a,r,t,s);for(let d of i)s.has(d)||(o.push(d),s.add(d))}return s.add(e),o},P=()=>{let e=new URL("./main.ts",import.meta.url),r=e.protocol==="file:"?e.pathname:e.href;return`${S.process.execPath()} run --allow-all ${r}`},R=e=>{if(e==="eser"||e.startsWith("eser ")){let r=e.slice(4);return`${P()}${r}`}return e},$=async(e,r,t)=>{let s=R(e),n=t!==void 0&&t.length>0?`${s} ${t.join(" ")}`:s,c=r??".";return(await new x("sh",["-c",n]).cwd(c).stdout("inherit").stderr("inherit").noThrow().spawn()).code},O=async(e,r,t,s)=>{let n=w({renderer:y.ansi(),sink:g.stdout()}),c=k(e,t);for(let i of c){let d=l(i,t[i]);n.writeln(p(`$ ${i}`));let u=await $(d.command,d.workingDirectory);if(u!==0)return n.writeln(C(`Script dependency "${i}" failed with exit code ${u}`)),await n.close(),f({exitCode:u})}let o=l(e,t[e]);n.writeln(p(`$ ${e}`));let a=await $(o.command,o.workingDirectory,s);return a!==0?(await n.close(),f({exitCode:a})):(await n.close(),h(void 0))},B=e=>{let r=w({renderer:y.ansi(),sink:g.stdout()});r.writeln(m("Scripts:"));for(let[t,s]of Object.entries(e)){let n=l(t,s);r.writeln(m(` ${t.padEnd(20)} `),p(n.description))}r.writeln()};export{$ as executeCommand,l as parseScript,k as resolveDependencies,O as runScript,B as showScripts};
@@ -0,0 +1,18 @@
1
+ import{a as xt,b as zt,c as Qt,d as St}from"./chunk-IA7GIU76.js";import{a as Gt}from"./chunk-AK3OJD4W.js";import{b as bt,c as _t}from"./chunk-FKF2SWQM.js";import{e as Qe}from"./chunk-DXB73IDG.js";var N="0.39.0";var Pt=!1,U,Ye,Yt,Zt,er,Mt,tr,Me,Ze,Et,et,ue,At;function Rt(s,e={auto:!1}){if(Pt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${s.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(U)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${s.kind}'\` after \`import '@anthropic-ai/sdk/shims/${U}'\``);Pt=e.auto,U=s.kind,Ye=s.fetch,Yt=s.Request,Zt=s.Response,er=s.Headers,Mt=s.FormData,tr=s.Blob,Me=s.File,Ze=s.ReadableStream,Et=s.getMultipartRequestOptions,et=s.getDefaultAgent,ue=s.fileFromPath,At=s.isFsReadStream}var O=Qe(Gt(),1);var tt=Qe(zt(),1),It=Qe(Qt(),1);import{ReadStream as sr}from"node:fs";import{Readable as nr}from"node:stream";var Ee=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};import{ReadableStream as ir}from"node:stream/web";var kt=!1;async function or(s,...e){let{fileFromPath:t}=await import("./fileFromPath-4UEDFJ4U.js");return kt||(console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(s)}) instead`),kt=!0),await t(s,...e)}var ar=new tt.default({keepAlive:!0,timeout:5*60*1e3}),cr=new tt.default.HttpsAgent({keepAlive:!0,timeout:5*60*1e3});async function ur(s,e){let t=new St(s),r=nr.from(t),n=new Ee(r),i={...e.headers,...t.headers,"Content-Length":t.contentLength};return{...e,body:n,headers:i}}function Bt(){return typeof AbortController>"u"&&(globalThis.AbortController=It.AbortController),{kind:"node",fetch:O.default,Request:O.Request,Response:O.Response,Headers:O.Headers,FormData:xt,Blob:bt,File:_t,ReadableStream:ir,getMultipartRequestOptions:ur,getDefaultAgent:s=>s.startsWith("https")?cr:ar,fileFromPath:or,isFsReadStream:s=>s instanceof sr}}U||Rt(Bt(),{auto:!0});var c=class extends Error{},m=class s extends c{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["request-id"],this.error=t}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new R({message:r,cause:Ae(t)});let i=t;return e===400?new K(e,i,r,n):e===401?new V(e,i,r,n):e===403?new G(e,i,r,n):e===404?new z(e,i,r,n):e===409?new Q(e,i,r,n):e===422?new Y(e,i,r,n):e===429?new Z(e,i,r,n):e>=500?new ee(e,i,r,n):new s(e,i,r,n)}},p=class extends m{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},R=class extends m{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},$=class extends R{constructor({message:e}={}){super({message:e??"Request timed out."})}},K=class extends m{},V=class extends m{},G=class extends m{},z=class extends m{},Q=class extends m{},Y=class extends m{},Z=class extends m{},ee=class extends m{};var Re=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},L=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},b,k=class{constructor(){b.set(this,void 0),this.buffer=new Uint8Array,Re(this,b,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;let n=[],i;for(;(i=fr(this.buffer,L(this,b,"f")))!=null;){if(i.carriage&&L(this,b,"f")==null){Re(this,b,i.index,"f");continue}if(L(this,b,"f")!=null&&(i.index!==L(this,b,"f")+1||i.carriage)){n.push(this.decodeText(this.buffer.slice(0,L(this,b,"f")-1))),this.buffer=this.buffer.slice(L(this,b,"f")),Re(this,b,null,"f");continue}let o=L(this,b,"f")!==null?i.preceding-1:i.preceding,a=this.decodeText(this.buffer.slice(0,o));n.push(a),this.buffer=this.buffer.slice(i.index),Re(this,b,null,"f")}return n}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new c(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new c(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new c("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
2
+ `):[]}};b=new WeakMap;k.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);k.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function fr(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Tt(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}function le(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var M=class s{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*n(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(let o of hr(e,t)){if(o.event==="completion")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event==="message_start"||o.event==="message_delta"||o.event==="message_stop"||o.event==="content_block_start"||o.event==="content_block_delta"||o.event==="content_block_stop")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event!=="ping"&&o.event==="error")throw m.generate(void 0,`SSE Error: ${o.data}`,o.data,st(e.headers))}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new s(n,t)}static fromReadableStream(e,t){let r=!1;async function*n(){let o=new k,a=le(e);for await(let h of a)for(let d of o.decode(h))yield d;for(let h of o.flush())yield h}async function*i(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(let a of n())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new s(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=i=>({next:()=>{if(i.length===0){let o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new s(()=>n(e),this.controller),new s(()=>n(t),this.controller)]}toReadableStream(){let e=this,t,r=new TextEncoder;return new Ze({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await t.next();if(o)return n.close();let a=r.encode(JSON.stringify(i)+`
4
+ `);n.enqueue(a)}catch(i){n.error(i)}},async cancel(){await t.return?.()}})}};async function*hr(s,e){if(!s.body)throw e.abort(),new c("Attempted to iterate over a response with no body");let t=new rt,r=new k,n=le(s.body);for await(let i of dr(n))for(let o of r.decode(i)){let a=t.decode(o);a&&(yield a)}for(let i of r.flush()){let o=t.decode(i);o&&(yield o)}}async function*dr(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let i;for(;(i=Tt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var rt=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 i={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=mr(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function mr(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}var pr=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",gr=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&fe(s),fe=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function";async function it(s,e,t){if(s=await s,gr(s))return s;if(pr(s)){let n=await s.blob();e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=fe(n)?[await n.arrayBuffer()]:[n];return new Me(i,e,t)}let r=await yr(s);if(e||(e=br(s)??"unknown_file"),!t?.type){let n=r[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new Me(r,e,t)}async function yr(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(fe(s))e.push(await s.arrayBuffer());else if(_r(s))for await(let t of s)e.push(t);else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${s?.constructor?.name}; props: ${wr(s)}`);return e}function wr(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function br(s){return nt(s.name)||nt(s.filename)||nt(s.path)?.split(/[\\/]/).pop()}var nt=s=>{if(typeof s=="string")return s;if(typeof Buffer<"u"&&s instanceof Buffer)return String(s)},_r=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",ot=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody";var Sr=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},Pr=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},ke;async function Ft(s){let{response:e}=s;if(s.options.stream)return te("response",e.status,e.url,e.headers,e.body),s.options.__streamClass?s.options.__streamClass.fromSSEResponse(e,s.controller):M.fromSSEResponse(e,s.controller);if(e.status===204)return null;if(s.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let i=await e.json();return te("response",e.status,e.url,e.headers,i),jt(i,e)}let n=await e.text();return te("response",e.status,e.url,e.headers,n),n}function jt(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Be=class s extends Promise{constructor(e,t=Ft){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new s(this.responsePromise,async t=>jt(e(await this.parseResponse(t),t),t.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("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),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)}},Te=class{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:i}){this.baseURL=e,this.maxRetries=at("maxRetries",t),this.timeout=at("timeout",r),this.httpAgent=n,this.fetch=i??Ye}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Rr(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Cr()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(async n=>{let i=n&&fe(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:i}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};let{method:r,path:n,query:i,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:ot(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,h=this.calculateContentLength(a),d=this.buildURL(n,i);"timeout"in e&&at("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let _=e.httpAgent??this.httpAgent??et(d),C=e.timeout+1e3;typeof _?.options?.timeout=="number"&&C>(_.options.timeout??0)&&(_.options.timeout=C),this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let Pe=this.buildHeaders({options:e,headers:o,contentLength:h,retryCount:t});return{req:{method:r,...a&&{body:a},headers:Pe,..._&&{agent:_},signal:e.signal??null},url:d,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){let i={};r&&(i["content-length"]=r);let o=this.defaultHeaders(e);return qt(i,o),qt(i,t),ot(e.body)&&U!=="node"&&delete i["content-type"],Ie(o,"x-stainless-retry-count")===void 0&&Ie(t,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(n)),Ie(o,"x-stainless-timeout")===void 0&&Ie(t,"x-stainless-timeout")===void 0&&e.timeout&&(i["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(i,t),i}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new c("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,r,n){return m.generate(e,t,r,n)}request(e,t=null){return new Be(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,n=r.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(r);let{req:i,url:o,timeout:a}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(i,{url:o,options:r}),te("request",o,r,i.headers),r.signal?.aborted)throw new p;let h=new AbortController,d=await this.fetchWithTimeout(o,i,a,h).catch(Ae);if(d instanceof Error){if(r.signal?.aborted)throw new p;if(t)return this.retryRequest(r,t);throw d.name==="AbortError"?new $:new R({cause:d})}let _=st(d.headers);if(!d.ok){if(t&&this.shouldRetry(d)){let ze=`retrying, ${t} attempts remaining`;return te(`response (error; ${ze})`,d.status,o,_),this.retryRequest(r,t,_)}let C=await d.text().catch(ze=>Ae(ze).message),Pe=kr(C),Ge=Pe?void 0:C;throw te(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,d.status,o,_,Ge),this.makeStatusError(d.status,Pe,Ge,_)}return{response:d,options:r,controller:h}}requestAPIList(e,t){let r=this.makeRequest(t,null);return new ct(this,r,e)}buildURL(e,t){let r=Br(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return he(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new c(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,n){let{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r),h={signal:n.signal,...o};h.method&&(h.method=h.method.toUpperCase());let d=60*1e3,_=setTimeout(()=>{if(h&&h?.agent?.sockets)for(let C of Object.values(h?.agent?.sockets).flat())C?.setKeepAlive&&C.setKeepAlive(!0,d)},d);return this.fetch.call(void 0,e,h).finally(()=>{clearTimeout(a),clearTimeout(_)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r){let n,i=r?.["retry-after-ms"];if(i){let a=parseFloat(i);Number.isNaN(a)||(n=a)}let o=r?.["retry-after"];if(o&&!n){let a=parseFloat(o);Number.isNaN(a)?n=Date.parse(o)-Date.now():n=a*1e3}if(!(n&&0<=n&&n<60*1e3)){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await Tr(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${N}`}},Ce=class{constructor(e,t,r,n){ke.set(this,void 0),Sr(this,ke,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new c("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,i]of r)e.url.searchParams.set(n,i);t.query=void 0,t.path=e.url.toString()}return await Pr(this,ke,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ke=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ct=class extends Be{constructor(e,t,r){super(t,async n=>new r(e,n.response,await Ft(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},st=s=>new Proxy(Object.fromEntries(s.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),Mr={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},x=s=>typeof s=="object"&&s!==null&&!he(s)&&Object.keys(s).every(e=>Nt(Mr,e)),Er=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N,"X-Stainless-OS":Ot(Deno.build.os),"X-Stainless-Arch":Ct(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":N,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N,"X-Stainless-OS":Ot(process.platform),"X-Stainless-Arch":Ct(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let s=Ar();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ar(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:e,version:`${n}.${i}.${o}`}}}return null}var Ct=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Ot=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),vt,Rr=()=>vt??(vt=Er()),kr=s=>{try{return JSON.parse(s)}catch{return}},Ir=/^[a-z][a-z0-9+.-]*:/i,Br=s=>Ir.test(s),Tr=s=>new Promise(e=>setTimeout(e,s)),at=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new c(`${s} must be an integer`);if(e<0)throw new c(`${s} must be a positive integer`);return e},Ae=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null)try{return new Error(JSON.stringify(s))}catch{}return new Error(String(s))};var Oe=s=>{if(typeof process<"u")return process.env?.[s]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(s)?.trim()};function he(s){if(!s)return!0;for(let e in s)return!1;return!0}function Nt(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function qt(s,e){for(let t in e){if(!Nt(e,t))continue;let r=t.toLowerCase();if(!r)continue;let n=e[t];n===null?delete s[r]:n!==void 0&&(s[r]=n)}}function te(s,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${s}`,...e)}var Cr=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)}),Ut=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Or=s=>typeof s?.get=="function";var Ie=(s,e)=>{let t=e.toLowerCase();if(Or(s)){let r=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,i,o)=>i+o.toUpperCase());for(let n of[e,t,e.toUpperCase(),r]){let i=s.get(n);if(i)return i}}for(let[r,n]of Object.entries(s))if(r.toLowerCase()===t)return Array.isArray(n)?(n.length<=1||console.warn(`Received ${n.length} entries for the ${e} header, using the first entry.`),n[0]):n};var E=class extends Ce{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};var g=class{constructor(e){this._client=e}};var D=class extends g{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return x(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",re,{query:e,...t})}},re=class extends E{};D.BetaModelInfosPage=re;var se=class s{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new k;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new c("Attempted to iterate over a response with no body");return new s(le(e.body),t)}};var W=class extends g{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},r){if(x(t))return this.retrieve(e,{},t);let{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}list(e={},t){if(x(e))return this.list({},e);let{betas:r,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",ne,{query:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},r){if(x(t))return this.delete(e,{},t);let{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}cancel(e,t={},r){if(x(t))return this.cancel(e,{},t);let{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}async results(e,t={},r){if(x(t))return this.results(e,{},t);let n=await this.retrieve(e);if(!n.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:i}=t;return this._client.get(n.results_url,{...r,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,a)=>se.fromResponse(a.response,a.controller))}},ne=class extends E{};W.BetaMessageBatchesPage=ne;var jr=s=>{let e=0,t=[];for(;e<s.length;){let r=s[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(r==="["){t.push({type:"paren",value:"["}),e++;continue}if(r==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(r===":"){t.push({type:"separator",value:":"}),e++;continue}if(r===","){t.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let a="",h=!1;for(r=s[++e];r!=='"';){if(e===s.length){h=!0;break}if(r==="\\"){if(e++,e===s.length){h=!0;break}a+=r+s[e],r=s[++e]}else a+=r,r=s[++e]}r=s[++e],h||t.push({type:"string",value:a});continue}if(r&&/\s/.test(r)){e++;continue}let i=/[0-9]/;if(r&&i.test(r)||r==="-"||r==="."){let a="";for(r==="-"&&(a+=r,r=s[++e]);r&&i.test(r)||r===".";)a+=r,r=s[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(r&&o.test(r)){let a="";for(;r&&o.test(r)&&e!==s.length;)a+=r,r=s[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},ie=s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),ie(s);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),ie(s);case"string":let r=s[s.length-2];if(r?.type==="delimiter")return s=s.slice(0,s.length-1),ie(s);if(r?.type==="brace"&&r.value==="{")return s=s.slice(0,s.length-1),ie(s);break;case"delimiter":return s=s.slice(0,s.length-1),ie(s);break}return s},Nr=s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},Ur=s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},ve=s=>JSON.parse(Ur(Nr(ie(jr(s)))));var y=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},u=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},S,v,de,qe,me,pe,Fe,ge,I,ye,je,Ne,oe,Ue,$e,ut,$t,lt,ft,ht,dt,Lt,Dt="__json_buf",Le=class s{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],v.set(this,void 0),this.controller=new AbortController,de.set(this,void 0),qe.set(this,()=>{}),me.set(this,()=>{}),pe.set(this,void 0),Fe.set(this,()=>{}),ge.set(this,()=>{}),I.set(this,{}),ye.set(this,!1),je.set(this,!1),Ne.set(this,!1),oe.set(this,!1),Ue.set(this,void 0),$e.set(this,void 0),lt.set(this,e=>{if(y(this,je,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new p),e instanceof p)return y(this,Ne,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),y(this,de,new Promise((e,t)=>{y(this,qe,e,"f"),y(this,me,t,"f")}),"f"),y(this,pe,new Promise((e,t)=>{y(this,Fe,e,"f"),y(this,ge,t,"f")}),"f"),u(this,de,"f").catch(()=>{}),u(this,pe,"f").catch(()=>{})}get response(){return u(this,Ue,"f")}get request_id(){return u(this,$e,"f")}async withResponse(){let e=await u(this,de,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new s;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new s;for(let i of t.messages)n._addMessageParam(i);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,lt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,S,"m",ft).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)u(this,S,"m",ht).call(this,a);if(o.controller.signal?.aborted)throw new p;u(this,S,"m",dt).call(this)}_connected(e){this.ended||(y(this,Ue,e,"f"),y(this,$e,e?.headers.get("request-id"),"f"),u(this,qe,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,ye,"f")}get errored(){return u(this,je,"f")}get aborted(){return u(this,Ne,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,I,"f")[e]||(u(this,I,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,I,"f")[e];if(!r)return this;let n=r.findIndex(i=>i.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(u(this,I,"f")[e]||(u(this,I,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{y(this,oe,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){y(this,oe,!0,"f"),await u(this,pe,"f")}get currentMessage(){return u(this,v,"f")}async finalMessage(){return await this.done(),u(this,S,"m",ut).call(this)}async finalText(){return await this.done(),u(this,S,"m",$t).call(this)}_emit(e,...t){if(u(this,ye,"f"))return;e==="end"&&(y(this,ye,!0,"f"),u(this,Fe,"f").call(this));let r=u(this,I,"f")[e];if(r&&(u(this,I,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,oe,"f")&&!r?.length&&Promise.reject(n),u(this,me,"f").call(this,n),u(this,ge,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,oe,"f")&&!r?.length&&Promise.reject(n),u(this,me,"f").call(this,n),u(this,ge,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,S,"m",ut).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,S,"m",ft).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let i of n)u(this,S,"m",ht).call(this,i);if(n.controller.signal?.aborted)throw new p;u(this,S,"m",dt).call(this)}[(v=new WeakMap,de=new WeakMap,qe=new WeakMap,me=new WeakMap,pe=new WeakMap,Fe=new WeakMap,ge=new WeakMap,I=new WeakMap,ye=new WeakMap,je=new WeakMap,Ne=new WeakMap,oe=new WeakMap,Ue=new WeakMap,$e=new WeakMap,lt=new WeakMap,S=new WeakSet,ut=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},$t=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},ft=function(){this.ended||y(this,v,void 0,"f")},ht=function(t){if(this.ended)return;let r=u(this,S,"m",Lt).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let n=r.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(r,!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{y(this,v,r,"f");break}case"content_block_start":case"message_delta":break}},dt=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=u(this,v,"f");if(!t)throw new c("request ended without sending any chunks");return y(this,v,void 0,"f"),t},Lt=function(t){let r=u(this,v,"f");if(t.type==="message_start"){if(r)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let n=r.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let i=n[Dt]||"";i+=t.delta.partial_json,Object.defineProperty(n,Dt,{value:i,enumerable:!1,writable:!0}),i&&(n.input=ve(i))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Wt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},q=class extends g{constructor(){super(...arguments),this.batches=new W(this._client)}create(e,t){let{betas:r,...n}=e;return n.model in Wt&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Wt[n.model]}
6
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return Le.createMessage(this,e,t)}countTokens(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};q.Batches=W;q.BetaMessageBatchesPage=ne;var A=class extends g{constructor(){super(...arguments),this.models=new D(this._client),this.messages=new q(this._client)}};A.Models=D;A.BetaModelInfosPage=re;A.Messages=q;var H=class extends g{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var X=class extends g{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return x(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",ae,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((n,i)=>se.fromResponse(i.response,i.controller))}},ae=class extends E{};X.MessageBatchesPage=ae;var w=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},l=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},P,F,we,De,be,_e,We,xe,B,Se,He,Xe,ce,Je,Ke,mt,Ht,pt,gt,yt,wt,Xt,Jt="__json_buf",Ve=class s{constructor(){P.add(this),this.messages=[],this.receivedMessages=[],F.set(this,void 0),this.controller=new AbortController,we.set(this,void 0),De.set(this,()=>{}),be.set(this,()=>{}),_e.set(this,void 0),We.set(this,()=>{}),xe.set(this,()=>{}),B.set(this,{}),Se.set(this,!1),He.set(this,!1),Xe.set(this,!1),ce.set(this,!1),Je.set(this,void 0),Ke.set(this,void 0),pt.set(this,e=>{if(w(this,He,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new p),e instanceof p)return w(this,Xe,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),w(this,we,new Promise((e,t)=>{w(this,De,e,"f"),w(this,be,t,"f")}),"f"),w(this,_e,new Promise((e,t)=>{w(this,We,e,"f"),w(this,xe,t,"f")}),"f"),l(this,we,"f").catch(()=>{}),l(this,_e,"f").catch(()=>{})}get response(){return l(this,Je,"f")}get request_id(){return l(this,Ke,"f")}async withResponse(){let e=await l(this,we,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new s;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new s;for(let i of t.messages)n._addMessageParam(i);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},l(this,pt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,P,"m",gt).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)l(this,P,"m",yt).call(this,a);if(o.controller.signal?.aborted)throw new p;l(this,P,"m",wt).call(this)}_connected(e){this.ended||(w(this,Je,e,"f"),w(this,Ke,e?.headers.get("request-id"),"f"),l(this,De,"f").call(this,e),this._emit("connect"))}get ended(){return l(this,Se,"f")}get errored(){return l(this,He,"f")}get aborted(){return l(this,Xe,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,B,"f")[e]||(l(this,B,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=l(this,B,"f")[e];if(!r)return this;let n=r.findIndex(i=>i.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(l(this,B,"f")[e]||(l(this,B,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,ce,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){w(this,ce,!0,"f"),await l(this,_e,"f")}get currentMessage(){return l(this,F,"f")}async finalMessage(){return await this.done(),l(this,P,"m",mt).call(this)}async finalText(){return await this.done(),l(this,P,"m",Ht).call(this)}_emit(e,...t){if(l(this,Se,"f"))return;e==="end"&&(w(this,Se,!0,"f"),l(this,We,"f").call(this));let r=l(this,B,"f")[e];if(r&&(l(this,B,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!l(this,ce,"f")&&!r?.length&&Promise.reject(n),l(this,be,"f").call(this,n),l(this,xe,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!l(this,ce,"f")&&!r?.length&&Promise.reject(n),l(this,be,"f").call(this,n),l(this,xe,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",l(this,P,"m",mt).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),l(this,P,"m",gt).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let i of n)l(this,P,"m",yt).call(this,i);if(n.controller.signal?.aborted)throw new p;l(this,P,"m",wt).call(this)}[(F=new WeakMap,we=new WeakMap,De=new WeakMap,be=new WeakMap,_e=new WeakMap,We=new WeakMap,xe=new WeakMap,B=new WeakMap,Se=new WeakMap,He=new WeakMap,Xe=new WeakMap,ce=new WeakMap,Je=new WeakMap,Ke=new WeakMap,pt=new WeakMap,P=new WeakSet,mt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ht=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},gt=function(){this.ended||w(this,F,void 0,"f")},yt=function(t){if(this.ended)return;let r=l(this,P,"m",Xt).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let n=r.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(r,!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{w(this,F,r,"f");break}case"content_block_start":case"message_delta":break}},wt=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=l(this,F,"f");if(!t)throw new c("request ended without sending any chunks");return w(this,F,void 0,"f"),t},Xt=function(t){let r=l(this,F,"f");if(t.type==="message_start"){if(r)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let n=r.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let i=n[Jt]||"";i+=t.delta.partial_json,Object.defineProperty(n,Jt,{value:i,enumerable:!1,writable:!0}),i&&(n.input=ve(i))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var T=class extends g{constructor(){super(...arguments),this.batches=new X(this._client)}create(e,t){return e.model in Kt&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Kt[e.model]}
7
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return Ve.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Kt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};T.Batches=X;T.MessageBatchesPage=ae;var j=class extends g{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return x(e)?this.list({},e):this._client.getAPIList("/v1/models",J,{query:e,...t})}},J=class extends E{};j.ModelInfosPage=J;var Vt,f=class extends Te{constructor({baseURL:e=Oe("ANTHROPIC_BASE_URL"),apiKey:t=Oe("ANTHROPIC_API_KEY")??null,authToken:r=Oe("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){let i={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&Ut())throw new c(`It looks like you're running in a browser-like environment.
8
+
9
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
+ If you understand the risks and have appropriate mitigations in place,
11
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
+
13
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
14
+ `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new H(this),this.messages=new T(this),this.models=new j(this),this.beta=new A(this),this._options=i,this.apiKey=t,this.authToken=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"])&&t["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&t.authorization!==null)throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){let t=this.apiKeyAuth(e),r=this.bearerAuth(e);return t!=null&&!he(t)?t:r!=null&&!he(r)?r:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};Vt=f;f.Anthropic=Vt;f.HUMAN_PROMPT=`
15
+
16
+ Human:`;f.AI_PROMPT=`
17
+
18
+ Assistant:`;f.DEFAULT_TIMEOUT=6e5;f.AnthropicError=c;f.APIError=m;f.APIConnectionError=R;f.APIConnectionTimeoutError=$;f.APIUserAbortError=p;f.NotFoundError=z;f.ConflictError=Q;f.RateLimitError=Z;f.BadRequestError=K;f.AuthenticationError=V;f.InternalServerError=ee;f.PermissionDeniedError=G;f.UnprocessableEntityError=Y;f.toFile=it;f.fileFromPath=ue;f.Completions=H;f.Messages=T;f.Models=j;f.ModelInfosPage=J;f.Beta=A;var{HUMAN_PROMPT:Pn,AI_PROMPT:Mn}=f,En=f;export{Mn as AI_PROMPT,R as APIConnectionError,$ as APIConnectionTimeoutError,m as APIError,p as APIUserAbortError,f as Anthropic,c as AnthropicError,V as AuthenticationError,K as BadRequestError,Q as ConflictError,Pn as HUMAN_PROMPT,ee as InternalServerError,z as NotFoundError,G as PermissionDeniedError,Z as RateLimitError,Y as UnprocessableEntityError,En as default,ue as fileFromPath,it as toFile};
@@ -0,0 +1,3 @@
1
+ import{f as l,h as a,k as i}from"./chunk-FGDJVQG3.js";import{j as n}from"./chunk-PLJNPQFC.js";import"./chunk-ZOZYBQX2.js";import{a as o}from"./chunk-WE7PSSAQ.js";import"./chunk-HPPFA3XU.js";import{a as t}from"./chunk-DQAEQEXD.js";import"./chunk-GRTR6TNJ.js";import"./chunk-Z7742D7Q.js";import"./chunk-VTQ72OK7.js";import"./chunk-QXTK62N4.js";import"./chunk-DXB73IDG.js";var v=["trace","debug","info","warn","error","fatal"],P=async m=>{let{flags:e}=o(m??[],[{name:"port",short:"p",type:"number",default:8e3,description:"Server port"},{name:"log-level",type:"string",default:"info",description:"Log level"}]),r=l({renderer:i.ansi(),sink:a.stdout()});r.writeln(n(`
2
+ \u{1F680} Serving production build...
3
+ `));let p=e.port,s=e["log-level"]??"info",u=v.includes(s.toLowerCase())?s.toLowerCase():"info",[{startServer:g},{reactRenderer:c,reactHtmlShellBuilder:d},{reactPlugin:L},{createTailwindPlugin:f}]=await Promise.all([import("./main-WVXCURBF.js"),import("./mod-MKMQWZ6G.js"),import("./mod-CI56JMO4.js"),import("./mod-JTBNNSZZ.js")]);return await r.close(),await g({mode:"serve",port:p,logLevel:u,hmr:!1,renderer:c,htmlShell:d,frameworkPlugin:L,cssPlugin:f({globalCssPath:"src/app/styles/global.css"})}),t(void 0)};export{P as main};