@shumai-one/shumai 0.4.3 → 0.4.4

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 (168) hide show
  1. package/bin/chunk-071x515q.js +4 -0
  2. package/bin/chunk-0cmx7k4c.js +1 -0
  3. package/bin/{chunk-cqb415s6.js → chunk-0qaq0sp8.js} +2 -2
  4. package/bin/chunk-0qjfahk9.js +2 -0
  5. package/bin/{chunk-9t1ne8xr.js → chunk-0zv3bks2.js} +2 -2
  6. package/bin/chunk-16xax8kk.js +1 -0
  7. package/bin/chunk-1gvscz88.js +5 -0
  8. package/bin/{chunk-6gg1ymer.js → chunk-1j27fzy1.js} +2 -2
  9. package/bin/chunk-1t167cvj.js +11 -0
  10. package/bin/{chunk-pb1zf0vb.js → chunk-1xh34aew.js} +2 -2
  11. package/bin/{chunk-zmv8cg4s.js → chunk-1zwajpwf.js} +3 -3
  12. package/bin/chunk-2w5xqhjm.js +1 -0
  13. package/bin/{chunk-f3ehv01n.js → chunk-3tedzb2j.js} +26 -26
  14. package/bin/{chunk-zehyn6vd.js → chunk-3ttrhqy3.js} +2 -2
  15. package/bin/chunk-3zkasqb8.js +1 -0
  16. package/bin/chunk-453ykvaw.js +2 -0
  17. package/bin/{chunk-3cyrcgm5.js → chunk-4991gz3y.js} +9 -9
  18. package/bin/chunk-4hkkdm2q.js +2 -0
  19. package/bin/chunk-4mjywsj8.js +3 -0
  20. package/bin/{chunk-cnxwmycy.js → chunk-4v41a1r9.js} +3 -3
  21. package/bin/{chunk-87zxtf66.js → chunk-4wy87hwd.js} +2 -2
  22. package/bin/{chunk-sfx2588q.js → chunk-579e4wv4.js} +2 -2
  23. package/bin/{chunk-1yacmegc.js → chunk-5adsx8x4.js} +2 -2
  24. package/bin/{chunk-b235azv4.js → chunk-5hg6kcfz.js} +13 -13
  25. package/bin/{chunk-rbj4fad9.js → chunk-5nm2jvg5.js} +13 -13
  26. package/bin/chunk-5tcdwep5.js +11 -0
  27. package/bin/chunk-5vzrpz50.js +2 -0
  28. package/bin/chunk-6ghcj4a9.js +3 -0
  29. package/bin/{chunk-b9yrw9et.js → chunk-77fmkpdz.js} +4 -4
  30. package/bin/chunk-7bcxj1jd.js +2 -0
  31. package/bin/{chunk-qf24e71w.js → chunk-7gmdnsdg.js} +1 -1
  32. package/bin/{chunk-fxswt9hc.js → chunk-7jtmwt5a.js} +2 -2
  33. package/bin/chunk-7kjgvxqa.js +2 -0
  34. package/bin/{chunk-bay038pj.js → chunk-7pw1550a.js} +2 -2
  35. package/bin/chunk-7rhz2gze.js +211 -0
  36. package/bin/chunk-837fky18.js +3 -0
  37. package/bin/chunk-84as6x83.js +1 -0
  38. package/bin/chunk-8e28hcny.js +2 -0
  39. package/bin/{chunk-k7hss0bd.js → chunk-914bp49r.js} +3 -3
  40. package/bin/chunk-97f2af6d.js +12 -0
  41. package/bin/{chunk-4r81ghg8.js → chunk-98715kc3.js} +2 -2
  42. package/bin/chunk-9ccw540k.js +2 -0
  43. package/bin/{chunk-ag6p3mbf.js → chunk-9t8n2des.js} +2 -2
  44. package/bin/chunk-9ybt6vbm.js +1 -0
  45. package/bin/{chunk-f15qyp41.js → chunk-a6gx7f5q.js} +1 -1
  46. package/bin/chunk-avwgktxb.js +2 -0
  47. package/bin/chunk-bkr5zm4h.js +2 -0
  48. package/bin/{chunk-2yxj593j.js → chunk-cbgq517y.js} +2 -2
  49. package/bin/chunk-d27mm390.js +1 -0
  50. package/bin/{chunk-185qefn1.js → chunk-dj92fss9.js} +2 -2
  51. package/bin/{chunk-v9w25rp2.js → chunk-dqxeztfa.js} +2 -2
  52. package/bin/chunk-drepsbb4.js +2 -0
  53. package/bin/chunk-f6svp4dp.js +2 -0
  54. package/bin/{chunk-q2bvyv39.js → chunk-fahk9h62.js} +2 -2
  55. package/bin/{chunk-v9b3w8q5.js → chunk-fb40xxz3.js} +2 -2
  56. package/bin/chunk-fnmwksnb.js +3 -0
  57. package/bin/chunk-fpc4p0j8.js +3 -0
  58. package/bin/{chunk-aqbrzx9z.js → chunk-fsyzs0tf.js} +1 -1
  59. package/bin/{chunk-e2mvmq2m.js → chunk-fxecgp5k.js} +1 -1
  60. package/bin/{chunk-wfzqnpc1.js → chunk-g3fpmyyn.js} +2 -2
  61. package/bin/{chunk-ehc9adfz.js → chunk-gc5sbfa5.js} +2 -2
  62. package/bin/chunk-gdm6yfqq.js +2 -0
  63. package/bin/{chunk-ea79xnn3.js → chunk-gk2q9a3f.js} +2 -2
  64. package/bin/{chunk-jje8nj8h.js → chunk-gt4csat6.js} +2 -2
  65. package/bin/chunk-gye8gabk.js +2 -0
  66. package/bin/{chunk-wry2hvrq.js → chunk-hk5rc6cd.js} +2 -2
  67. package/bin/{chunk-zqv0zhfb.js → chunk-hm0dkzed.js} +2 -2
  68. package/bin/chunk-hmpwg5za.js +16 -0
  69. package/bin/{chunk-rpywcvg1.js → chunk-j1tkmcae.js} +2 -2
  70. package/bin/chunk-j2bvj2yn.js +2 -0
  71. package/bin/chunk-jffktpqg.js +1 -0
  72. package/bin/chunk-jgs8an3h.js +18 -0
  73. package/bin/{chunk-8fmy5jtp.js → chunk-jmpb5633.js} +1 -1
  74. package/bin/{chunk-xp59apdb.js → chunk-jrjnqx78.js} +1 -1
  75. package/bin/chunk-k2k9vjq6.js +1 -0
  76. package/bin/{chunk-32pcmaqm.js → chunk-kpgfqkp0.js} +2 -2
  77. package/bin/{chunk-twdxayky.js → chunk-ks8xzc95.js} +2 -2
  78. package/bin/{chunk-qwqvt9v6.js → chunk-kswvyqq1.js} +2 -2
  79. package/bin/{chunk-gk3eqd50.js → chunk-m9pr03kn.js} +2 -2
  80. package/bin/chunk-mfn9qjm4.js +2 -0
  81. package/bin/{chunk-e99dv20z.js → chunk-msfw3jmc.js} +2 -2
  82. package/bin/chunk-mz0yjra0.js +5 -0
  83. package/bin/chunk-nbdw8fen.js +1 -0
  84. package/bin/{chunk-cak32x57.js → chunk-nkdk229f.js} +1 -1
  85. package/bin/chunk-nr20tvnw.js +3 -0
  86. package/bin/{chunk-ck8azecb.js → chunk-pazjhrnf.js} +5 -5
  87. package/bin/chunk-q806pqeh.js +1 -0
  88. package/bin/{chunk-abt0azmv.js → chunk-qka4mkmj.js} +2 -2
  89. package/bin/{chunk-0e4wawpq.js → chunk-qsr1a0rp.js} +1 -1
  90. package/bin/chunk-rchsme43.js +3 -0
  91. package/bin/{chunk-tf28796q.js → chunk-reyxk4bw.js} +1 -1
  92. package/bin/{chunk-av1a8fqp.js → chunk-rhvv1vvk.js} +2 -2
  93. package/bin/{chunk-a32vreya.js → chunk-rq0n0vcc.js} +2 -2
  94. package/bin/chunk-rqf7999q.js +42 -0
  95. package/bin/chunk-rssgmj7x.js +2 -0
  96. package/bin/chunk-ryzz5fht.js +2 -0
  97. package/bin/chunk-s2fnfyn9.js +2 -0
  98. package/bin/{chunk-83e12sjg.js → chunk-s2k4qntr.js} +2 -2
  99. package/bin/{chunk-c007p0t8.js → chunk-snhsjs4x.js} +56 -56
  100. package/bin/{chunk-j8fxp8ej.js → chunk-t2hy6tj9.js} +1 -1
  101. package/bin/chunk-t7nsgg5k.js +4 -0
  102. package/bin/chunk-tm7f32c7.js +14 -0
  103. package/bin/{chunk-2291ehh5.js → chunk-trveq4wg.js} +2 -2
  104. package/bin/chunk-vap4k11j.js +20 -0
  105. package/bin/chunk-vm5fx7td.js +3 -0
  106. package/bin/chunk-vy8gntez.js +1 -0
  107. package/bin/{chunk-awfwk64v.js → chunk-vyzptrea.js} +2 -2
  108. package/bin/{chunk-hfh0c082.js → chunk-w4ghe71n.js} +1 -1
  109. package/bin/chunk-wdsf44hs.js +2 -0
  110. package/bin/chunk-wjyaezs7.js +2 -0
  111. package/bin/{chunk-3a13dcs1.js → chunk-wndm3px3.js} +1 -1
  112. package/bin/chunk-x5jwwvs0.js +1 -0
  113. package/bin/chunk-x92cq59c.js +1 -0
  114. package/bin/{chunk-vgn5zcpv.js → chunk-xa18z1py.js} +2 -2
  115. package/bin/{chunk-4v5n0ayb.js → chunk-xarsrs08.js} +1 -1
  116. package/bin/{chunk-66hsjnw6.js → chunk-xx337zcw.js} +2 -2
  117. package/bin/chunk-xz6713tj.js +2 -0
  118. package/bin/chunk-yfnem6se.js +2 -0
  119. package/bin/{chunk-m7m9d4fb.js → chunk-ytdwk2fq.js} +2 -2
  120. package/bin/{chunk-jy006gcv.js → chunk-ze20rm02.js} +4 -4
  121. package/bin/chunk-zw86wnwe.js +7 -0
  122. package/bin/{chunk-h3tbf521.js → chunk-zxk7q0zk.js} +1 -1
  123. package/bin/shumai-app.html +1 -1
  124. package/bin/shumai-app.js +773 -776
  125. package/package.json +7 -7
  126. package/prisma/migrations/20260907021754_add_asset_upload_id/migration.sql +2 -0
  127. package/prisma/schema.prisma +1 -0
  128. package/bin/chunk-1kw2mbqb.js +0 -1
  129. package/bin/chunk-1wm6ptdx.js +0 -1
  130. package/bin/chunk-2520aq8j.js +0 -2
  131. package/bin/chunk-29zdp63z.js +0 -3
  132. package/bin/chunk-3swpwb9v.js +0 -1
  133. package/bin/chunk-3wmcx2bv.js +0 -2
  134. package/bin/chunk-5a8nt4me.js +0 -1
  135. package/bin/chunk-6bhn1p8v.js +0 -211
  136. package/bin/chunk-70c3xrgd.js +0 -2
  137. package/bin/chunk-7esm0hqb.js +0 -2
  138. package/bin/chunk-7fst8kdw.js +0 -12
  139. package/bin/chunk-8zqgaxvv.js +0 -1
  140. package/bin/chunk-a3dmtt2j.js +0 -1
  141. package/bin/chunk-ce8m4zeg.js +0 -3
  142. package/bin/chunk-e7mqtkzn.js +0 -2
  143. package/bin/chunk-ejbvfj4r.js +0 -1
  144. package/bin/chunk-ekfem7kf.js +0 -1
  145. package/bin/chunk-etwkk0xh.js +0 -1
  146. package/bin/chunk-evrdd32b.js +0 -2
  147. package/bin/chunk-fm6p03ad.js +0 -2
  148. package/bin/chunk-fyha3r13.js +0 -2
  149. package/bin/chunk-g0vs7k2x.js +0 -1
  150. package/bin/chunk-g84z2w7v.js +0 -16
  151. package/bin/chunk-h837fyed.js +0 -2
  152. package/bin/chunk-j20e0qsw.js +0 -7
  153. package/bin/chunk-n1jwdb0a.js +0 -1
  154. package/bin/chunk-p5gf1zdm.js +0 -4
  155. package/bin/chunk-pfgxggaj.js +0 -11
  156. package/bin/chunk-q16490pv.js +0 -2
  157. package/bin/chunk-qh81zhg1.js +0 -1
  158. package/bin/chunk-qwp3kwbz.js +0 -2
  159. package/bin/chunk-qydeqgyj.js +0 -5
  160. package/bin/chunk-r7dty1tg.js +0 -2
  161. package/bin/chunk-rhdxwebf.js +0 -2
  162. package/bin/chunk-rhh716z0.js +0 -42
  163. package/bin/chunk-rza4ae5z.js +0 -3
  164. package/bin/chunk-sk4e6rb1.js +0 -1
  165. package/bin/chunk-t2n1dbgx.js +0 -4
  166. package/bin/chunk-x8f4defx.js +0 -3
  167. package/bin/chunk-z3gkt8w1.js +0 -3
  168. package/bin/chunk-zh6fqq44.js +0 -1
@@ -1,13 +1,13 @@
1
1
  // @bun
2
- import{zd,Qr}from"./chunk-qydeqgyj.js";import{nr}from"./chunk-sfx2588q.js";import{vs}from"./chunk-vgn5zcpv.js";import{ws,xs}from"./chunk-twdxayky.js";import{$o}from"./chunk-jje8nj8h.js";import{Fe,oo,Fd,xr,Bp,ao}from"./chunk-zqv0zhfb.js";import{Xr}from"./chunk-29zdp63z.js";import{en}from"./chunk-2291ehh5.js";import{Vt}from"./chunk-x8f4defx.js";function f(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function a(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Jt=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Jt=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function U(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var ye=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class k extends m{constructor(e,t,r,s,n){super(`${k.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("request-id"),this.error=t,this.type=n??null}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Y({message:r,cause:ye(t)});let n=t,o=n?.error?.type;if(e===400)return new xe(e,n,r,s,o);if(e===401)return new Se(e,n,r,s,o);if(e===403)return new ke(e,n,r,s,o);if(e===404)return new Pe(e,n,r,s,o);if(e===409)return new Re(e,n,r,s,o);if(e===422)return new ve(e,n,r,s,o);if(e===429)return new Ee(e,n,r,s,o);if(e>=500)return new Me(e,n,r,s,o);return new k(e,n,r,s,o)}}class E extends k{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Y extends k{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class we extends Y{constructor({message:e}={}){super({message:e??"Request timed out."})}}class xe extends k{}class Se extends k{}class ke extends k{}class Pe extends k{}class Re extends k{}class ve extends k{}class Ee extends k{}class Me extends k{}var Os=/^[a-z][a-z0-9+.-]*:/i,Ir=(e)=>Os.test(e),Xt=(e)=>(Xt=Array.isArray,Xt(e)),Kt=Xt;function mt(e){if(typeof e!=="object")return{};return e??{}}function Gt(e){if(!e)return!0;for(let t in e)return!1;return!0}function $r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Cr=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var gt=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Or=(e)=>new Promise((t)=>setTimeout(t,e));var V="0.91.1";var qr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Ns(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Ls=()=>{let e=Ns();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":Lr(Deno.build.os),"X-Stainless-Arch":Nr(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":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":Lr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Fs();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Fs(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,c=s[3]||0;return{browser:t,version:`${n}.${o}.${c}`}}}return null}var Nr=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Lr=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Fr,Br=()=>Fr??(Fr=Ls());function jr(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function zt(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function _t(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return zt({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Te(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ur(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var Hr=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});function Wr(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 m(`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("&")}function Vr(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var Dr;function Ae(e){let t;return(Dr??(t=new globalThis.TextEncoder,Dr=t.encode.bind(t)))(e)}var Jr;function Qt(e){let t;return(Jr??(t=new globalThis.TextDecoder,Jr=t.decode.bind(t)))(e)}var A,I;class X{constructor(){A.set(this,void 0),I.set(this,void 0),f(this,A,new Uint8Array,"f"),f(this,I,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ae(e):e;f(this,A,Vr([a(this,A,"f"),t]),"f");let r=[],s;while((s=js(a(this,A,"f"),a(this,I,"f")))!=null){if(s.carriage&&a(this,I,"f")==null){f(this,I,s.index,"f");continue}if(a(this,I,"f")!=null&&(s.index!==a(this,I,"f")+1||s.carriage)){r.push(Qt(a(this,A,"f").subarray(0,a(this,I,"f")-1))),f(this,A,a(this,A,"f").subarray(a(this,I,"f")),"f"),f(this,I,null,"f");continue}let n=a(this,I,"f")!==null?s.preceding-1:s.preceding,o=Qt(a(this,A,"f").subarray(0,n));r.push(o),f(this,A,a(this,A,"f").subarray(s.index),"f"),f(this,I,null,"f")}return r}flush(){if(!a(this,A,"f").length)return[];return this.decode(`
2
+ import{Wd,Wr}from"./chunk-mz0yjra0.js";import{ar}from"./chunk-579e4wv4.js";import{Ra}from"./chunk-xa18z1py.js";import{ka,Pa}from"./chunk-ks8xzc95.js";import{ts}from"./chunk-gt4csat6.js";import{je,io,Kd,Cr,Xp,lo}from"./chunk-hm0dkzed.js";import{on}from"./chunk-rchsme43.js";import{sn}from"./chunk-trveq4wg.js";import{Yt}from"./chunk-nr20tvnw.js";function f(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function a(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Jt=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Jt=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function U(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var ye=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class k extends m{constructor(e,t,r,s,n){super(`${k.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("request-id"),this.error=t,this.type=n??null}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Y({message:r,cause:ye(t)});let n=t,o=n?.error?.type;if(e===400)return new xe(e,n,r,s,o);if(e===401)return new Se(e,n,r,s,o);if(e===403)return new ke(e,n,r,s,o);if(e===404)return new Pe(e,n,r,s,o);if(e===409)return new Re(e,n,r,s,o);if(e===422)return new ve(e,n,r,s,o);if(e===429)return new Ee(e,n,r,s,o);if(e>=500)return new Me(e,n,r,s,o);return new k(e,n,r,s,o)}}class E extends k{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Y extends k{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class we extends Y{constructor({message:e}={}){super({message:e??"Request timed out."})}}class xe extends k{}class Se extends k{}class ke extends k{}class Pe extends k{}class Re extends k{}class ve extends k{}class Ee extends k{}class Me extends k{}var Is=/^[a-z][a-z0-9+.-]*:/i,Ar=(e)=>Is.test(e),Vt=(e)=>(Vt=Array.isArray,Vt(e)),Xt=Vt;function mt(e){if(typeof e!=="object")return{};return e??{}}function Kt(e){if(!e)return!0;for(let t in e)return!1;return!0}function Ir(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var $r=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var gt=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Or=(e)=>new Promise((t)=>setTimeout(t,e));var V="0.91.1";var qr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function $s(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Cs=()=>{let e=$s();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":Lr(Deno.build.os),"X-Stainless-Arch":Nr(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":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":Lr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Os();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Os(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,c=s[3]||0;return{browser:t,version:`${n}.${o}.${c}`}}}return null}var Nr=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Lr=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Fr,Br=()=>Fr??(Fr=Cs());function jr(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Gt(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function _t(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Gt({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Te(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ur(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var Hr=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});function Dr(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 m(`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("&")}function Xr(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var Jr;function Ae(e){let t;return(Jr??(t=new globalThis.TextEncoder,Jr=t.encode.bind(t)))(e)}var Vr;function zt(e){let t;return(Vr??(t=new globalThis.TextDecoder,Vr=t.decode.bind(t)))(e)}var A,I;class X{constructor(){A.set(this,void 0),I.set(this,void 0),f(this,A,new Uint8Array,"f"),f(this,I,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ae(e):e;f(this,A,Xr([a(this,A,"f"),t]),"f");let r=[],s;while((s=Fs(a(this,A,"f"),a(this,I,"f")))!=null){if(s.carriage&&a(this,I,"f")==null){f(this,I,s.index,"f");continue}if(a(this,I,"f")!=null&&(s.index!==a(this,I,"f")+1||s.carriage)){r.push(zt(a(this,A,"f").subarray(0,a(this,I,"f")-1))),f(this,A,a(this,A,"f").subarray(a(this,I,"f")),"f"),f(this,I,null,"f");continue}let n=a(this,I,"f")!==null?s.preceding-1:s.preceding,o=zt(a(this,A,"f").subarray(0,n));r.push(o),f(this,A,a(this,A,"f").subarray(s.index),"f"),f(this,I,null,"f")}return r}flush(){if(!a(this,A,"f").length)return[];return this.decode(`
3
3
  `)}}A=new WeakMap,I=new WeakMap;X.NEWLINE_CHARS=new Set([`
4
- `,"\r"]);X.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function js(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Kr(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var yt={off:0,error:200,warn:300,info:400,debug:500},Yt=(e,t,r)=>{if(!e)return;if($r(yt,e))return e;R(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(yt))}`);return};function Ie(){}function bt(e,t,r){if(!t||yt[e]>yt[r])return Ie;else return t[e].bind(t)}var Us={error:Ie,warn:Ie,info:Ie,debug:Ie},Gr=new WeakMap;function R(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Us;let s=Gr.get(t);if(s&&s[0]===r)return s[1];let n={error:bt("error",t,r),warn:bt("warn",t,r),info:bt("info",t,r),debug:bt("debug",t,r)};return Gr.set(t,[r,n]),n}var H=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="x-api-key"||t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var $e;class C{constructor(e,t,r){this.iterator=e,$e.set(this,void 0),this.controller=t,f(this,$e,r,"f")}static fromSSEResponse(e,t,r){let s=!1,n=r?R(r):console;async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let i of Hs(e,t)){if(i.event==="completion")try{yield JSON.parse(i.data)}catch(h){throw n.error("Could not parse message into JSON:",i.data),n.error("From chunk:",i.raw),h}if(i.event==="message_start"||i.event==="message_delta"||i.event==="message_stop"||i.event==="content_block_start"||i.event==="content_block_delta"||i.event==="content_block_stop"||i.event==="message"||i.event==="user.message"||i.event==="user.interrupt"||i.event==="user.tool_confirmation"||i.event==="user.custom_tool_result"||i.event==="agent.message"||i.event==="agent.thinking"||i.event==="agent.tool_use"||i.event==="agent.tool_result"||i.event==="agent.mcp_tool_use"||i.event==="agent.mcp_tool_result"||i.event==="agent.custom_tool_use"||i.event==="agent.thread_context_compacted"||i.event==="session.status_running"||i.event==="session.status_idle"||i.event==="session.status_rescheduled"||i.event==="session.status_terminated"||i.event==="session.error"||i.event==="session.deleted"||i.event==="span.model_request_start"||i.event==="span.model_request_end")try{yield JSON.parse(i.data)}catch(h){throw n.error("Could not parse message into JSON:",i.data),n.error("From chunk:",i.raw),h}if(i.event==="ping")continue;if(i.event==="error"){let h=gt(i.data)??i.data,b=h?.error?.type;throw new k(void 0,h,void 0,e.headers,b)}}c=!0}catch(i){if(U(i))return;throw i}finally{if(!c)t.abort()}}return new C(o,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let c=new X,i=Te(e);for await(let h of i)for(let b of c.decode(h))yield b;for(let h of c.flush())yield h}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let i of n()){if(c)continue;if(i)yield JSON.parse(i)}c=!0}catch(i){if(U(i))return;throw i}finally{if(!c)t.abort()}}return new C(o,t,r)}[($e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new C(()=>s(e),this.controller,a(this,$e,"f")),new C(()=>s(t),this.controller,a(this,$e,"f"))]}toReadableStream(){let e=this,t;return zt({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=Ae(JSON.stringify(s)+`
5
- `);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Hs(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new zr,s=new X,n=Te(e.body);for await(let o of Ws(n))for(let c of s.decode(o)){let i=r.decode(c);if(i)yield i}for(let o of s.flush()){let c=r.decode(o);if(c)yield c}}async function*Ws(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?Ae(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Kr(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class zr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
6
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Ds(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function Ds(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function wt(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,c=await(async()=>{if(t.options.stream){if(R(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller);return C.fromSSEResponse(r,t.controller)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let h=r.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let l=await r.json();return Zt(l,r)}return await r.text()})();return R(e).debug(`[${s}] response parsed`,H({retryOfRequestLogID:n,url:r.url,status:r.status,body:c,durationMs:Date.now()-o})),c}function Zt(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}var Ce;class Z extends Promise{constructor(e,t,r=wt){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Ce.set(this,void 0),f(this,Ce,e,"f")}_thenUnwrap(e){return new Z(a(this,Ce,"f"),this.responsePromise,async(t,r)=>Zt(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(a(this,Ce,"f"),e));return 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)}}Ce=new WeakMap;var xt;class er{constructor(e,t,r,s){xt.set(this,void 0),f(this,xt,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,xt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(xt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class St extends Z{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await wt(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class B extends er{constructor(e,t,r,s){super(e,t,r,s);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(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let t=this.first_id;if(!t)return null;return{...this.options,query:{...mt(this.options.query),before_id:t}}}let e=this.last_id;if(!e)return null;return{...this.options,query:{...mt(this.options.query),after_id:e}}}}class x extends er{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;if(!e)return null;return{...this.options,query:{...mt(this.options.query),page:e}}}}var rr=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ee(e,t,r){return rr(),new File(e,t??"unknown_file",r)}function Oe(e,t){let r=typeof e==="object"&&e!==null&&(("name"in e)&&e.name&&String(e.name)||("url"in e)&&e.url&&String(e.url)||("filename"in e)&&e.filename&&String(e.filename)||("path"in e)&&e.path&&String(e.path))||"";return t?r.split(/[\\/]/).pop()||void 0:r}var sr=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function";var ie=async(e,t,r=!0)=>({...e,body:await Xs(e.body,t,r)}),Yr=new WeakMap;function Vs(e){let t=typeof e==="function"?e:e.fetch,r=Yr.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return Yr.set(t,s),s}var Xs=async(e,t,r=!0)=>{if(!await Vs(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let s=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,o])=>tr(s,n,o,r))),s},Ks=(e)=>e instanceof Blob&&("name"in e);var tr=async(e,t,r,s)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response){let n={},o=r.headers.get("Content-Type");if(o)n={type:o};e.append(t,ee([await r.blob()],Oe(r,s),n))}else if(sr(r))e.append(t,ee([await new Response(_t(r)).blob()],Oe(r,s)));else if(Ks(r))e.append(t,ee([r],Oe(r,s),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map((n)=>tr(e,t+"[]",n,s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([n,o])=>tr(e,`${t}[${n}]`,o,s)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var Zr=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",Gs=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&Zr(e),zs=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function kt(e,t,r){if(rr(),e=await e,t||(t=Oe(e,!0)),Gs(e)){if(e instanceof File&&t==null&&r==null)return e;return ee([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...r})}if(zs(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),ee(await or(n),t,r)}let s=await or(e);if(!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return ee(s,t,r)}async function or(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Zr(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(sr(e))for await(let r of e)t.push(...await or(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Qs(e)}`)}return t}function Qs(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class y{constructor(e){this._client=e}}var es=Symbol.for("brand.privateNullableHeaders");function*Zs(e){if(!e)return;if(es in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Kt(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Kt(s[1])?s[1]:[s[1]],c=!1;for(let i of o){if(i===void 0)continue;if(t&&!c)c=!0,yield[n,null];yield[n,i]}}}var u=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,c]of Zs(s)){let i=o.toLowerCase();if(!n.has(i))t.delete(o),n.add(i);if(c===null)t.delete(o),r.add(i);else t.append(o,c),r.delete(i)}}return{[es]:!0,values:t,nulls:r}};function rs(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ts=Object.freeze(Object.create(null)),tn=(e=rs)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],c=r.reduce((g,_,l)=>{if(/[?#]/.test(_))n=!0;let p=s[l],w=(n?encodeURIComponent:e)(""+p);if(l!==s.length&&(p==null||typeof p==="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??ts)??ts)?.toString))w=p+"",o.push({start:g.length+_.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`});return g+_+(l===s.length?"":w)},""),i=c.split(/[?#]/,1)[0],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,b;while((b=h.exec(i))!==null)o.push({start:b.index,length:b[0].length,error:`Value "${b[0]}" can't be safely passed as a path parameter`});if(o.sort((g,_)=>g.start-_.start),o.length>0){let g=0,_=o.reduce((l,p)=>{let w=" ".repeat(p.start-g),v="^".repeat(p.length);return g=p.start+p.length,l+w+v},"");throw new m(`Path parameters result in path with invalid segments:
4
+ `,"\r"]);X.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Fs(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Kr(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var yt={off:0,error:200,warn:300,info:400,debug:500},Qt=(e,t,r)=>{if(!e)return;if(Ir(yt,e))return e;R(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(yt))}`);return};function Ie(){}function bt(e,t,r){if(!t||yt[e]>yt[r])return Ie;else return t[e].bind(t)}var qs={error:Ie,warn:Ie,info:Ie,debug:Ie},Gr=new WeakMap;function R(e){let t=e.logger,r=e.logLevel??"off";if(!t)return qs;let s=Gr.get(t);if(s&&s[0]===r)return s[1];let n={error:bt("error",t,r),warn:bt("warn",t,r),info:bt("info",t,r),debug:bt("debug",t,r)};return Gr.set(t,[r,n]),n}var H=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="x-api-key"||t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var $e;class C{constructor(e,t,r){this.iterator=e,$e.set(this,void 0),this.controller=t,f(this,$e,r,"f")}static fromSSEResponse(e,t,r){let s=!1,n=r?R(r):console;async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let i of Bs(e,t)){if(i.event==="completion")try{yield JSON.parse(i.data)}catch(h){throw n.error("Could not parse message into JSON:",i.data),n.error("From chunk:",i.raw),h}if(i.event==="message_start"||i.event==="message_delta"||i.event==="message_stop"||i.event==="content_block_start"||i.event==="content_block_delta"||i.event==="content_block_stop"||i.event==="message"||i.event==="user.message"||i.event==="user.interrupt"||i.event==="user.tool_confirmation"||i.event==="user.custom_tool_result"||i.event==="agent.message"||i.event==="agent.thinking"||i.event==="agent.tool_use"||i.event==="agent.tool_result"||i.event==="agent.mcp_tool_use"||i.event==="agent.mcp_tool_result"||i.event==="agent.custom_tool_use"||i.event==="agent.thread_context_compacted"||i.event==="session.status_running"||i.event==="session.status_idle"||i.event==="session.status_rescheduled"||i.event==="session.status_terminated"||i.event==="session.error"||i.event==="session.deleted"||i.event==="span.model_request_start"||i.event==="span.model_request_end")try{yield JSON.parse(i.data)}catch(h){throw n.error("Could not parse message into JSON:",i.data),n.error("From chunk:",i.raw),h}if(i.event==="ping")continue;if(i.event==="error"){let h=gt(i.data)??i.data,b=h?.error?.type;throw new k(void 0,h,void 0,e.headers,b)}}c=!0}catch(i){if(U(i))return;throw i}finally{if(!c)t.abort()}}return new C(o,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let c=new X,i=Te(e);for await(let h of i)for(let b of c.decode(h))yield b;for(let h of c.flush())yield h}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let i of n()){if(c)continue;if(i)yield JSON.parse(i)}c=!0}catch(i){if(U(i))return;throw i}finally{if(!c)t.abort()}}return new C(o,t,r)}[($e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new C(()=>s(e),this.controller,a(this,$e,"f")),new C(()=>s(t),this.controller,a(this,$e,"f"))]}toReadableStream(){let e=this,t;return Gt({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=Ae(JSON.stringify(s)+`
5
+ `);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Bs(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new zr,s=new X,n=Te(e.body);for await(let o of js(n))for(let c of s.decode(o)){let i=r.decode(c);if(i)yield i}for(let o of s.flush()){let c=r.decode(o);if(c)yield c}}async function*js(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?Ae(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Kr(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class zr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
6
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Us(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function Us(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function wt(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,c=await(async()=>{if(t.options.stream){if(R(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller);return C.fromSSEResponse(r,t.controller)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let h=r.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let l=await r.json();return Zt(l,r)}return await r.text()})();return R(e).debug(`[${s}] response parsed`,H({retryOfRequestLogID:n,url:r.url,status:r.status,body:c,durationMs:Date.now()-o})),c}function Zt(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}var Ce;class Z extends Promise{constructor(e,t,r=wt){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Ce.set(this,void 0),f(this,Ce,e,"f")}_thenUnwrap(e){return new Z(a(this,Ce,"f"),this.responsePromise,async(t,r)=>Zt(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(a(this,Ce,"f"),e));return 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)}}Ce=new WeakMap;var xt;class er{constructor(e,t,r,s){xt.set(this,void 0),f(this,xt,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,xt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(xt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class St extends Z{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await wt(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class B extends er{constructor(e,t,r,s){super(e,t,r,s);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(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let t=this.first_id;if(!t)return null;return{...this.options,query:{...mt(this.options.query),before_id:t}}}let e=this.last_id;if(!e)return null;return{...this.options,query:{...mt(this.options.query),after_id:e}}}}class x extends er{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;if(!e)return null;return{...this.options,query:{...mt(this.options.query),page:e}}}}var rr=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ee(e,t,r){return rr(),new File(e,t??"unknown_file",r)}function Oe(e,t){let r=typeof e==="object"&&e!==null&&(("name"in e)&&e.name&&String(e.name)||("url"in e)&&e.url&&String(e.url)||("filename"in e)&&e.filename&&String(e.filename)||("path"in e)&&e.path&&String(e.path))||"";return t?r.split(/[\\/]/).pop()||void 0:r}var sr=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function";var ie=async(e,t,r=!0)=>({...e,body:await Ds(e.body,t,r)}),Qr=new WeakMap;function Ws(e){let t=typeof e==="function"?e:e.fetch,r=Qr.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return Qr.set(t,s),s}var Ds=async(e,t,r=!0)=>{if(!await Ws(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let s=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,o])=>tr(s,n,o,r))),s},Js=(e)=>e instanceof Blob&&("name"in e);var tr=async(e,t,r,s)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response){let n={},o=r.headers.get("Content-Type");if(o)n={type:o};e.append(t,ee([await r.blob()],Oe(r,s),n))}else if(sr(r))e.append(t,ee([await new Response(_t(r)).blob()],Oe(r,s)));else if(Js(r))e.append(t,ee([r],Oe(r,s),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map((n)=>tr(e,t+"[]",n,s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([n,o])=>tr(e,`${t}[${n}]`,o,s)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var Yr=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",Vs=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&Yr(e),Xs=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function kt(e,t,r){if(rr(),e=await e,t||(t=Oe(e,!0)),Vs(e)){if(e instanceof File&&t==null&&r==null)return e;return ee([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...r})}if(Xs(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),ee(await nr(n),t,r)}let s=await nr(e);if(!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return ee(s,t,r)}async function nr(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Yr(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(sr(e))for await(let r of e)t.push(...await nr(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Ks(e)}`)}return t}function Ks(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class y{constructor(e){this._client=e}}var Zr=Symbol.for("brand.privateNullableHeaders");function*zs(e){if(!e)return;if(Zr in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Xt(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Xt(s[1])?s[1]:[s[1]],c=!1;for(let i of o){if(i===void 0)continue;if(t&&!c)c=!0,yield[n,null];yield[n,i]}}}var u=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,c]of zs(s)){let i=o.toLowerCase();if(!n.has(i))t.delete(o),n.add(i);if(c===null)t.delete(o),r.add(i);else t.append(o,c),r.delete(i)}}return{[Zr]:!0,values:t,nulls:r}};function rs(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var es=Object.freeze(Object.create(null)),Qs=(e=rs)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],c=r.reduce((g,_,l)=>{if(/[?#]/.test(_))n=!0;let p=s[l],w=(n?encodeURIComponent:e)(""+p);if(l!==s.length&&(p==null||typeof p==="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??es)??es)?.toString))w=p+"",o.push({start:g.length+_.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`});return g+_+(l===s.length?"":w)},""),i=c.split(/[?#]/,1)[0],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,b;while((b=h.exec(i))!==null)o.push({start:b.index,length:b[0].length,error:`Value "${b[0]}" can't be safely passed as a path parameter`});if(o.sort((g,_)=>g.start-_.start),o.length>0){let g=0,_=o.reduce((l,p)=>{let w=" ".repeat(p.start-g),v="^".repeat(p.length);return g=p.start+p.length,l+w+v},"");throw new m(`Path parameters result in path with invalid segments:
7
7
  ${o.map((l)=>l.error).join(`
8
8
  `)}
9
9
  ${c}
10
- ${_}`)}return c},d=tn(rs);class Ne extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/environments/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}var Le=Symbol("anthropic.sdk.stainlessHelper");function Pt(e){return typeof e==="object"&&e!==null&&Le in e}function ar(e,t){let r=new Set;if(e){for(let s of e)if(Pt(s))r.add(s[Le])}if(t)for(let s of t){if(Pt(s))r.add(s[Le]);if(Array.isArray(s.content)){for(let n of s.content)if(Pt(n))r.add(n[Le])}}return Array.from(r)}function Rt(e,t){let r=ar(e,t);if(r.length===0)return{};return{"x-stainless-helper":r.join(", ")}}function ss(e){if(Pt(e))return{"x-stainless-helper":e[Le]};return{}}class qe extends y{list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",B,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){let{betas:r,...s}=e;return this._client.post("/v1/files?beta=true",ie({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},ss(s.file),t?.headers])},this._client))}}class Be extends y{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/models/${e}?beta=true`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",B,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class je extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/user_profiles/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/user_profiles/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}createEnrollmentURL(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}}class Ue extends y{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/agents/${e}/versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ce extends y{constructor(){super(...arguments);this.versions=new Ue(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s,...n}=t??{};return this._client.get(d`/v1/agents/${e}?beta=true`,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/agents/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ce.Versions=Ue;class He extends y{create(e,t,r){let{view:s,betas:n,...o}=t;return this._client.post(d`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:s},body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{memory_store_id:s,view:n,betas:o,...c}=t;return this._client.post(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{view:n},body:c,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memories?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{memory_store_id:s,expected_content_sha256:n,betas:o}=t;return this._client.delete(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{expected_content_sha256:n},...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class We extends y{retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memory_versions/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memory_versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,t,r){let{memory_store_id:s,betas:n}=t;return this._client.post(d`/v1/memory_stores/${s}/memory_versions/${e}/redact?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class te extends y{constructor(){super(...arguments);this.memories=new He(this._client),this.memoryVersions=new We(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/memory_stores?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/memory_stores/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}te.Memories=He;te.MemoryVersions=We;var vt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function ns(e){return e?.output_format??e?.output_config?.format}function ir(e,t,r){let s=ns(t);if(!t||!("parse"in(s??{})))return{...e,content:e.content.map((n)=>{if(n.type==="text"){let o=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null};return cr(e,t,r)}function cr(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=dn(t,o.text);if(s===null)s=c;let i=Object.defineProperty({...o},"parsed_output",{value:c,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),c},enumerable:!1})}return o});return{...e,content:n,parsed_output:s}}function dn(e,t){let r=ns(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}var fn=(e)=>{let t=0,r=[];while(t<e.length){let s=e[t];if(s==="\\"){t++;continue}if(s==="{"){r.push({type:"brace",value:"{"}),t++;continue}if(s==="}"){r.push({type:"brace",value:"}"}),t++;continue}if(s==="["){r.push({type:"paren",value:"["}),t++;continue}if(s==="]"){r.push({type:"paren",value:"]"}),t++;continue}if(s===":"){r.push({type:"separator",value:":"}),t++;continue}if(s===","){r.push({type:"delimiter",value:","}),t++;continue}if(s==='"'){let i="",h=!1;s=e[++t];while(s!=='"'){if(t===e.length){h=!0;break}if(s==="\\"){if(t++,t===e.length){h=!0;break}i+=s+e[t],s=e[++t]}else i+=s,s=e[++t]}if(s=e[++t],!h)r.push({type:"string",value:i});continue}if(s&&/\s/.test(s)){t++;continue}let o=/[0-9]/;if(s&&o.test(s)||s==="-"||s==="."){let i="";if(s==="-")i+=s,s=e[++t];while(s&&o.test(s)||s===".")i+=s,s=e[++t];r.push({type:"number",value:i});continue}let c=/[a-z]/i;if(s&&c.test(s)){let i="";while(s&&c.test(s)){if(t===e.length)break;i+=s,s=e[++t]}if(i=="true"||i=="false"||i==="null")r.push({type:"name",value:i});else{t++;continue}continue}t++}return r},le=(e)=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),le(e);break;case"number":let r=t.value[t.value.length-1];if(r==="."||r==="-")return e=e.slice(0,e.length-1),le(e);case"string":let s=e[e.length-2];if(s?.type==="delimiter")return e=e.slice(0,e.length-1),le(e);else if(s?.type==="brace"&&s.value==="{")return e=e.slice(0,e.length-1),le(e);break;case"delimiter":return e=e.slice(0,e.length-1),le(e);break}return e},pn=(e)=>{let t=[];if(e.map((r)=>{if(r.type==="brace")if(r.value==="{")t.push("}");else t.splice(t.lastIndexOf("}"),1);if(r.type==="paren")if(r.value==="[")t.push("]");else t.splice(t.lastIndexOf("]"),1)}),t.length>0)t.reverse().map((r)=>{if(r==="}")e.push({type:"brace",value:"}"});else if(r==="]")e.push({type:"paren",value:"]"})});return e},mn=(e)=>{let t="";return e.map((r)=>{switch(r.type){case"string":t+='"'+r.value+'"';break;default:t+=r.value;break}}),t},Et=(e)=>JSON.parse(mn(pn(le(fn(e)))));var F,K,ue,De,Mt,Je,Ve,Tt,Xe,W,Ke,At,It,re,$t,Ct,Ge,lr,os,Ot,ur,hr,dr,as,is="__json_buf";function cs(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}class ze{constructor(e,t){F.add(this),this.messages=[],this.receivedMessages=[],K.set(this,void 0),ue.set(this,null),this.controller=new AbortController,De.set(this,void 0),Mt.set(this,()=>{}),Je.set(this,()=>{}),Ve.set(this,void 0),Tt.set(this,()=>{}),Xe.set(this,()=>{}),W.set(this,{}),Ke.set(this,!1),At.set(this,!1),It.set(this,!1),re.set(this,!1),$t.set(this,void 0),Ct.set(this,void 0),Ge.set(this,void 0),Ot.set(this,(r)=>{if(f(this,At,!0,"f"),U(r))r=new E;if(r instanceof E)return f(this,It,!0,"f"),this._emit("abort",r);if(r instanceof m)return this._emit("error",r);if(r instanceof Error){let s=new m(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new m(String(r)))}),f(this,De,new Promise((r,s)=>{f(this,Mt,r,"f"),f(this,Je,s,"f")}),"f"),f(this,Ve,new Promise((r,s)=>{f(this,Tt,r,"f"),f(this,Xe,s,"f")}),"f"),a(this,De,"f").catch(()=>{}),a(this,Ve,"f").catch(()=>{}),f(this,ue,e,"f"),f(this,Ge,t?.logger??console,"f")}get response(){return a(this,$t,"f")}get request_id(){return a(this,Ct,"f")}async withResponse(){f(this,re,!0,"f");let e=await a(this,De,"f");if(!e)throw 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 ze(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ze(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,ue,{...t,stream:!0},"f"),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")},a(this,Ot,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){if(this.receivedMessages.push(e),t)this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal,n;if(s){if(s.aborted)this.controller.abort();n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n)}try{a(this,F,"m",ur).call(this);let{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(let i of c)a(this,F,"m",hr).call(this,i);if(c.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,$t,e,"f"),f(this,Ct,e?.headers.get("request-id"),"f"),a(this,Mt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,Ke,"f")}get errored(){return a(this,At,"f")}get aborted(){return a(this,It,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,W,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,re,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,re,!0,"f"),await a(this,Ve,"f")}get currentMessage(){return a(this,K,"f")}async finalMessage(){return await this.done(),a(this,F,"m",lr).call(this)}async finalText(){return await this.done(),a(this,F,"m",os).call(this)}_emit(e,...t){if(a(this,Ke,"f"))return;if(e==="end")f(this,Ke,!0,"f"),a(this,Tt,"f").call(this);let r=a(this,W,"f")[e];if(r)a(this,W,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,F,"m",lr).call(this))}async _fromReadableStream(e,t){let r=t?.signal,s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s)}try{a(this,F,"m",ur).call(this),this._connected(null);let n=C.fromReadableStream(e,this.controller);for await(let o of n)a(this,F,"m",hr).call(this,o);if(n.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(K=new WeakMap,ue=new WeakMap,De=new WeakMap,Mt=new WeakMap,Je=new WeakMap,Ve=new WeakMap,Tt=new WeakMap,Xe=new WeakMap,W=new WeakMap,Ke=new WeakMap,At=new WeakMap,It=new WeakMap,re=new WeakMap,$t=new WeakMap,Ct=new WeakMap,Ge=new WeakMap,Ot=new WeakMap,F=new WeakSet,lr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},os=function(){if(this.receivedMessages.length===0)throw new m("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 m("stream ended without producing a content block with type=text");return t.join(" ")},ur=function(){if(this.ended)return;f(this,K,void 0,"f")},hr=function(t){if(this.ended)return;let r=a(this,F,"m",as).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text")this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{if(s.type==="text")this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{if(cs(s)&&s.input)this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{if(s.type==="thinking")this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{if(s.type==="thinking")this._emit("signature",s.signature);break}case"compaction_delta":{if(s.type==="compaction"&&s.content)this._emit("compaction",s.content);break}default:ls(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(ir(r,a(this,ue,"f"),{logger:a(this,Ge,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,K,r,"f");break}case"content_block_start":case"message_delta":break}},dr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,K,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,K,void 0,"f"),ir(t,a(this,ue,"f"),{logger:a(this,Ge,"f")})},as=function(t){let r=a(this,K,"f");if(t.type==="message_start"){if(r)throw new m(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new m(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":if(r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null)r.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)r.usage.server_tool_use=t.usage.server_tool_use;if(t.usage.iterations!=null)r.usage.iterations=t.usage.iterations;return r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text")r.content[t.index]={...s,text:(s.text||"")+t.delta.text};break}case"citations_delta":{if(s?.type==="text")r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]};break}case"input_json_delta":{if(s&&cs(s)){let n=s[is]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,is,{value:n,enumerable:!1,writable:!0}),n)try{o.input=Et(n)}catch(c){let i=new m(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${n}`);a(this,Ot,"f").call(this,i)}r.content[t.index]=o}break}case"thinking_delta":{if(s?.type==="thinking")r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking};break}case"signature_delta":{if(s?.type==="thinking")r.content[t.index]={...s,signature:t.delta.signature};break}case"compaction_delta":{if(s?.type==="compaction")r.content[t.index]={...s,content:(s.content||"")+t.delta.content};break}default:ls(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ls(e){}class he extends Error{constructor(e){let t=typeof e==="string"?e:e.map((r)=>{if(r.type==="text")return r.text;return`[${r.type}]`}).join(" ");super(t);this.name="ToolError",this.content=e}}var us=1e5,hs=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
10
+ ${_}`)}return c},d=Qs(rs);class Ne extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/environments/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}var Le=Symbol("anthropic.sdk.stainlessHelper");function Pt(e){return typeof e==="object"&&e!==null&&Le in e}function or(e,t){let r=new Set;if(e){for(let s of e)if(Pt(s))r.add(s[Le])}if(t)for(let s of t){if(Pt(s))r.add(s[Le]);if(Array.isArray(s.content)){for(let n of s.content)if(Pt(n))r.add(n[Le])}}return Array.from(r)}function Rt(e,t){let r=or(e,t);if(r.length===0)return{};return{"x-stainless-helper":r.join(", ")}}function ss(e){if(Pt(e))return{"x-stainless-helper":e[Le]};return{}}class Fe extends y{list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",B,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){let{betas:r,...s}=e;return this._client.post("/v1/files?beta=true",ie({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},ss(s.file),t?.headers])},this._client))}}class qe extends y{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/models/${e}?beta=true`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",B,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class Be extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/user_profiles/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/user_profiles/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}createEnrollmentURL(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}}class Ue extends y{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/agents/${e}/versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ce extends y{constructor(){super(...arguments);this.versions=new Ue(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s,...n}=t??{};return this._client.get(d`/v1/agents/${e}?beta=true`,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/agents/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ce.Versions=Ue;class He extends y{create(e,t,r){let{view:s,betas:n,...o}=t;return this._client.post(d`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:s},body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{memory_store_id:s,view:n,betas:o,...c}=t;return this._client.post(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{view:n},body:c,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memories?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{memory_store_id:s,expected_content_sha256:n,betas:o}=t;return this._client.delete(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{expected_content_sha256:n},...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class We extends y{retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memory_versions/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memory_versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,t,r){let{memory_store_id:s,betas:n}=t;return this._client.post(d`/v1/memory_stores/${s}/memory_versions/${e}/redact?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class te extends y{constructor(){super(...arguments);this.memories=new He(this._client),this.memoryVersions=new We(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/memory_stores?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/memory_stores/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}te.Memories=He;te.MemoryVersions=We;var vt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function ns(e){return e?.output_format??e?.output_config?.format}function ir(e,t,r){let s=ns(t);if(!t||!("parse"in(s??{})))return{...e,content:e.content.map((n)=>{if(n.type==="text"){let o=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null};return cr(e,t,r)}function cr(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=un(t,o.text);if(s===null)s=c;let i=Object.defineProperty({...o},"parsed_output",{value:c,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),c},enumerable:!1})}return o});return{...e,content:n,parsed_output:s}}function un(e,t){let r=ns(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}var hn=(e)=>{let t=0,r=[];while(t<e.length){let s=e[t];if(s==="\\"){t++;continue}if(s==="{"){r.push({type:"brace",value:"{"}),t++;continue}if(s==="}"){r.push({type:"brace",value:"}"}),t++;continue}if(s==="["){r.push({type:"paren",value:"["}),t++;continue}if(s==="]"){r.push({type:"paren",value:"]"}),t++;continue}if(s===":"){r.push({type:"separator",value:":"}),t++;continue}if(s===","){r.push({type:"delimiter",value:","}),t++;continue}if(s==='"'){let i="",h=!1;s=e[++t];while(s!=='"'){if(t===e.length){h=!0;break}if(s==="\\"){if(t++,t===e.length){h=!0;break}i+=s+e[t],s=e[++t]}else i+=s,s=e[++t]}if(s=e[++t],!h)r.push({type:"string",value:i});continue}if(s&&/\s/.test(s)){t++;continue}let o=/[0-9]/;if(s&&o.test(s)||s==="-"||s==="."){let i="";if(s==="-")i+=s,s=e[++t];while(s&&o.test(s)||s===".")i+=s,s=e[++t];r.push({type:"number",value:i});continue}let c=/[a-z]/i;if(s&&c.test(s)){let i="";while(s&&c.test(s)){if(t===e.length)break;i+=s,s=e[++t]}if(i=="true"||i=="false"||i==="null")r.push({type:"name",value:i});else{t++;continue}continue}t++}return r},le=(e)=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),le(e);break;case"number":let r=t.value[t.value.length-1];if(r==="."||r==="-")return e=e.slice(0,e.length-1),le(e);case"string":let s=e[e.length-2];if(s?.type==="delimiter")return e=e.slice(0,e.length-1),le(e);else if(s?.type==="brace"&&s.value==="{")return e=e.slice(0,e.length-1),le(e);break;case"delimiter":return e=e.slice(0,e.length-1),le(e);break}return e},dn=(e)=>{let t=[];if(e.map((r)=>{if(r.type==="brace")if(r.value==="{")t.push("}");else t.splice(t.lastIndexOf("}"),1);if(r.type==="paren")if(r.value==="[")t.push("]");else t.splice(t.lastIndexOf("]"),1)}),t.length>0)t.reverse().map((r)=>{if(r==="}")e.push({type:"brace",value:"}"});else if(r==="]")e.push({type:"paren",value:"]"})});return e},fn=(e)=>{let t="";return e.map((r)=>{switch(r.type){case"string":t+='"'+r.value+'"';break;default:t+=r.value;break}}),t},Et=(e)=>JSON.parse(fn(dn(le(hn(e)))));var F,K,ue,De,Mt,Je,Ve,Tt,Xe,W,Ke,At,It,re,$t,Ct,Ge,lr,os,Ot,ur,hr,dr,as,is="__json_buf";function cs(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}class ze{constructor(e,t){F.add(this),this.messages=[],this.receivedMessages=[],K.set(this,void 0),ue.set(this,null),this.controller=new AbortController,De.set(this,void 0),Mt.set(this,()=>{}),Je.set(this,()=>{}),Ve.set(this,void 0),Tt.set(this,()=>{}),Xe.set(this,()=>{}),W.set(this,{}),Ke.set(this,!1),At.set(this,!1),It.set(this,!1),re.set(this,!1),$t.set(this,void 0),Ct.set(this,void 0),Ge.set(this,void 0),Ot.set(this,(r)=>{if(f(this,At,!0,"f"),U(r))r=new E;if(r instanceof E)return f(this,It,!0,"f"),this._emit("abort",r);if(r instanceof m)return this._emit("error",r);if(r instanceof Error){let s=new m(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new m(String(r)))}),f(this,De,new Promise((r,s)=>{f(this,Mt,r,"f"),f(this,Je,s,"f")}),"f"),f(this,Ve,new Promise((r,s)=>{f(this,Tt,r,"f"),f(this,Xe,s,"f")}),"f"),a(this,De,"f").catch(()=>{}),a(this,Ve,"f").catch(()=>{}),f(this,ue,e,"f"),f(this,Ge,t?.logger??console,"f")}get response(){return a(this,$t,"f")}get request_id(){return a(this,Ct,"f")}async withResponse(){f(this,re,!0,"f");let e=await a(this,De,"f");if(!e)throw 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 ze(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ze(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,ue,{...t,stream:!0},"f"),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")},a(this,Ot,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){if(this.receivedMessages.push(e),t)this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal,n;if(s){if(s.aborted)this.controller.abort();n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n)}try{a(this,F,"m",ur).call(this);let{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(let i of c)a(this,F,"m",hr).call(this,i);if(c.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,$t,e,"f"),f(this,Ct,e?.headers.get("request-id"),"f"),a(this,Mt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,Ke,"f")}get errored(){return a(this,At,"f")}get aborted(){return a(this,It,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,W,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,re,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,re,!0,"f"),await a(this,Ve,"f")}get currentMessage(){return a(this,K,"f")}async finalMessage(){return await this.done(),a(this,F,"m",lr).call(this)}async finalText(){return await this.done(),a(this,F,"m",os).call(this)}_emit(e,...t){if(a(this,Ke,"f"))return;if(e==="end")f(this,Ke,!0,"f"),a(this,Tt,"f").call(this);let r=a(this,W,"f")[e];if(r)a(this,W,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,F,"m",lr).call(this))}async _fromReadableStream(e,t){let r=t?.signal,s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s)}try{a(this,F,"m",ur).call(this),this._connected(null);let n=C.fromReadableStream(e,this.controller);for await(let o of n)a(this,F,"m",hr).call(this,o);if(n.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(K=new WeakMap,ue=new WeakMap,De=new WeakMap,Mt=new WeakMap,Je=new WeakMap,Ve=new WeakMap,Tt=new WeakMap,Xe=new WeakMap,W=new WeakMap,Ke=new WeakMap,At=new WeakMap,It=new WeakMap,re=new WeakMap,$t=new WeakMap,Ct=new WeakMap,Ge=new WeakMap,Ot=new WeakMap,F=new WeakSet,lr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},os=function(){if(this.receivedMessages.length===0)throw new m("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 m("stream ended without producing a content block with type=text");return t.join(" ")},ur=function(){if(this.ended)return;f(this,K,void 0,"f")},hr=function(t){if(this.ended)return;let r=a(this,F,"m",as).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text")this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{if(s.type==="text")this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{if(cs(s)&&s.input)this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{if(s.type==="thinking")this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{if(s.type==="thinking")this._emit("signature",s.signature);break}case"compaction_delta":{if(s.type==="compaction"&&s.content)this._emit("compaction",s.content);break}default:ls(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(ir(r,a(this,ue,"f"),{logger:a(this,Ge,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,K,r,"f");break}case"content_block_start":case"message_delta":break}},dr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,K,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,K,void 0,"f"),ir(t,a(this,ue,"f"),{logger:a(this,Ge,"f")})},as=function(t){let r=a(this,K,"f");if(t.type==="message_start"){if(r)throw new m(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new m(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":if(r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null)r.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)r.usage.server_tool_use=t.usage.server_tool_use;if(t.usage.iterations!=null)r.usage.iterations=t.usage.iterations;return r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text")r.content[t.index]={...s,text:(s.text||"")+t.delta.text};break}case"citations_delta":{if(s?.type==="text")r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]};break}case"input_json_delta":{if(s&&cs(s)){let n=s[is]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,is,{value:n,enumerable:!1,writable:!0}),n)try{o.input=Et(n)}catch(c){let i=new m(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${n}`);a(this,Ot,"f").call(this,i)}r.content[t.index]=o}break}case"thinking_delta":{if(s?.type==="thinking")r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking};break}case"signature_delta":{if(s?.type==="thinking")r.content[t.index]={...s,signature:t.delta.signature};break}case"compaction_delta":{if(s?.type==="compaction")r.content[t.index]={...s,content:(s.content||"")+t.delta.content};break}default:ls(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ls(e){}class he extends Error{constructor(e){let t=typeof e==="string"?e:e.map((r)=>{if(r.type==="text")return r.text;return`[${r.type}]`}).join(" ");super(t);this.name="ToolError",this.content=e}}var us=1e5,hs=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
11
11
  1. Task Overview
12
12
  The user's core request and success criteria
13
13
  Any clarifications or constraints they specified
@@ -29,17 +29,17 @@ User preferences or style requirements
29
29
  Domain-specific details that aren't obvious
30
30
  Any promises made to the user
31
31
  Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
32
- Wrap your summary in <summary></summary> tags.`;var Qe,de,se,P,T,O,D,G,Ye,ds,fr;function fs(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class Ze{constructor(e,t,r){Qe.add(this),this.client=e,de.set(this,!1),se.set(this,!1),P.set(this,void 0),T.set(this,void 0),O.set(this,void 0),D.set(this,void 0),G.set(this,void 0),Ye.set(this,0),f(this,P,{params:{...t,messages:structuredClone(t.messages)}},"f");let n=["BetaToolRunner",...ar(t.tools,t.messages)].join(", ");if(f(this,T,{...r,headers:u([{"x-stainless-helper":n},r?.headers])},"f"),f(this,G,fs(),"f"),t.compactionControl?.enabled)console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(de=new WeakMap,se=new WeakMap,P=new WeakMap,T=new WeakMap,O=new WeakMap,D=new WeakMap,G=new WeakMap,Ye=new WeakMap,Qe=new WeakSet,ds=async function(){let t=a(this,P,"f").params.compactionControl;if(!t||!t.enabled)return!1;let r=0;if(a(this,O,"f")!==void 0)try{let h=await a(this,O,"f");r=h.usage.input_tokens+(h.usage.cache_creation_input_tokens??0)+(h.usage.cache_read_input_tokens??0)+h.usage.output_tokens}catch{return!1}let s=t.contextTokenThreshold??us;if(r<s)return!1;let n=t.model??a(this,P,"f").params.model,o=t.summaryPrompt??hs,c=a(this,P,"f").params.messages;if(c[c.length-1].role==="assistant"){let h=c[c.length-1];if(Array.isArray(h.content)){let b=h.content.filter((g)=>g.type!=="tool_use");if(b.length===0)c.pop();else h.content=b}}let i=await this.client.beta.messages.create({model:n,messages:[...c,{role:"user",content:[{type:"text",text:o}]}],max_tokens:a(this,P,"f").params.max_tokens},{signal:a(this,T,"f").signal,headers:u([a(this,T,"f").headers,{"x-stainless-helper":"compaction"}])});if(i.content[0]?.type!=="text")throw new m("Expected text response for compaction");return a(this,P,"f").params.messages=[{role:"user",content:i.content}],!0},Symbol.asyncIterator)](){var e;if(a(this,de,"f"))throw new m("Cannot iterate over a consumed stream");f(this,de,!0,"f"),f(this,se,!0,"f"),f(this,D,void 0,"f");try{while(!0){let t;try{if(a(this,P,"f").params.max_iterations&&a(this,Ye,"f")>=a(this,P,"f").params.max_iterations)break;f(this,se,!1,"f"),f(this,D,void 0,"f"),f(this,Ye,(e=a(this,Ye,"f"),e++,e),"f"),f(this,O,void 0,"f");let{max_iterations:r,compactionControl:s,...n}=a(this,P,"f").params;if(n.stream)t=this.client.beta.messages.stream({...n},a(this,T,"f")),f(this,O,t.finalMessage(),"f"),a(this,O,"f").catch(()=>{}),yield t;else f(this,O,this.client.beta.messages.create({...n,stream:!1},a(this,T,"f")),"f"),yield a(this,O,"f");if(!await a(this,Qe,"m",ds).call(this)){if(!a(this,se,"f")){let{role:i,content:h}=await a(this,O,"f");a(this,P,"f").params.messages.push({role:i,content:h})}let c=await a(this,Qe,"m",fr).call(this,a(this,P,"f").params.messages.at(-1));if(c)a(this,P,"f").params.messages.push(c);else if(!a(this,se,"f"))break}}finally{if(t)t.abort()}}if(!a(this,O,"f"))throw new m("ToolRunner concluded without a message from the server");a(this,G,"f").resolve(await a(this,O,"f"))}catch(t){throw f(this,de,!1,"f"),a(this,G,"f").promise.catch(()=>{}),a(this,G,"f").reject(t),f(this,G,fs(),"f"),t}}setMessagesParams(e){if(typeof e==="function")a(this,P,"f").params=e(a(this,P,"f").params);else a(this,P,"f").params=e;f(this,se,!0,"f"),f(this,D,void 0,"f")}setRequestOptions(e){if(typeof e==="function")f(this,T,e(a(this,T,"f")),"f");else f(this,T,{...a(this,T,"f"),...e},"f")}async generateToolResponse(e=a(this,T,"f").signal){let t=await a(this,O,"f")??this.params.messages.at(-1);if(!t)return null;return a(this,Qe,"m",fr).call(this,t,e)}done(){return a(this,G,"f").promise}async runUntilDone(){if(!a(this,de,"f"))for await(let e of this);return this.done()}get params(){return a(this,P,"f").params}pushMessages(...e){this.setMessagesParams((t)=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}fr=async function(t,r=a(this,T,"f").signal){if(a(this,D,"f")!==void 0)return a(this,D,"f");return f(this,D,gn(a(this,P,"f").params,t,{...a(this,T,"f"),signal:r}),"f"),a(this,D,"f")};async function gn(e,t=e.messages.at(-1),r){if(!t||t.role!=="assistant"||!t.content||typeof t.content==="string")return null;let s=t.content.filter((o)=>o.type==="tool_use");if(s.length===0)return null;return{role:"user",content:await Promise.all(s.map(async(o)=>{let c=e.tools.find((i)=>("name"in i?i.name:i.mcp_server_name)===o.name);if(!c||!("run"in c))return{type:"tool_result",tool_use_id:o.id,content:`Error: Tool '${o.name}' not found`,is_error:!0};try{let i=o.input;if("parse"in c&&c.parse)i=c.parse(i);let h=await c.run(i,{toolUseBlock:o,signal:r?.signal});return{type:"tool_result",tool_use_id:o.id,content:h}}catch(i){return{type:"tool_result",tool_use_id:o.id,content:i instanceof he?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}))}}class fe{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new X;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){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}return new fe(Te(e.body),t)}}class et extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",B,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){let s=await this.retrieve(e);if(!s.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:n}=t??{};return this._client.get(s.results_url,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,c)=>fe.fromResponse(c.response,c.controller))}}var ps={"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-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},bn=["claude-mythos-preview","claude-opus-4-6"];class z extends y{constructor(){super(...arguments);this.batches=new et(this._client)}create(e,t){let r=ms(e),{betas:s,...n}=r;if(n.model in ps)console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${ps[n.model]}
33
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(bn.includes(n.model)&&n.thinking&&n.thinking.type==="enabled")console.warn(`Using Claude with ${n.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let o=this._client._options.timeout;if(!n.stream&&o==null){let i=vt[n.model]??void 0;o=this._client.calculateNonstreamingTimeout(n.max_tokens,i)}let c=Rt(n.tools,n.messages);return this._client.post("/v1/messages?beta=true",{body:n,timeout:o??600000,...t,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},c,t?.headers]),stream:r.stream??!1})}parse(e,t){return t={...t,headers:u([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then((r)=>cr(r,e,{logger:this._client.logger??console}))}stream(e,t){return ze.createMessage(this,e,t)}countTokens(e,t){let r=ms(e),{betas:s,...n}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new Ze(this._client,e,t)}}function ms(e){if(!e.output_format)return e;if(e.output_config?.format)throw new m("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:t,...r}=e;return{...r,output_config:{...e.output_config,format:t}}}z.Batches=et;z.BetaToolRunner=Ze;z.ToolError=he;class tt extends y{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/sessions/${e}/events?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}/events?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}class rt extends y{retrieve(e,t,r){let{session_id:s,betas:n}=t;return this._client.get(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{session_id:s,betas:n,...o}=t;return this._client.post(d`/v1/sessions/${s}/resources/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/sessions/${e}/resources?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{session_id:s,betas:n}=t;return this._client.delete(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}/resources?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ne extends y{constructor(){super(...arguments);this.events=new tt(this._client),this.resources=new rt(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/sessions?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/sessions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/sessions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/sessions/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ne.Events=tt;ne.Resources=rt;class st extends y{create(e,t={},r){let{betas:s,...n}=t??{};return this._client.post(d`/v1/skills/${e}/versions?beta=true`,ie({body:n,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,t,r){let{skill_id:s,betas:n}=t;return this._client.get(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/skills/${e}/versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,t,r){let{skill_id:s,betas:n}=t;return this._client.delete(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}}class pe extends y{constructor(){super(...arguments);this.versions=new st(this._client)}create(e={},t){let{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",ie({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/skills?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}}pe.Versions=st;class nt extends y{create(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/vaults/${e}/credentials?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{vault_id:s,betas:n}=t;return this._client.get(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{vault_id:s,betas:n,...o}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/vaults/${e}/credentials?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{vault_id:s,betas:n}=t;return this._client.delete(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t,r){let{vault_id:s,betas:n}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class me extends y{constructor(){super(...arguments);this.credentials=new nt(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/vaults?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/vaults/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/vaults/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/vaults/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/vaults/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}me.Credentials=nt;class M extends y{constructor(){super(...arguments);this.models=new Be(this._client),this.messages=new z(this._client),this.agents=new ce(this._client),this.environments=new Ne(this._client),this.sessions=new ne(this._client),this.vaults=new me(this._client),this.memoryStores=new te(this._client),this.files=new qe(this._client),this.skills=new pe(this._client),this.userProfiles=new je(this._client)}}M.Models=Be;M.Messages=z;M.Agents=ce;M.Environments=Ne;M.Sessions=ne;M.Vaults=me;M.MemoryStores=te;M.Files=qe;M.Skills=pe;M.UserProfiles=je;class ge extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??600000,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}function gs(e){return e?.output_config?.format}function pr(e,t,r){let s=gs(t);if(!t||!("parse"in(s??{})))return{...e,content:e.content.map((n)=>{if(n.type==="text")return Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return n}),parsed_output:null};return mr(e,t,r)}function mr(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=En(t,o.text);if(s===null)s=c;return Object.defineProperty({...o},"parsed_output",{value:c,enumerable:!1})}return o});return{...e,content:n,parsed_output:s}}function En(e,t){let r=gs(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}var q,Q,_e,ot,Nt,at,it,Lt,ct,J,lt,Ft,qt,oe,Bt,jt,ut,gr,_s,_r,br,yr,wr,bs,ys="__json_buf";function Ss(e){return e.type==="tool_use"||e.type==="server_tool_use"}class ht{constructor(e,t){q.add(this),this.messages=[],this.receivedMessages=[],Q.set(this,void 0),_e.set(this,null),this.controller=new AbortController,ot.set(this,void 0),Nt.set(this,()=>{}),at.set(this,()=>{}),it.set(this,void 0),Lt.set(this,()=>{}),ct.set(this,()=>{}),J.set(this,{}),lt.set(this,!1),Ft.set(this,!1),qt.set(this,!1),oe.set(this,!1),Bt.set(this,void 0),jt.set(this,void 0),ut.set(this,void 0),_r.set(this,(r)=>{if(f(this,Ft,!0,"f"),U(r))r=new E;if(r instanceof E)return f(this,qt,!0,"f"),this._emit("abort",r);if(r instanceof m)return this._emit("error",r);if(r instanceof Error){let s=new m(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new m(String(r)))}),f(this,ot,new Promise((r,s)=>{f(this,Nt,r,"f"),f(this,at,s,"f")}),"f"),f(this,it,new Promise((r,s)=>{f(this,Lt,r,"f"),f(this,ct,s,"f")}),"f"),a(this,ot,"f").catch(()=>{}),a(this,it,"f").catch(()=>{}),f(this,_e,e,"f"),f(this,ut,t?.logger??console,"f")}get response(){return a(this,Bt,"f")}get request_id(){return a(this,jt,"f")}async withResponse(){f(this,oe,!0,"f");let e=await a(this,ot,"f");if(!e)throw 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 ht(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ht(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,_e,{...t,stream:!0},"f"),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")},a(this,_r,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){if(this.receivedMessages.push(e),t)this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal,n;if(s){if(s.aborted)this.controller.abort();n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n)}try{a(this,q,"m",br).call(this);let{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(let i of c)a(this,q,"m",yr).call(this,i);if(c.controller.signal?.aborted)throw new E;a(this,q,"m",wr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,Bt,e,"f"),f(this,jt,e?.headers.get("request-id"),"f"),a(this,Nt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,lt,"f")}get errored(){return a(this,Ft,"f")}get aborted(){return a(this,qt,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,J,"f")[e]||(a(this,J,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,J,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(a(this,J,"f")[e]||(a(this,J,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,oe,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,oe,!0,"f"),await a(this,it,"f")}get currentMessage(){return a(this,Q,"f")}async finalMessage(){return await this.done(),a(this,q,"m",gr).call(this)}async finalText(){return await this.done(),a(this,q,"m",_s).call(this)}_emit(e,...t){if(a(this,lt,"f"))return;if(e==="end")f(this,lt,!0,"f"),a(this,Lt,"f").call(this);let r=a(this,J,"f")[e];if(r)a(this,J,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,oe,"f")&&!r?.length)Promise.reject(s);a(this,at,"f").call(this,s),a(this,ct,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,oe,"f")&&!r?.length)Promise.reject(s);a(this,at,"f").call(this,s),a(this,ct,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,q,"m",gr).call(this))}async _fromReadableStream(e,t){let r=t?.signal,s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s)}try{a(this,q,"m",br).call(this),this._connected(null);let n=C.fromReadableStream(e,this.controller);for await(let o of n)a(this,q,"m",yr).call(this,o);if(n.controller.signal?.aborted)throw new E;a(this,q,"m",wr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(Q=new WeakMap,_e=new WeakMap,ot=new WeakMap,Nt=new WeakMap,at=new WeakMap,it=new WeakMap,Lt=new WeakMap,ct=new WeakMap,J=new WeakMap,lt=new WeakMap,Ft=new WeakMap,qt=new WeakMap,oe=new WeakMap,Bt=new WeakMap,jt=new WeakMap,ut=new WeakMap,_r=new WeakMap,q=new WeakSet,gr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},_s=function(){if(this.receivedMessages.length===0)throw new m("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 m("stream ended without producing a content block with type=text");return t.join(" ")},br=function(){if(this.ended)return;f(this,Q,void 0,"f")},yr=function(t){if(this.ended)return;let r=a(this,q,"m",bs).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text")this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{if(s.type==="text")this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{if(Ss(s)&&s.input)this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{if(s.type==="thinking")this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{if(s.type==="thinking")this._emit("signature",s.signature);break}default:ks(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(pr(r,a(this,_e,"f"),{logger:a(this,ut,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,Q,r,"f");break}case"content_block_start":case"message_delta":break}},wr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,Q,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,Q,void 0,"f"),pr(t,a(this,_e,"f"),{logger:a(this,ut,"f")})},bs=function(t){let r=a(this,Q,"f");if(t.type==="message_start"){if(r)throw new m(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new m(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":if(r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null)r.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)r.usage.server_tool_use=t.usage.server_tool_use;return r;case"content_block_start":return r.content.push({...t.content_block}),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text")r.content[t.index]={...s,text:(s.text||"")+t.delta.text};break}case"citations_delta":{if(s?.type==="text")r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]};break}case"input_json_delta":{if(s&&Ss(s)){let n=s[ys]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,ys,{value:n,enumerable:!1,writable:!0}),n)o.input=Et(n);r.content[t.index]=o}break}case"thinking_delta":{if(s?.type==="thinking")r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking};break}case"signature_delta":{if(s?.type==="thinking")r.content[t.index]={...s,signature:t.delta.signature};break}default:ks(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ks(e){}class dt extends y{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",B,{query:e,...t})}delete(e,t){return this._client.delete(d`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(d`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:u([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,n)=>fe.fromResponse(n.response,n.controller))}}class ae extends y{constructor(){super(...arguments);this.batches=new dt(this._client)}create(e,t){if(e.model in Ps)console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Ps[e.model]}
34
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Tn.includes(e.model)&&e.thinking&&e.thinking.type==="enabled")console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let n=vt[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,n)}let s=Rt(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??600000,...t,headers:u([s,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then((r)=>mr(r,e,{logger:this._client.logger??console}))}stream(e,t){return ht.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}var Ps={"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-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},Tn=["claude-mythos-preview","claude-opus-4-6"];ae.Batches=dt;class be extends y{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/models/${e}`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models",B,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}var ft=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0;return};var Sr,kr,Ut,Rs,Es="\\n\\nHuman:",Ms="\\n\\nAssistant:";class S{constructor({baseURL:e=ft("ANTHROPIC_BASE_URL"),apiKey:t=ft("ANTHROPIC_API_KEY")??null,authToken:r=ft("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){Sr.add(this),Ut.set(this,void 0);let n={apiKey:t,authToken:r,...s,baseURL:e||"https://api.anthropic.com"};if(!n.dangerouslyAllowBrowser&&qr())throw new m(`It looks like you're running in a browser-like environment.
32
+ Wrap your summary in <summary></summary> tags.`;var Qe,de,se,P,T,O,D,G,Ye,ds,fr;function fs(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class Ze{constructor(e,t,r){Qe.add(this),this.client=e,de.set(this,!1),se.set(this,!1),P.set(this,void 0),T.set(this,void 0),O.set(this,void 0),D.set(this,void 0),G.set(this,void 0),Ye.set(this,0),f(this,P,{params:{...t,messages:structuredClone(t.messages)}},"f");let n=["BetaToolRunner",...or(t.tools,t.messages)].join(", ");if(f(this,T,{...r,headers:u([{"x-stainless-helper":n},r?.headers])},"f"),f(this,G,fs(),"f"),t.compactionControl?.enabled)console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(de=new WeakMap,se=new WeakMap,P=new WeakMap,T=new WeakMap,O=new WeakMap,D=new WeakMap,G=new WeakMap,Ye=new WeakMap,Qe=new WeakSet,ds=async function(){let t=a(this,P,"f").params.compactionControl;if(!t||!t.enabled)return!1;let r=0;if(a(this,O,"f")!==void 0)try{let h=await a(this,O,"f");r=h.usage.input_tokens+(h.usage.cache_creation_input_tokens??0)+(h.usage.cache_read_input_tokens??0)+h.usage.output_tokens}catch{return!1}let s=t.contextTokenThreshold??us;if(r<s)return!1;let n=t.model??a(this,P,"f").params.model,o=t.summaryPrompt??hs,c=a(this,P,"f").params.messages;if(c[c.length-1].role==="assistant"){let h=c[c.length-1];if(Array.isArray(h.content)){let b=h.content.filter((g)=>g.type!=="tool_use");if(b.length===0)c.pop();else h.content=b}}let i=await this.client.beta.messages.create({model:n,messages:[...c,{role:"user",content:[{type:"text",text:o}]}],max_tokens:a(this,P,"f").params.max_tokens},{signal:a(this,T,"f").signal,headers:u([a(this,T,"f").headers,{"x-stainless-helper":"compaction"}])});if(i.content[0]?.type!=="text")throw new m("Expected text response for compaction");return a(this,P,"f").params.messages=[{role:"user",content:i.content}],!0},Symbol.asyncIterator)](){var e;if(a(this,de,"f"))throw new m("Cannot iterate over a consumed stream");f(this,de,!0,"f"),f(this,se,!0,"f"),f(this,D,void 0,"f");try{while(!0){let t;try{if(a(this,P,"f").params.max_iterations&&a(this,Ye,"f")>=a(this,P,"f").params.max_iterations)break;f(this,se,!1,"f"),f(this,D,void 0,"f"),f(this,Ye,(e=a(this,Ye,"f"),e++,e),"f"),f(this,O,void 0,"f");let{max_iterations:r,compactionControl:s,...n}=a(this,P,"f").params;if(n.stream)t=this.client.beta.messages.stream({...n},a(this,T,"f")),f(this,O,t.finalMessage(),"f"),a(this,O,"f").catch(()=>{}),yield t;else f(this,O,this.client.beta.messages.create({...n,stream:!1},a(this,T,"f")),"f"),yield a(this,O,"f");if(!await a(this,Qe,"m",ds).call(this)){if(!a(this,se,"f")){let{role:i,content:h}=await a(this,O,"f");a(this,P,"f").params.messages.push({role:i,content:h})}let c=await a(this,Qe,"m",fr).call(this,a(this,P,"f").params.messages.at(-1));if(c)a(this,P,"f").params.messages.push(c);else if(!a(this,se,"f"))break}}finally{if(t)t.abort()}}if(!a(this,O,"f"))throw new m("ToolRunner concluded without a message from the server");a(this,G,"f").resolve(await a(this,O,"f"))}catch(t){throw f(this,de,!1,"f"),a(this,G,"f").promise.catch(()=>{}),a(this,G,"f").reject(t),f(this,G,fs(),"f"),t}}setMessagesParams(e){if(typeof e==="function")a(this,P,"f").params=e(a(this,P,"f").params);else a(this,P,"f").params=e;f(this,se,!0,"f"),f(this,D,void 0,"f")}setRequestOptions(e){if(typeof e==="function")f(this,T,e(a(this,T,"f")),"f");else f(this,T,{...a(this,T,"f"),...e},"f")}async generateToolResponse(e=a(this,T,"f").signal){let t=await a(this,O,"f")??this.params.messages.at(-1);if(!t)return null;return a(this,Qe,"m",fr).call(this,t,e)}done(){return a(this,G,"f").promise}async runUntilDone(){if(!a(this,de,"f"))for await(let e of this);return this.done()}get params(){return a(this,P,"f").params}pushMessages(...e){this.setMessagesParams((t)=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}fr=async function(t,r=a(this,T,"f").signal){if(a(this,D,"f")!==void 0)return a(this,D,"f");return f(this,D,pn(a(this,P,"f").params,t,{...a(this,T,"f"),signal:r}),"f"),a(this,D,"f")};async function pn(e,t=e.messages.at(-1),r){if(!t||t.role!=="assistant"||!t.content||typeof t.content==="string")return null;let s=t.content.filter((o)=>o.type==="tool_use");if(s.length===0)return null;return{role:"user",content:await Promise.all(s.map(async(o)=>{let c=e.tools.find((i)=>("name"in i?i.name:i.mcp_server_name)===o.name);if(!c||!("run"in c))return{type:"tool_result",tool_use_id:o.id,content:`Error: Tool '${o.name}' not found`,is_error:!0};try{let i=o.input;if("parse"in c&&c.parse)i=c.parse(i);let h=await c.run(i,{toolUseBlock:o,signal:r?.signal});return{type:"tool_result",tool_use_id:o.id,content:h}}catch(i){return{type:"tool_result",tool_use_id:o.id,content:i instanceof he?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}))}}class fe{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new X;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){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}return new fe(Te(e.body),t)}}class et extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",B,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){let s=await this.retrieve(e);if(!s.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:n}=t??{};return this._client.get(s.results_url,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,c)=>fe.fromResponse(c.response,c.controller))}}var ps={"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-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},gn=["claude-mythos-preview","claude-opus-4-6"];class z extends y{constructor(){super(...arguments);this.batches=new et(this._client)}create(e,t){let r=ms(e),{betas:s,...n}=r;if(n.model in ps)console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${ps[n.model]}
33
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(gn.includes(n.model)&&n.thinking&&n.thinking.type==="enabled")console.warn(`Using Claude with ${n.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let o=this._client._options.timeout;if(!n.stream&&o==null){let i=vt[n.model]??void 0;o=this._client.calculateNonstreamingTimeout(n.max_tokens,i)}let c=Rt(n.tools,n.messages);return this._client.post("/v1/messages?beta=true",{body:n,timeout:o??600000,...t,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},c,t?.headers]),stream:r.stream??!1})}parse(e,t){return t={...t,headers:u([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then((r)=>cr(r,e,{logger:this._client.logger??console}))}stream(e,t){return ze.createMessage(this,e,t)}countTokens(e,t){let r=ms(e),{betas:s,...n}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new Ze(this._client,e,t)}}function ms(e){if(!e.output_format)return e;if(e.output_config?.format)throw new m("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:t,...r}=e;return{...r,output_config:{...e.output_config,format:t}}}z.Batches=et;z.BetaToolRunner=Ze;z.ToolError=he;class tt extends y{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/sessions/${e}/events?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}/events?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}class rt extends y{retrieve(e,t,r){let{session_id:s,betas:n}=t;return this._client.get(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{session_id:s,betas:n,...o}=t;return this._client.post(d`/v1/sessions/${s}/resources/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/sessions/${e}/resources?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{session_id:s,betas:n}=t;return this._client.delete(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}/resources?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ne extends y{constructor(){super(...arguments);this.events=new tt(this._client),this.resources=new rt(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/sessions?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/sessions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/sessions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/sessions/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ne.Events=tt;ne.Resources=rt;class st extends y{create(e,t={},r){let{betas:s,...n}=t??{};return this._client.post(d`/v1/skills/${e}/versions?beta=true`,ie({body:n,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,t,r){let{skill_id:s,betas:n}=t;return this._client.get(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/skills/${e}/versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,t,r){let{skill_id:s,betas:n}=t;return this._client.delete(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}}class pe extends y{constructor(){super(...arguments);this.versions=new st(this._client)}create(e={},t){let{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",ie({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/skills?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}}pe.Versions=st;class nt extends y{create(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/vaults/${e}/credentials?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{vault_id:s,betas:n}=t;return this._client.get(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{vault_id:s,betas:n,...o}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/vaults/${e}/credentials?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{vault_id:s,betas:n}=t;return this._client.delete(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t,r){let{vault_id:s,betas:n}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class me extends y{constructor(){super(...arguments);this.credentials=new nt(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/vaults?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/vaults/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/vaults/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/vaults/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/vaults/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}me.Credentials=nt;class M extends y{constructor(){super(...arguments);this.models=new qe(this._client),this.messages=new z(this._client),this.agents=new ce(this._client),this.environments=new Ne(this._client),this.sessions=new ne(this._client),this.vaults=new me(this._client),this.memoryStores=new te(this._client),this.files=new Fe(this._client),this.skills=new pe(this._client),this.userProfiles=new Be(this._client)}}M.Models=qe;M.Messages=z;M.Agents=ce;M.Environments=Ne;M.Sessions=ne;M.Vaults=me;M.MemoryStores=te;M.Files=Fe;M.Skills=pe;M.UserProfiles=Be;class ge extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??600000,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}function gs(e){return e?.output_config?.format}function pr(e,t,r){let s=gs(t);if(!t||!("parse"in(s??{})))return{...e,content:e.content.map((n)=>{if(n.type==="text")return Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return n}),parsed_output:null};return mr(e,t,r)}function mr(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=Rn(t,o.text);if(s===null)s=c;return Object.defineProperty({...o},"parsed_output",{value:c,enumerable:!1})}return o});return{...e,content:n,parsed_output:s}}function Rn(e,t){let r=gs(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}var q,Q,_e,ot,Nt,at,it,Lt,ct,J,lt,Ft,qt,oe,Bt,jt,ut,gr,_s,_r,br,yr,wr,bs,ys="__json_buf";function ws(e){return e.type==="tool_use"||e.type==="server_tool_use"}class ht{constructor(e,t){q.add(this),this.messages=[],this.receivedMessages=[],Q.set(this,void 0),_e.set(this,null),this.controller=new AbortController,ot.set(this,void 0),Nt.set(this,()=>{}),at.set(this,()=>{}),it.set(this,void 0),Lt.set(this,()=>{}),ct.set(this,()=>{}),J.set(this,{}),lt.set(this,!1),Ft.set(this,!1),qt.set(this,!1),oe.set(this,!1),Bt.set(this,void 0),jt.set(this,void 0),ut.set(this,void 0),_r.set(this,(r)=>{if(f(this,Ft,!0,"f"),U(r))r=new E;if(r instanceof E)return f(this,qt,!0,"f"),this._emit("abort",r);if(r instanceof m)return this._emit("error",r);if(r instanceof Error){let s=new m(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new m(String(r)))}),f(this,ot,new Promise((r,s)=>{f(this,Nt,r,"f"),f(this,at,s,"f")}),"f"),f(this,it,new Promise((r,s)=>{f(this,Lt,r,"f"),f(this,ct,s,"f")}),"f"),a(this,ot,"f").catch(()=>{}),a(this,it,"f").catch(()=>{}),f(this,_e,e,"f"),f(this,ut,t?.logger??console,"f")}get response(){return a(this,Bt,"f")}get request_id(){return a(this,jt,"f")}async withResponse(){f(this,oe,!0,"f");let e=await a(this,ot,"f");if(!e)throw 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 ht(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ht(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,_e,{...t,stream:!0},"f"),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")},a(this,_r,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){if(this.receivedMessages.push(e),t)this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal,n;if(s){if(s.aborted)this.controller.abort();n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n)}try{a(this,q,"m",br).call(this);let{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(let i of c)a(this,q,"m",yr).call(this,i);if(c.controller.signal?.aborted)throw new E;a(this,q,"m",wr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,Bt,e,"f"),f(this,jt,e?.headers.get("request-id"),"f"),a(this,Nt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,lt,"f")}get errored(){return a(this,Ft,"f")}get aborted(){return a(this,qt,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,J,"f")[e]||(a(this,J,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,J,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(a(this,J,"f")[e]||(a(this,J,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,oe,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,oe,!0,"f"),await a(this,it,"f")}get currentMessage(){return a(this,Q,"f")}async finalMessage(){return await this.done(),a(this,q,"m",gr).call(this)}async finalText(){return await this.done(),a(this,q,"m",_s).call(this)}_emit(e,...t){if(a(this,lt,"f"))return;if(e==="end")f(this,lt,!0,"f"),a(this,Lt,"f").call(this);let r=a(this,J,"f")[e];if(r)a(this,J,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,oe,"f")&&!r?.length)Promise.reject(s);a(this,at,"f").call(this,s),a(this,ct,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,oe,"f")&&!r?.length)Promise.reject(s);a(this,at,"f").call(this,s),a(this,ct,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,q,"m",gr).call(this))}async _fromReadableStream(e,t){let r=t?.signal,s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s)}try{a(this,q,"m",br).call(this),this._connected(null);let n=C.fromReadableStream(e,this.controller);for await(let o of n)a(this,q,"m",yr).call(this,o);if(n.controller.signal?.aborted)throw new E;a(this,q,"m",wr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(Q=new WeakMap,_e=new WeakMap,ot=new WeakMap,Nt=new WeakMap,at=new WeakMap,it=new WeakMap,Lt=new WeakMap,ct=new WeakMap,J=new WeakMap,lt=new WeakMap,Ft=new WeakMap,qt=new WeakMap,oe=new WeakMap,Bt=new WeakMap,jt=new WeakMap,ut=new WeakMap,_r=new WeakMap,q=new WeakSet,gr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},_s=function(){if(this.receivedMessages.length===0)throw new m("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 m("stream ended without producing a content block with type=text");return t.join(" ")},br=function(){if(this.ended)return;f(this,Q,void 0,"f")},yr=function(t){if(this.ended)return;let r=a(this,q,"m",bs).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text")this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{if(s.type==="text")this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{if(ws(s)&&s.input)this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{if(s.type==="thinking")this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{if(s.type==="thinking")this._emit("signature",s.signature);break}default:xs(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(pr(r,a(this,_e,"f"),{logger:a(this,ut,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,Q,r,"f");break}case"content_block_start":case"message_delta":break}},wr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,Q,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,Q,void 0,"f"),pr(t,a(this,_e,"f"),{logger:a(this,ut,"f")})},bs=function(t){let r=a(this,Q,"f");if(t.type==="message_start"){if(r)throw new m(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new m(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":if(r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null)r.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)r.usage.server_tool_use=t.usage.server_tool_use;return r;case"content_block_start":return r.content.push({...t.content_block}),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text")r.content[t.index]={...s,text:(s.text||"")+t.delta.text};break}case"citations_delta":{if(s?.type==="text")r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]};break}case"input_json_delta":{if(s&&ws(s)){let n=s[ys]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,ys,{value:n,enumerable:!1,writable:!0}),n)o.input=Et(n);r.content[t.index]=o}break}case"thinking_delta":{if(s?.type==="thinking")r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking};break}case"signature_delta":{if(s?.type==="thinking")r.content[t.index]={...s,signature:t.delta.signature};break}default:xs(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function xs(e){}class dt extends y{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",B,{query:e,...t})}delete(e,t){return this._client.delete(d`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(d`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:u([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,n)=>fe.fromResponse(n.response,n.controller))}}class ae extends y{constructor(){super(...arguments);this.batches=new dt(this._client)}create(e,t){if(e.model in Ss)console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Ss[e.model]}
34
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(En.includes(e.model)&&e.thinking&&e.thinking.type==="enabled")console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let n=vt[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,n)}let s=Rt(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??600000,...t,headers:u([s,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then((r)=>mr(r,e,{logger:this._client.logger??console}))}stream(e,t){return ht.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}var Ss={"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-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},En=["claude-mythos-preview","claude-opus-4-6"];ae.Batches=dt;class be extends y{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/models/${e}`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models",B,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}var ft=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0;return};var xr,Sr,Ut,ks,Ps="\\n\\nHuman:",Rs="\\n\\nAssistant:";class S{constructor({baseURL:e=ft("ANTHROPIC_BASE_URL"),apiKey:t=ft("ANTHROPIC_API_KEY")??null,authToken:r=ft("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){xr.add(this),Ut.set(this,void 0);let n={apiKey:t,authToken:r,...s,baseURL:e||"https://api.anthropic.com"};if(!n.dangerouslyAllowBrowser&&qr())throw new m(`It looks like you're running in a browser-like environment.
35
35
 
36
36
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
37
37
  If you understand the risks and have appropriate mitigations in place,
38
38
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
39
39
 
40
40
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
41
- `);this.baseURL=n.baseURL,this.timeout=n.timeout??kr.DEFAULT_TIMEOUT,this.logger=n.logger??console;let o="warn";this.logLevel=o,this.logLevel=Yt(n.logLevel,"ClientOptions.logLevel",this)??Yt(ft("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??jr(),f(this,Ut,Hr,"f"),this._options=n,this.apiKey=typeof t==="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(e.get("x-api-key")||e.get("authorization"))return;if(this.apiKey&&e.get("x-api-key"))return;if(t.has("x-api-key"))return;if(this.authToken&&e.get("authorization"))return;if(t.has("authorization"))return;throw 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')}async authHeaders(e){return u([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey==null)return;return u([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken==null)return;return u([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Wr(e)}getUserAgent(){return`${this.constructor.name}/JS ${V}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jt()}`}makeStatusError(e,t,r,s){return k.generate(e,t,r,s)}buildURL(e,t,r){let s=!a(this,Sr,"m",Rs).call(this)&&r||this.baseURL,n=Ir(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(n.searchParams);if(!Gt(o)||!Gt(c))t={...c,...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128000>600)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Z(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:c,timeout:i}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:c,options:s});let h="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),b=r===void 0?"":`, retryOf: ${r}`,g=Date.now();if(R(this).debug(`[${h}] sending request`,H({retryOfRequestLogID:r,method:s.method,url:c,options:s,headers:o.headers})),s.signal?.aborted)throw new E;let _=new AbortController,l=await this.fetchWithTimeout(c,o,i,_).catch(ye),p=Date.now();if(l instanceof globalThis.Error){let N=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new E;let L=U(l)||/timed? ?out/i.test(String(l)+("cause"in l?String(l.cause):""));if(t)return R(this).info(`[${h}] connection ${L?"timed out":"failed"} - ${N}`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (${N})`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),this.retryRequest(s,t,r??h);if(R(this).info(`[${h}] connection ${L?"timed out":"failed"} - error; no more retries left`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (error; no more retries left)`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),L)throw new we;throw new Y({cause:l})}let w=[...l.headers.entries()].filter(([N])=>N==="request-id").map(([N,L])=>", "+N+": "+JSON.stringify(L)).join(""),v=`[${h}${b}${w}] ${o.method} ${c} ${l.ok?"succeeded":"failed"} with status ${l.status} in ${p-g}ms`;if(!l.ok){let N=await this.shouldRetry(l);if(t&&N){let pt=`retrying, ${t} attempts remaining`;return await Ur(l.body),R(this).info(`${v} - ${pt}`),R(this).debug(`[${h}] response error (${pt})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),this.retryRequest(s,t,r??h,l.headers)}let L=N?"error; no more retries left":"error; not retryable";R(this).info(`${v} - ${L}`);let Mr=await l.text().catch((pt)=>ye(pt).message),Tr=gt(Mr),Ar=Tr?void 0:Mr;throw R(this).debug(`[${h}] response error (${L})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,message:Ar,durationMs:Date.now()-g})),this.makeStatusError(l.status,Tr,Ar,l.headers)}return R(this).info(v),R(this).debug(`[${h}] response start`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),{response:l,options:s,controller:_,requestLogID:h,retryOfRequestLogID:r,startTime:g}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new St(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...c}=t||{},i=this._makeAbort(s);if(n)n.addEventListener("abort",i,{once:!0});let h=setTimeout(i,r),b=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==="object"&&c.body!==null&&Symbol.asyncIterator in c.body,g={signal:s.signal,...b?{duplex:"half"}:{},method:"GET",...c};if(o)g.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(h)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let i=parseFloat(o);if(!Number.isNaN(i))n=i}let c=s?.get("retry-after");if(c&&!n){let i=parseFloat(c);if(!Number.isNaN(i))n=i*1000;else n=Date.parse(c)-Date.now()}if(n===void 0){let i=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,i)}return await Or(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),c=1-Math.random()*0.25;return o*c*1000}calculateNonstreamingTimeout(e,t){if(3600000*e/128000>600000||t!=null&&e>t)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:c}=r,i=this.buildURL(n,o,c);if("timeout"in r)Cr("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:b}=this.buildBody({options:r}),g=await this.buildHeaders({options:e,method:s,bodyHeaders:h,retryCount:t});return{req:{method:s,headers:g,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&b instanceof globalThis.ReadableStream&&{duplex:"half"},...b&&{body:b},...this.fetchOptions??{},...r.fetchOptions??{}},url:i,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=u([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Br(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=u([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:_t(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return a(this,Ut,"f").call(this,{body:e,headers:r})}}kr=S,Ut=new WeakMap,Sr=new WeakSet,Rs=function(){return this.baseURL!=="https://api.anthropic.com"};S.Anthropic=kr;S.HUMAN_PROMPT=Es;S.AI_PROMPT=Ms;S.DEFAULT_TIMEOUT=600000;S.AnthropicError=m;S.APIError=k;S.APIConnectionError=Y;S.APIConnectionTimeoutError=we;S.APIUserAbortError=E;S.NotFoundError=Pe;S.ConflictError=Re;S.RateLimitError=Ee;S.BadRequestError=xe;S.AuthenticationError=Se;S.InternalServerError=Me;S.PermissionDeniedError=ke;S.UnprocessableEntityError=ve;S.toFile=kt;class j extends S{constructor(){super(...arguments);this.completions=new ge(this),this.messages=new ae(this),this.models=new be(this),this.beta=new M(this)}}j.Completions=ge;j.Messages=ae;j.Models=be;j.Beta=M;function As(e,t){if(e)return e;if(nr("PI_CACHE_RETENTION",t)==="long")return"long";return"short"}function In(e,t,r){let s=As(t,r);if(s==="none")return{retention:s};let n=s==="long"&&Dt(e).supportsLongCacheRetention?"1h":void 0;return{retention:s,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}var $n="2.1.75",Cn=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],On=new Map(Cn.map((e)=>[e.toLowerCase(),e])),Wt=(e)=>On.get(e.toLowerCase())??e,Nn=(e,t)=>{if(t&&t.length>0){let r=e.toLowerCase(),s=t.find((n)=>n.name.toLowerCase()===r);if(s)return s.name}return e};function Ln(e){if(!e.some((n)=>n.type==="image"))return Fe(e.map((n)=>n.text).join(`
42
- `));let r=e.map((n)=>{if(n.type==="text")return{type:"text",text:Fe(n.text)};return{type:"image",source:{type:"base64",media_type:n.mimeType,data:n.data}}});if(!r.some((n)=>n.type==="text"))r.unshift({type:"text",text:"(see attached image)"});return r}var Fn="fine-grained-tool-streaming-2025-05-14",qn="interleaved-thinking-2025-05-14";function Dt(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??!1,supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1,supportsStrictTools:e.compat?.supportsStrictTools??!1,supportsToolReferences:e.compat?.supportsToolReferences??Bn(e)}}function Bn(e){if(e.provider!=="anthropic"||e.id.includes("haiku"))return!1;let t=e.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);if(!t)return!1;let r=Number(t[1]),s=t[2]&&t[2].length<8?Number(t[2]):0;return r>4||r===4&&s>=5}function Pr(...e){let t={};for(let r of e)if(r)Object.assign(t,r);return t}function Rr(e,t){if(!e)return!1;let r=t.toLowerCase();for(let[s,n]of Object.entries(e))if(s.toLowerCase()===r&&n!==null&&n.trim().length>0)return!0;return!1}function Is(e,t,r){if(t)return;if(Rr(r,"authorization")||Rr(r,"x-api-key")||Rr(r,"cf-aig-authorization"))return;throw Error(`No API key for provider: ${e}`)}var jn=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function $s(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
43
- `),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function vr(e,t){if(e==="")return $s(t);if(t.raw.push(e),e.startsWith(":"))return null;let r=e.indexOf(":"),s=r===-1?e:e.slice(0,r),n=r===-1?"":e.slice(r+1);if(n.startsWith(" "))n=n.slice(1);if(s==="event")t.event=n;else if(s==="data")t.data.push(n);return null}function Un(e){let t=e.indexOf("\r"),r=e.indexOf(`
44
- `);if(t===-1)return r;if(r===-1)return t;return Math.min(t,r)}function Ht(e){let t=Un(e);if(t===-1)return null;let r=t+1;if(e[t]==="\r"&&e[r]===`
45
- `)r+=1;return{line:e.slice(0,t),rest:e.slice(r)}}async function*Hn(e,t){let r=e.getReader(),s=new TextDecoder,n={event:null,data:[],raw:[]},o="";try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{value:h,done:b}=await r.read();if(b)break;o+=s.decode(h,{stream:!0});let g=Ht(o);while(g){o=g.rest;let _=vr(g.line,n);if(_)yield _;g=Ht(o)}}o+=s.decode();let c=Ht(o);while(c){o=c.rest;let h=vr(c.line,n);if(h)yield h;c=Ht(o)}if(o.length>0){let h=vr(o,n);if(h)yield h}let i=$s(n);if(i)yield i}finally{r.releaseLock()}}async function*Wn(e,t){if(!e.body)throw Error("Attempted to iterate over an Anthropic response with no body");let r=!1,s=!1;for await(let n of Hn(e.body,t)){if(n.event==="error")throw Error(n.data);if(!jn.has(n.event??""))continue;try{let o=zd(n.data);if(o.type==="message_start")r=!0;else if(o.type==="message_stop")s=!0;yield o}catch(o){let c=o instanceof Error?o.message:String(o);throw Error(`Could not parse Anthropic SSE event ${n.event}: ${c}; data=${n.data}; raw=${n.raw.join("\\n")}`)}}if(r&&!s)throw Error("Anthropic stream ended before message_stop")}var Er=(e,t,r)=>{let s=new Vt;return(async()=>{let n={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o,c;if(r?.client)o=r.client,c=!1;else{let l=r?.apiKey;Is(e.provider,l,r?.headers);let p;if(e.provider==="github-copilot"){let L=ws(t.messages);p=xs({messages:t.messages,hasImages:L})}let v=As(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,N=Vn(e,l,r?.interleavedThinking??!0,Qn(e,t),r?.headers,p,v);o=N.client,c=N.isOAuthToken}let i=Xn(e,t,c,r),h=await r?.onPayload?.(i,e);if(h!==void 0)i=h;let b={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},g=await $o(()=>o.messages.create({...i,stream:!0},b).asResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:g.status,headers:Xr(g.headers)},e),s.push({type:"start",partial:n});let _=n.content;for await(let l of Wn(g,r?.signal))if(l.type==="message_start")n.responseId=l.message.id,n.usage.input=l.message.usage.input_tokens||0,n.usage.output=l.message.usage.output_tokens||0,n.usage.cacheRead=l.message.usage.cache_read_input_tokens||0,n.usage.cacheWrite=l.message.usage.cache_creation_input_tokens||0,n.usage.cacheWrite1h=l.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,en(e,n.usage);else if(l.type==="content_block_start"){if(l.content_block.type==="text"){let p={type:"text",text:"",index:l.index};n.content.push(p),s.push({type:"text_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="thinking"){let p={type:"thinking",thinking:"",thinkingSignature:"",index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="redacted_thinking"){let p={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:l.content_block.data,redacted:!0,index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="tool_use"){let p={type:"toolCall",id:l.content_block.id,name:c?Nn(l.content_block.name,t.tools):l.content_block.name,arguments:l.content_block.input??{},partialJson:"",index:l.index};n.content.push(p),s.push({type:"toolcall_start",contentIndex:n.content.length-1,partial:n})}}else if(l.type==="content_block_delta"){if(l.delta.type==="text_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="text")w.text+=l.delta.text,s.push({type:"text_delta",contentIndex:p,delta:l.delta.text,partial:n})}else if(l.delta.type==="thinking_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinking+=l.delta.thinking,s.push({type:"thinking_delta",contentIndex:p,delta:l.delta.thinking,partial:n})}else if(l.delta.type==="input_json_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="toolCall")w.partialJson+=l.delta.partial_json,w.arguments=Qr(w.partialJson),s.push({type:"toolcall_delta",contentIndex:p,delta:l.delta.partial_json,partial:n})}else if(l.delta.type==="signature_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinkingSignature=w.thinkingSignature||"",w.thinkingSignature+=l.delta.signature}}else if(l.type==="content_block_stop"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w){if(delete w.index,w.type==="text")s.push({type:"text_end",contentIndex:p,content:w.text,partial:n});else if(w.type==="thinking")s.push({type:"thinking_end",contentIndex:p,content:w.thinking,partial:n});else if(w.type==="toolCall")w.arguments=Qr(w.partialJson),delete w.partialJson,s.push({type:"toolcall_end",contentIndex:p,toolCall:w,partial:n})}}else if(l.type==="message_delta"){if(l.delta.stop_reason){let p=Yn(l.delta.stop_reason,l.delta.stop_details);if(n.stopReason=p.stopReason,p.errorMessage)n.errorMessage=p.errorMessage}if(l.usage){if(l.usage.input_tokens!=null)n.usage.input=l.usage.input_tokens;if(l.usage.output_tokens!=null)n.usage.output=l.usage.output_tokens;if(l.usage.cache_read_input_tokens!=null)n.usage.cacheRead=l.usage.cache_read_input_tokens;if(l.usage.cache_creation_input_tokens!=null)n.usage.cacheWrite=l.usage.cache_creation_input_tokens;let p=l.usage.output_tokens_details?.thinking_tokens;if(p!=null)n.usage.reasoning=p}n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,en(e,n.usage)}if(r?.signal?.aborted)throw Error("Request was aborted");if(n.stopReason==="aborted"||n.stopReason==="error")throw Error(n.errorMessage||"An unknown error occurred");s.push({type:"done",reason:n.stopReason,message:n}),s.end()}catch(o){for(let c of n.content)delete c.index,delete c.partialJson;n.stopReason=r?.signal?.aborted?"aborted":"error",n.errorMessage=o instanceof Error?o.message:JSON.stringify(o),s.push({type:"error",reason:n.stopReason,error:n}),s.end()}})(),s};function Dn(e,t){let r=t?e.thinkingLevelMap?.[t]:void 0;if(typeof r==="string")return r;switch(t){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var Gl=(e,t,r)=>{Is(e.provider,r?.apiKey,r?.headers);let s=xr(e,t,r,r?.apiKey);if(!r?.reasoning)return Er(e,t,{...s,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let c=Dn(e,r.reasoning);return Er(e,t,{...s,thinkingEnabled:!0,effort:c})}let n=Bp(s.maxTokens,e.maxTokens,r.reasoning,r.thinkingBudgets),o=Fd(e,t,n.maxTokens);return Er(e,t,{...s,maxTokens:o,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(n.thinkingBudget,Math.max(0,o-1024))})};function Jn(e){return e.includes("sk-ant-oat")}function Vn(e,t,r,s,n,o,c){let i=r&&e.compat?.forceAdaptiveThinking!==!0,h=[];if(s)h.push(Fn);if(i)h.push(qn);if(e.provider==="github-copilot")return{client:new j({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Pr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},e.headers,o,n)}),isOAuthToken:!1};if(t&&Jn(t))return{client:new j({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Pr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...h].join(","),"user-agent":`claude-cli/${$n}`,"x-app":"cli"},e.headers,n)}),isOAuthToken:!0};let b=c&&Dt(e).sendSessionAffinityHeaders?{"x-session-affinity":c}:{},g=Pr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},b,e.headers,n);return{client:new j({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:g}),isOAuthToken:!1}}function Xn(e,t,r,s){let{cacheControl:n}=In(e,s?.cacheRetention,s?.env),o=Dt(e),c=ao(t.messages,e,Kn),i=r?Wt:(p)=>p,h=vs({...t,messages:c},o.supportsToolReferences,i),b=h.immediate,g=[...h.deferred.values()];if(b.length===0&&g.length>0)b=g,g=[];let _=new Set(g.map((p)=>i(p.name))),l={model:e.id,messages:zn(c,r,n,o.allowEmptySignature,_,i),max_tokens:s?.maxTokens??e.maxTokens,stream:!0};if(r){if(l.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...n?{cache_control:n}:{}}],t.systemPrompt)l.system.push({type:"text",text:Fe(t.systemPrompt),...n?{cache_control:n}:{}})}else if(t.systemPrompt)l.system=[{type:"text",text:Fe(t.systemPrompt),...n?{cache_control:n}:{}}];if(s?.temperature!==void 0&&!s?.thinkingEnabled&&o.supportsTemperature)l.temperature=s.temperature;if(b.length>0||g.length>0)l.tools=[...Ts(b,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?n:void 0),...Ts(g,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,void 0,!0)];if(e.reasoning){if(s?.thinkingEnabled){let p=s.thinkingDisplay??"summarized";if(e.compat?.forceAdaptiveThinking===!0){if(l.thinking={type:"adaptive",display:p},s.effort)l.output_config=s.effort==="xhigh"?{effort:s.effort}:{effort:s.effort}}else l.thinking={type:"enabled",budget_tokens:s.thinkingBudgetTokens||1024,display:p}}else if(s?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null)l.thinking={type:"disabled"}}if(s?.metadata){let p=s.metadata.user_id;if(typeof p==="string")l.metadata={user_id:p}}if(s?.toolChoice)if(typeof s.toolChoice==="string")l.tool_choice={type:s.toolChoice};else l.tool_choice=s.toolChoice;return l}function Kn(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Gn(e,t,r,s,n){let o=[];for(let i of e.addedToolNames??[]){let h=n(i);if(!r.has(h)||s.has(h))continue;s.add(h),o.push({type:"tool_reference",tool_name:t?Wt(i):i})}let c=Ln(e.content);return{toolResult:{type:"tool_result",tool_use_id:e.toolCallId,content:o.length>0?o:c,is_error:e.isError},siblingContent:o.length===0?[]:typeof c==="string"?[{type:"text",text:c}]:c}}function zn(e,t,r,s=!1,n=new Set,o=(c)=>c){let c=[],i=new Set;for(let h=0;h<e.length;h++){let b=e[h];if(b.role==="user")if(typeof b.content==="string"){if(b.content.trim().length>0)c.push({role:"user",content:Fe(b.content)})}else{let _=b.content.map((l)=>{if(l.type==="text")return{type:"text",text:Fe(l.text)};else return{type:"image",source:{type:"base64",media_type:l.mimeType,data:l.data}}}).filter((l)=>{if(l.type==="text")return l.text.trim().length>0;return!0});if(_.length===0)continue;c.push({role:"user",content:_})}else if(b.role==="assistant"){let g=[];for(let _ of b.content)if(_.type==="text"){if(_.text.trim().length===0)continue;g.push({type:"text",text:Fe(_.text)})}else if(_.type==="thinking"){if(_.redacted){g.push({type:"redacted_thinking",data:_.thinkingSignature});continue}let l=_.thinkingSignature,p=!!l&&l.trim().length>0;if(_.thinking.trim().length===0&&!p)continue;if(!p)g.push(s?{type:"thinking",thinking:Fe(_.thinking),signature:""}:{type:"text",text:Fe(_.thinking)});else g.push({type:"thinking",thinking:Fe(_.thinking),signature:l})}else if(_.type==="toolCall")g.push({type:"tool_use",id:_.id,name:t?Wt(_.name):_.name,input:_.arguments??{}});if(g.length===0)continue;c.push({role:"assistant",content:g})}else if(b.role==="toolResult"){let g=[],_=[],l=h;while(l<e.length&&e[l].role==="toolResult"){let p=Gn(e[l],t,n,i,o);g.push(p.toolResult),_.push(...p.siblingContent),l++}h=l-1,c.push({role:"user",content:[...g,..._]})}}if(r&&c.length>0){let h=c[c.length-1];if(h.role==="user"){if(Array.isArray(h.content)){let b=h.content[h.content.length-1];if(b&&(b.type==="text"||b.type==="image"||b.type==="tool_result"))b.cache_control=r}else if(typeof h.content==="string")h.content=[{type:"text",text:h.content,cache_control:r}]}}return c}function Qn(e,t){return!!t.tools?.length&&!Dt(e).supportsEagerToolInputStreaming}function Ts(e,t,r,s,n,o=!1){if(!e)return[];return e.map((c,i)=>{let h=oo(c,s),b=c.parameters,g={type:"object",properties:b.properties??{},required:b.required??[]},_=h===!0?{...c.parameters,...g}:g;return{name:t?Wt(c.name):c.name,description:c.description,...r?{eager_input_streaming:!0}:{},...h===!0?{strict:!0}:{},input_schema:_,...o?{defer_loading:!0}:{},...n&&i===e.length-1?{cache_control:n}:{}}})}function Yn(e,t){switch(e){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:t?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error"};default:throw Error(`Unhandled stop reason: ${e}`)}}export{Er as stream,Gl as streamSimple};
41
+ `);this.baseURL=n.baseURL,this.timeout=n.timeout??Sr.DEFAULT_TIMEOUT,this.logger=n.logger??console;let o="warn";this.logLevel=o,this.logLevel=Qt(n.logLevel,"ClientOptions.logLevel",this)??Qt(ft("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??jr(),f(this,Ut,Hr,"f"),this._options=n,this.apiKey=typeof t==="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(e.get("x-api-key")||e.get("authorization"))return;if(this.apiKey&&e.get("x-api-key"))return;if(t.has("x-api-key"))return;if(this.authToken&&e.get("authorization"))return;if(t.has("authorization"))return;throw 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')}async authHeaders(e){return u([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey==null)return;return u([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken==null)return;return u([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Dr(e)}getUserAgent(){return`${this.constructor.name}/JS ${V}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jt()}`}makeStatusError(e,t,r,s){return k.generate(e,t,r,s)}buildURL(e,t,r){let s=!a(this,xr,"m",ks).call(this)&&r||this.baseURL,n=Ar(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(n.searchParams);if(!Kt(o)||!Kt(c))t={...c,...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128000>600)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Z(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:c,timeout:i}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:c,options:s});let h="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),b=r===void 0?"":`, retryOf: ${r}`,g=Date.now();if(R(this).debug(`[${h}] sending request`,H({retryOfRequestLogID:r,method:s.method,url:c,options:s,headers:o.headers})),s.signal?.aborted)throw new E;let _=new AbortController,l=await this.fetchWithTimeout(c,o,i,_).catch(ye),p=Date.now();if(l instanceof globalThis.Error){let N=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new E;let L=U(l)||/timed? ?out/i.test(String(l)+("cause"in l?String(l.cause):""));if(t)return R(this).info(`[${h}] connection ${L?"timed out":"failed"} - ${N}`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (${N})`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),this.retryRequest(s,t,r??h);if(R(this).info(`[${h}] connection ${L?"timed out":"failed"} - error; no more retries left`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (error; no more retries left)`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),L)throw new we;throw new Y({cause:l})}let w=[...l.headers.entries()].filter(([N])=>N==="request-id").map(([N,L])=>", "+N+": "+JSON.stringify(L)).join(""),v=`[${h}${b}${w}] ${o.method} ${c} ${l.ok?"succeeded":"failed"} with status ${l.status} in ${p-g}ms`;if(!l.ok){let N=await this.shouldRetry(l);if(t&&N){let pt=`retrying, ${t} attempts remaining`;return await Ur(l.body),R(this).info(`${v} - ${pt}`),R(this).debug(`[${h}] response error (${pt})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),this.retryRequest(s,t,r??h,l.headers)}let L=N?"error; no more retries left":"error; not retryable";R(this).info(`${v} - ${L}`);let Er=await l.text().catch((pt)=>ye(pt).message),Mr=gt(Er),Tr=Mr?void 0:Er;throw R(this).debug(`[${h}] response error (${L})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,message:Tr,durationMs:Date.now()-g})),this.makeStatusError(l.status,Mr,Tr,l.headers)}return R(this).info(v),R(this).debug(`[${h}] response start`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),{response:l,options:s,controller:_,requestLogID:h,retryOfRequestLogID:r,startTime:g}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new St(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...c}=t||{},i=this._makeAbort(s);if(n)n.addEventListener("abort",i,{once:!0});let h=setTimeout(i,r),b=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==="object"&&c.body!==null&&Symbol.asyncIterator in c.body,g={signal:s.signal,...b?{duplex:"half"}:{},method:"GET",...c};if(o)g.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(h)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let i=parseFloat(o);if(!Number.isNaN(i))n=i}let c=s?.get("retry-after");if(c&&!n){let i=parseFloat(c);if(!Number.isNaN(i))n=i*1000;else n=Date.parse(c)-Date.now()}if(n===void 0){let i=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,i)}return await Or(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),c=1-Math.random()*0.25;return o*c*1000}calculateNonstreamingTimeout(e,t){if(3600000*e/128000>600000||t!=null&&e>t)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:c}=r,i=this.buildURL(n,o,c);if("timeout"in r)$r("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:b}=this.buildBody({options:r}),g=await this.buildHeaders({options:e,method:s,bodyHeaders:h,retryCount:t});return{req:{method:s,headers:g,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&b instanceof globalThis.ReadableStream&&{duplex:"half"},...b&&{body:b},...this.fetchOptions??{},...r.fetchOptions??{}},url:i,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=u([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Br(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=u([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:_t(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return a(this,Ut,"f").call(this,{body:e,headers:r})}}Sr=S,Ut=new WeakMap,xr=new WeakSet,ks=function(){return this.baseURL!=="https://api.anthropic.com"};S.Anthropic=Sr;S.HUMAN_PROMPT=Ps;S.AI_PROMPT=Rs;S.DEFAULT_TIMEOUT=600000;S.AnthropicError=m;S.APIError=k;S.APIConnectionError=Y;S.APIConnectionTimeoutError=we;S.APIUserAbortError=E;S.NotFoundError=Pe;S.ConflictError=Re;S.RateLimitError=Ee;S.BadRequestError=xe;S.AuthenticationError=Se;S.InternalServerError=Me;S.PermissionDeniedError=ke;S.UnprocessableEntityError=ve;S.toFile=kt;class j extends S{constructor(){super(...arguments);this.completions=new ge(this),this.messages=new ae(this),this.models=new be(this),this.beta=new M(this)}}j.Completions=ge;j.Messages=ae;j.Models=be;j.Beta=M;function Es(e,t){if(e)return e;if(ar("PI_CACHE_RETENTION",t)==="long")return"long";return"short"}function Tn(e,t,r){let s=Es(t,r);if(s==="none")return{retention:s};let n=s==="long"&&Dt(e).supportsLongCacheRetention?"1h":void 0;return{retention:s,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}var An="2.1.75",In=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],$n=new Map(In.map((e)=>[e.toLowerCase(),e])),Wt=(e)=>$n.get(e.toLowerCase())??e,Cn=(e,t)=>{if(t&&t.length>0){let r=e.toLowerCase(),s=t.find((n)=>n.name.toLowerCase()===r);if(s)return s.name}return e};function On(e){if(!e.some((n)=>n.type==="image"))return je(e.map((n)=>n.text).join(`
42
+ `));let r=e.map((n)=>{if(n.type==="text")return{type:"text",text:je(n.text)};return{type:"image",source:{type:"base64",media_type:n.mimeType,data:n.data}}});if(!r.some((n)=>n.type==="text"))r.unshift({type:"text",text:"(see attached image)"});return r}var Nn="fine-grained-tool-streaming-2025-05-14",Ln="interleaved-thinking-2025-05-14";function Dt(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??!1,supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1,supportsStrictTools:e.compat?.supportsStrictTools??!1,supportsToolReferences:e.compat?.supportsToolReferences??Fn(e)}}function Fn(e){if(e.provider!=="anthropic"||e.id.includes("haiku"))return!1;let t=e.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);if(!t)return!1;let r=Number(t[1]),s=t[2]&&t[2].length<8?Number(t[2]):0;return r>4||r===4&&s>=5}function kr(...e){let t={};for(let r of e)if(r)Object.assign(t,r);return t}function Pr(e,t){if(!e)return!1;let r=t.toLowerCase();for(let[s,n]of Object.entries(e))if(s.toLowerCase()===r&&n!==null&&n.trim().length>0)return!0;return!1}function Ms(e,t,r){if(t)return;if(Pr(r,"authorization")||Pr(r,"x-api-key")||Pr(r,"cf-aig-authorization"))return;throw Error(`No API key for provider: ${e}`)}var qn=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function Ts(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
43
+ `),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Rr(e,t){if(e==="")return Ts(t);if(t.raw.push(e),e.startsWith(":"))return null;let r=e.indexOf(":"),s=r===-1?e:e.slice(0,r),n=r===-1?"":e.slice(r+1);if(n.startsWith(" "))n=n.slice(1);if(s==="event")t.event=n;else if(s==="data")t.data.push(n);return null}function Bn(e){let t=e.indexOf("\r"),r=e.indexOf(`
44
+ `);if(t===-1)return r;if(r===-1)return t;return Math.min(t,r)}function Ht(e){let t=Bn(e);if(t===-1)return null;let r=t+1;if(e[t]==="\r"&&e[r]===`
45
+ `)r+=1;return{line:e.slice(0,t),rest:e.slice(r)}}async function*jn(e,t){let r=e.getReader(),s=new TextDecoder,n={event:null,data:[],raw:[]},o="";try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{value:h,done:b}=await r.read();if(b)break;o+=s.decode(h,{stream:!0});let g=Ht(o);while(g){o=g.rest;let _=Rr(g.line,n);if(_)yield _;g=Ht(o)}}o+=s.decode();let c=Ht(o);while(c){o=c.rest;let h=Rr(c.line,n);if(h)yield h;c=Ht(o)}if(o.length>0){let h=Rr(o,n);if(h)yield h}let i=Ts(n);if(i)yield i}finally{r.releaseLock()}}async function*Un(e,t){if(!e.body)throw Error("Attempted to iterate over an Anthropic response with no body");let r=!1,s=!1;for await(let n of jn(e.body,t)){if(n.event==="error")throw Error(n.data);if(!qn.has(n.event??""))continue;try{let o=Wd(n.data);if(o.type==="message_start")r=!0;else if(o.type==="message_stop")s=!0;yield o}catch(o){let c=o instanceof Error?o.message:String(o);throw Error(`Could not parse Anthropic SSE event ${n.event}: ${c}; data=${n.data}; raw=${n.raw.join("\\n")}`)}}if(r&&!s)throw Error("Anthropic stream ended before message_stop")}var vr=(e,t,r)=>{let s=new Yt;return(async()=>{let n={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o,c;if(r?.client)o=r.client,c=!1;else{let l=r?.apiKey;Ms(e.provider,l,r?.headers);let p;if(e.provider==="github-copilot"){let L=ka(t.messages);p=Pa({messages:t.messages,hasImages:L})}let v=Es(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,N=Dn(e,l,r?.interleavedThinking??!0,Gn(e,t),r?.headers,p,v);o=N.client,c=N.isOAuthToken}let i=Jn(e,t,c,r),h=await r?.onPayload?.(i,e);if(h!==void 0)i=h;let b={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},g=await ts(()=>o.messages.create({...i,stream:!0},b).asResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:g.status,headers:on(g.headers)},e),s.push({type:"start",partial:n});let _=n.content;for await(let l of Un(g,r?.signal))if(l.type==="message_start")n.responseId=l.message.id,n.usage.input=l.message.usage.input_tokens||0,n.usage.output=l.message.usage.output_tokens||0,n.usage.cacheRead=l.message.usage.cache_read_input_tokens||0,n.usage.cacheWrite=l.message.usage.cache_creation_input_tokens||0,n.usage.cacheWrite1h=l.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,sn(e,n.usage);else if(l.type==="content_block_start"){if(l.content_block.type==="text"){let p={type:"text",text:"",index:l.index};n.content.push(p),s.push({type:"text_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="thinking"){let p={type:"thinking",thinking:"",thinkingSignature:"",index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="redacted_thinking"){let p={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:l.content_block.data,redacted:!0,index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="tool_use"){let p={type:"toolCall",id:l.content_block.id,name:c?Cn(l.content_block.name,t.tools):l.content_block.name,arguments:l.content_block.input??{},partialJson:"",index:l.index};n.content.push(p),s.push({type:"toolcall_start",contentIndex:n.content.length-1,partial:n})}}else if(l.type==="content_block_delta"){if(l.delta.type==="text_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="text")w.text+=l.delta.text,s.push({type:"text_delta",contentIndex:p,delta:l.delta.text,partial:n})}else if(l.delta.type==="thinking_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinking+=l.delta.thinking,s.push({type:"thinking_delta",contentIndex:p,delta:l.delta.thinking,partial:n})}else if(l.delta.type==="input_json_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="toolCall")w.partialJson+=l.delta.partial_json,w.arguments=Wr(w.partialJson),s.push({type:"toolcall_delta",contentIndex:p,delta:l.delta.partial_json,partial:n})}else if(l.delta.type==="signature_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinkingSignature=w.thinkingSignature||"",w.thinkingSignature+=l.delta.signature}}else if(l.type==="content_block_stop"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w){if(delete w.index,w.type==="text")s.push({type:"text_end",contentIndex:p,content:w.text,partial:n});else if(w.type==="thinking")s.push({type:"thinking_end",contentIndex:p,content:w.thinking,partial:n});else if(w.type==="toolCall")w.arguments=Wr(w.partialJson),delete w.partialJson,s.push({type:"toolcall_end",contentIndex:p,toolCall:w,partial:n})}}else if(l.type==="message_delta"){if(l.delta.stop_reason){let p=zn(l.delta.stop_reason,l.delta.stop_details);if(n.stopReason=p.stopReason,p.errorMessage)n.errorMessage=p.errorMessage}if(l.usage){if(l.usage.input_tokens!=null)n.usage.input=l.usage.input_tokens;if(l.usage.output_tokens!=null)n.usage.output=l.usage.output_tokens;if(l.usage.cache_read_input_tokens!=null)n.usage.cacheRead=l.usage.cache_read_input_tokens;if(l.usage.cache_creation_input_tokens!=null)n.usage.cacheWrite=l.usage.cache_creation_input_tokens;let p=l.usage.output_tokens_details?.thinking_tokens;if(p!=null)n.usage.reasoning=p}n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,sn(e,n.usage)}if(r?.signal?.aborted)throw Error("Request was aborted");if(n.stopReason==="aborted"||n.stopReason==="error")throw Error(n.errorMessage||"An unknown error occurred");s.push({type:"done",reason:n.stopReason,message:n}),s.end()}catch(o){for(let c of n.content)delete c.index,delete c.partialJson;n.stopReason=r?.signal?.aborted?"aborted":"error",n.errorMessage=o instanceof Error?o.message:JSON.stringify(o),s.push({type:"error",reason:n.stopReason,error:n}),s.end()}})(),s};function Hn(e,t){let r=t?e.thinkingLevelMap?.[t]:void 0;if(typeof r==="string")return r;switch(t){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var Gl=(e,t,r)=>{Ms(e.provider,r?.apiKey,r?.headers);let s=Cr(e,t,r,r?.apiKey);if(!r?.reasoning)return vr(e,t,{...s,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let c=Hn(e,r.reasoning);return vr(e,t,{...s,thinkingEnabled:!0,effort:c})}let n=Xp(s.maxTokens,e.maxTokens,r.reasoning,r.thinkingBudgets),o=Kd(e,t,n.maxTokens);return vr(e,t,{...s,maxTokens:o,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(n.thinkingBudget,Math.max(0,o-1024))})};function Wn(e){return e.includes("sk-ant-oat")}function Dn(e,t,r,s,n,o,c){let i=r&&e.compat?.forceAdaptiveThinking!==!0,h=[];if(s)h.push(Nn);if(i)h.push(Ln);if(e.provider==="github-copilot")return{client:new j({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},e.headers,o,n)}),isOAuthToken:!1};if(t&&Wn(t))return{client:new j({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...h].join(","),"user-agent":`claude-cli/${An}`,"x-app":"cli"},e.headers,n)}),isOAuthToken:!0};let b=c&&Dt(e).sendSessionAffinityHeaders?{"x-session-affinity":c}:{},g=kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},b,e.headers,n);return{client:new j({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:g}),isOAuthToken:!1}}function Jn(e,t,r,s){let{cacheControl:n}=Tn(e,s?.cacheRetention,s?.env),o=Dt(e),c=lo(t.messages,e,Vn),i=r?Wt:(p)=>p,h=Ra({...t,messages:c},o.supportsToolReferences,i),b=h.immediate,g=[...h.deferred.values()];if(b.length===0&&g.length>0)b=g,g=[];let _=new Set(g.map((p)=>i(p.name))),l={model:e.id,messages:Kn(c,r,n,o.allowEmptySignature,_,i),max_tokens:s?.maxTokens??e.maxTokens,stream:!0};if(r){if(l.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...n?{cache_control:n}:{}}],t.systemPrompt)l.system.push({type:"text",text:je(t.systemPrompt),...n?{cache_control:n}:{}})}else if(t.systemPrompt)l.system=[{type:"text",text:je(t.systemPrompt),...n?{cache_control:n}:{}}];if(s?.temperature!==void 0&&!s?.thinkingEnabled&&o.supportsTemperature)l.temperature=s.temperature;if(b.length>0||g.length>0)l.tools=[...vs(b,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?n:void 0),...vs(g,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,void 0,!0)];if(e.reasoning){if(s?.thinkingEnabled){let p=s.thinkingDisplay??"summarized";if(e.compat?.forceAdaptiveThinking===!0){if(l.thinking={type:"adaptive",display:p},s.effort)l.output_config=s.effort==="xhigh"?{effort:s.effort}:{effort:s.effort}}else l.thinking={type:"enabled",budget_tokens:s.thinkingBudgetTokens||1024,display:p}}else if(s?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null)l.thinking={type:"disabled"}}if(s?.metadata){let p=s.metadata.user_id;if(typeof p==="string")l.metadata={user_id:p}}if(s?.toolChoice)if(typeof s.toolChoice==="string")l.tool_choice={type:s.toolChoice};else l.tool_choice=s.toolChoice;return l}function Vn(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Xn(e,t,r,s,n){let o=[];for(let i of e.addedToolNames??[]){let h=n(i);if(!r.has(h)||s.has(h))continue;s.add(h),o.push({type:"tool_reference",tool_name:t?Wt(i):i})}let c=On(e.content);return{toolResult:{type:"tool_result",tool_use_id:e.toolCallId,content:o.length>0?o:c,is_error:e.isError},siblingContent:o.length===0?[]:typeof c==="string"?[{type:"text",text:c}]:c}}function Kn(e,t,r,s=!1,n=new Set,o=(c)=>c){let c=[],i=new Set;for(let h=0;h<e.length;h++){let b=e[h];if(b.role==="user")if(typeof b.content==="string"){if(b.content.trim().length>0)c.push({role:"user",content:je(b.content)})}else{let _=b.content.map((l)=>{if(l.type==="text")return{type:"text",text:je(l.text)};else return{type:"image",source:{type:"base64",media_type:l.mimeType,data:l.data}}}).filter((l)=>{if(l.type==="text")return l.text.trim().length>0;return!0});if(_.length===0)continue;c.push({role:"user",content:_})}else if(b.role==="assistant"){let g=[];for(let _ of b.content)if(_.type==="text"){if(_.text.trim().length===0)continue;g.push({type:"text",text:je(_.text)})}else if(_.type==="thinking"){if(_.redacted){g.push({type:"redacted_thinking",data:_.thinkingSignature});continue}let l=_.thinkingSignature,p=!!l&&l.trim().length>0;if(_.thinking.trim().length===0&&!p)continue;if(!p)g.push(s?{type:"thinking",thinking:je(_.thinking),signature:""}:{type:"text",text:je(_.thinking)});else g.push({type:"thinking",thinking:je(_.thinking),signature:l})}else if(_.type==="toolCall")g.push({type:"tool_use",id:_.id,name:t?Wt(_.name):_.name,input:_.arguments??{}});if(g.length===0)continue;c.push({role:"assistant",content:g})}else if(b.role==="toolResult"){let g=[],_=[],l=h;while(l<e.length&&e[l].role==="toolResult"){let p=Xn(e[l],t,n,i,o);g.push(p.toolResult),_.push(...p.siblingContent),l++}h=l-1,c.push({role:"user",content:[...g,..._]})}}if(r&&c.length>0){let h=c[c.length-1];if(h.role==="user"){if(Array.isArray(h.content)){let b=h.content[h.content.length-1];if(b&&(b.type==="text"||b.type==="image"||b.type==="tool_result"))b.cache_control=r}else if(typeof h.content==="string")h.content=[{type:"text",text:h.content,cache_control:r}]}}return c}function Gn(e,t){return!!t.tools?.length&&!Dt(e).supportsEagerToolInputStreaming}function vs(e,t,r,s,n,o=!1){if(!e)return[];return e.map((c,i)=>{let h=io(c,s),b=c.parameters,g={type:"object",properties:b.properties??{},required:b.required??[]},_=h===!0?{...c.parameters,...g}:g;return{name:t?Wt(c.name):c.name,description:c.description,...r?{eager_input_streaming:!0}:{},...h===!0?{strict:!0}:{},input_schema:_,...o?{defer_loading:!0}:{},...n&&i===e.length-1?{cache_control:n}:{}}})}function zn(e,t){switch(e){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:t?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error"};default:throw Error(`Unhandled stop reason: ${e}`)}}export{vr as stream,Gl as streamSimple};