@bkm016/basalt 0.1.11 → 0.1.13
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.
- package/{chunk-7jezts2n.js → chunk-06s9pr82.js} +2 -2
- package/{chunk-msm9hmk9.js → chunk-095adzn5.js} +2 -2
- package/chunk-0a7ft50x.js +18 -0
- package/{chunk-tevejprz.js → chunk-0nedq669.js} +4 -4
- package/chunk-0x9netvr.js +5 -0
- package/{chunk-9as0p561.js → chunk-15ve3nmv.js} +11 -11
- package/chunk-1dbfmejf.js +2 -0
- package/{chunk-hbnmymaq.js → chunk-1q6e3mj7.js} +2 -2
- package/{chunk-wnzvnskb.js → chunk-22az84sh.js} +2 -2
- package/{chunk-ax04trym.js → chunk-2q56egb8.js} +1 -1
- package/{chunk-r4ttdkrz.js → chunk-2tf7qfbx.js} +2 -2
- package/{chunk-a1352w87.js → chunk-2zbj8ny6.js} +2 -2
- package/chunk-302n9g7p.js +2 -0
- package/{chunk-bk4rpnm8.js → chunk-37ndxehw.js} +2 -2
- package/chunk-41das1ty.js +2 -0
- package/{chunk-c71173py.js → chunk-44a7f5ta.js} +6 -6
- package/{chunk-jn5pqy5v.js → chunk-46vy2m29.js} +1 -1
- package/{chunk-1zj3zvw5.js → chunk-4k9t9jvx.js} +4 -4
- package/{chunk-c4qr1f41.js → chunk-4rnmxtpx.js} +2 -2
- package/{chunk-fgwda4m0.js → chunk-4w9zqv0k.js} +1 -1
- package/chunk-6d9r9p91.js +20 -0
- package/chunk-6f4ht2hw.js +2 -0
- package/{chunk-jj4hqbrx.js → chunk-6sea12mw.js} +3 -3
- package/chunk-74wwdx3y.js +3 -0
- package/{chunk-gkf5jwvj.js → chunk-77c2cqp2.js} +1 -1
- package/chunk-7chv3knf.js +2 -0
- package/chunk-86yr2c0r.js +3 -0
- package/{chunk-d0a1jxk5.js → chunk-8cgz8xv7.js} +2 -2
- package/{chunk-tvm4zmgj.js → chunk-959z9efn.js} +2 -2
- package/{chunk-zc9ar0r4.js → chunk-9e8vhzy7.js} +1 -1
- package/chunk-b516bp7n.js +3 -0
- package/chunk-bja7p3em.js +25 -0
- package/chunk-bng72094.js +2 -0
- package/{chunk-a98wma9j.js → chunk-bp61xdsc.js} +1 -1
- package/chunk-bq54argx.js +2 -0
- package/chunk-ct77cdg7.js +2 -0
- package/{chunk-02d3x4mj.js → chunk-dk6fgprw.js} +3 -3
- package/chunk-drett6hb.js +2 -0
- package/{chunk-4gtgqcct.js → chunk-edbq461k.js} +3 -3
- package/{chunk-xh444pfn.js → chunk-f0h2bv11.js} +12 -12
- package/{chunk-8mezk0cb.js → chunk-g2etemv5.js} +2 -2
- package/{chunk-n0ybj4h9.js → chunk-g5p9mj1r.js} +2 -2
- package/{chunk-zyyzk5ha.js → chunk-gpnqmtbk.js} +1 -1
- package/{chunk-q9f4xb0w.js → chunk-h9zxqeqr.js} +3 -3
- package/{chunk-hb4f2v34.js → chunk-jjtt9aq8.js} +3 -3
- package/{chunk-29qrxygd.js → chunk-kbpbrr11.js} +2 -2
- package/chunk-m71pj3g1.js +2 -0
- package/chunk-mdkfm1ak.js +7 -0
- package/chunk-mf04h0yy.js +7 -0
- package/chunk-n22vd4at.js +2 -0
- package/{chunk-c0zfefq8.js → chunk-nbjnwd54.js} +1 -1
- package/{chunk-d5j74pcp.js → chunk-pryvvs96.js} +22 -22
- package/{chunk-13gvs0ax.js → chunk-r1jn77q6.js} +2 -2
- package/{chunk-ypqjfv3a.js → chunk-rn3jwyh1.js} +2 -2
- package/chunk-sgrrxsnz.js +482 -0
- package/chunk-sgz87ht5.js +2 -0
- package/{chunk-stj493dn.js → chunk-snz19yc2.js} +2 -2
- package/{chunk-n2jcx65v.js → chunk-szj85dqe.js} +2 -2
- package/{chunk-nrsd810j.js → chunk-tfhp09nj.js} +2 -2
- package/{chunk-xtq1xpq0.js → chunk-tfhze1vq.js} +2 -2
- package/{chunk-755sy11p.js → chunk-tjg0gcks.js} +1 -1
- package/{chunk-en218k4y.js → chunk-tnj2kqb8.js} +1 -1
- package/{chunk-h1kb8b49.js → chunk-vqm94hz2.js} +2 -2
- package/{chunk-82v8jh1h.js → chunk-xvm0y99b.js} +2 -2
- package/{chunk-asyr3gnq.js → chunk-y23dpz5e.js} +2 -2
- package/{chunk-1n7dat03.js → chunk-y4pvhes1.js} +6 -6
- package/{chunk-bwawt15q.js → chunk-ydzag81d.js} +2 -2
- package/chunk-ymg7mtcx.js +3 -0
- package/chunk-yy1f9jxc.js +4044 -0
- package/{chunk-30rjf7my.js → chunk-z0c8ek0j.js} +5 -5
- package/chunk-zk91579b.js +3 -0
- package/{chunk-jtsve11b.js → chunk-zx75vnw8.js} +18 -18
- package/compiled.js +85 -12
- package/package.json +1 -1
- package/ui-test-worker.js +53 -53
- package/web/{chunk-3a57m7xm.js → chunk-0jbf73pr.js} +3 -3
- package/web/{chunk-dk0fnj87.js → chunk-0rhx7qb8.js} +1 -1
- package/web/{chunk-q8v5j963.js → chunk-0rvwj2wh.js} +2 -2
- package/web/chunk-12qf1r6m.js +1 -0
- package/web/{chunk-2ds0a2z1.js → chunk-14vmr99v.js} +3 -3
- package/web/{chunk-v3dn9bfw.js → chunk-16jc5m0f.js} +1 -1
- package/web/{chunk-f79ajymt.js → chunk-1m6fx2h7.js} +2 -2
- package/web/{chunk-793m5jjh.js → chunk-1xm9x7d6.js} +2 -2
- package/web/{chunk-j4gvtszc.js → chunk-1zwc09e8.js} +2 -2
- package/web/{chunk-mykbcvqz.js → chunk-20jxvmbw.js} +1 -1
- package/web/chunk-2n5xbnrt.js +1 -0
- package/web/{chunk-57pyz29y.js → chunk-2sef2wft.js} +2 -2
- package/web/{chunk-9kkzmss7.js → chunk-2x7vmhm0.js} +3 -3
- package/web/{chunk-cbwvfedy.js → chunk-2y1avvqj.js} +8 -8
- package/web/chunk-36s08nye.js +1 -0
- package/web/chunk-3ctmehg4.js +1 -0
- package/web/{chunk-cpshsp24.js → chunk-3jjksgze.js} +1 -1
- package/web/{chunk-94denx9h.js → chunk-3p9w8sg5.js} +3 -3
- package/web/{chunk-47mbbmst.js → chunk-3wpxymxa.js} +3 -3
- package/web/{chunk-2tsxj613.js → chunk-4py9sndw.js} +9 -9
- package/web/chunk-4swea9sn.js +1 -0
- package/web/chunk-4zz5a483.js +1 -0
- package/web/{chunk-hjyev38w.js → chunk-5cwxhhae.js} +5 -5
- package/web/chunk-5ym5ffd5.js +4 -0
- package/web/{chunk-gten0rpx.js → chunk-6e87m0nm.js} +2 -2
- package/web/{chunk-5ahx98zj.js → chunk-6rsr2cyw.js} +8 -8
- package/web/chunk-6y55gk1n.js +1 -0
- package/web/chunk-7aep7k4v.js +1 -0
- package/web/{chunk-tggja45g.js → chunk-8j4tzff5.js} +4 -4
- package/web/chunk-8tgavnwx.js +1 -0
- package/web/{chunk-zdhyq3ch.js → chunk-97t3ngqf.js} +12 -12
- package/web/{chunk-0hvxb5d5.js → chunk-980zhtht.js} +1 -1
- package/web/chunk-9k7fkx80.js +1 -0
- package/web/{chunk-yrh86m0n.js → chunk-9wz8jne3.js} +1 -1
- package/web/chunk-a00vg115.js +1 -0
- package/web/chunk-a4gbxnm3.js +1 -0
- package/web/{chunk-nhx8pw7p.js → chunk-a6g3nqp0.js} +2 -2
- package/web/{chunk-xjc5fmcr.js → chunk-a9er7a7c.js} +24 -24
- package/web/chunk-atppv8fk.js +1 -0
- package/web/{chunk-xbyrgyy0.js → chunk-awkdw9rw.js} +2 -2
- package/web/{chunk-2f2agfpj.js → chunk-b4gcpsbg.js} +11 -11
- package/web/{chunk-n33753da.js → chunk-b9jry5a3.js} +1 -1
- package/web/chunk-ba9qy65y.js +2 -0
- package/web/chunk-bq6mep6p.js +2 -0
- package/web/chunk-bwy3e58v.js +1 -0
- package/web/{chunk-drchr3yn.js → chunk-c57f714b.js} +2 -2
- package/web/{chunk-e763h2px.js → chunk-c6m4vfn5.js} +118 -118
- package/web/{chunk-mpdeqzc9.js → chunk-cr04125j.js} +9 -9
- package/web/{chunk-dsbyfvwz.js → chunk-cr05dttm.js} +1 -1
- package/web/{chunk-a3pye9ag.js → chunk-ct7z7bea.js} +3 -3
- package/web/{chunk-2weaa3gn.js → chunk-ct90yf8z.js} +2 -2
- package/web/{chunk-gyhr27dm.js → chunk-ddg8rz82.js} +3 -3
- package/web/{chunk-wbwets5x.js → chunk-dmha2y9c.js} +28 -28
- package/web/{chunk-4gc663j0.js → chunk-e57h40qa.js} +6 -6
- package/web/chunk-eeesa5q1.js +1 -0
- package/web/{chunk-4wwd3pfz.js → chunk-eqndhs21.js} +2 -2
- package/web/{chunk-zv73g4qq.js → chunk-eqxy6535.js} +2 -2
- package/web/{chunk-hm8thq7c.js → chunk-et1rsgmp.js} +3 -3
- package/web/chunk-f7jpakwh.js +1 -0
- package/web/{chunk-enryqmj7.js → chunk-fnvgdvrg.js} +5 -5
- package/web/chunk-fp62avjh.js +1 -0
- package/web/{chunk-6jb2zyp6.js → chunk-frnh4zqf.js} +2 -2
- package/web/chunk-g0be12na.js +1 -0
- package/web/{chunk-1zfxaafq.js → chunk-g7hqafb8.js} +1 -1
- package/web/{chunk-kfbgvh0c.js → chunk-ga07tv37.js} +1 -1
- package/web/chunk-gr163fex.js +1 -0
- package/web/chunk-gx340asc.js +1 -0
- package/web/chunk-gxtz10wf.js +1 -0
- package/web/chunk-h0c42zy3.js +1 -0
- package/web/{chunk-b3j07x0n.js → chunk-h1k2kqbs.js} +6 -6
- package/web/{chunk-pq56b3mq.js → chunk-h6k1x096.js} +2 -2
- package/web/{chunk-885kpj14.js → chunk-jccz14ye.js} +2 -2
- package/web/{chunk-1t38sgrk.js → chunk-jh33m2mq.js} +4 -4
- package/web/{chunk-g0rtcedn.js → chunk-jh3k7xex.js} +3 -3
- package/web/{chunk-nafe18y9.js → chunk-jpem3qvs.js} +10 -10
- package/web/{chunk-s0xy00v5.js → chunk-k0cg4n2k.js} +2 -2
- package/web/chunk-k9qnvx86.js +2 -0
- package/web/chunk-kcnj0gan.js +1 -0
- package/web/{chunk-8csw0mvf.js → chunk-ke8dffnk.js} +2 -2
- package/web/chunk-kpp5xqsb.js +1 -0
- package/web/chunk-m33yted6.js +1 -0
- package/web/chunk-me5jqqn6.js +1 -0
- package/web/{chunk-tpdcrrf1.js → chunk-mkxeenph.js} +1 -1
- package/web/chunk-mnf4ngj9.js +2 -0
- package/web/{chunk-30aeb767.js → chunk-mykrm8ba.js} +2 -2
- package/web/chunk-mzqqwbmr.js +1 -0
- package/web/chunk-mzzaet63.js +1 -0
- package/web/chunk-npyrdsf8.css +1 -0
- package/web/chunk-p6e2vr51.js +34 -0
- package/web/chunk-p7pa02k9.js +2 -0
- package/web/chunk-q34as3v6.js +1 -0
- package/web/{chunk-27812gqr.js → chunk-q4vy3dkk.js} +3 -3
- package/web/chunk-q6c8p73w.js +1 -0
- package/web/{chunk-m24yb8md.js → chunk-qb8mbptk.js} +1 -1
- package/web/{chunk-b6sqwmq7.js → chunk-qbmtah1x.js} +1 -1
- package/web/{chunk-ydtrc1ay.js → chunk-qh62nkem.js} +2 -2
- package/web/chunk-qn93we3a.js +1 -0
- package/web/{chunk-3ftb27f3.js → chunk-qq06x2ce.js} +8 -8
- package/web/{chunk-fj753yzt.js → chunk-qq6m2my8.js} +2 -2
- package/web/chunk-r1f1egve.js +1 -0
- package/web/chunk-s935z8er.js +2 -0
- package/web/{chunk-90fkdzx3.js → chunk-sq75q603.js} +21 -21
- package/web/{chunk-05mvzx00.js → chunk-ss96cz1f.js} +1 -1
- package/web/{chunk-3b4wqmnh.js → chunk-t82sngk9.js} +7 -7
- package/web/chunk-tt9410zw.js +8 -0
- package/web/{chunk-8151c970.js → chunk-v4cqc9f9.js} +1 -1
- package/web/chunk-ve8gy05p.js +1142 -0
- package/web/chunk-vg1ebkce.js +1 -0
- package/web/{chunk-g31dbnzm.js → chunk-vk7ch6fh.js} +5 -5
- package/web/chunk-vnt34mkb.js +1 -0
- package/web/{chunk-59nk506k.js → chunk-w28dn4dw.js} +1 -1
- package/web/{chunk-ppjw1mps.js → chunk-w4tfad6c.js} +4 -4
- package/web/{chunk-36dc7tcg.js → chunk-wpxtkxjt.js} +2 -2
- package/web/chunk-xcyqd7cn.js +1 -0
- package/web/chunk-xe121vg7.js +1 -0
- package/web/chunk-xh4xn1az.js +1 -0
- package/web/{chunk-d4519smc.js → chunk-xk1vkcj4.js} +15 -15
- package/web/chunk-xrk5ewsn.js +1 -0
- package/web/{chunk-96xhmmqz.js → chunk-xvm66b7v.js} +5 -5
- package/web/chunk-xxmaqj1m.js +2 -0
- package/web/chunk-xzwxcxb4.js +1 -0
- package/web/{chunk-7dycbjxn.js → chunk-y9waq403.js} +4 -4
- package/web/chunk-ydhnkws0.js +1 -0
- package/web/{chunk-3020mmp1.js → chunk-yn4t5s9r.js} +1 -1
- package/web/chunk-ys2tns0p.js +1 -0
- package/web/chunk-zb61mf0a.js +1 -0
- package/web/{chunk-g4as4zzd.js → chunk-ze6azq7z.js} +4 -4
- package/web/chunk-zh7193nq.js +2 -0
- package/web/chunk-zqcg6frm.js +1 -0
- package/web/{chunk-qykt7avq.js → chunk-zxrbbbtp.js} +2 -2
- package/web/index.html +1 -1
- package/worker.js +1 -1
- package/chunk-38g3gctw.js +0 -3
- package/chunk-3k627vf2.js +0 -3
- package/chunk-4dw43syb.js +0 -2
- package/chunk-7zkswxvk.js +0 -2
- package/chunk-95964592.js +0 -25
- package/chunk-a1rb1a48.js +0 -20
- package/chunk-b2bxqeb4.js +0 -2
- package/chunk-bdjr0kfr.js +0 -7
- package/chunk-bpw6q7g0.js +0 -3
- package/chunk-c6q04xrd.js +0 -3
- package/chunk-cmwdjes8.js +0 -18
- package/chunk-dfh9m9n7.js +0 -7
- package/chunk-dq01v5eq.js +0 -2
- package/chunk-e1x629v0.js +0 -5
- package/chunk-gbjn6d81.js +0 -2
- package/chunk-jymx3a77.js +0 -3951
- package/chunk-m1eam0s5.js +0 -2
- package/chunk-mbpb5c7w.js +0 -2
- package/chunk-pnspvnyd.js +0 -2
- package/chunk-pz2afna8.js +0 -2
- package/chunk-qaeyhe65.js +0 -2
- package/chunk-qnkrrwmg.js +0 -2
- package/chunk-v3ee9z3f.js +0 -2
- package/chunk-vtqr7dm8.js +0 -3
- package/chunk-zq32mwxj.js +0 -479
- package/web/chunk-086dshck.js +0 -1
- package/web/chunk-0fy590s0.js +0 -1
- package/web/chunk-0mdf1qja.js +0 -1
- package/web/chunk-0y971zgq.js +0 -2
- package/web/chunk-32zmk3f5.js +0 -1
- package/web/chunk-3d3wnh8a.js +0 -2
- package/web/chunk-48479gnx.js +0 -1
- package/web/chunk-4rwwtfnd.js +0 -2
- package/web/chunk-6cjm2yr7.js +0 -1
- package/web/chunk-7ycxz39p.js +0 -1
- package/web/chunk-8z7texmv.js +0 -1
- package/web/chunk-9jy8nc4r.js +0 -1
- package/web/chunk-9wr33d0t.js +0 -1
- package/web/chunk-a4tdrxdh.js +0 -1
- package/web/chunk-a9fvsyc1.js +0 -1
- package/web/chunk-apvbvg4d.js +0 -1
- package/web/chunk-bkxcc7v5.js +0 -1
- package/web/chunk-bve354k7.js +0 -1
- package/web/chunk-cwpxakby.js +0 -1
- package/web/chunk-d3f763n7.js +0 -2
- package/web/chunk-dtrh40vr.js +0 -1
- package/web/chunk-e68jw0bg.js +0 -1
- package/web/chunk-jd7npyv9.js +0 -8
- package/web/chunk-jhpg2kcf.js +0 -1
- package/web/chunk-jqqbkdtw.js +0 -4
- package/web/chunk-jzz5htxp.js +0 -1
- package/web/chunk-ka3q31t1.js +0 -1
- package/web/chunk-kahab58k.js +0 -1139
- package/web/chunk-krgvx75q.js +0 -1
- package/web/chunk-kxeaj44h.js +0 -1
- package/web/chunk-m1rdyvb5.js +0 -1
- package/web/chunk-m7k4wr3k.js +0 -1
- package/web/chunk-mdj3r75b.js +0 -1
- package/web/chunk-nbcpbqq4.js +0 -1
- package/web/chunk-nkpdd9hw.js +0 -1
- package/web/chunk-p1yc8hwn.js +0 -2
- package/web/chunk-p29brxyt.js +0 -1
- package/web/chunk-p8fbes0t.js +0 -1
- package/web/chunk-pbp1p5ex.js +0 -1
- package/web/chunk-q65zxczs.js +0 -34
- package/web/chunk-r6q1301x.js +0 -1
- package/web/chunk-r8kghrkb.js +0 -1
- package/web/chunk-rhxn7mxg.js +0 -1
- package/web/chunk-rqympya7.js +0 -2
- package/web/chunk-svqshmpg.js +0 -1
- package/web/chunk-swzxq7r3.css +0 -1
- package/web/chunk-t18tn37m.js +0 -2
- package/web/chunk-tbsaseer.js +0 -1
- package/web/chunk-tgkdyxbn.js +0 -1
- package/web/chunk-v0zfnvc1.js +0 -1
- package/web/chunk-vj31fs16.js +0 -1
- package/web/chunk-vr79r8vh.js +0 -1
- package/web/chunk-wb9tax0m.js +0 -1
- package/web/chunk-x9eghjjd.js +0 -1
- package/web/chunk-z3ky5ews.js +0 -2
package/chunk-95964592.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{P}from"./chunk-c4qr1f41.js";import{Qr,W}from"./chunk-4gtgqcct.js";import{o,e,ze,Lt,u,Z,Ee,wt,yn,_o,bn,Sn,wn,xn,vn,_n,An,En,ri,ve,Ao,Cr,Eo,Po,Pn,Tn,xt,R,ni,Ot,vt,Ir,kn,T,oi,Ze,ue,Nt,Rn,ii,Cn,E,Mr,Dt}from"./chunk-vtqr7dm8.js";import{_t,At}from"./chunk-stj493dn.js";import{se}from"./chunk-h1kb8b49.js";import{ee}from"./chunk-tvm4zmgj.js";import{fe,pe,Zt,K,Dr,ge}from"./chunk-r4ttdkrz.js";import{y}from"./chunk-3k627vf2.js";import{j}from"./chunk-nrsd810j.js";import{U,Le,me,oe,re,Q}from"./chunk-1n7dat03.js";import{M,ke}from"./chunk-n2jcx65v.js";import{i,r}from"./chunk-bwawt15q.js";var ya=r(function(ye){var tl=ye&&ye.__extends||function(){var s=function(n,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,c){a.__proto__=c}||function(a,c){for(var l in c)if(c.hasOwnProperty(l))a[l]=c[l]},s(n,t)};return function(n,t){s(n,t);function a(){this.constructor=n}n.prototype=t===null?Object.create(t):(a.prototype=t.prototype,new a)}}();Object.defineProperty(ye,"__esModule",{value:!0});var X=256,Mi=function(){function s(n){if(n===void 0)n="=";this._paddingCharacter=n}return s.prototype.encodedLength=function(n){if(!this._paddingCharacter)return(n*8+5)/6|0;return(n+2)/3*4|0},s.prototype.encode=function(n){var t="",a=0;for(;a<n.length-2;a+=3){var c=n[a]<<16|n[a+1]<<8|n[a+2];t+=this._encodeByte(c>>>18&63),t+=this._encodeByte(c>>>12&63),t+=this._encodeByte(c>>>6&63),t+=this._encodeByte(c>>>0&63)}var l=n.length-a;if(l>0){var c=n[a]<<16|(l===2?n[a+1]<<8:0);if(t+=this._encodeByte(c>>>18&63),t+=this._encodeByte(c>>>12&63),l===2)t+=this._encodeByte(c>>>6&63);else t+=this._paddingCharacter||"";t+=this._paddingCharacter||""}return t},s.prototype.maxDecodedLength=function(n){if(!this._paddingCharacter)return(n*6+7)/8|0;return n/4*3|0},s.prototype.decodedLength=function(n){return this.maxDecodedLength(n.length-this._getPaddingLength(n))},s.prototype.decode=function(n){if(n.length===0)return new Uint8Array(0);var t=this._getPaddingLength(n),a=n.length-t,c=new Uint8Array(this.maxDecodedLength(a)),l=0,d=0,h=0,f=0,g=0,x=0,_=0;for(;d<a-4;d+=4)f=this._decodeChar(n.charCodeAt(d+0)),g=this._decodeChar(n.charCodeAt(d+1)),x=this._decodeChar(n.charCodeAt(d+2)),_=this._decodeChar(n.charCodeAt(d+3)),c[l++]=f<<2|g>>>4,c[l++]=g<<4|x>>>2,c[l++]=x<<6|_,h|=f&X,h|=g&X,h|=x&X,h|=_&X;if(d<a-1)f=this._decodeChar(n.charCodeAt(d)),g=this._decodeChar(n.charCodeAt(d+1)),c[l++]=f<<2|g>>>4,h|=f&X,h|=g&X;if(d<a-2)x=this._decodeChar(n.charCodeAt(d+2)),c[l++]=g<<4|x>>>2,h|=x&X;if(d<a-3)_=this._decodeChar(n.charCodeAt(d+3)),c[l++]=x<<6|_,h|=_&X;if(h!==0)throw Error("Base64Coder: incorrect characters for decoding");return c},s.prototype._encodeByte=function(n){var t=n;return t+=65,t+=25-n>>>8&6,t+=51-n>>>8&-75,t+=61-n>>>8&-15,t+=62-n>>>8&3,String.fromCharCode(t)},s.prototype._decodeChar=function(n){var t=X;return t+=(42-n&n-44)>>>8&-X+n-43+62,t+=(46-n&n-48)>>>8&-X+n-47+63,t+=(47-n&n-58)>>>8&-X+n-48+52,t+=(64-n&n-91)>>>8&-X+n-65+0,t+=(96-n&n-123)>>>8&-X+n-97+26,t},s.prototype._getPaddingLength=function(n){var t=0;if(this._paddingCharacter){for(var a=n.length-1;a>=0;a--){if(n[a]!==this._paddingCharacter)break;t++}if(n.length<4||t>2)throw Error("Base64Coder: incorrect padding")}return t},s}();ye.Coder=Mi;var or=new Mi;function rl(s){return or.encode(s)}ye.encode=rl;function nl(s){return or.decode(s)}ye.decode=nl;var ga=function(s){tl(n,s);function n(){return s!==null&&s.apply(this,arguments)||this}return n.prototype._encodeByte=function(t){var a=t;return a+=65,a+=25-t>>>8&6,a+=51-t>>>8&-75,a+=61-t>>>8&-13,a+=62-t>>>8&49,String.fromCharCode(a)},n.prototype._decodeChar=function(t){var a=X;return a+=(44-t&t-46)>>>8&-X+t-45+62,a+=(94-t&t-96)>>>8&-X+t-95+63,a+=(47-t&t-58)>>>8&-X+t-48+52,a+=(64-t&t-91)>>>8&-X+t-65+0,a+=(96-t&t-123)>>>8&-X+t-97+26,a},n}(Mi);ye.URLSafeCoder=ga;var wa=new ga;function sl(s){return wa.encode(s)}ye.encodeURLSafe=sl;function il(s){return wa.decode(s)}ye.decodeURLSafe=il;ye.encodedLength=function(s){return or.encodedLength(s)};ye.maxDecodedLength=function(s){return or.maxDecodedLength(s)};ye.decodedLength=function(s){return or.decodedLength(s)}});var ka=r(function(ba,Xn){(function(s,n){var t={};n(t);var a=t.default;for(var c in t)a[c]=t[c];if(typeof Xn==="object"&&typeof Xn.exports==="object")Xn.exports=a;else if(typeof define==="function"&&define.amd)define(function(){return a});else s.sha256=a})(ba,function(s){s.__esModule=!0,s.digestLength=32,s.blockSize=64;var n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function t(_,k,w,v,O){var S,I,b,N,L,F,Y,H,J,B,q,xe,tt;while(O>=64){S=k[0],I=k[1],b=k[2],N=k[3],L=k[4],F=k[5],Y=k[6],H=k[7];for(B=0;B<16;B++)q=v+B*4,_[B]=(w[q]&255)<<24|(w[q+1]&255)<<16|(w[q+2]&255)<<8|w[q+3]&255;for(B=16;B<64;B++)J=_[B-2],xe=(J>>>17|J<<15)^(J>>>19|J<<13)^J>>>10,J=_[B-15],tt=(J>>>7|J<<25)^(J>>>18|J<<14)^J>>>3,_[B]=(xe+_[B-7]|0)+(tt+_[B-16]|0);for(B=0;B<64;B++)xe=(((L>>>6|L<<26)^(L>>>11|L<<21)^(L>>>25|L<<7))+(L&F^~L&Y)|0)+(H+(n[B]+_[B]|0)|0)|0,tt=((S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10))+(S&I^S&b^I&b)|0,H=Y,Y=F,F=L,L=N+xe|0,N=b,b=I,I=S,S=xe+tt|0;k[0]+=S,k[1]+=I,k[2]+=b,k[3]+=N,k[4]+=L,k[5]+=F,k[6]+=Y,k[7]+=H,v+=64,O-=64}return v}var a=function(){function _(){this.digestLength=s.digestLength,this.blockSize=s.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return _.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},_.prototype.clean=function(){for(var k=0;k<this.buffer.length;k++)this.buffer[k]=0;for(var k=0;k<this.temp.length;k++)this.temp[k]=0;this.reset()},_.prototype.update=function(k,w){if(w===void 0)w=k.length;if(this.finished)throw Error("SHA256: can't update because hash was finished.");var v=0;if(this.bytesHashed+=w,this.bufferLength>0){while(this.bufferLength<64&&w>0)this.buffer[this.bufferLength++]=k[v++],w--;if(this.bufferLength===64)t(this.temp,this.state,this.buffer,0,64),this.bufferLength=0}if(w>=64)v=t(this.temp,this.state,k,v,w),w%=64;while(w>0)this.buffer[this.bufferLength++]=k[v++],w--;return this},_.prototype.finish=function(k){if(!this.finished){var w=this.bytesHashed,v=this.bufferLength,O=w/536870912|0,S=w<<3,I=w%64<56?64:128;this.buffer[v]=128;for(var b=v+1;b<I-8;b++)this.buffer[b]=0;this.buffer[I-8]=O>>>24&255,this.buffer[I-7]=O>>>16&255,this.buffer[I-6]=O>>>8&255,this.buffer[I-5]=O>>>0&255,this.buffer[I-4]=S>>>24&255,this.buffer[I-3]=S>>>16&255,this.buffer[I-2]=S>>>8&255,this.buffer[I-1]=S>>>0&255,t(this.temp,this.state,this.buffer,0,I),this.finished=!0}for(var b=0;b<8;b++)k[b*4+0]=this.state[b]>>>24&255,k[b*4+1]=this.state[b]>>>16&255,k[b*4+2]=this.state[b]>>>8&255,k[b*4+3]=this.state[b]>>>0&255;return this},_.prototype.digest=function(){var k=new Uint8Array(this.digestLength);return this.finish(k),k},_.prototype._saveState=function(k){for(var w=0;w<this.state.length;w++)k[w]=this.state[w]},_.prototype._restoreState=function(k,w){for(var v=0;v<this.state.length;v++)this.state[v]=k[v];this.bytesHashed=w,this.finished=!1,this.bufferLength=0},_}();s.Hash=a;var c=function(){function _(k){this.inner=new a,this.outer=new a,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var w=new Uint8Array(this.blockSize);if(k.length>this.blockSize)new a().update(k).finish(w).clean();else for(var v=0;v<k.length;v++)w[v]=k[v];for(var v=0;v<w.length;v++)w[v]^=54;this.inner.update(w);for(var v=0;v<w.length;v++)w[v]^=106;this.outer.update(w),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var v=0;v<w.length;v++)w[v]=0}return _.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},_.prototype.clean=function(){for(var k=0;k<this.istate.length;k++)this.ostate[k]=this.istate[k]=0;this.inner.clean(),this.outer.clean()},_.prototype.update=function(k){return this.inner.update(k),this},_.prototype.finish=function(k){if(this.outer.finished)this.outer.finish(k);else this.inner.finish(k),this.outer.update(k,this.digestLength).finish(k);return this},_.prototype.digest=function(){var k=new Uint8Array(this.digestLength);return this.finish(k),k},_}();s.HMAC=c;function l(_){var k=new a().update(_),w=k.digest();return k.clean(),w}s.hash=l,s.default=l;function d(_,k){var w=new c(_).update(k),v=w.digest();return w.clean(),v}s.hmac=d;function h(_,k,w,v){var O=v[0];if(O===0)throw Error("hkdf: cannot expand more");if(k.reset(),O>1)k.update(_);if(w)k.update(w);k.update(v),k.finish(_),v[0]++}var f=new Uint8Array(s.digestLength);function g(_,k,w,v){if(k===void 0)k=f;if(v===void 0)v=32;var O=new Uint8Array([1]),S=d(k,_),I=new c(S),b=new Uint8Array(I.digestLength),N=b.length,L=new Uint8Array(v);for(var F=0;F<v;F++){if(N===b.length)h(b,I,w,O),N=0;L[F]=b[N++]}return I.clean(),b.fill(0),O.fill(0),L}s.hkdf=g;function x(_,k,w,v){var O=new c(_),S=O.digestLength,I=new Uint8Array(4),b=new Uint8Array(S),N=new Uint8Array(S),L=new Uint8Array(v);for(var F=0;F*S<v;F++){var Y=F+1;I[0]=Y>>>24&255,I[1]=Y>>>16&255,I[2]=Y>>>8&255,I[3]=Y>>>0&255,O.reset(),O.update(k),O.update(I),O.finish(N);for(var H=0;H<S;H++)b[H]=N[H];for(var H=2;H<=w;H++){O.reset(),O.update(N).finish(N);for(var J=0;J<S;J++)b[J]^=N[J]}for(var H=0;H<S&&F*S+H<v;H++)L[F*S+H]=b[H]}for(var F=0;F<S;F++)b[F]=N[F]=0;for(var F=0;F<4;F++)I[F]=0;return O.clean(),L}s.pbkdf2=x})});var xa=r(function(va){Object.defineProperty(va,"__esModule",{value:!0});va.timingSafeEqual=ol;function Sa(s,n=""){if(!s)throw Error(n)}function ol(s,n){if(s.byteLength!==n.byteLength)return!1;if(!(s instanceof DataView))s=new DataView(ArrayBuffer.isView(s)?s.buffer:s);if(!(n instanceof DataView))n=new DataView(ArrayBuffer.isView(n)?n.buffer:n);Sa(s instanceof DataView),Sa(n instanceof DataView);let t=s.byteLength,a=0,c=-1;while(++c<t)a|=s.getUint8(c)^n.getUint8(c);return a===0}});var Pa=r(function(Ia){Object.defineProperty(Ia,"__esModule",{value:!0});Ia.Webhook=Ia.WebhookVerificationError=void 0;var Qn=ya(),Aa=ka(),Ra=xa(),Ea=300;class Ni extends Error{constructor(s){super(s);Object.setPrototypeOf(this,Ni.prototype),this.name="ExtendableError",this.stack=Error(s).stack}}class qe extends Ni{constructor(s){super(s);Object.setPrototypeOf(this,qe.prototype),this.name="WebhookVerificationError"}}Ia.WebhookVerificationError=qe;class ar{constructor(s,n){if((n===null||n===void 0?void 0:n.format)==="raw")if(s instanceof Uint8Array)this.key=s;else this.key=Uint8Array.from(s,(t)=>t.charCodeAt(0));else{if(typeof s!=="string")throw Error("Expected secret to be of type string");if(s.startsWith(ar.prefix))s=s.substring(ar.prefix.length);this.key=Qn.decode(s)}if(this.key.length===0)throw Error("Secret can't be empty.")}verify(s,n,t){var a;let c=(a=t===null||t===void 0?void 0:t.jsonParse)!==null&&a!==void 0?a:!0,l={};for(let v of Object.keys(n))l[v.toLowerCase()]=n[v];let d=l["webhook-id"],h=l["webhook-signature"],f=l["webhook-timestamp"];if(!h||!d||!f)throw new qe("Missing required headers");let g=this.verifyTimestamp(f),_=this.sign(d,g,s).split(",")[1],k=h.split(" "),w=new globalThis.TextEncoder;for(let v of k){let[O,S]=v.split(",");if(O!=="v1")continue;if(Ra.timingSafeEqual(w.encode(S),w.encode(_))){let I=s.toString();if(I==="")return;if(c)return JSON.parse(I);else return}}throw new qe("No matching signature found")}sign(s,n,t){if(typeof t==="string");else if(t.constructor.name==="Buffer")t=t.toString();else throw Error("Expected payload to be of type string or Buffer.");let a=new TextEncoder,c=Math.floor(n.getTime()/1000),l=a.encode(`${s}.${c}.${t}`);return`v1,${Qn.encode(Aa.hmac(this.key,l))}`}verifyTimestamp(s){let n=Math.floor(Date.now()/1000),t=parseInt(s,10);if(Number.isNaN(t))throw new qe("Invalid Signature Headers");if(n-t>Ea)throw new qe("Message timestamp too old");if(t>n+Ea)throw new qe("Message timestamp too new");return new Date(t*1000)}}Ia.Webhook=ar;ar.prefix="whsec_"});var Ce=(s,n)=>new Promise((t)=>{if(n?.aborted)return t();let a=()=>{clearTimeout(c),t()},c=setTimeout(()=>{n?.removeEventListener("abort",a),t()},s);n?.addEventListener("abort",a,{once:!0})});var Ae="0.129.0";var Io=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function wc(){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 yc=()=>{let s=wc();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":So(Deno.build.os),"X-Stainless-Arch":ko(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":Ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":So(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ko(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let n=bc();if(n)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${n.browser}`,"X-Stainless-Runtime-Version":n.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function bc(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:n,pattern:t}of s){let a=t.exec(navigator.userAgent);if(a){let c=a[1]||0,l=a[2]||0,d=a[3]||0;return{browser:n,version:`${c}.${l}.${d}`}}}return null}var ko=(s)=>{if(s==="x32")return"x32";if(s==="x86_64"||s==="x64")return"x64";if(s==="arm")return"arm";if(s==="aarch64"||s==="arm64")return"arm64";if(s)return`other:${s}`;return"unknown"},So=(s)=>{if(s=s.toLowerCase(),s.includes("ios"))return"iOS";if(s==="android")return"Android";if(s==="darwin")return"MacOS";if(s==="win32")return"Windows";if(s==="freebsd")return"FreeBSD";if(s==="openbsd")return"OpenBSD";if(s==="linux")return"Linux";if(s)return`Other:${s}`;return"Unknown"},Ro,qt=()=>Ro??(Ro=yc());var Mn=new WeakMap,To=typeof globalThis.FinalizationRegistry==="function"?new globalThis.FinalizationRegistry((s)=>Ne(s)):null;function kc(s,n){return()=>s.removeEventListener("abort",n)}function Co(s,n,t){Mn.set(s,kc(n,t))}function Oo(s,n){if(Mn.has(n))To?.register(s,n,n)}function Ne(s){let n=Mn.get(s);if(n)Mn.delete(s),To?.unregister(s),n()}function Mo(){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 di(...s){let n=globalThis.ReadableStream;if(typeof n>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new n(...s)}function Nn(s){let n=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return di({start(){},async pull(t){let{done:a,value:c}=await n.next();if(a)t.close();else t.enqueue(c)},async cancel(){await n.return?.()}})}function Kt(s){if(s[Symbol.asyncIterator])return s;let n=s.getReader();return{async next(){try{let t=await n.read();if(t?.done)n.releaseLock();return t}catch(t){throw n.releaseLock(),t}},async return(){let t=n.cancel();return n.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function No(s){if(s===null||typeof s!=="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let n=s.getReader(),t=n.cancel();n.releaseLock(),await t}var Lo=({headers:s,body:n})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(n)});var hi="RFC3986",fi=(s)=>String(s),pi={RFC1738:(s)=>String(s).replace(/%20/g,"+"),RFC3986:fi},$o="RFC1738";var Ln=(s,n)=>(Ln=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ln(s,n)),$e=(()=>{let s=[];for(let n=0;n<256;++n)s.push("%"+((n<16?"0":"")+n.toString(16)).toUpperCase());return s})();var mi=1024,Fo=(s,n,t,a,c)=>{if(s.length===0)return s;let l=s;if(typeof s==="symbol")l=Symbol.prototype.toString.call(s);else if(typeof s!=="string")l=String(s);if(t==="iso-8859-1")return escape(l).replace(/%u[0-9a-f]{4}/gi,function(h){return"%26%23"+parseInt(h.slice(2),16)+"%3B"});let d="";for(let h=0;h<l.length;h+=mi){let f=l.length>=mi?l.slice(h,h+mi):l,g=[];for(let x=0;x<f.length;++x){let _=f.charCodeAt(x);if(_===45||_===46||_===95||_===126||_>=48&&_<=57||_>=65&&_<=90||_>=97&&_<=122||c===$o&&(_===40||_===41)){g[g.length]=f.charAt(x);continue}if(_<128){g[g.length]=$e[_];continue}if(_<2048){g[g.length]=$e[192|_>>6]+$e[128|_&63];continue}if(_<55296||_>=57344){g[g.length]=$e[224|_>>12]+$e[128|_>>6&63]+$e[128|_&63];continue}x+=1,_=65536+((_&1023)<<10|f.charCodeAt(x)&1023),g[g.length]=$e[240|_>>18]+$e[128|_>>12&63]+$e[128|_>>6&63]+$e[128|_&63]}d+=g.join("")}return d};function Ho(s){if(!s||typeof s!=="object")return!1;return!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function _i(s,n){if(ve(s)){let t=[];for(let a=0;a<s.length;a+=1)t.push(n(s[a]));return t}return n(s)}var Bo={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,n){return String(s)+"["+n+"]"},repeat(s){return String(s)}},Wo=function(s,n){Array.prototype.push.apply(s,ve(n)?n:[n])},Do,ne={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Fo,encodeValuesOnly:!1,format:hi,formatter:fi,indices:!1,serializeDate(s){return(Do??(Do=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function xc(s){return typeof s==="string"||typeof s==="number"||typeof s==="boolean"||typeof s==="symbol"||typeof s==="bigint"}var gi={};function Uo(s,n,t,a,c,l,d,h,f,g,x,_,k,w,v,O,S,I){let b=s,N=I,L=0,F=!1;while((N=N.get(gi))!==void 0&&!F){let q=N.get(s);if(L+=1,typeof q<"u")if(q===L)throw RangeError("Cyclic object value");else F=!0;if(typeof N.get(gi)>"u")L=0}if(typeof g==="function")b=g(n,b);else if(b instanceof Date)b=k?.(b);else if(t==="comma"&&ve(b))b=_i(b,function(q){if(q instanceof Date)return k?.(q);return q});if(b===null){if(l)return f&&!O?f(n,ne.encoder,S,"key",w):n;b=""}if(xc(b)||Ho(b)){if(f){let q=O?n:f(n,ne.encoder,S,"key",w);return[v?.(q)+"="+v?.(f(b,ne.encoder,S,"value",w))]}return[v?.(n)+"="+v?.(String(b))]}let Y=[];if(typeof b>"u")return Y;let H;if(t==="comma"&&ve(b)){if(O&&f)b=_i(b,f);H=[{value:b.length>0?b.join(",")||null:void 0}]}else if(ve(g))H=g;else{let q=Object.keys(b);H=x?q.sort(x):q}let J=h?String(n).replace(/\./g,"%2E"):String(n),B=a&&ve(b)&&b.length===1?J+"[]":J;if(c&&ve(b)&&b.length===0)return B+"[]";for(let q=0;q<H.length;++q){let xe=H[q],tt=typeof xe==="object"&&typeof xe.value<"u"?xe.value:b[xe];if(d&&tt===null)continue;let ui=_&&h?xe.replace(/\./g,"%2E"):xe,gc=ve(b)?typeof t==="function"?t(B,ui):B:B+(_?"."+ui:"["+ui+"]");I.set(s,L);let bo=new WeakMap;bo.set(gi,I),Wo(Y,Uo(tt,gc,t,a,c,l,d,h,t==="comma"&&O&&ve(b)?null:f,g,x,_,k,w,v,O,S,bo))}return Y}function Ec(s=ne){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!=="function")throw TypeError("Encoder has to be a function.");let n=s.charset||ne.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=hi;if(typeof s.format<"u"){if(!Ln(pi,s.format))throw TypeError("Unknown format option provided.");t=s.format}let a=pi[t],c=ne.filter;if(typeof s.filter==="function"||ve(s.filter))c=s.filter;let l;if(s.arrayFormat&&s.arrayFormat in Bo)l=s.arrayFormat;else if("indices"in s)l=s.indices?"indices":"repeat";else l=ne.arrayFormat;if("commaRoundTrip"in s&&typeof s.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let d=typeof s.allowDots>"u"?!!s.encodeDotInKeys===!0?!0:ne.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix==="boolean"?s.addQueryPrefix:ne.addQueryPrefix,allowDots:d,allowEmptyArrays:typeof s.allowEmptyArrays==="boolean"?!!s.allowEmptyArrays:ne.allowEmptyArrays,arrayFormat:l,charset:n,charsetSentinel:typeof s.charsetSentinel==="boolean"?s.charsetSentinel:ne.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?ne.delimiter:s.delimiter,encode:typeof s.encode==="boolean"?s.encode:ne.encode,encodeDotInKeys:typeof s.encodeDotInKeys==="boolean"?s.encodeDotInKeys:ne.encodeDotInKeys,encoder:typeof s.encoder==="function"?s.encoder:ne.encoder,encodeValuesOnly:typeof s.encodeValuesOnly==="boolean"?s.encodeValuesOnly:ne.encodeValuesOnly,filter:c,format:t,formatter:a,serializeDate:typeof s.serializeDate==="function"?s.serializeDate:ne.serializeDate,skipNulls:typeof s.skipNulls==="boolean"?s.skipNulls:ne.skipNulls,sort:typeof s.sort==="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling==="boolean"?s.strictNullHandling:ne.strictNullHandling}}function jo(s,n={}){let t=s,a=Ec(n),c,l;if(typeof a.filter==="function")l=a.filter,t=l("",t);else if(ve(a.filter))l=a.filter,c=l;let d=[];if(typeof t!=="object"||t===null)return"";let h=Bo[a.arrayFormat],f=h==="comma"&&a.commaRoundTrip;if(!c)c=Object.keys(t);if(a.sort)c.sort(a.sort);let g=new WeakMap;for(let k=0;k<c.length;++k){let w=c[k];if(a.skipNulls&&t[w]===null)continue;Wo(d,Uo(t[w],w,h,f,a.allowEmptyArrays,a.strictNullHandling,a.skipNulls,a.encodeDotInKeys,a.encode?a.encoder:null,a.filter,a.sort,a.allowDots,a.serializeDate,a.format,a.formatter,a.encodeValuesOnly,a.charset,g))}let x=d.join(a.delimiter),_=a.addQueryPrefix===!0?"?":"";if(a.charsetSentinel)if(a.charset==="iso-8859-1")_+="utf8=%26%2310003%3B&";else _+="utf8=%E2%9C%93&";return x.length>0?_+x:""}function qo(s){return jo(s,{arrayFormat:"brackets"})}var zo="urn:ietf:params:oauth:grant-type:jwt-bearer",Vo="refresh_token",$n="/v1/oauth/token",rt="oauth-2025-04-20",Yo="oidc-federation-2026-04-01",Jo=120,dt=30,Go=5,Ko=1048576;function Fn(s){if(!s)return;let n;try{n=new URL(s)}catch(a){throw new D(`Invalid token endpoint base URL "${s}": ${a}`)}if(n.protocol==="https:")return;let t=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(n.protocol==="http:"&&(t==="localhost"||t==="127.0.0.1"||t==="::1"))return;throw new D(`Refusing to send credential over non-https token endpoint "${s}"`)}async function Hn(s,n){let t=await Ic(s),a;try{a=JSON.parse(t)}catch{throw new D(`Token endpoint returned non-JSON response (status ${s.status})`,s.status,ce(t),n)}if(!a.access_token)throw new D(`Token endpoint response missing access_token: ${JSON.stringify(ce(a))}`,s.status,ce(a),n);if(a.token_type&&a.token_type.toLowerCase()!=="bearer")throw new D(`Token endpoint response: unsupported token_type "${a.token_type}" (want Bearer)`,s.status,ce(a),n);return a}var wi=2000,Rc=new Set(["error","error_description","error_uri"]);function ce(s){if(s==null)return s;if(typeof s==="string"){let n;try{n=JSON.parse(s)}catch{if(s.length<=wi)return s;return s.slice(0,wi)+`... <${s.length-wi} more chars>`}return JSON.stringify(ce(n))}if(typeof s==="object"&&!Array.isArray(s)){let n={};for(let[t,a]of Object.entries(s))if(Rc.has(t))n[t]=a;return n}return null}async function Dn(s,n=(t)=>console.warn(`anthropic-sdk: ${t}`)){if(typeof process>"u"||process.platform==="win32")return;let{fs:t}=await import("./chunk-pnspvnyd.js"),a=s,c;try{a=await t.promises.realpath(s),c=await t.promises.stat(a)}catch{return}let l=c.mode&511;if(l&18)throw new D(`Credentials file at ${a} is group/world-writable (mode 0o${l.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${a}\`.`);if(l&36)throw new D(`Credentials file at ${a} is group/world-readable (mode 0o${l.toString(8)}); run \`chmod 600 ${a}\` before retrying.`);if(typeof process.getuid==="function"&&c.uid!==process.getuid())n(`credentials file at ${a} is owned by uid ${c.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Bn(s,n){let{fs:t,path:a}=await import("./chunk-pnspvnyd.js"),c=a.dirname(s);await t.promises.mkdir(c,{recursive:!0,mode:448});let l=`${s}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let d=await t.promises.open(l,"w",384);try{await d.writeFile(JSON.stringify(n,null,2)),await d.sync()}finally{await d.close()}await t.promises.rename(l,s)}catch(d){throw await t.promises.unlink(l).catch(()=>{}),d}try{let d=await t.promises.open(c,"r");try{await d.sync()}finally{await d.close()}}catch{}}async function Ic(s){if(!s.body)return"";let n=s.body.getReader(),t=[],a=0;for(;;){let{done:l,value:d}=await n.read();if(l)break;if(a+d.length>Ko){let h=Ko-a;if(h>0)t.push(d.subarray(0,h));await n.cancel();break}t.push(d),a+=d.length}let c;if(t.length===1)c=t[0];else{c=new Uint8Array(t.reduce((d,h)=>d+h.length,0));let l=0;for(let d of t)c.set(d,l),l+=d.length}return new TextDecoder("utf-8").decode(c)}class D extends u{constructor(s,n=null,t=null,a=null){super(s);this.statusCode=n,this.body=t,this.requestId=a}}function Oe(){return Math.floor(Date.now()/1000)}class yi{constructor(s,n){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=s,this.onAdvisoryRefreshError=n}async getToken(){let s=this.nextForce;this.nextForce=!1;let n=this.cached;if(s||n==null)return(await this.refresh(s)).token;if(n.expiresAt==null)return n.token;let t=n.expiresAt-Oe();if(t>Jo)return n.token;if(t>dt)return this.backgroundRefresh(),n.token;return(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(s=!1){if(this.pendingRefresh&&!s)return this.pendingRefresh;return this.doRefresh(s)}backgroundRefresh(){if(this.pendingRefresh)return;if(Oe()-this.lastAdvisoryError<Go)return;this.doRefresh().catch((s)=>{this.lastAdvisoryError=Oe(),this.onAdvisoryRefreshError?.(s)})}doRefresh(s=!1){return this.pendingRefresh=this.provider(s?{forceRefresh:!0}:void 0).then((n)=>(this.cached=n,this.pendingRefresh=null,n),(n)=>{throw this.pendingRefresh=null,n}),this.pendingRefresh}}var Xo=(s)=>{if(typeof globalThis.Buffer<"u"){let n=globalThis.Buffer.from(s,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob<"u"){let n=atob(s),t=new Uint8Array(n.length);for(let a=0;a<n.length;a++)t[a]=n.charCodeAt(a);return t}throw new u("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var Wn=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Wn=s.randomUUID.bind(s),s.randomUUID();let n=new Uint8Array(1),t=s?()=>s.getRandomValues(n)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(a)=>(+a^t()&15>>+a/4).toString(16))};var Un="1.0",Tc=/^[A-Za-z0-9_.-]+$/;function Qo(s){if(!s)throw Error("profile name is empty");if(s==="."||s==="..")throw Error(`profile name "${s}" is not allowed`);if(s.includes("/")||s.includes("\\"))throw Error(`profile name "${s}" must not contain path separators`);if(!Tc.test(s))throw Error(`profile name "${s}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var Zo=async(s)=>{var n,t;let a=await bi();if(a===null)return null;let c=s??await ta();if(c===null)return null;Qo(c);let{fs:l,path:d}=await import("./chunk-pnspvnyd.js"),h=d.join(a,"configs",`${c}.json`),f;try{f=await l.promises.readFile(h,"utf-8")}catch(_){if(_?.code!=="ENOENT")throw Error(`failed to read config file ${h}: ${_}`);f=null}if(f===null){let _=R("ANTHROPIC_ORGANIZATION_ID"),k=R("ANTHROPIC_IDENTITY_TOKEN_FILE"),w=R("ANTHROPIC_FEDERATION_RULE_ID");if(w&&_)return{fromFile:!1,config:{organization_id:_,workspace_id:R("ANTHROPIC_WORKSPACE_ID"),base_url:R("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:w,service_account_id:R("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:k?{source:"file",path:k}:void 0,scope:R("ANTHROPIC_SCOPE")}}};return null}let g;try{g=JSON.parse(f)}catch(_){throw Error(`failed to parse config file ${h}: ${_}`)}if(!g.authentication)throw Error(`config file ${h} is missing "authentication"`);let x=g.authentication.type;if(x!=="oidc_federation"&&x!=="user_oauth")throw Error(`authentication.type "${x}" is not a known authentication type`);if(g.organization_id??(g.organization_id=R("ANTHROPIC_ORGANIZATION_ID")),g.workspace_id??(g.workspace_id=R("ANTHROPIC_WORKSPACE_ID")),g.base_url??(g.base_url=R("ANTHROPIC_BASE_URL")),(n=g.authentication).scope??(n.scope=R("ANTHROPIC_SCOPE")),g.authentication.type==="oidc_federation"){if(!g.authentication.identity_token){let _=R("ANTHROPIC_IDENTITY_TOKEN_FILE");if(_)g.authentication.identity_token={source:"file",path:_}}if(!g.authentication.federation_rule_id)g.authentication.federation_rule_id=R("ANTHROPIC_FEDERATION_RULE_ID")??"";(t=g.authentication).service_account_id??(t.service_account_id=R("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:g,fromFile:!0}};var ea=async(s,n)=>{if(s?.authentication.credentials_path)return s.authentication.credentials_path;let t=await bi();if(!t)return null;let a=n??await ta();if(!a)return null;Qo(a);let{path:c}=await import("./chunk-pnspvnyd.js");return c.join(t,"credentials",`${a}.json`)},bi=async()=>{if(!Pc())return null;let{path:s}=await import("./chunk-pnspvnyd.js"),n=R("ANTHROPIC_CONFIG_DIR");if(n)return n;if(qt()["X-Stainless-OS"]==="Windows"){let l=R("APPDATA");if(l)return s.join(l,"Anthropic");let d=R("USERPROFILE");if(d)return s.join(d,"AppData","Roaming","Anthropic");return null}let a=R("XDG_CONFIG_HOME");if(a)return s.join(a,"anthropic");let c=R("HOME");if(c)return s.join(c,".config","anthropic");return null},Pc=()=>{let s=qt()["X-Stainless-Runtime"];return s==="node"||s==="deno"},ta=async()=>{let s=await bi();if(!s)return null;let n=R("ANTHROPIC_PROFILE");if(n)return n;let{fs:t,path:a}=await import("./chunk-pnspvnyd.js"),c=a.join(s,"active_config");try{return(await t.promises.readFile(c,"utf-8")).trim()||"default"}catch(l){if(l?.code!=="ENOENT")throw Error(`failed to read ${c}: ${l}`);return"default"}};function ki(s){if(!s)throw new u("Identity token file path is empty");return async()=>{let{fs:n}=await import("./chunk-pnspvnyd.js"),t;try{t=await n.promises.readFile(s,"utf-8")}catch(c){throw new u(`Failed to read identity token file at ${s}: ${c}`)}let a=t.trim();if(!a)throw new u(`Identity token file at ${s} is empty`);return a}}function ra(s){if(!s)throw new u("Identity token value is empty");return()=>s}function na(s){return async()=>{Fn(s.baseURL);let n=await s.identityTokenProvider();if(n.length>16384)throw new D(`Identity token is ${Math.ceil(n.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let t={grant_type:zo,assertion:n,federation_rule_id:s.federationRuleId,organization_id:s.organizationId};if(s.serviceAccountId)t.service_account_id=s.serviceAccountId;if(s.workspaceId)t.workspace_id=s.workspaceId;let a=`${s.baseURL}${$n}`,c;try{c=await s.fetch(a,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${rt},${Yo}`,"User-Agent":s.userAgent||`anthropic-sdk-typescript/${Ae} oidcFederationProvider`},body:JSON.stringify(t)})}catch(f){throw new D(`Failed to reach token endpoint ${a}: ${f}`)}let l=c.headers.get("Request-Id");if(!c.ok){let f=await c.text().catch(()=>""),g=ce(f),x="";if(c.status===401)x=` Ensure your federation rule matches your identity token. ${s.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`;throw new D(`Token exchange failed with status ${c.status}${l?` (request-id ${l})`:""}: ${g}${x}`,c.status,g,l)}let d=await Hn(c,l),h=Number(d.expires_in);if(!Number.isFinite(h))throw new D(`Token endpoint response missing required fields: ${JSON.stringify(ce(d))}`,c.status,ce(d),l);return{token:d.access_token,expiresAt:Oe()+h}}}function sa(s){return async(n)=>{let{fs:t}=await import("./chunk-pnspvnyd.js");await Dn(s.credentialsPath,s.onSafetyWarning);let a;try{a=await t.promises.readFile(s.credentialsPath,"utf-8")}catch(S){throw new D(`Credentials file not found at ${s.credentialsPath}: ${S}`)}let c;try{c=JSON.parse(a)}catch(S){throw new D(`Credentials file at ${s.credentialsPath} is not valid JSON: ${S}`)}let l=c.access_token;if(!l)throw new D(`Credentials file at ${s.credentialsPath} must include 'access_token'`);let d=c.expires_at;if(!n?.forceRefresh&&(d==null||Oe()<d-dt))return{token:l,expiresAt:d??null};let h=c.refresh_token;if(!s.clientId||!h)throw new D(`Access token at ${s.credentialsPath} has expired and no refresh is available (client_id ${s.clientId?"set":"empty"}, refresh_token ${h?"set":"empty"})`);Fn(s.baseURL);let f={grant_type:Vo,refresh_token:h,client_id:s.clientId},g=`${s.baseURL}${$n}`,x;try{x=await s.fetch(g,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":rt,"User-Agent":s.userAgent||`anthropic-sdk-typescript/${Ae} userOAuthProvider`},body:JSON.stringify(f)})}catch(S){throw new D(`User OAuth refresh failed to reach token endpoint: ${S}`)}let _=x.headers.get("Request-Id");if(!x.ok){let S=await x.text().catch(()=>"");throw new D(`User OAuth refresh failed (HTTP ${x.status}): ${ce(S)}`,x.status,ce(S),_)}let k=await Hn(x,_),w=Number(k.expires_in);if(!Number.isFinite(w))throw new D(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(ce(k))}`,x.status,ce(k),_);let v=Oe()+w,O=k.refresh_token||h;return await Bn(s.credentialsPath,{...c,version:Un,type:"oauth_token",access_token:k.access_token,expires_at:v,refresh_token:O}),{token:k.access_token,expiresAt:v}}}function Si(s,n){let t=s.authentication.credentials_path??null,a=(s.base_url||n.baseURL).replace(/\/+$/,""),c=Cc(s,t,a,n),l={};if(s.workspace_id&&s.authentication.type==="user_oauth")l["anthropic-workspace-id"]=s.workspace_id;return{provider:c,extraHeaders:l,baseURL:s.base_url||void 0}}async function ia(s,n){let t=await Zo(n);if(!t)return null;let{config:a,fromFile:c}=t,l=a.authentication.credentials_path||!c?a:{...a,authentication:{...a.authentication,credentials_path:await ea(a,n)??void 0}};return Si(l,s)}function Cc(s,n,t,a){switch(s.authentication.type){case"oidc_federation":{let c=s.authentication,l=Oc(c);if(!l)throw new D("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!c.federation_rule_id)throw new D("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!s.organization_id)throw new D("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let d=na({identityTokenProvider:l,federationRuleId:c.federation_rule_id,organizationId:s.organization_id,serviceAccountId:c.service_account_id,workspaceId:s.workspace_id,baseURL:t,fetch:a.fetch,userAgent:a.userAgent});if(n)return Mc(d,n,a.onCacheWriteError,a.onSafetyWarning);return d}case"user_oauth":{if(!n)throw new D("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return sa({credentialsPath:n,clientId:s.authentication.client_id,baseURL:t,fetch:a.fetch,userAgent:a.userAgent,onSafetyWarning:a.onSafetyWarning})}default:{let c=s.authentication.type;throw new D(`authentication.type "${c}" is not a known authentication type`)}}}function Oc(s){if(s.identity_token){let a=s.identity_token.source;if(a!=="file")throw new D(`identity_token.source "${a}" is not supported by this SDK version (only "file")`);if(!s.identity_token.path)throw new D('identity_token.source "file" requires a non-empty path');return ki(s.identity_token.path)}let n=R("ANTHROPIC_IDENTITY_TOKEN_FILE");if(n)return ki(n);let t=R("ANTHROPIC_IDENTITY_TOKEN");if(t)return ra(t);return null}function Mc(s,n,t,a){return async(c)=>{let{fs:l}=await import("./chunk-pnspvnyd.js");await Dn(n,a);let d;try{let f=await l.promises.readFile(n,"utf-8");d=JSON.parse(f);let g=d?.access_token;if(g&&!c?.forceRefresh){let x=d?.expires_at;if(x==null||Oe()<x-dt)return{token:g,expiresAt:x??null}}}catch(f){if(f?.code!=="ENOENT"&&!(f instanceof SyntaxError))t?.(f)}let h=await s(c);try{await Bn(n,{...d??{},version:Un,type:"oauth_token",access_token:h.token,expires_at:h.expiresAt})}catch(f){t?.(f)}return h}}var _e,we,zt=(()=>{class s{constructor(){_e.set(this,void 0),we.set(this,void 0),o(this,_e,new Uint8Array,"f"),o(this,we,null,"f")}decode(n){if(n==null)return[];let t=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==="string"?Ot(n):n;o(this,_e,ni([e(this,_e,"f"),t]),"f");let a=[],c;while((c=Nc(e(this,_e,"f"),e(this,we,"f")))!=null){if(c.carriage&&e(this,we,"f")==null){o(this,we,c.index,"f");continue}if(e(this,we,"f")!=null&&(c.index!==e(this,we,"f")+1||c.carriage)){a.push(vt(e(this,_e,"f").subarray(0,e(this,we,"f")-1))),o(this,_e,e(this,_e,"f").subarray(e(this,we,"f")),"f"),o(this,we,null,"f");continue}let l=e(this,we,"f")!==null?c.preceding-1:c.preceding,d=vt(e(this,_e,"f").subarray(0,l));a.push(d),o(this,_e,e(this,_e,"f").subarray(c.index),"f"),o(this,we,null,"f")}return a}flush(){if(!e(this,_e,"f").length)return[];return this.decode(`
|
|
3
|
-
`)}}return _e=new WeakMap,we=new WeakMap,s.NEWLINE_CHARS=new Set([`
|
|
4
|
-
`,"\r"]),s.NEWLINE_REGEXP=/\r\n|[\n\r]/g,s})();function Nc(s,n){for(let c=n??0;c<s.length;c++){if(s[c]===10)return{preceding:c,index:c+1,carriage:!1};if(s[c]===13)return{preceding:c,index:c+1,carriage:!0}}return null}var Vt,Fe=(()=>{class s{constructor(n,t,a){this.iterator=n,Vt.set(this,void 0),this.controller=t,o(this,Vt,a,"f")}static rawEvents(n,t=new AbortController){return oa(n,t)}static fromSSEResponse(n,t,a){let c=!1,l=a?T(a):console;async function*d(){if(c)throw new u("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let h=!1;try{for await(let f of oa(n,t)){if(f.event==="completion")try{yield JSON.parse(f.data)}catch(g){throw l.error("Could not parse message into JSON:",f.data),l.error("From chunk:",f.raw),g}if(f.event==="message_start"||f.event==="message_delta"||f.event==="message_stop"||f.event==="content_block_start"||f.event==="content_block_delta"||f.event==="content_block_stop"||f.event==="message"||f.event==="user.message"||f.event==="user.interrupt"||f.event==="user.tool_confirmation"||f.event==="user.custom_tool_result"||f.event==="user.tool_result"||f.event==="agent.message"||f.event==="agent.thinking"||f.event==="agent.tool_use"||f.event==="agent.tool_result"||f.event==="agent.mcp_tool_use"||f.event==="agent.mcp_tool_result"||f.event==="agent.custom_tool_use"||f.event==="agent.thread_context_compacted"||f.event==="session.status_running"||f.event==="session.status_idle"||f.event==="session.status_rescheduled"||f.event==="session.status_terminated"||f.event==="session.error"||f.event==="session.deleted"||f.event==="session.updated"||f.event==="span.model_request_start"||f.event==="span.model_request_end"||f.event==="span.outcome_evaluation_start"||f.event==="span.outcome_evaluation_ongoing"||f.event==="span.outcome_evaluation_end"||f.event==="user.define_outcome"||f.event==="agent.thread_message_received"||f.event==="agent.thread_message_sent"||f.event==="agent.session_thread_message_received"||f.event==="agent.session_thread_message_sent"||f.event==="session.thread_created"||f.event==="session.thread_status_created"||f.event==="session.thread_status_running"||f.event==="session.thread_status_idle"||f.event==="session.thread_status_rescheduled"||f.event==="session.thread_status_terminated"||f.event==="event_start"||f.event==="event_delta"||f.event==="system.message")try{yield JSON.parse(f.data)}catch(g){throw l.error("Could not parse message into JSON:",f.data),l.error("From chunk:",f.raw),g}if(f.event==="ping")continue;if(f.event==="error"){let g=Tn(f.data)??f.data,x=g?.error?.type;throw new Z(void 0,g,void 0,n.headers,x)}}h=!0}catch(f){if(ze(f))return;throw f}finally{if(!h)t.abort();Ne(t)}}return new s(d,t,a)}static fromReadableStream(n,t,a){let c=!1;async function*l(){let h=new zt,f=Kt(n);for await(let g of f)for(let x of h.decode(g))yield x;for(let g of h.flush())yield g}async function*d(){if(c)throw new u("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let h=!1;try{for await(let f of l()){if(h)continue;if(f)yield JSON.parse(f)}h=!0}catch(f){if(ze(f))return;throw f}finally{if(!h)t.abort();Ne(t)}}return new s(d,t,a)}[(Vt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let n=[],t=[],a=this.iterator(),c=(l)=>({next:()=>{if(l.length===0){let d=a.next();n.push(d),t.push(d)}return l.shift()}});return[new s(()=>c(n),this.controller,e(this,Vt,"f")),new s(()=>c(t),this.controller,e(this,Vt,"f"))]}toReadableStream(){let n=this,t;return di({async start(){t=n[Symbol.asyncIterator]()},async pull(a){try{let{value:c,done:l}=await t.next();if(l)return a.close();let d=Ot(JSON.stringify(c)+`
|
|
5
|
-
`);a.enqueue(d)}catch(c){a.error(c)}},async cancel(){await t.return?.()}})}}return s})();async function*oa(s,n){if(!s.body){if(n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new u("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 u("Attempted to iterate over a response with no body")}let t=new aa,a=new zt,c=Kt(s.body);for await(let l of c)for(let d of a.decode(l)){let h=t.decode(d);if(h)yield h}for(let l of a.flush()){let d=t.decode(l);if(d)yield d}}class aa{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(s){if(s.endsWith("\r"))s=s.substring(0,s.length-1);if(!s){if(!this.event&&!this.data.length)return null;let c={event:this.event,data:this.data.join(`
|
|
6
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],c}if(this.chunks.push(s),s.startsWith(":"))return null;let[n,t,a]=Lc(s,":");if(a.startsWith(" "))a=a.substring(1);if(n==="event")this.event=a;else if(n==="data")this.data.push(a);return null}}function Lc(s,n){let t=s.indexOf(n);if(t!==-1)return[s.substring(0,t),n,s.substring(t+n.length)];return[s,"",""]}async function jn(s,n){let{response:t,requestLogID:a,retryOfRequestLogID:c,startTime:l}=n,d=await(async()=>{if(n.options.stream)return T(s).debug("response",t.status,t.url,t.headers,t.body),Fe.fromSSEResponse(t,n.controller,s);if(t.status===204)return null;if(n.options.__binaryResponse)return t;let f=t.headers.get("content-type")?.split(";")[0]?.trim();if(f?.includes("application/json")||f?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let k=await t.json();return Yt(k,t)}return await t.text()})().finally(()=>{if(!n.options.stream&&!n.options.__binaryResponse)Ne(n.controller)});return Ze(T(s),`[${a}] response parsed`,{retryOfRequestLogID:c,url:t.url,status:t.status,body:d,durationMs:Date.now()-l}),d}function Yt(s,n){if(!s||typeof s!=="object"||Array.isArray(s))return s;return Object.defineProperties(s,{_request_id:{value:n.headers.get("request-id"),enumerable:!1},_workspace_id:{value:n.headers.get("anthropic-workspace-id"),enumerable:!1}})}var la=new WeakSet;function vi(s){return typeof s==="object"&&s!==null&&la.has(s)}function ua(s){let n=new Set;while(typeof s==="object"&&s!==null&&!n.has(s)){if(n.add(s),vi(s)||ze(s)||s instanceof wt||s instanceof _o)return!0;s=s.cause}return!1}function xi(s,n,t,a){return async(c,l={})=>{if(n.length===0)return s.call(void 0,c,l);let d=l.headers instanceof Headers?l.headers:new Headers(l.headers),h=await Fc(s,n,t,a)({...l,headers:d,url:typeof c==="string"?c:c instanceof URL?c.href:c.url});if(h.bodyUsed||h.body?.locked)throw new u("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return h}}function $c(s,n){let t=new WeakMap;return{options:s,logger:n?T(n):oi(),parse(a){if(s?.stream&&a.ok)return ca(a,s,n);let c=t.get(a);if(!c)c=ca(a,s,n),t.set(a,c);return c}}}async function ca(s,n,t){if(s.bodyUsed||s.body?.locked)throw new u("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(n?.stream&&s.ok)return Fe.fromSSEResponse(s.clone(),new AbortController,t);if(s.status===204)return null;if(n?.__binaryResponse)return s;let c=s.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(s.headers.get("content-length")==="0")return;return Yt(await s.clone().json(),s)}return await s.clone().text()}function Fc(s,n,t,a){let c=async({url:d,...h})=>{try{return await s.call(void 0,d,h)}catch(f){let g=Lt(f);throw la.add(g),g}},l=$c(t,a);for(let d=n.length-1;d>=0;d--){let h=n[d],f=c;c=async(g)=>h(g,f,l)}return c}var Jt,qn=(()=>{class s extends Promise{constructor(n,t,a=jn){super((c)=>{c(null)});this.responsePromise=t,this.parseResponse=a,Jt.set(this,void 0),o(this,Jt,n,"f")}_thenUnwrap(n){return new s(e(this,Jt,"f"),this.responsePromise,async(t,a)=>Yt(n(await this.parseResponse(t,a),a),a.response))}asResponse(){return this.responsePromise.then((n)=>n.response)}async withResponse(){let[n,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:n,response:t,request_id:t.headers.get("request-id"),workspace_id:t.headers.get("anthropic-workspace-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((n)=>this.parseResponse(e(this,Jt,"f"),n));return this.parsedPromise}then(n,t){return this.parse().then(n,t)}catch(n){return this.parse().catch(n)}finally(n){return this.parse().finally(n)}}return Jt=new WeakMap,s})();var Kn,Ei=(()=>{class s{constructor(n,t,a,c){Kn.set(this,void 0),o(this,Kn,n,"f"),this.options=c,this.response=t,this.body=a}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let n=this.nextPageRequestOptions();if(!n)throw new u("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await e(this,Kn,"f").requestAPIList(this.constructor,n)}async*iterPages(){let n=this;yield n;while(n.hasNextPage())n=await n.getNextPage(),yield n}async*[(Kn=new WeakMap,Symbol.asyncIterator)](){for await(let n of this.iterPages())for(let t of n.getPaginatedItems())yield t}}return s})(),da=(()=>{class s extends qn{constructor(n,t,a){super(n,t,async(c,l)=>new a(c,l.response,await jn(c,l),l.options))}async*[Symbol.asyncIterator](){let n=await this;for await(let t of n)yield t}}return s})();class ie extends Ei{constructor(s,n,t,a){super(s,n,t,a);this.data=t.data||[],this.has_more=t.has_more||!1,this.first_id=t.first_id||null,this.last_id=t.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 n=this.first_id;if(!n)return null;return{...this.options,query:{...Cr(this.options.query),before_id:n}}}let s=this.last_id;if(!s)return null;return{...this.options,query:{...Cr(this.options.query),after_id:s}}}}class C extends Ei{constructor(s,n,t,a){super(s,n,t,a);this.data=t.data||[],this.next_page=t.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let s=this.next_page;if(!s)return null;return{...this.options,query:{...Cr(this.options.query),page:s}}}}class Ai extends Ei{constructor(s,n,t,a){super(s,n,t,a);this.data=t.data||[],this.next_page=t.next_page||null,this.prev_page=t.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let s=this.next_page;if(!s)return null;return{...this.options,query:{...Cr(this.options.query),page:s}}}}var Ii=()=>{if(typeof File>"u"){let{process:s}=globalThis,n=typeof s?.versions?.node==="string"&&parseInt(s.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function nt(s,n,t){return Ii(),new File(s,n??"",t)}function Gt(s,n){let t=typeof s==="object"&&s!==null&&(("name"in s)&&s.name&&String(s.name)||("url"in s)&&s.url&&String(s.url)||("filename"in s)&&s.filename&&String(s.filename)||("path"in s)&&s.path&&String(s.path))||"";return n?t.split(/[\\/]/).pop()||void 0:t}var Ti=(s)=>s!=null&&typeof s==="object"&&typeof s[Symbol.asyncIterator]==="function";var Re=async(s,n,t=!0)=>({...s,body:await Bc(s.body,n,t)}),ha=new WeakMap;function Dc(s){let n=typeof s==="function"?s:s.fetch,t=ha.get(n);if(t)return t;let a=(async()=>{try{let c="Response"in n?n.Response:(await n("data:,")).constructor,l=new FormData;if(l.toString()===await new c(l).text())return!1;return!0}catch{return!0}})();return ha.set(n,a),a}var Bc=async(s,n,t=!0)=>{if(!await Dc(n))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let a=new FormData;return await Promise.all(Object.entries(s||{}).map(([c,l])=>Ri(a,c,l,t))),a};var Ri=async(s,n,t,a)=>{if(t===void 0)return;if(t==null)throw TypeError(`Received null for "${n}"; to pass null in FormData, you must use the string 'null'`);if(typeof t==="string"||typeof t==="number"||typeof t==="boolean")s.append(n,String(t));else if(t instanceof Response){let c={},l=t.headers.get("Content-Type");if(l)c={type:l};s.append(n,nt([await t.blob()],Gt(t,a),c))}else if(Ti(t))s.append(n,nt([await new Response(Nn(t)).blob()],Gt(t,a)));else if(t instanceof Blob){let l=typeof File<"u"&&t instanceof File?t.name:Gt(t,a);s.append(n,nt([t],l,{type:t.type}))}else if(Array.isArray(t))await Promise.all(t.map((c)=>Ri(s,n+"[]",c,a)));else if(typeof t.then==="function")throw TypeError(`Received a Promise for "${n}"; await it first, e.g. \`await toFile(...)\``);else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))throw TypeError(`Received ${t.constructor.name} for "${n}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);else if(typeof t==="object")await Promise.all(Object.entries(t).map(([c,l])=>Ri(s,`${n}[${c}]`,l,a)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)};var fa=(s)=>s!=null&&typeof s==="object"&&typeof s.size==="number"&&typeof s.type==="string"&&typeof s.text==="function"&&typeof s.slice==="function"&&typeof s.arrayBuffer==="function",Wc=(s)=>s!=null&&typeof s==="object"&&typeof s.name==="string"&&typeof s.lastModified==="number"&&fa(s),Uc=(s)=>s!=null&&typeof s==="object"&&typeof s.url==="string"&&typeof s.blob==="function";async function Ci(s,n,t){if(Ii(),s=await s,n||(n=s instanceof File?s.name:Gt(s,!0)),Wc(s)){if(s instanceof File&&n==null&&t==null)return s;return nt([await s.arrayBuffer()],n??s.name,{type:s.type,lastModified:s.lastModified,...t})}if(Uc(s)){let c=await s.blob();return n||(n=new URL(s.url).pathname.split(/[\\/]/).pop()),nt(await Pi(c),n,t)}let a=await Pi(s);if(!t?.type){let c=a.find((l)=>typeof l==="object"&&("type"in l)&&l.type);if(typeof c==="string")t={...t,type:c}}return nt(a,n,t)}async function Pi(s){let n=[];if(typeof s==="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)n.push(s);else if(fa(s))n.push(s instanceof Blob?s:await s.arrayBuffer());else if(Ti(s))for await(let t of s)n.push(...await Pi(t));else{let t=s?.constructor?.name;throw Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${jc(s)}`)}return n}function jc(s){if(typeof s!=="object"||s===null)return"";return`; props: [${Object.getOwnPropertyNames(s).map((t)=>`"${t}"`).join(", ")}]`}class A{constructor(s){this._client=s}}var pa=Symbol.for("brand.privateNullableHeaders");function*Kc(s){if(!s)return;if(pa in s){let{values:a,nulls:c}=s;yield*a.entries();for(let l of c)yield[l,null];return}let n=!1,t;if(s instanceof Headers)t=s.entries();else if(Ao(s))t=s;else n=!0,t=Object.entries(s??{});for(let a of t){let c=a[0];if(typeof c!=="string")throw TypeError("expected header name to be a string");let l=Ao(a[1])?a[1]:[a[1]],d=!1;for(let h of l){if(h===void 0)continue;if(n&&!d)d=!0,yield[c,zn];yield[c,h]}}}var zn=Symbol("clear"),zc=new Set(["x-stainless-helper"]),Vc=(s,n)=>{let t=s?s.split(",").map((a)=>a.trim()).filter(Boolean):[];for(let a of n.split(",").map((c)=>c.trim()))if(a&&!t.includes(a))t.push(a);return t.join(", ")},p=(s)=>{let n=new Headers,t=new Set;for(let a of s){let c=new Set;for(let[l,d]of Kc(a)){let h=l.toLowerCase();if(zc.has(h)){if(d===zn)continue;if(d===null)n.delete(l),t.add(h);else n.set(l,Vc(n.get(l),d)),t.delete(h);continue}if(d===zn||!c.has(h)){if(n.delete(l),c.add(h),d===zn)continue}if(d===null)n.delete(l),t.add(h);else n.append(l,d),t.delete(h)}}return{[pa]:!0,values:n,nulls:t}};function _a(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ma=Object.freeze(Object.create(null)),Yc=(s=_a)=>function(t,...a){if(t.length===1)return t[0];let c=!1,l=[],d=t.reduce((x,_,k)=>{if(/[?#]/.test(_))c=!0;let w=a[k],v=(c?encodeURIComponent:s)(""+w);if(k!==a.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??ma)??ma)?.toString))v=w+"",l.push({start:x.length+_.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return x+_+(k===a.length?"":v)},""),h=d.split(/[?#]/,1)[0],f=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,g;while((g=f.exec(h))!==null)l.push({start:g.index,length:g[0].length,error:`Value "${g[0]}" can't be safely passed as a path parameter`});if(l.sort((x,_)=>x.start-_.start),l.length>0){let x=0,_=l.reduce((k,w)=>{let v=" ".repeat(w.start-x),O="^".repeat(w.length);return x=w.start+w.length,k+v+O},"");throw new u(`Path parameters result in path with invalid segments:
|
|
7
|
-
${l.map((k)=>k.error).join(`
|
|
8
|
-
`)}
|
|
9
|
-
${d}
|
|
10
|
-
${_}`)}return d},m=Yc(_a);class Qt extends A{retrieve(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/deployment_runs/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",C,{query:c,...n,headers:p([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}}class er extends A{create(s,n){let{betas:t,workspace_id:a,...c}=s;return this._client.post("/v1/deployments?beta=true",{body:c,...n,headers:p([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}retrieve(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/deployments/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}update(s,n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post(m`/v1/deployments/${s}?beta=true`,{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/deployments?beta=true",C,{query:c,...n,headers:p([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}archive(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/deployments/${s}/archive?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}pause(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/deployments/${s}/pause?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}run(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/deployments/${s}/run?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}unpause(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/deployments/${s}/unpause?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}class tr extends A{create(s,n){let{betas:t,workspace_id:a,...c}=s;return this._client.post("/v1/dreams?beta=true",{body:c,...n,headers:p([{"anthropic-beta":[...t??[],"dreaming-2026-04-21"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}retrieve(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/dreams/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/dreams?beta=true",C,{query:c,...n,headers:p([{"anthropic-beta":[...t??[],"dreaming-2026-04-21"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}archive(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/dreams/${s}/archive?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}cancel(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/dreams/${s}/cancel?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}var Vn="x-stainless-helper",ft="x-stainless-helper-method";function Yn(s){return{["x-stainless-helper"]:s}}var ht=Symbol("anthropic.sdk.stainlessHelper");function rr(s){return typeof s==="object"&&s!==null&&ht in s}function Oi(s,n){let t=new Set;if(s){for(let a of s)if(rr(a))t.add(a[ht])}if(n)for(let a of n){if(rr(a))t.add(a[ht]);let c=a.content;if(Array.isArray(c))for(let l of c){if(rr(l))t.add(l[ht]);let d=l?.tool?.definition;if(rr(d))t.add(d[ht])}}return Array.from(t)}function Jn(s,n){let t=Oi(s,n);if(t.length===0)return{};return{["x-stainless-helper"]:t.join(", ")}}function Gn(s){if(rr(s))return{["x-stainless-helper"]:s[ht]};return{}}class nr extends A{list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/files?beta=true",C,{query:c,...n,headers:p([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}delete(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.delete(m`/v1/files/${s}?beta=true`,{...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}download(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/files/${s}/content?beta=true`,{...t,headers:p([{Accept:"application/binary",...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers]),__binaryResponse:!0})}retrieveMetadata(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/files/${s}?beta=true`,{...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}upload(s,n){let{betas:t,workspace_id:a,...c}=s;return this._client.post("/v1/files?beta=true",Re({body:c,...n,headers:p([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},Gn(c.file),n?.headers])},this._client))}}class sr extends A{retrieve(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/models/${s}?beta=true`,{...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/models?beta=true",ie,{query:c,...n,headers:p([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}}class ir extends A{create(s,n){let{betas:t,workspace_id:a,...c}=s;return this._client.post("/v1/user_profiles?beta=true",{body:c,...n,headers:p([{"anthropic-beta":[...t??[],"user-profiles-2026-08-18"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}retrieve(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/user_profiles/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}update(s,n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post(m`/v1/user_profiles/${s}?beta=true`,{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/user_profiles?beta=true",C,{query:c,...n,headers:p([{"anthropic-beta":[...t??[],"user-profiles-2026-08-18"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}createEnrollmentURL(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/user_profiles/${s}/enrollment_url?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}var Ca=i(Pa(),1);class cr extends A{parseUnverified(s){return JSON.parse(s)}unwrap(s,n){let t=n?.headers;if(t==null)throw Error("Webhook headers are required in order to verify the signature");let a=n.key===void 0?this._client.webhookKey:n.key;if(!a)throw Error("Webhook key must not be null or empty in order to unwrap");return new Ca.Webhook(a).verify(s,t),JSON.parse(s)}}class lr extends A{list(s,n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList(m`/v1/agents/${s}/versions?beta=true`,C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}var Zn=(()=>{class s extends A{constructor(){super(...arguments);this.versions=new lr(this._client)}create(n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post("/v1/agents?beta=true",{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c,workspace_id:l,...d}=t??{};return this._client.get(m`/v1/agents/${n}?beta=true`,{query:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}update(n,t,a){let{betas:c,workspace_id:l,...d}=t;return this._client.post(m`/v1/agents/${n}?beta=true`,{body:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}list(n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList("/v1/agents?beta=true",C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}archive(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.post(m`/v1/agents/${n}/archive?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}}return s.Versions=lr,s})();function Ke(s,n){if(!s)return()=>{};if(s.aborted)return n.abort(),()=>{};let t=()=>n.abort();return s.addEventListener("abort",t),()=>s.removeEventListener("abort",t)}function es(s,{authToken:n,helper:t}){if(!n)throw new u(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(n)}`);let a=s,c=a._options.defaultHeaders,l=a._authState?.extraHeaders,d=l?Object.fromEntries(Object.entries(l).filter(([f])=>{let g=f.toLowerCase();return g!=="authorization"&&g!=="x-api-key"})):void 0,h=p([d,c,{[Vn]:t}]);return s.withOptions({apiKey:null,authToken:n,baseURL:s.baseURL,credentials:void 0,defaultHeaders:h})}var pt,ts,Ie,rs,ns,ss,ur,dr,mt,gt,is,yt,hr,hl=999,fl=1000,pl=60000,ml=300000,fr=(()=>{class s{constructor(n){pt.set(this,void 0),ts.set(this,!1),Ie.set(this,void 0),rs.set(this,void 0),ns.set(this,void 0),ss.set(this,void 0),ur.set(this,void 0),dr.set(this,void 0),mt.set(this,void 0),this.client=n.client,this.environmentId=n.environmentId,this.environmentKey=n.environmentKey,this.workerId=n.workerId??wl(),o(this,pt,es(n.client,{authToken:n.environmentKey,helper:"environments-work-poller"}),"f"),o(this,ns,n.autoStop??!0,"f"),o(this,ss,n.drain??!1,"f"),o(this,ur,n.blockMs===void 0?hl:n.blockMs,"f"),o(this,dr,n.reclaimOlderThanMs??null,"f"),o(this,mt,n.requestOptions,"f"),o(this,Ie,new AbortController,"f"),o(this,rs,Ke(n.signal,e(this,Ie,"f")),"f")}get signal(){return e(this,Ie,"f").signal}abort(){e(this,Ie,"f").abort()}async*[(pt=new WeakMap,ts=new WeakMap,Ie=new WeakMap,rs=new WeakMap,ns=new WeakMap,ss=new WeakMap,ur=new WeakMap,dr=new WeakMap,mt=new WeakMap,Symbol.asyncIterator)](){if(e(this,ts,"f"))throw new u("Cannot iterate over a consumed WorkPoller");o(this,ts,!0,"f");let n=T(this.client);n.info("poller starting",{component:"work-poller",environment_id:this.environmentId});let t=new gl(n,this.environmentId);try{let a=0;while(!e(this,Ie,"f").signal.aborted){let c;try{c=await e(this,pt,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...e(this,ur,"f")!==null?{block_ms:e(this,ur,"f")}:{},...e(this,dr,"f")!==null?{reclaim_older_than_ms:e(this,dr,"f")}:{}},{headers:p([e(this,mt,"f")?.headers]),signal:e(this,Ie,"f").signal})}catch(l){if(e(this,Ie,"f").signal.aborted)return;if(Nt(l))throw n.error("poll failed permanently, stopping poller",{error:String(l)}),l;let d=Cn(_l(a));n.warn("poll failed, backing off",{error:String(l),backoff_ms:d}),a++,await Ce(d,e(this,Ie,"f").signal);continue}if(a=0,c==null){if(e(this,ss,"f"))return;t.onEmptyPoll(),await Ce(ii(1000,3000),e(this,Ie,"f").signal);continue}t.onClaim(),n.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:c.id,work_type:c.data.type});try{await e(this,pt,"f").beta.environments.work.ack(c.id,{environment_id:c.environment_id},{headers:p([e(this,mt,"f")?.headers]),signal:e(this,Ie,"f").signal})}catch(l){n.error("ack failed",{work_id:c.id,error:String(l)});continue}try{yield c}finally{if(e(this,ns,"f"))try{await e(this,pt,"f").beta.environments.work.stop(c.id,{environment_id:c.environment_id},{headers:p([e(this,mt,"f")?.headers])})}catch(l){if(!ue(l,409))n.warn("stop failed",{work_id:c.id,error:String(l)})}}}}finally{e(this,rs,"f").call(this)}}}return s})();function _l(s){return Rn(s,fl,pl)}var gl=(()=>{class s{constructor(n,t){gt.set(this,void 0),is.set(this,void 0),yt.set(this,void 0),hr.set(this,0),o(this,gt,n,"f"),o(this,is,t,"f")}onEmptyPoll(){let n=Date.now(),t={component:"work-poller",environment_id:e(this,is,"f")};if(e(this,yt,"f")===void 0)o(this,yt,o(this,hr,n,"f"),"f"),e(this,gt,"f").info("idle; polling for work",t);else if(n-e(this,hr,"f")>=ml)o(this,hr,n,"f"),e(this,gt,"f").info(`still polling; idle for ${Math.round((n-e(this,yt,"f"))/1000)}s`,t);else e(this,gt,"f").debug("poll returned no work",t)}onClaim(){o(this,yt,void 0,"f")}}return gt=new WeakMap,is=new WeakMap,yt=new WeakMap,hr=new WeakMap,s})();function wl(){let n=globalThis.process?.env?.HOSTNAME;return n?`${n}-${Wn()}`:Wn()}var bt,Ve,kt,Oa=(()=>{class s{constructor(){bt.set(this,[]),Ve.set(this,[]),kt.set(this,!1)}push(n){if(e(this,kt,"f"))return!1;let t=e(this,Ve,"f").shift();if(t)t({done:!1,value:n});else e(this,bt,"f").push(n);return!0}close(){if(e(this,kt,"f"))return;o(this,kt,!0,"f");while(e(this,Ve,"f").length>0)e(this,Ve,"f").shift()({done:!0,value:void 0})}next(n){if(e(this,bt,"f").length>0)return Promise.resolve({done:!1,value:e(this,bt,"f").shift()});if(e(this,kt,"f")||n?.aborted)return Promise.resolve({done:!0,value:void 0});return new Promise((t)=>{let a=(l)=>{n?.removeEventListener("abort",c),t(l)},c=()=>{let l=e(this,Ve,"f").indexOf(a);if(l>=0)e(this,Ve,"f").splice(l,1);t({done:!0,value:void 0})};e(this,Ve,"f").push(a),n?.addEventListener("abort",c,{once:!0})})}tryShift(){return e(this,bt,"f").shift()}}return bt=new WeakMap,Ve=new WeakMap,kt=new WeakMap,s})();function Li(s){return"name"in s?s.name:("mcp_server_name"in s)?s.mcp_server_name:s.type}function yl(s){return s instanceof E?s.content:`Error: ${s instanceof Error?s.message:String(s)}`}async function Ma(s,n,t){try{let a=s.parse?s.parse(n):n;return{content:await s.run(a,t),isError:!1}}catch(a){return{content:yl(a),isError:!0}}}var pr,os,St,st,Me,G,as,ae,cs,mr,ls,te,Et,be,Rt,Ye,It,Ue,us,_r,Te,ds,Na,La,$a,Fa,$i,Ha,hs,fs,Fi,Da,Ba;var Wa=500,bl=1e4,kl=120000,Sl=30000,vl=1000,xl=30000,El=300000,Al=60000;function Ua(s){return s.type==="session.status_idle"&&s.stop_reason?.type==="end_turn"}var Rl=(()=>{class s{constructor(n,t){pr.set(this,void 0),os.set(this,void 0),St.set(this,new Set),st.set(this,!1),Me.set(this,void 0),o(this,pr,n,"f"),o(this,os,t,"f")}noteEvent(n){if(n.type==="user.tool_confirmation")return;if(Ua(n))this.arm();else this.disarm()}block(n){if(e(this,St,"f").add(n),e(this,Me,"f")!==void 0)o(this,st,!0,"f"),clearTimeout(e(this,Me,"f")),o(this,Me,void 0,"f")}unblock(n){if(e(this,St,"f").delete(n),e(this,St,"f").size===0&&e(this,st,"f"))this.arm()}arm(){if(e(this,pr,"f")<=0)return;if(e(this,St,"f").size>0){o(this,st,!0,"f");return}if(o(this,st,!1,"f"),e(this,Me,"f")!==void 0)clearTimeout(e(this,Me,"f"));o(this,Me,setTimeout(e(this,os,"f"),e(this,pr,"f")),"f")}disarm(){if(o(this,st,!1,"f"),e(this,Me,"f")!==void 0)clearTimeout(e(this,Me,"f")),o(this,Me,void 0,"f")}}return pr=new WeakMap,os=new WeakMap,St=new WeakMap,st=new WeakMap,Me=new WeakMap,s})(),gr=(()=>{class s{constructor(n,t){G.add(this),as.set(this,!1),ae.set(this,void 0),cs.set(this,void 0),mr.set(this,void 0),ls.set(this,void 0),te.set(this,void 0),Et.set(this,new Set),be.set(this,new Set),Rt.set(this,new Map),Ye.set(this,new Map),It.set(this,new Oa),Ue.set(this,0),us.set(this,El),_r.set(this,null),Te.set(this,void 0),this.client=t.client,this.sessionId=n,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??Al,o(this,te,T(t.client),"f"),o(this,ls,new Map(t.tools.map((a)=>[Li(a),a])),"f"),o(this,ae,new AbortController,"f"),o(this,cs,Ke(t.signal,e(this,ae,"f")),"f"),o(this,mr,t.requestOptions,"f"),o(this,Te,new Rl(this.maxIdleMs,()=>{e(this,te,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),e(this,ae,"f").abort()}),"f")}get signal(){return e(this,ae,"f").signal}abort(){e(this,ae,"f").abort()}_setSendRetryWindow(n){o(this,us,n,"f")}async*[(as=new WeakMap,ae=new WeakMap,cs=new WeakMap,mr=new WeakMap,ls=new WeakMap,te=new WeakMap,Et=new WeakMap,be=new WeakMap,Rt=new WeakMap,Ye=new WeakMap,It=new WeakMap,Ue=new WeakMap,us=new WeakMap,_r=new WeakMap,Te=new WeakMap,G=new WeakSet,Symbol.asyncIterator)](){if(e(this,as,"f"))throw new u("Cannot iterate over a consumed SessionToolRunner");o(this,as,!0,"f"),e(this,te,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});let n=e(this,G,"m",Na).call(this).catch((t)=>{if(!e(this,ae,"f").signal.aborted)e(this,te,"f").error("stream loop failed",{error:String(t)});e(this,ae,"f").abort()});try{while(!0){let a=await e(this,It,"f").next(e(this,ae,"f").signal);if(a.done)break;yield a.value}await n;let t;while((t=e(this,It,"f").tryShift())!==void 0)yield t}finally{e(this,ae,"f").abort(),e(this,Te,"f").disarm(),await n;try{await e(this,G,"m",Ba).call(this)}catch(t){e(this,te,"f").warn("drain failed",{error:String(t)})}e(this,It,"f").close();for(let t of this.tools)try{await t.close?.()}catch(a){e(this,te,"f").warn("tool.close failed",{tool:Li(t),error:String(a)})}e(this,cs,"f").call(this)}}}return ds=function(){return{...e(this,mr,"f"),headers:p([Yn("session-tool-runner"),e(this,mr,"f")?.headers]),signal:e(this,ae,"f").signal}},Na=async function(){let t=e(this,ae,"f"),a=Wa;while(!t.signal.aborted){try{let c=await this.client.beta.sessions.events.stream(this.sessionId,{},e(this,G,"m",ds).call(this));await e(this,G,"m",La).call(this);for await(let l of c)if(a=Wa,await e(this,G,"m",Fa).call(this,l))return}catch(c){if(t.signal.throwIfAborted(),Nt(c))throw e(this,te,"f").error("permanent stream failure, shutting down",{error:String(c)}),t.abort(),c;e(this,te,"f").warn("stream disconnected, reconnecting",{error:String(c),backoff_ms:a})}t.signal.throwIfAborted(),await Ce(a,t.signal),a=Math.min(a*2,bl)}},La=async function(){let t=e(this,ae,"f"),a=[],c=!1;try{for await(let h of this.client.beta.sessions.events.list(this.sessionId,{limit:1000},e(this,G,"m",ds).call(this)))e(this,G,"m",$a).call(this,h,a),c=Ua(h)}catch(h){t.signal.throwIfAborted(),e(this,te,"f").warn("reconcile list failed",{error:String(h)});for(let f of a)e(this,Et,"f").delete(f.id);return}let l=a.filter((h)=>!e(this,be,"f").has(h.id));e(this,Te,"f").disarm();for(let h of l)await e(this,G,"m",$i).call(this,h);for(let h of[...e(this,Ye,"f").values()]){let f=e(this,Rt,"f").get(h.id);if(f!==void 0)await e(this,G,"m",hs).call(this,h,f)}let d=l.filter((h)=>!e(this,be,"f").has(h.id)&&!e(this,Ye,"f").has(h.id));if(c&&d.length===0)e(this,Te,"f").arm();else e(this,Te,"f").disarm()},$a=function(t,a){if(t.type==="agent.tool_use"||t.type==="agent.custom_tool_use"){if(e(this,Et,"f").add(t.id),!e(this,be,"f").has(t.id))a.push(t)}else if(t.type==="user.tool_result")e(this,be,"f").add(t.tool_use_id);else if(t.type==="user.custom_tool_result")e(this,be,"f").add(t.custom_tool_use_id);else if(t.type==="user.tool_confirmation"){if(!e(this,be,"f").has(t.tool_use_id))e(this,Rt,"f").set(t.tool_use_id,t.result)}},Fa=async function(t){switch(e(this,Te,"f").noteEvent(t),t.type){case"agent.tool_use":case"agent.custom_tool_use":if(!e(this,Et,"f").has(t.id))e(this,Et,"f").add(t.id),await e(this,G,"m",$i).call(this,t);return!1;case"user.tool_confirmation":return await e(this,G,"m",Ha).call(this,t),!1;case"user.tool_result":return e(this,be,"f").add(t.tool_use_id),!1;case"user.custom_tool_result":return e(this,be,"f").add(t.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return e(this,te,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),e(this,ae,"f").abort(),!0;default:return!1}},$i=async function(t){let a=t.evaluated_permission,c=a==="deny"?"deny":e(this,Rt,"f").get(t.id);if(c===void 0){if(a===void 0||a==="allow")await e(this,G,"m",Fi).call(this,t,void 0);else if(!e(this,Ye,"f").has(t.id))e(this,te,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:t.name,tool_use_id:t.id}),e(this,Ye,"f").set(t.id,t),e(this,Te,"f").block(t.id);return}await e(this,G,"m",hs).call(this,t,c)},Ha=async function(t){e(this,Rt,"f").set(t.tool_use_id,t.result);let a=e(this,Ye,"f").get(t.tool_use_id);if(a===void 0)return;await e(this,G,"m",hs).call(this,a,t.result)},hs=async function(t,a){let c=e(this,Ye,"f").delete(t.id);if(a==="allow"){if(e(this,te,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:t.name,tool_use_id:t.id}),!c)e(this,Te,"f").block(t.id);try{await e(this,G,"m",Fi).call(this,t,"allow")}finally{e(this,Te,"f").unblock(t.id)}return}if(c)e(this,Te,"f").unblock(t.id);e(this,be,"f").add(t.id),e(this,te,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:t.name,tool_use_id:t.id}),e(this,G,"m",fs).call(this,{event:t,toolUseId:t.id,name:t.name,isError:!1,posted:!1,confirmation:"deny"})},fs=function(t){e(this,It,"f").push(t)},Fi=async function(t,a){var c,l;if(e(this,be,"f").has(t.id))return;e(this,te,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:t.name,tool_use_id:t.id}),o(this,Ue,(c=e(this,Ue,"f"),c++,c),"f");try{let d=e(this,ls,"f").get(t.name);if(!d){e(this,te,"f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner",{component:"session-tool-runner",session_id:this.sessionId,tool:t.name,tool_use_id:t.id}),e(this,G,"m",fs).call(this,{event:t,toolUseId:t.id,name:t.name,isError:!1,posted:!1,confirmation:a});return}let h,f,g=new AbortController,x=Ke(e(this,ae,"f").signal,g),_=setTimeout(()=>g.abort(),kl);try{let v=await Ma(d,t.input,{toolUse:t,toolUseBlock:t,signal:g.signal});h=v.content,f=v.isError}finally{clearTimeout(_),x()}let k=Il(t,f,Tl(h)),w=await e(this,G,"m",Da).call(this,k,t.id);e(this,G,"m",fs).call(this,{event:t,result:k,toolUseId:t.id,name:t.name,isError:f,posted:w,confirmation:a})}finally{if(o(this,Ue,(l=e(this,Ue,"f"),l--,l),"f"),e(this,Ue,"f")===0)e(this,_r,"f")?.call(this)}},Da=async function(t,a){let c=e(this,ae,"f"),l=Date.now(),d,h=0;while(!0){h++,c.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[t]},e(this,G,"m",ds).call(this)),e(this,be,"f").add(a),!0}catch(f){if(d=f,Nt(f))break;let g=e(this,us,"f")-(Date.now()-l);if(g<=0)break;let x=Math.min(Cn(Rn(h-1,vl,xl)),g);e(this,te,"f").warn("tool result send failed; retrying",{tool_use_id:a,attempt:h,backoff_ms:x,error:String(f)}),await Ce(x,c.signal)}}return e(this,te,"f").error("failed to send tool result",{tool_use_id:a,attempts:h,error:String(d)}),!1},Ba=async function(){if(e(this,Ue,"f")===0)return;if(await Promise.race([new Promise((t)=>o(this,_r,t,"f")),Ce(Sl)]),o(this,_r,null,"f"),e(this,Ue,"f")>0)e(this,te,"f").warn("drain timeout exceeded")},s})();function Il(s,n,t){if(s.type==="agent.custom_tool_use")return{type:"user.custom_tool_result",custom_tool_use_id:s.id,is_error:n,content:t};return{type:"user.tool_result",tool_use_id:s.id,is_error:n,content:t}}function Tl(s){if(typeof s==="string")return[{type:"text",text:s||"(no output)"}];let n=s.map((t)=>{if(t.type==="text")return{type:"text",text:t.text||"(no output)"};if(t.type==="image"||t.type==="document")return t;if(t.type==="search_result")return{type:"search_result",source:t.source,title:t.title,content:t.content.map((a)=>({type:"text",text:a.text})),citations:{enabled:t.citations?.enabled??!1}};return{type:"text",text:JSON.stringify(t)}});return n.length>0?n:[{type:"text",text:"(no output)"}]}var ps,wr,Hi,yr,Tt,ja=30000,Pl=90000,Cl="NO_HEARTBEAT";function Ol(s){return s.resources.some((n)=>n.type==="memory_store")}function Ml(s){if(!s)return null;let n;try{let a=s.replace(/-/g,"+").replace(/_/g,"/"),c=a.padEnd(Math.ceil(a.length/4)*4,"=");n=JSON.parse(vt(Xo(c)))}catch{return null}if(n===null||typeof n!=="object"||Array.isArray(n))return null;let t=n.sessions_token;return typeof t==="string"&&t!==""?t:null}var Di=(()=>{class s{constructor(n){if(ps.add(this),wr.set(this,void 0),n.unrestrictedPaths!==void 0)throw new u("The `unrestrictedPaths` option you passed to EnvironmentWorker (or client.beta.environments.work.worker()) is no longer supported. The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a `tools` factory.");if(this.client=n.client,this.environmentId=n.environmentId,this.environmentKey=n.environmentKey,this.tools=n.tools,this.workdir=n.workdir??process.cwd(),this.maxFileBytes=n.maxFileBytes,this.maxIdleMs=n.maxIdleMs,n.memorySyncIntervalMs!=null)Mr(n.memorySyncIntervalMs,"memorySyncIntervalMs");this.memorySyncIntervalMs=n.memorySyncIntervalMs,this.memorySyncDeletions=n.memorySyncDeletions??"enabled",this.workerId=n.workerId,this.requestOptions=n.requestOptions,o(this,wr,n.signal,"f")}async run(n){let{environmentId:t,environmentKey:a}=this;if(t===void 0||a===void 0)throw new u("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");let c=n??e(this,wr,"f"),l=new fr({client:this.client,environmentId:t,environmentKey:a,...this.workerId!==void 0?{workerId:this.workerId}:{},...c?{signal:c}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(let d of l)try{await e(this,ps,"m",Hi).call(this,d,a,l.signal)}catch(h){if(l.signal?.aborted)throw h;T(this.client).error("work item failed",{work_id:d.id,error:String(h)})}}async handleItem(n){let t=n?.workId??R("ANTHROPIC_WORK_ID"),a=n?.environmentId??R("ANTHROPIC_ENVIRONMENT_ID"),c=n?.sessionId??R("ANTHROPIC_SESSION_ID"),l=(n?.environmentKey??this.environmentKey??R("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,d=n?.workSecret||R("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new u("handleItem: workId is required \u2014 pass it or set ANTHROPIC_WORK_ID");if(!a)throw new u("handleItem: environmentId is required \u2014 pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!c)throw new u("handleItem: sessionId is required \u2014 pass it or set ANTHROPIC_SESSION_ID");if(!l&&!d)throw new u("handleItem: environmentKey is required when there is no work secret \u2014 pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");let h={id:t,environment_id:a,secret:d,data:{type:"session",id:c}};await e(this,ps,"m",Hi).call(this,h,l,n?.signal??e(this,wr,"f"))}}return wr=new WeakMap,ps=new WeakSet,Hi=async function(t,a,c){let l=T(this.client),d=Ml(t.secret),h=d??a;if(h===void 0)throw new u("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");if(t.secret&&d===null)l.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key",{work_id:t.id});let f=es(this.client,{authToken:h,helper:"environments-worker"}),g=t.data.id,x=new AbortController,_=Ke(c,x),k=new Ll(x),w=await import("./chunk-xh444pfn.js"),v,O,S=Fl(f,t,k,l,this.requestOptions,(L)=>{v=L,O?._setSendRetryWindow(L)}).catch((L)=>{if(!x.signal.aborted)l.error("heartbeat loop failed",{work_id:t.id,error:String(L)});x.abort()}),I=async()=>{},b,N=!1;try{if(t.data.type!=="session"){l.debug("skipping non-session work item",{work_id:t.id,type:t.data.type});return}let L=await f.beta.sessions.retrieve(g);if(d===null&&this.memorySyncIntervalMs!==null&&Ol(L))throw new w.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${t.id}, session_id=${g}); the memory endpoints reject the environment key, so the poller must issue a per-item \`secret\` carrying \`sessions_token\`, or set \`memorySyncIntervalMs: null\` to run without memory`);let F={workdir:this.workdir,client:f,session:L,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{I=await w.setupSkills(F)}catch(H){l.warn("skill setup failed",{session_id:g,work_id:t.id,error:String(H)})}if(d!==null&&this.memorySyncIntervalMs!==null)b=new w.SessionMemoryStores(f,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await b.download(L),F.allowedRoots=b.roots,F.readOnlyRoots=b.readOnlyRoots;else l.debug("memory stores disabled for this item",{work_id:t.id});let Y=typeof this.tools==="function"?this.tools(F):this.tools??w.betaAgentToolset20260401(F);if(O=new gr(g,{client:f,tools:Y,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:x.signal}),v!==void 0)O._setSendRetryWindow(v);for await(let H of O)if(b)await b.syncIfDue();N=!x.signal.aborted}finally{try{await I().catch((L)=>{l.warn("skill cleanup failed",{session_id:g,work_id:t.id,error:String(L)})})}finally{if(b){let L=w.MEMORY_FLUSH_TIMEOUT_MS;if(N){if(await qa(b.finish(),L))l.warn(`final memory sync cut off after ${L}ms; the flush that follows still uploads changed files`,{session_id:g,work_id:t.id})}let F=new AbortController;if(await qa(b.flushWrites(F.signal),L))F.abort(),l.warn(`memory flush cut off after ${L}ms; changed files it had not uploaded yet are not saved`,{session_id:g,work_id:t.id});await b.dispose().catch((H)=>{l.warn("memory store cleanup failed",{session_id:g,work_id:t.id,error:String(H)})})}}if(k.finish("runner_done"),_(),await S,k.lost)l.info("lease lost; released without stopping it",{session_id:g,work_id:t.id});else await Nl(f,t,l,this.requestOptions)}},s})();async function qa(s,n){let t;try{return await Promise.race([s.then(()=>!1,()=>!1),new Promise((a)=>{t=setTimeout(()=>a(!0),n)})])}finally{if(t!==void 0)clearTimeout(t)}}async function Nl(s,n,t,a){try{await s.beta.environments.work.stop(n.id,{environment_id:n.environment_id,force:!0},{...a,headers:p([a?.headers])})}catch(c){if(!ue(c,409))t.error("force-stop on exit failed",{work_id:n.id,error:String(c)})}}var Ll=(()=>{class s{constructor(n){yr.set(this,void 0),Tt.set(this,void 0),o(this,yr,n,"f")}get signal(){return e(this,yr,"f").signal}finish(n){o(this,Tt,e(this,Tt,"f")??n,"f"),e(this,yr,"f").abort()}get lost(){return e(this,Tt,"f")==="lease_lost"||e(this,Tt,"f")==="assumed_lost"}}return yr=new WeakMap,Tt=new WeakMap,s})();function $l(s){let n=s instanceof Z?s.error:void 0;for(let t of["error","details","current_state"]){if(!Po(n))return{};n=n[t]}return Po(n)?n:{}}async function Fl(s,n,t,a,c,l){let d=ja,h=Pl,f=Date.now(),g=Cl,x=async()=>{let _=new AbortController,k=Ke(t.signal,_),w=setTimeout(()=>_.abort(),d);try{let v=await s.beta.environments.work.heartbeat(n.id,{environment_id:n.environment_id,expected_last_heartbeat:g},{...c,headers:p([c?.headers]),signal:_.signal});if(f=Date.now(),g=v.last_heartbeat,v.ttl_seconds>0)h=v.ttl_seconds*1000,d=Math.max(1000,Math.min(h/2,ja)),l?.(h);if(v.state==="stopping"||v.state==="stopped")a.info("heartbeat signals shutdown",{work_id:n.id,state:v.state}),t.finish("control_plane_stop");if(!v.lease_extended)a.warn("lease not extended, shutting down",{work_id:n.id}),t.finish("control_plane_stop")}catch(v){if(t.signal.throwIfAborted(),ue(v,412)){let O=$l(v);a.error("lease lost: heartbeat precondition failed",{work_id:n.id,server_state:O.state,server_ttl_seconds:O.ttl_seconds,server_last_heartbeat:O.last_heartbeat}),t.finish("lease_lost");return}if(Nt(v))throw a.error("permanent heartbeat failure",{work_id:n.id,error:String(v)}),t.finish("heartbeat_rejected"),v;if(Date.now()-f>h){a.error("lease assumed lost: no successful heartbeat in ttl",{work_id:n.id,ttl_ms:h,error:String(v)}),t.finish("assumed_lost");return}a.warn("transient heartbeat failure",{work_id:n.id,error:String(v)})}finally{clearTimeout(w),k()}};await x();while(!t.signal.aborted)await Ce(d,t.signal),t.signal.throwIfAborted(),await x()}var ms=(()=>{class s extends A{retrieve(n,t,a){let{environment_id:c,betas:l,workspace_id:d}=t;return this._client.get(m`/v1/environments/${c}/work/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...l??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},a?.headers])})}update(n,t,a){let{environment_id:c,betas:l,workspace_id:d,...h}=t;return this._client.post(m`/v1/environments/${c}/work/${n}?beta=true`,{body:h,...a,headers:p([{"anthropic-beta":[...l??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},a?.headers])})}list(n,t={},a){let{betas:c,...l}=t??{};return this._client.getAPIList(m`/v1/environments/${n}/work?beta=true`,C,{query:l,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString()},a?.headers])})}ack(n,t,a){let{environment_id:c,betas:l}=t;return this._client.post(m`/v1/environments/${c}/work/${n}/ack?beta=true`,{...a,headers:p([{"anthropic-beta":[...l??[],"managed-agents-2026-04-01"].toString()},a?.headers])})}heartbeat(n,t,a){let{environment_id:c,desired_ttl_seconds:l,expected_last_heartbeat:d,betas:h}=t;return this._client.post(m`/v1/environments/${c}/work/${n}/heartbeat?beta=true`,{query:{desired_ttl_seconds:l,expected_last_heartbeat:d},...a,headers:p([{"anthropic-beta":[...h??[],"managed-agents-2026-04-01"].toString()},a?.headers])})}poll(n,t={},a){let{betas:c,"Anthropic-Worker-ID":l,...d}=t??{};return this._client.get(m`/v1/environments/${n}/work/poll?beta=true`,{query:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"Anthropic-Worker-ID":l}:void 0},a?.headers])})}stats(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.get(m`/v1/environments/${n}/work/stats?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}stop(n,t,a){let{environment_id:c,betas:l,workspace_id:d,...h}=t;return this._client.post(m`/v1/environments/${c}/work/${n}/stop?beta=true`,{body:h,...a,headers:p([{"anthropic-beta":[...l??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},a?.headers])})}poller(n){return new fr({...n,client:this._client})}worker(n){return new Di({...n,client:this._client})}}return s.WorkPoller=fr,s.EnvironmentWorker=Di,s})();var _s=(()=>{class s extends A{constructor(){super(...arguments);this.work=new ms(this._client)}create(n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post("/v1/environments?beta=true",{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.get(m`/v1/environments/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}update(n,t,a){let{betas:c,workspace_id:l,...d}=t;return this._client.post(m`/v1/environments/${n}?beta=true`,{body:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}list(n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList("/v1/environments?beta=true",C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.delete(m`/v1/environments/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}archive(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.post(m`/v1/environments/${n}/archive?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}}return s.Work=ms,s})();class br extends A{create(s,n,t){let{view:a,betas:c,workspace_id:l,...d}=n;return this._client.post(m`/v1/memory_stores/${s}/memories?beta=true`,{query:{view:a},body:d,...t,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}retrieve(s,n,t){let{memory_store_id:a,betas:c,workspace_id:l,...d}=n;return this._client.get(m`/v1/memory_stores/${a}/memories/${s}?beta=true`,{query:d,...t,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}update(s,n,t){let{memory_store_id:a,view:c,betas:l,workspace_id:d,...h}=n;return this._client.post(m`/v1/memory_stores/${a}/memories/${s}?beta=true`,{query:{view:c},body:h,...t,headers:p([{"anthropic-beta":[...l??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},t?.headers])})}list(s,n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList(m`/v1/memory_stores/${s}/memories?beta=true`,C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(s,n,t){let{memory_store_id:a,expected_content_sha256:c,betas:l,workspace_id:d}=n;return this._client.delete(m`/v1/memory_stores/${a}/memories/${s}?beta=true`,{query:{expected_content_sha256:c},...t,headers:p([{"anthropic-beta":[...l??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},t?.headers])})}}class kr extends A{retrieve(s,n,t){let{memory_store_id:a,betas:c,workspace_id:l,...d}=n;return this._client.get(m`/v1/memory_stores/${a}/memory_versions/${s}?beta=true`,{query:d,...t,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}list(s,n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList(m`/v1/memory_stores/${s}/memory_versions?beta=true`,C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}redact(s,n,t){let{memory_store_id:a,betas:c,workspace_id:l}=n;return this._client.post(m`/v1/memory_stores/${a}/memory_versions/${s}/redact?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}}var gs=(()=>{class s extends A{constructor(){super(...arguments);this.memories=new br(this._client),this.memoryVersions=new kr(this._client)}create(n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post("/v1/memory_stores?beta=true",{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.get(m`/v1/memory_stores/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}update(n,t,a){let{betas:c,workspace_id:l,...d}=t;return this._client.post(m`/v1/memory_stores/${n}?beta=true`,{body:d,...a,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}list(n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList("/v1/memory_stores?beta=true",C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.delete(m`/v1/memory_stores/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}archive(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.post(m`/v1/memory_stores/${n}/archive?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}}return s.Memories=br,s.MemoryVersions=kr,s})();var ws=(()=>{class s{constructor(n,t){this.iterator=n,this.controller=t}async*decoder(){let n=new zt;for await(let t of this.iterator)for(let a of n.decode(t))yield JSON.parse(a);for(let t of n.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(n,t){if(!n.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new u("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 u("Attempted to iterate over a response with no body")}return new s(Kt(n.body),t)}}return s})();class Sr extends A{create(s,n){let{betas:t,user_profile_id:a,workspace_id:c,...l}=s;return this._client.post("/v1/messages/batches?beta=true",{body:l,...n,headers:p([{"anthropic-beta":[...t??[],"message-batches-2024-09-24"].toString(),...a!=null?{"anthropic-user-profile-id":a}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}retrieve(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/messages/batches/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/messages/batches?beta=true",ie,{query:c,...n,headers:p([{"anthropic-beta":[...t??[],"message-batches-2024-09-24"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}delete(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.delete(m`/v1/messages/batches/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}cancel(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.post(m`/v1/messages/batches/${s}/cancel?beta=true`,{...t,headers:p([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}async results(s,n={},t){let a=await this.retrieve(s,n,t);if(!a.results_url)throw new u(`No batch \`results_url\`; Has it finished processing? ${a.processing_status} - ${a.id}`);let{betas:c,workspace_id:l}=n??{};return this._client.get(a.results_url,{...t,headers:p([{"anthropic-beta":[...c??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((d,h)=>ws.fromResponse(h.response,h.controller))}}var ys={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Ka(s){return s?.output_format??s?.output_config?.format}function Bi(s,n,t){let a=Ka(n);if(!n||!("parse"in(a??{})))return{...s,content:s.content.map((c)=>{if(c.type==="text"){let l=Object.defineProperty({...c},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(l,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return c}),parsed_output:null};return Wi(s,n,t)}function Wi(s,n,t){let a=null,c=s.content.map((l)=>{if(l.type==="text"){let d=ql(n,l.text);if(a===null)a=d;let h=Object.defineProperty({...l},"parsed_output",{value:d,enumerable:!1});return Object.defineProperty(h,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),d},enumerable:!1})}return l});return{...s,content:c,parsed_output:a}}function ql(s,n){let t=Ka(s);if(t?.type!=="json_schema")return null;try{if("parse"in t)return t.parse(n);return JSON.parse(n)}catch(a){throw new u(`Failed to parse structured output: ${a}`)}}var Kl=(s)=>{let n=0,t=[];while(n<s.length){let a=s[n];if(a==="\\"){n++;continue}if(a==="{"){t.push({type:"brace",value:"{"}),n++;continue}if(a==="}"){t.push({type:"brace",value:"}"}),n++;continue}if(a==="["){t.push({type:"paren",value:"["}),n++;continue}if(a==="]"){t.push({type:"paren",value:"]"}),n++;continue}if(a===":"){t.push({type:"separator",value:":"}),n++;continue}if(a===","){t.push({type:"delimiter",value:","}),n++;continue}if(a==='"'){let h=n+1,f=h,g=!1;while(!0){if(f=s.indexOf('"',f),f===-1){g=!0;break}let x=0,_=f-1;while(_>=h&&s[_]==="\\")x++,_--;if(x%2===0)break;f++}if(g)n=s.length;else t.push({type:"string",value:s.slice(h,f)}),n=f+1;continue}if(a&&/\s/.test(a)){n++;continue}let l=/[0-9]/;if(a&&l.test(a)||a==="-"||a==="."){let h="";if(a==="-")h+=a,a=s[++n];while(a&&(l.test(a)||a==="."||a==="e"||a==="E"||(a==="-"||a==="+")&&(h[h.length-1]==="e"||h[h.length-1]==="E")))h+=a,a=s[++n];t.push({type:"number",value:h,unterminated:n===s.length});continue}let d=/[a-z]/i;if(a&&d.test(a)){let h="";while(a&&d.test(a)){if(n===s.length)break;h+=a,a=s[++n]}if(h=="true"||h=="false"||h==="null")t.push({type:"name",value:h});else{n++;continue}continue}n++}return t},zl=(s)=>{let n=[];for(let l of s)if(l.type==="brace"||l.type==="paren")if(l.value==="{"||l.value==="[")n.push(l.value);else n.pop();let t=n[n.length-1],a=s.length,c=/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;while(a>0){let l=s[a-1];switch(l.type){case"separator":a--;continue;case"number":if(l.unterminated||!c.test(l.value)){a--;continue}break;case"string":let d=s[a-2];if(t==="{"&&(d?.type==="delimiter"||d?.type==="brace"&&d.value==="{")){a--;continue}break;case"delimiter":a--;break}break}return s.slice(0,a)},Vl=(s)=>{let n=[];if(s.map((t)=>{if(t.type==="brace")if(t.value==="{")n.push("}");else n.splice(n.lastIndexOf("}"),1);if(t.type==="paren")if(t.value==="[")n.push("]");else n.splice(n.lastIndexOf("]"),1)}),n.length>0)n.reverse().map((t)=>{if(t==="}")s.push({type:"brace",value:"}"});else if(t==="]")s.push({type:"paren",value:"]"})});return s},Yl=(s)=>{let n="";return s.map((t)=>{switch(t.type){case"string":n+='"'+t.value+'"';break;default:n+=t.value;break}}),n},za=(s)=>JSON.parse(Yl(Vl(zl(Kl(s)))));var Je="__json_buf";function bs(s,n){let t={};for(let l of Object.keys(s))if(l!=="input")t[l]=s[l];Object.defineProperty(t,Je,{value:n,enumerable:!1,writable:!0});let a,c=!1;return Object.defineProperty(t,"input",{enumerable:!0,configurable:!0,get(){if(!c)a=n?za(n):{},c=!0;return a}}),t}var le,Ge,Pt,vr,ks,xr,Er,Ss,Ar,He,Rr,vs,xs,it,Es,As,Rs,Tr,Ui,Va,Pr,ji,qi,Ki,Ya,zi;function Vi(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}var Is=(()=>{class s{constructor(n,t){le.add(this),this.messages=[],this.receivedMessages=[],Ge.set(this,void 0),Pt.set(this,null),this.controller=new AbortController,vr.set(this,void 0),ks.set(this,()=>{}),xr.set(this,()=>{}),Er.set(this,void 0),Ss.set(this,()=>{}),Ar.set(this,()=>{}),He.set(this,{}),Rr.set(this,!1),vs.set(this,!1),xs.set(this,!1),it.set(this,!1),Es.set(this,void 0),As.set(this,void 0),Rs.set(this,void 0),Tr.set(this,void 0),Pr.set(this,(a)=>{if(o(this,vs,!0,"f"),ze(a))a=new Ee;if(a instanceof Ee)return o(this,xs,!0,"f"),this._emit("abort",a);if(a instanceof u)return this._emit("error",a);if(a instanceof Error){let c=new u(a.message);return c.cause=a,this._emit("error",c)}return this._emit("error",new u(String(a)))}),o(this,vr,new Promise((a,c)=>{o(this,ks,a,"f"),o(this,xr,c,"f")}),"f"),o(this,Er,new Promise((a,c)=>{o(this,Ss,a,"f"),o(this,Ar,c,"f")}),"f"),e(this,vr,"f").catch(()=>{}),e(this,Er,"f").catch(()=>{}),o(this,Pt,n,"f"),o(this,Tr,t?.logger??console,"f")}get response(){return e(this,Es,"f")}get request_id(){return e(this,As,"f")}get workspace_id(){return e(this,Rs,"f")}async withResponse(){o(this,it,!0,"f");let n=await e(this,vr,"f");if(!n)throw Error("Could not resolve a `Response` object");return{data:this,response:n,request_id:n.headers.get("request-id"),workspace_id:n.headers.get("anthropic-workspace-id")}}static fromReadableStream(n){let t=new s(null);return t._run(()=>t._fromReadableStream(n)),t}static createMessage(n,t,a,{logger:c}={}){let l=new s(t,{logger:c});for(let d of t.messages)l._addMessageParam(d);return o(l,Pt,{...t,stream:!0},"f"),l._run(()=>l._createMessage(n,{...t,stream:!0},{...a,headers:{...a?.headers,[ft]:"stream"}})),l}_run(n){n().then(()=>{this._emitFinal(),this._emit("end")},e(this,Pr,"f"))}_addMessageParam(n){this.messages.push(n)}_addMessage(n,t=!0){if(this.receivedMessages.push(n),t)this._emit("message",n)}async _createMessage(n,t,a){let c=a?.signal,l;if(c){if(c.aborted)this.controller.abort();l=this.controller.abort.bind(this.controller),c.addEventListener("abort",l)}try{e(this,le,"m",ji).call(this);let{response:d,data:h}=await n.create({...t,stream:!0},{...a,signal:this.controller.signal}).withResponse();this._connected(d);for await(let f of h)e(this,le,"m",qi).call(this,f);if(h.controller.signal?.aborted)throw new Ee;e(this,le,"m",Ki).call(this)}finally{if(c&&l)c.removeEventListener("abort",l)}}_connected(n){if(this.ended)return;o(this,Es,n,"f"),o(this,As,n?.headers.get("request-id"),"f"),o(this,Rs,n?.headers.get("anthropic-workspace-id"),"f"),e(this,ks,"f").call(this,n),this._emit("connect")}get ended(){return e(this,Rr,"f")}get errored(){return e(this,vs,"f")}get aborted(){return e(this,xs,"f")}abort(){this.controller.abort()}on(n,t){return(e(this,He,"f")[n]||(e(this,He,"f")[n]=[])).push({listener:t}),this}off(n,t){let a=e(this,He,"f")[n];if(!a)return this;let c=a.findIndex((l)=>l.listener===t);if(c>=0)a.splice(c,1);return this}once(n,t){return(e(this,He,"f")[n]||(e(this,He,"f")[n]=[])).push({listener:t,once:!0}),this}emitted(n){return new Promise((t,a)=>{if(o(this,it,!0,"f"),n!=="error")this.once("error",a);this.once(n,t)})}async done(){o(this,it,!0,"f"),await e(this,Er,"f")}get currentMessage(){return e(this,Ge,"f")}async finalMessage(){return await this.done(),e(this,le,"m",Ui).call(this)}async finalText(){return await this.done(),e(this,le,"m",Va).call(this)}_emit(n,...t){if(e(this,Rr,"f"))return;if(n==="end")o(this,Rr,!0,"f"),e(this,Ss,"f").call(this);let a=e(this,He,"f")[n];if(a)e(this,He,"f")[n]=a.filter((c)=>!c.once),a.forEach(({listener:c})=>c(...t));if(n==="abort"){let c=t[0];if(!e(this,it,"f")&&!a?.length)Promise.reject(c);e(this,xr,"f").call(this,c),e(this,Ar,"f").call(this,c),this._emit("end");return}if(n==="error"){let c=t[0];if(!e(this,it,"f")&&!a?.length)Promise.reject(c);e(this,xr,"f").call(this,c),e(this,Ar,"f").call(this,c),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",e(this,le,"m",Ui).call(this))}async _fromReadableStream(n,t){let a=t?.signal,c;if(a){if(a.aborted)this.controller.abort();c=this.controller.abort.bind(this.controller),a.addEventListener("abort",c)}try{e(this,le,"m",ji).call(this),this._connected(null);let l=Fe.fromReadableStream(n,this.controller);for await(let d of l)e(this,le,"m",qi).call(this,d);if(l.controller.signal?.aborted)throw new Ee;e(this,le,"m",Ki).call(this)}finally{if(a&&c)a.removeEventListener("abort",c)}}[(Ge=new WeakMap,Pt=new WeakMap,vr=new WeakMap,ks=new WeakMap,xr=new WeakMap,Er=new WeakMap,Ss=new WeakMap,Ar=new WeakMap,He=new WeakMap,Rr=new WeakMap,vs=new WeakMap,xs=new WeakMap,it=new WeakMap,Es=new WeakMap,As=new WeakMap,Rs=new WeakMap,Tr=new WeakMap,Pr=new WeakMap,le=new WeakSet,Ui=function(){if(this.receivedMessages.length===0)throw new u("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Va=function(){if(this.receivedMessages.length===0)throw new u("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter((a)=>a.type==="text").map((a)=>a.text);if(t.length===0)throw new u("stream ended without producing a content block with type=text");return t.join(" ")},ji=function(){if(this.ended)return;o(this,Ge,void 0,"f")},qi=function(t){if(this.ended)return;let a=e(this,le,"m",Ya).call(this,t);switch(this._emit("streamEvent",t,a),t.type){case"content_block_delta":{let c=a.content.at(-1);switch(t.delta.type){case"text_delta":{if(c.type==="text")this._emit("text",t.delta.text,c.text||"");break}case"citations_delta":{if(c.type==="text")this._emit("citation",t.delta.citation,c.citations??[]);break}case"input_json_delta":{if(Vi(c)&&e(this,He,"f").inputJson?.length){let l;try{l=c.input}catch(d){e(this,Pr,"f").call(this,e(this,le,"m",zi).call(this,c,d));break}this._emit("inputJson",t.delta.partial_json,l)}break}case"thinking_delta":{if(c.type==="thinking")this._emit("thinking",t.delta.thinking,c.thinking);break}case"signature_delta":{if(c.type==="thinking")this._emit("signature",c.signature);break}case"compaction_delta":{if(c.type==="compaction"&&c.content)this._emit("compaction",c.content);break}default:xt(t.delta)}break}case"message_stop":{this._addMessageParam(a),this._addMessage(Bi(a,e(this,Pt,"f"),{logger:e(this,Tr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",a.content.at(-1));break}case"message_start":{o(this,Ge,a,"f");break}case"content_block_start":case"message_delta":break}},Ki=function(){if(this.ended)throw new u("stream has ended, this shouldn't happen");let t=e(this,Ge,"f");if(!t)throw new u("request ended without sending any chunks");return o(this,Ge,void 0,"f"),Bi(t,e(this,Pt,"f"),{logger:e(this,Tr,"f")})},Ya=function(t){let a=e(this,Ge,"f");if(t.type==="message_start"){if(a)throw new u(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!a)throw new u(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return a;case"message_delta":if(a.stop_reason=t.delta.stop_reason,a.stop_sequence=t.delta.stop_sequence,a.stop_details=t.delta.stop_details,a.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null)a.container=t.delta.container;if(t.context_management!=null)a.context_management=t.context_management;if(t.input_transformations!=null)a.input_transformations=t.input_transformations;if(t.usage.input_tokens!=null)a.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)a.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)a.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)a.usage.server_tool_use=t.usage.server_tool_use;if(t.usage.iterations!=null)a.usage.iterations=t.usage.iterations;if(t.usage.fallback_credit!=null)a.usage.fallback_credit=t.usage.fallback_credit;if(t.usage.output_tokens_details!=null)a.usage.output_tokens_details=t.usage.output_tokens_details;return a;case"content_block_start":if(a.content.push(t.content_block),t.content_block.type==="fallback")a.model=t.content_block.to.model;return a;case"content_block_delta":{let c=a.content.at(t.index);switch(t.delta.type){case"text_delta":{if(c?.type==="text")a.content[t.index]={...c,text:(c.text||"")+t.delta.text};break}case"citations_delta":{if(c?.type==="text")a.content[t.index]={...c,citations:[...c.citations??[],t.delta.citation]};break}case"input_json_delta":{if(c&&Vi(c)){let l=(c[Je]||"")+t.delta.partial_json;a.content[t.index]=bs(c,l)}break}case"thinking_delta":{if(c?.type==="thinking")a.content[t.index]={...c,thinking:c.thinking+t.delta.thinking};break}case"signature_delta":{if(c?.type==="thinking")a.content[t.index]={...c,signature:t.delta.signature};break}case"compaction_delta":{if(c?.type==="compaction"){let l={...c,content:t.delta.content};if("encrypted_content"in t.delta)l.encrypted_content=t.delta.encrypted_content;a.content[t.index]=l}break}default:xt(t.delta)}return a}case"content_block_stop":{let c=a.content.at(t.index);if(c&&Vi(c)&&Je in c){let l;try{l=c.input}catch(d){l={},e(this,Pr,"f").call(this,e(this,le,"m",zi).call(this,c,d))}Object.defineProperty(c,"input",{value:l,enumerable:!0,configurable:!0,writable:!0})}return a}}},zi=function(t,a){let c=t[Je];return new u(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${c}`)},Symbol.asyncIterator)](){let n=[],t=[],a=!1;return this.on("streamEvent",(c)=>{let l=t.shift();if(l)l.resolve(c);else n.push(c)}),this.on("end",()=>{a=!0;for(let c of t)c.resolve(void 0);t.length=0}),this.on("abort",(c)=>{a=!0;for(let l of t)l.reject(c);t.length=0}),this.on("error",(c)=>{a=!0;for(let l of t)l.reject(c);t.length=0}),{next:async()=>{if(!n.length){if(a)return{value:void 0,done:!0};return new Promise((l,d)=>t.push({resolve:l,reject:d})).then((l)=>l?{value:l,done:!1}:{value:void 0,done:!0})}return{value:n.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Fe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return s})();var je,Ts,ot,Ct,Ps,at,Mt,Cs,Ja,Os,Ms,Yi=(()=>{class s extends Is{constructor(n,t){super(n);je.add(this),Ts.set(this,void 0),ot.set(this,0),Ct.set(this,[]),Ps.set(this,[]),at.set(this,void 0),Mt.set(this,[]),Cs.set(this,!1),o(this,Ts,t,"f")}get toolCalls(){return e(this,Ps,"f")}static start(n,t,a,c){let l=new s({...t,stream:!0},c);for(let d of t.messages)l._addMessageParam(d);return l._run(()=>l._createMessage(n,{...t,stream:!0},{...a,headers:{...a?.headers,[ft]:"stream"}})),l}_emit(n,...t){var a;if(n!=="streamEvent"||this.ended){super._emit(n,...t);return}o(this,ot,(a=e(this,ot,"f"),a++,a),"f");let[c,l]=t,d=c.type==="content_block_stop"?l.content[c.index]:void 0,h=d?.type==="tool_use"?d:void 0;if(h)e(this,Ps,"f").push(h);super._emit(n,...t),e(this,je,"m",Ja).call(this,c,h),e(this,je,"m",Os).call(this)}[(Ts=new WeakMap,ot=new WeakMap,Ct=new WeakMap,Ps=new WeakMap,at=new WeakMap,Mt=new WeakMap,Cs=new WeakMap,je=new WeakSet,Symbol.asyncIterator)](){let n=super[Symbol.asyncIterator](),t={handled:e(this,ot,"f")};e(this,Ct,"f").push(t);let a=!1;return{next:async()=>{if(a)a=!1,t.handled++,e(this,je,"m",Os).call(this);try{let c=await n.next();if(a=!c.done,c.done)e(this,je,"m",Ms).call(this,t);return c}catch(c){throw e(this,je,"m",Ms).call(this,t),c}},return:async()=>{let c=n.return?.();return e(this,je,"m",Ms).call(this,t),await c??{value:void 0,done:!0}}}}}return Ja=function(t,a){if(e(this,Cs,"f"))return;if(t.type==="content_block_start"&&t.content_block.type==="fallback"){o(this,Cs,!0,"f"),o(this,at,void 0,"f");return}let c=t.type==="content_block_start"||t.type==="message_delta"&&t.delta.stop_reason==="tool_use";if(e(this,at,"f")&&c)e(this,Mt,"f").push({toolUse:e(this,at,"f"),event:e(this,ot,"f")}),o(this,at,void 0,"f");if(a)o(this,at,a,"f")},Os=function(){if(this.errored||this.controller.signal.aborted)return;let t=Math.min(e(this,ot,"f"),...e(this,Ct,"f").map((a)=>a.handled));while(e(this,Mt,"f")[0]&&e(this,Mt,"f")[0].event<=t)e(this,Ts,"f").call(this,e(this,Mt,"f").shift().toolUse)},Ms=function(t){let a=e(this,Ct,"f").indexOf(t);if(a>=0)e(this,Ct,"f").splice(a,1),e(this,je,"m",Os).call(this)},s})();var V,$t,ct,z,de,he,Xe,De,Qe,Or,Se,Be,Ft,Ht,lt,Ji,Ga,Gi,Xi,Nr,Ns,Xa,Qi,Zi,Qa,eo,ro=(()=>{class s{constructor(n,t,a){V.add(this),this.client=n,$t.set(this,!1),ct.set(this,!1),z.set(this,void 0),de.set(this,void 0),he.set(this,void 0),Xe.set(this,void 0),De.set(this,void 0),Qe.set(this,void 0),Or.set(this,0),Se.set(this,{status:"idle"}),Be.set(this,void 0),Ft.set(this,null),Ht.set(this,new Map),lt.set(this,[]),Za(t),Jl(t),ec(t),o(this,z,{params:{...t,messages:JSON.parse(JSON.stringify(t.messages))}},"f");let c=Oi(t.tools,t.messages);o(this,de,{...a,headers:p([Yn("BetaToolRunner"),c.length?{[Vn]:c.join(", ")}:void 0,a?.headers])},"f"),o(this,Qe,Dt(),"f")}async*[($t=new WeakMap,ct=new WeakMap,z=new WeakMap,de=new WeakMap,he=new WeakMap,Xe=new WeakMap,De=new WeakMap,Qe=new WeakMap,Or=new WeakMap,Se=new WeakMap,Be=new WeakMap,Ft=new WeakMap,Ht=new WeakMap,lt=new WeakMap,V=new WeakSet,Symbol.asyncIterator)](){var n;if(e(this,$t,"f"))throw new u("Cannot iterate over a consumed stream");o(this,$t,!0,"f"),o(this,ct,!0,"f"),o(this,De,void 0,"f");try{while(!0)try{if(e(this,z,"f").params.max_iterations&&e(this,Or,"f")>=e(this,z,"f").params.max_iterations)break;if(e(this,V,"m",Qa).call(this),e(this,Se,"f").status==="scheduled"&&rc(e(this,Ft,"f"))!=="resume"){yield*e(this,V,"m",Xi).call(this,e(this,Se,"f").config);continue}o(this,ct,!1,"f"),o(this,De,void 0,"f"),o(this,Or,(n=e(this,Or,"f"),n++,n),"f"),o(this,he,void 0,"f");let{max_iterations:t,runToolsEagerly:a,...c}=e(this,z,"f").params;if(yield*e(this,V,"m",Ji).call(this,c),!e(this,ct,"f")){let d=await e(this,he,"f"),h=rc(d.stop_reason);o(this,Ft,d.stop_reason,"f"),e(this,z,"f").params.messages.push({role:d.role,content:Ql(d.content)});let{container:f}=e(this,z,"f").params;if(d.container){if(f==null)e(this,z,"f").params.container=d.container.id;else if(typeof f==="object"&&f.id==null)e(this,z,"f").params.container={...f,id:d.container.id}}if(h==="stop"){yield*e(this,V,"m",Qi).call(this);break}if(h==="resume")continue}else o(this,Ft,null,"f");let l=await e(this,V,"m",Zi).call(this,e(this,z,"f").params.messages.at(-1));if(l)e(this,z,"f").params.messages.push(l);else if(!e(this,ct,"f")){yield*e(this,V,"m",Qi).call(this);break}}finally{e(this,Xe,"f")?.abort(),o(this,Xe,void 0,"f")}if(await e(this,V,"m",Gi).call(this),!e(this,he,"f"))throw new u("ToolRunner concluded without a message from the server");e(this,Qe,"f").resolve(await e(this,he,"f"))}catch(t){throw o(this,$t,!1,"f"),e(this,Qe,"f").promise.catch(()=>{}),e(this,Qe,"f").reject(t),o(this,Qe,Dt(),"f"),t}}setMessagesParams(n){let t=typeof n==="function"?n(e(this,z,"f").params):n;if(Za(t),ec(t),e(this,Se,"f").status!=="idle")to(t);if(e(this,Se,"f").status==="in_flight"&&t.messages!==e(this,z,"f").params.messages)throw new u("Message params can't be changed while the conversation is being compacted, because the compaction response is about to replace them. Change them after this iteration instead.");e(this,z,"f").params=t,o(this,ct,!0,"f"),o(this,De,void 0,"f")}setRequestOptions(n){if(typeof n==="function")o(this,de,n(e(this,de,"f")),"f");else o(this,de,{...e(this,de,"f"),...n},"f")}async generateToolResponse(n=e(this,de,"f").signal){let t=await e(this,he,"f")??this.params.messages.at(-1);if(!t)return null;return e(this,V,"m",Zi).call(this,t,n)}deferToolCall(n){let t=typeof n==="string"?n:n.id;if(e(this,Be,"f")&&!e(this,Be,"f").has(t))e(this,Be,"f").set(t,{status:"held"})}get deferredToolCalls(){let n=e(this,Xe,"f"),t=e(this,Be,"f");if(!(n instanceof Yi)||!t)return[];return n.toolCalls.filter((a)=>t.get(a.id)?.status==="held")}done(){return e(this,Qe,"f").promise}async runUntilDone(){if(!e(this,$t,"f"))for await(let n of this);return this.done()}get params(){return e(this,z,"f").params}pushMessages(...n){this.setMessagesParams((t)=>({...t,messages:[...t.messages,...n]}))}compactBeforeNextTurn(n){if(e(this,Se,"f").status==="in_flight")return;to(e(this,z,"f").params),o(this,Se,{status:"scheduled",config:n??{type:"summarize"}},"f")}addTools(...n){for(let t of n){if("name"in t)e(this,Ht,"f").set(t.name,"run"in t?t:null);e(this,lt,"f").push({type:"addition",tool:t})}}removeTools(...n){for(let t of n){let a=typeof t==="string"?t:t.name;e(this,Ht,"f").set(a,null),e(this,lt,"f").push({type:"removal",name:a})}}then(n,t){return this.runUntilDone().then(n,t)}}return Ji=async function*(t){if(await e(this,V,"m",Gi).call(this),o(this,Be,void 0,"f"),t.stream)o(this,Xe,e(this,z,"f").params.runToolsEagerly?e(this,V,"m",Ga).call(this,t):this.client.beta.messages.stream({...t},e(this,de,"f")),"f"),o(this,he,e(this,Xe,"f").finalMessage(),"f"),e(this,he,"f").catch(()=>{}),yield e(this,Xe,"f");else o(this,he,this.client.beta.messages.create({...t,stream:!1},e(this,de,"f")),"f"),yield e(this,he,"f")},Ga=function(t){let a=new Map;return o(this,Be,a,"f"),Yi.start(this.client.beta.messages,t,e(this,de,"f"),(c)=>{if(a.has(c.id))return;let l=nc(e(this,V,"m",Nr).call(this),e(this,V,"m",Ns).call(this),c,e(this,de,"f"));l.catch(()=>{}),a.set(c.id,{status:"started",result:l})})},Gi=async function(){let t=[...e(this,Be,"f")?.values()??[]].filter((a)=>a.status==="started");await Promise.allSettled(t.map((a)=>a.result))},Xi=async function*(t){to(e(this,z,"f").params);let{max_iterations:a,runToolsEagerly:c,...l}=e(this,z,"f").params,d=Gl(l);o(this,Se,{status:"in_flight"},"f"),o(this,De,void 0,"f");let h=e(this,he,"f");try{yield*e(this,V,"m",Ji).call(this,{...d,compaction:t});let f=await e(this,he,"f");if(f.content.some((g)=>g.type==="compaction"&&g.content))e(this,V,"m",Xa).call(this),e(this,z,"f").params.messages=[{role:f.role,content:f.content}];else T(this.client).warn("Compaction produced no summary; keeping the conversation as it is."),o(this,he,h,"f")}finally{o(this,Se,{status:"idle"},"f")}},Nr=function(){let t=new Map;for(let a of e(this,z,"f").params.tools)if("run"in a)t.set(a.name,a);for(let[a,c]of e(this,Ht,"f"))if(c)t.set(a,c);else t.delete(a);return t},Ns=function(){let t=new Set(e(this,V,"m",Nr).call(this).keys());for(let a of[...e(this,z,"f").params.messages,e(this,V,"m",eo).call(this)]){if(typeof a.content==="string")continue;for(let c of a.content)if(a.role==="system")tc(c,t);else if(a.role==="assistant"&&c.type==="compaction")for(let l of c.tool_changes??[])tc(l,t)}return t},Xa=function(){let t=e(this,V,"m",Ns).call(this);for(let a of e(this,V,"m",Nr).call(this).keys())if(!t.has(a))e(this,Ht,"f").set(a,null)},Qi=async function*(){if(e(this,Se,"f").status!=="scheduled")return;let t=e(this,z,"f").params.messages.at(-1)?.content;if(Array.isArray(t)&&t.some((a)=>a.type==="tool_use")){T(this.client).warn("The pending compaction was skipped because the last turn ended with tool calls that were not run. Call `compactBeforeNextTurn()` again if you continue the conversation."),o(this,Se,{status:"idle"},"f");return}yield*e(this,V,"m",Xi).call(this,e(this,Se,"f").config)},Zi=async function(t,a=e(this,de,"f").signal){if(e(this,De,"f")!==void 0)return e(this,De,"f");return o(this,De,Xl(e(this,V,"m",Nr).call(this),e(this,V,"m",Ns).call(this),t,{...e(this,de,"f"),signal:a},e(this,Be,"f")),"f"),e(this,De,"f")},Qa=function(){if(e(this,Ft,"f")==="pause_turn"||e(this,lt,"f").length===0)return;e(this,z,"f").params.messages.push(e(this,V,"m",eo).call(this)),o(this,lt,[],"f")},eo=function(){let t=[];for(let a of e(this,lt,"f")){if(a.type==="removal"){t.push({type:"tool_removal",tool:{type:"tool_reference",name:a.name}});continue}let c=a.tool;if("run"in a.tool){let{run:l,parse:d,close:h,...f}=a.tool;c=f}t.push({type:"tool_addition",tool:{type:"tool_definition",definition:c}})}return{role:"system",content:t}},s})();function Za(s){if("compaction"in s&&s.compaction!=null)throw new u("`compaction` cannot be set on a tool runner: every request in the loop would compact again. Call `runner.compactBeforeNextTurn()` when the conversation should be compacted instead.")}function Jl(s){if("compactionControl"in s&&s.compactionControl!=null)throw new u("`compactionControl` has been removed from the tool runner. Use server-side compaction instead: call `runner.compactBeforeNextTurn()` when the conversation should be compacted.")}function ec(s){if(s.runToolsEagerly&&!s.stream)throw TypeError("`runToolsEagerly: true` needs `stream: true` in the tool runner's params, because a reply that isn't streamed arrives whole.")}function to(s){if(s.context_management?.edits?.some((n)=>n.type.startsWith("compact_")))throw new u("`compactBeforeNextTurn()` can't be used while `context_management` has a compaction edit, because the API doesn't accept a compaction block together with one. Remove the edit first.")}function Gl(s){let{context_management:n,stop_sequences:t,output_format:a,...c}=s,l=({format:d,...h})=>h;if(c.tool_choice?.type==="any"||c.tool_choice?.type==="tool")delete c.tool_choice;if(c.output_config)c.output_config=l(c.output_config);if(Array.isArray(c.fallbacks))c.fallbacks=c.fallbacks.map((d)=>d.output_config?{...d,output_config:l(d.output_config)}:d);return c}async function Xl(s,n,t,a,c){if(!t||t.role!=="assistant"||!t.content||typeof t.content==="string")return null;let l=t.content.filter((h)=>h.type==="tool_use");if(l.length===0)return null;return{role:"user",content:await Promise.all(l.map((h)=>{let f=c?.get(h.id);if(f?.status==="started")return f.result;let g=nc(s,n,h,a);return c?.set(h.id,{status:"started",result:g}),g}))}}async function nc(s,n,t,a){let c=n.has(t.name)?s.get(t.name):void 0;if(!c)return Zl(t);try{let l=t.input;if("parse"in c&&c.parse)l=c.parse(l);let d=await c.run(l,{toolUse:t,toolUseBlock:t,signal:a?.signal});return{type:"tool_result",tool_use_id:t.id,content:d}}catch(l){return{type:"tool_result",tool_use_id:t.id,content:l instanceof E?l.content:`Error: ${l instanceof Error?l.message:String(l)}`,is_error:!0}}}function Ql(s){return s}function Zl(s){return{type:"tool_result",tool_use_id:s.id,content:`Error: Tool '${s.name}' not found`,is_error:!0}}function tc(s,n){switch(s.type){case"tool_removal":case"tool_addition":eu(s,n);break}}function eu(s,n){let t=tu(s.tool);if(t===void 0)return;if(s.type==="tool_removal")n.delete(t);else n.add(t)}function tu(s){switch(s.type){case"tool_reference":return s.name;case"tool_definition":return"name"in s.definition?s.definition.name:void 0;default:return}}function rc(s){if(s===null)return"stop";switch(s){case"tool_use":return"run_tools";case"pause_turn":case"compaction":return"resume";case"end_turn":case"stop_sequence":case"max_tokens":case"model_context_window_exceeded":case"refusal":return"stop";default:return xt(s),"stop"}}var sc={},ru=["claude-mythos-preview","claude-opus-4-6"],Ls=(()=>{class s extends A{constructor(){super(...arguments);this.batches=new Sr(this._client)}create(n,t){let a=ic(n),{betas:c,user_profile_id:l,workspace_id:d,...h}=a;if(h.model in sc)console.warn(`The model '${h.model}' is deprecated and will reach end-of-life on ${sc[h.model]}
|
|
11
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(ru.includes(h.model)&&h.thinking&&h.thinking.type==="enabled")console.warn(`Using Claude with ${h.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 f=t?.timeout??this._client._options.timeout;if(!h.stream&&f==null){let x=ys[h.model]??void 0;f=this._client.calculateNonstreamingTimeout(h.max_tokens,x)}let g=Jn(h.tools,h.messages);return this._client.post("/v1/messages?beta=true",{body:h,timeout:f??600000,...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...l!=null?{"anthropic-user-profile-id":l}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},g,t?.headers]),stream:a.stream??!1})}parse(n,t){return t={...t,headers:p([{"anthropic-beta":[...n.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(n,t).then((a)=>Wi(a,n,{logger:this._client.logger??console}))}stream(n,t){return Is.createMessage(this,n,t)}countTokens(n,t){let a=ic(n),{betas:c,user_profile_id:l,workspace_id:d,...h}=a;return this._client.post("/v1/messages/count_tokens?beta=true",{body:h,...t,headers:p([{"anthropic-beta":[...c??[],"token-counting-2024-11-01"].toString(),...l!=null?{"anthropic-user-profile-id":l}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},t?.headers])})}toolRunner(n,t){return new ro(this._client,n,t)}}return s.Batches=Sr,s.BetaToolRunner=ro,s.ToolError=E,s})();function ic(s){if(!s.output_format)return s;if(s.output_config?.format)throw new u("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:n,...t}=s;return{...t,output_config:{...s.output_config,format:n}}}class Lr extends A{retrieve(s,n){return this._client.get(m`/v1/organizations/api_keys/${s}?beta=true`,n)}update(s,n,t){return this._client.post(m`/v1/organizations/api_keys/${s}?beta=true`,{body:n,...t})}list(s={},n){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",ie,{query:s,...n})}}class $r extends A{retrieve(s){return this._client.get("/v1/organizations/compliance_settings?beta=true",s)}update(s,n){return this._client.post("/v1/organizations/compliance_settings?beta=true",{body:s,...n})}}class Fr extends A{create(s,n){return this._client.post("/v1/organizations/external_keys?beta=true",{body:s,...n})}retrieve(s,n){return this._client.get(m`/v1/organizations/external_keys/${s}?beta=true`,n)}update(s,n,t){return this._client.post(m`/v1/organizations/external_keys/${s}?beta=true`,{body:n,...t})}list(s={},n){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",C,{query:s,...n})}delete(s,n){return this._client.delete(m`/v1/organizations/external_keys/${s}?beta=true`,n)}validate(s,n){return this._client.post(m`/v1/organizations/external_keys/${s}/validate?beta=true`,n)}}class Hr extends A{create(s,n){return this._client.post("/v1/organizations/invites?beta=true",{body:s,...n})}retrieve(s,n){return this._client.get(m`/v1/organizations/invites/${s}?beta=true`,n)}list(s={},n){return this._client.getAPIList("/v1/organizations/invites?beta=true",ie,{query:s,...n})}delete(s,n){return this._client.delete(m`/v1/organizations/invites/${s}?beta=true`,n)}}class Br extends A{list(s={},n){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",C,{query:s,...n})}}class Wr extends A{retrieve(s,n){return this._client.get(m`/v1/organizations/users/${s}?beta=true`,n)}update(s,n,t){return this._client.post(m`/v1/organizations/users/${s}?beta=true`,{body:n,...t})}list(s={},n){return this._client.getAPIList("/v1/organizations/users?beta=true",ie,{query:s,...n})}remove(s,n){return this._client.delete(m`/v1/organizations/users/${s}?beta=true`,n)}}class Ur extends A{create(s,n){let{betas:t,...a}=s;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:a,...n,headers:p([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0},n?.headers])})}retrieve(s,n={},t){let{betas:a}=n??{};return this._client.get(m`/v1/organizations/federation_issuers/${s}?beta=true`,{...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}update(s,n,t){let{betas:a,...c}=n;return this._client.post(m`/v1/organizations/federation_issuers/${s}?beta=true`,{body:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}list(s={},n){let{betas:t,...a}=s??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",C,{query:a,...n,headers:p([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0},n?.headers])})}archive(s,n={},t){let{betas:a}=n??{};return this._client.post(m`/v1/organizations/federation_issuers/${s}/archive?beta=true`,{...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}}class jr extends A{list(s,n={},t){let{betas:a,...c}=n??{};return this._client.getAPIList(m`/v1/organizations/federation_rules/${s}/workspaces?beta=true`,C,{query:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}add(s,n,t){let{betas:a,...c}=n;return this._client.post(m`/v1/organizations/federation_rules/${s}/workspaces?beta=true`,{body:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}remove(s,n,t){let{federation_rule_id:a,betas:c}=n;return this._client.delete(m`/v1/organizations/federation_rules/${a}/workspaces/${s}?beta=true`,{...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},t?.headers])})}}var $s=(()=>{class s extends A{constructor(){super(...arguments);this.workspaces=new jr(this._client)}create(n,t){let{betas:a,...c}=n;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c}=t??{};return this._client.get(m`/v1/organizations/federation_rules/${n}?beta=true`,{...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},a?.headers])})}update(n,t,a){let{betas:c,...l}=t;return this._client.post(m`/v1/organizations/federation_rules/${n}?beta=true`,{body:l,...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},a?.headers])})}list(n={},t){let{betas:a,...c}=n??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",C,{query:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}archive(n,t={},a){let{betas:c}=t??{};return this._client.post(m`/v1/organizations/federation_rules/${n}/archive?beta=true`,{...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},a?.headers])})}}return s.Workspaces=jr,s})();var Fs=(()=>{class s extends A{constructor(){super(...arguments);this.issuers=new Ur(this._client),this.rules=new $s(this._client)}}return s.Issuers=Ur,s.Rules=$s,s})();class qr extends A{list(s,n={},t){let{betas:a,...c}=n??{};return this._client.getAPIList(m`/v1/organizations/service_accounts/${s}/workspaces?beta=true`,C,{query:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}add(s,n,t){let{betas:a,...c}=n;return this._client.post(m`/v1/organizations/service_accounts/${s}/workspaces?beta=true`,{body:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}remove(s,n,t){let{service_account_id:a,betas:c}=n;return this._client.delete(m`/v1/organizations/service_accounts/${a}/workspaces/${s}?beta=true`,{...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},t?.headers])})}}var Hs=(()=>{class s extends A{constructor(){super(...arguments);this.workspaces=new qr(this._client)}create(n,t){let{betas:a,...c}=n;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c}=t??{};return this._client.get(m`/v1/organizations/service_accounts/${n}?beta=true`,{...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},a?.headers])})}update(n,t,a){let{betas:c,...l}=t;return this._client.post(m`/v1/organizations/service_accounts/${n}?beta=true`,{body:l,...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},a?.headers])})}list(n={},t){let{betas:a,...c}=n??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",C,{query:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}archive(n,t={},a){let{betas:c}=t??{};return this._client.post(m`/v1/organizations/service_accounts/${n}/archive?beta=true`,{...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},a?.headers])})}}return s.Workspaces=qr,s})();class Kr extends A{retrieve(s,n,t){let{workspace_id:a}=n;return this._client.get(m`/v1/organizations/workspaces/${a}/members/${s}?beta=true`,t)}update(s,n,t){let{workspace_id:a,...c}=n;return this._client.post(m`/v1/organizations/workspaces/${a}/members/${s}?beta=true`,{body:c,...t})}list(s,n={},t){return this._client.getAPIList(m`/v1/organizations/workspaces/${s}/members?beta=true`,ie,{query:n,...t})}add(s,n,t){return this._client.post(m`/v1/organizations/workspaces/${s}/members?beta=true`,{body:n,...t})}remove(s,n,t){let{workspace_id:a}=n;return this._client.delete(m`/v1/organizations/workspaces/${a}/members/${s}?beta=true`,t)}}class zr extends A{list(s,n={},t){return this._client.getAPIList(m`/v1/organizations/workspaces/${s}/rate_limits?beta=true`,C,{query:n,...t})}}class Vr extends A{retrieve(s,n,t){let{workspace_id:a,betas:c}=n;return this._client.get(m`/v1/organizations/workspaces/${a}/service_accounts/${s}?beta=true`,{...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},t?.headers])})}update(s,n,t){let{workspace_id:a,betas:c,...l}=n;return this._client.post(m`/v1/organizations/workspaces/${a}/service_accounts/${s}?beta=true`,{body:l,...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},t?.headers])})}list(s,n={},t){let{betas:a,...c}=n??{};return this._client.getAPIList(m`/v1/organizations/workspaces/${s}/service_accounts?beta=true`,C,{query:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}add(s,n,t){let{betas:a,...c}=n;return this._client.post(m`/v1/organizations/workspaces/${s}/service_accounts?beta=true`,{body:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}remove(s,n,t){let{workspace_id:a,betas:c}=n;return this._client.delete(m`/v1/organizations/workspaces/${a}/service_accounts/${s}?beta=true`,{...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},t?.headers])})}}var Ds=(()=>{class s extends A{constructor(){super(...arguments);this.rateLimits=new zr(this._client),this.members=new Kr(this._client),this.serviceAccounts=new Vr(this._client)}create(n,t){let{betas:a,...c}=n;return this._client.post("/v1/organizations/workspaces?beta=true",{body:c,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},t?.headers])})}retrieve(n,t){return this._client.get(m`/v1/organizations/workspaces/${n}?beta=true`,t)}update(n,t,a){return this._client.post(m`/v1/organizations/workspaces/${n}?beta=true`,{body:t,...a})}list(n={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",ie,{query:n,...t})}archive(n,t){return this._client.post(m`/v1/organizations/workspaces/${n}/archive?beta=true`,t)}}return s.RateLimits=zr,s.Members=Kr,s.ServiceAccounts=Vr,s})();var Bs=(()=>{class s extends A{constructor(){super(...arguments);this.apiKeys=new Lr(this._client),this.externalKeys=new Fr(this._client),this.federation=new Fs(this._client),this.invites=new Hr(this._client),this.serviceAccounts=new Hs(this._client),this.users=new Wr(this._client),this.workspaces=new Ds(this._client),this.rateLimits=new Br(this._client),this.complianceSettings=new $r(this._client)}retrieve(n){return this._client.get("/v1/organizations/me?beta=true",n)}}return s.APIKeys=Lr,s.ExternalKeys=Fr,s.Federation=Fs,s.Invites=Hr,s.ServiceAccounts=Hs,s.Users=Wr,s.Workspaces=Ds,s.RateLimits=Br,s.ComplianceSettings=$r,s})();var Ws=(()=>{class s extends A{list(n,t={},a){let{betas:c,workspace_id:l,...d}=t??{};return this._client.getAPIList(m`/v1/sessions/${n}/events?beta=true`,C,{query:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}send(n,t,a){let{betas:c,workspace_id:l,...d}=t;return this._client.post(m`/v1/sessions/${n}/events?beta=true`,{body:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}stream(n,t={},a){let{betas:c,workspace_id:l,...d}=t??{};return this._client.get(m`/v1/sessions/${n}/events/stream?beta=true`,{query:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers]),stream:!0})}toolRunner(n,t){return new gr(n,{...t,client:this._client})}}return s.SessionToolRunner=gr,s})();class Yr extends A{retrieve(s,n,t){let{session_id:a,betas:c,workspace_id:l}=n;return this._client.get(m`/v1/sessions/${a}/resources/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}update(s,n,t){let{session_id:a,betas:c,workspace_id:l,...d}=n;return this._client.post(m`/v1/sessions/${a}/resources/${s}?beta=true`,{body:d,...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}list(s,n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList(m`/v1/sessions/${s}/resources?beta=true`,C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(s,n,t){let{session_id:a,betas:c,workspace_id:l}=n;return this._client.delete(m`/v1/sessions/${a}/resources/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}add(s,n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post(m`/v1/sessions/${s}/resources?beta=true`,{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}class Jr extends A{list(s,n,t){let{session_id:a,betas:c,workspace_id:l,...d}=n;return this._client.getAPIList(m`/v1/sessions/${a}/threads/${s}/events?beta=true`,C,{query:d,...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}stream(s,n,t){let{session_id:a,betas:c,workspace_id:l,...d}=n;return this._client.get(m`/v1/sessions/${a}/threads/${s}/stream?beta=true`,{query:d,...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers]),stream:!0})}}var Us=(()=>{class s extends A{constructor(){super(...arguments);this.events=new Jr(this._client)}retrieve(n,t,a){let{session_id:c,betas:l,workspace_id:d}=t;return this._client.get(m`/v1/sessions/${c}/threads/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...l??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},a?.headers])})}list(n,t={},a){let{betas:c,workspace_id:l,...d}=t??{};return this._client.getAPIList(m`/v1/sessions/${n}/threads?beta=true`,C,{query:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}archive(n,t,a){let{session_id:c,betas:l,workspace_id:d}=t;return this._client.post(m`/v1/sessions/${c}/threads/${n}/archive?beta=true`,{...a,headers:p([{"anthropic-beta":[...l??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},a?.headers])})}}return s.Events=Jr,s})();var js=(()=>{class s extends A{constructor(){super(...arguments);this.events=new Ws(this._client),this.resources=new Yr(this._client),this.threads=new Us(this._client)}create(n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post("/v1/sessions?beta=true",{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.get(m`/v1/sessions/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}update(n,t,a){let{betas:c,workspace_id:l,...d}=t;return this._client.post(m`/v1/sessions/${n}?beta=true`,{body:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}list(n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList("/v1/sessions?beta=true",Ai,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.delete(m`/v1/sessions/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}archive(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.post(m`/v1/sessions/${n}/archive?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}}return s.Events=Ws,s.Resources=Yr,s.Threads=Us,s})();class Gr extends A{create(s,n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post(m`/v1/skills/${s}/versions?beta=true`,Re({body:l,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])},this._client,!1))}retrieve(s,n,t){let{skill_id:a,betas:c,workspace_id:l}=n;return this._client.get(m`/v1/skills/${a}/versions/${s}?beta=true`,{...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}list(s,n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList(m`/v1/skills/${s}/versions?beta=true`,C,{query:l,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(s,n,t){let{skill_id:a,betas:c,workspace_id:l}=n;return this._client.delete(m`/v1/skills/${a}/versions/${s}?beta=true`,{...t,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}download(s,n,t){let{skill_id:a,betas:c,workspace_id:l}=n;return this._client.get(m`/v1/skills/${a}/versions/${s}/content?beta=true`,{...t,headers:p([{Accept:"application/binary",...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers]),__binaryResponse:!0})}}var qs=(()=>{class s extends A{constructor(){super(...arguments);this.versions=new Gr(this._client)}create(n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post("/v1/skills?beta=true",Re({body:l,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])},this._client,!1))}retrieve(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.get(m`/v1/skills/${n}?beta=true`,{...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}list(n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList("/v1/skills?beta=true",C,{query:l,...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.delete(m`/v1/skills/${n}?beta=true`,{...a,headers:p([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}}return s.Versions=Gr,s})();class Xr extends A{create(s,n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post(m`/v1/tunnels/${s}/certificates?beta=true`,{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(s,n,t){let{tunnel_id:a,betas:c,workspace_id:l}=n;return this._client.get(m`/v1/tunnels/${a}/certificates/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}list(s,n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList(m`/v1/tunnels/${s}/certificates?beta=true`,C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}archive(s,n,t){let{tunnel_id:a,betas:c,workspace_id:l}=n;return this._client.post(m`/v1/tunnels/${a}/certificates/${s}/archive?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}}var Ks=(()=>{class s extends A{constructor(){super(...arguments);this.certificates=new Xr(this._client)}create(n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post("/v1/tunnels?beta=true",{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.get(m`/v1/tunnels/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}list(n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList("/v1/tunnels?beta=true",C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}archive(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.post(m`/v1/tunnels/${n}/archive?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}revealToken(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.post(m`/v1/tunnels/${n}/reveal_token?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}rotateToken(n,t,a){let{betas:c,workspace_id:l,...d}=t;return this._client.post(m`/v1/tunnels/${n}/rotate_token?beta=true`,{body:d,...a,headers:p([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}}return s.Certificates=Xr,s})();class Zr extends A{create(s,n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post(m`/v1/vaults/${s}/credentials?beta=true`,{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(s,n,t){let{vault_id:a,betas:c,workspace_id:l}=n;return this._client.get(m`/v1/vaults/${a}/credentials/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}update(s,n,t){let{vault_id:a,betas:c,workspace_id:l,...d}=n;return this._client.post(m`/v1/vaults/${a}/credentials/${s}?beta=true`,{body:d,...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}list(s,n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList(m`/v1/vaults/${s}/credentials?beta=true`,C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(s,n,t){let{vault_id:a,betas:c,workspace_id:l}=n;return this._client.delete(m`/v1/vaults/${a}/credentials/${s}?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}archive(s,n,t){let{vault_id:a,betas:c,workspace_id:l}=n;return this._client.post(m`/v1/vaults/${a}/credentials/${s}/archive?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}mcpOAuthValidate(s,n,t){let{vault_id:a,betas:c,workspace_id:l}=n;return this._client.post(m`/v1/vaults/${a}/credentials/${s}/mcp_oauth_validate?beta=true`,{...t,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},t?.headers])})}}var zs=(()=>{class s extends A{constructor(){super(...arguments);this.credentials=new Zr(this._client)}create(n,t){let{betas:a,workspace_id:c,...l}=n;return this._client.post("/v1/vaults?beta=true",{body:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}retrieve(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.get(m`/v1/vaults/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}update(n,t,a){let{betas:c,workspace_id:l,...d}=t;return this._client.post(m`/v1/vaults/${n}?beta=true`,{body:d,...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}list(n={},t){let{betas:a,workspace_id:c,...l}=n??{};return this._client.getAPIList("/v1/vaults?beta=true",C,{query:l,...t,headers:p([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}delete(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.delete(m`/v1/vaults/${n}?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}archive(n,t={},a){let{betas:c,workspace_id:l}=t??{};return this._client.post(m`/v1/vaults/${n}/archive?beta=true`,{...a,headers:p([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...l!=null?{"anthropic-workspace-id":l}:void 0},a?.headers])})}}return s.Credentials=Zr,s})();var en=(()=>{class s extends A{constructor(){super(...arguments);this.models=new sr(this._client),this.messages=new Ls(this._client),this.agents=new Zn(this._client),this.environments=new _s(this._client),this.sessions=new js(this._client),this.deployments=new er(this._client),this.deploymentRuns=new Qt(this._client),this.vaults=new zs(this._client),this.memoryStores=new gs(this._client),this.files=new nr(this._client),this.skills=new qs(this._client),this.webhooks=new cr(this._client),this.userProfiles=new ir(this._client),this.dreams=new tr(this._client),this.tunnels=new Ks(this._client),this.organization=new Bs(this._client)}}return s.Models=sr,s.Messages=Ls,s.Agents=Zn,s.Environments=_s,s.Sessions=js,s.Deployments=er,s.DeploymentRuns=Qt,s.Vaults=zs,s.MemoryStores=gs,s.Files=nr,s.Skills=qs,s.Webhooks=cr,s.UserProfiles=ir,s.Dreams=tr,s.Tunnels=Ks,s.Organization=Bs,s})();class Bt extends A{create(s,n){let{betas:t,workspace_id:a,...c}=s;return this._client.post("/v1/complete",{body:c,timeout:this._client._options.timeout??600000,...n,headers:p([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers]),stream:s.stream??!1})}}class Wt extends A{list(s={},n){let{workspace_id:t,...a}=s??{};return this._client.getAPIList("/v1/files",C,{query:a,...n,headers:p([{...t!=null?{"anthropic-workspace-id":t}:void 0},n?.headers])})}delete(s,n={},t){let{workspace_id:a}=n??{};return this._client.delete(m`/v1/files/${s}`,{...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}download(s,n={},t){let{workspace_id:a}=n??{};return this._client.get(m`/v1/files/${s}/content`,{...t,headers:p([{Accept:"application/binary",...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers]),__binaryResponse:!0})}retrieveMetadata(s,n={},t){let{workspace_id:a}=n??{};return this._client.get(m`/v1/files/${s}`,{...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}upload(s,n){let{workspace_id:t,...a}=s;return this._client.post("/v1/files",Re({body:a,...n,headers:p([{...t!=null?{"anthropic-workspace-id":t}:void 0},Gn(a.file),n?.headers])},this._client))}}function oc(s){return s?.output_config?.format}function no(s,n,t){let a=oc(n);if(!n||!("parse"in(a??{})))return{...s,content:s.content.map((c)=>{if(c.type==="text")return Object.defineProperty({...c},"parsed_output",{value:null,enumerable:!1});return c}),parsed_output:null};return so(s,n,t)}function so(s,n,t){let a=null,c=s.content.map((l)=>{if(l.type==="text"){let d=Ou(n,l.text);if(a===null)a=d;return Object.defineProperty({...l},"parsed_output",{value:d,enumerable:!1})}return l});return{...s,content:c,parsed_output:a}}function Ou(s,n){let t=oc(s);if(t?.type!=="json_schema")return null;try{if("parse"in t)return t.parse(n);return JSON.parse(n)}catch(a){throw new u(`Failed to parse structured output: ${a}`)}}var Pe,et,Ut,tn,Vs,rn,nn,Ys,sn,We,on,Js,Gs,ut,Xs,Qs,Zs,an,io,ac,oo,ao,co,lo,cc;function uo(s){return s.type==="tool_use"||s.type==="server_tool_use"}var lc=(()=>{class s{constructor(n,t){Pe.add(this),this.messages=[],this.receivedMessages=[],et.set(this,void 0),Ut.set(this,null),this.controller=new AbortController,tn.set(this,void 0),Vs.set(this,()=>{}),rn.set(this,()=>{}),nn.set(this,void 0),Ys.set(this,()=>{}),sn.set(this,()=>{}),We.set(this,{}),on.set(this,!1),Js.set(this,!1),Gs.set(this,!1),ut.set(this,!1),Xs.set(this,void 0),Qs.set(this,void 0),Zs.set(this,void 0),an.set(this,void 0),oo.set(this,(a)=>{if(o(this,Js,!0,"f"),ze(a))a=new Ee;if(a instanceof Ee)return o(this,Gs,!0,"f"),this._emit("abort",a);if(a instanceof u)return this._emit("error",a);if(a instanceof Error){let c=new u(a.message);return c.cause=a,this._emit("error",c)}return this._emit("error",new u(String(a)))}),o(this,tn,new Promise((a,c)=>{o(this,Vs,a,"f"),o(this,rn,c,"f")}),"f"),o(this,nn,new Promise((a,c)=>{o(this,Ys,a,"f"),o(this,sn,c,"f")}),"f"),e(this,tn,"f").catch(()=>{}),e(this,nn,"f").catch(()=>{}),o(this,Ut,n,"f"),o(this,an,t?.logger??console,"f")}get response(){return e(this,Xs,"f")}get request_id(){return e(this,Qs,"f")}get workspace_id(){return e(this,Zs,"f")}async withResponse(){o(this,ut,!0,"f");let n=await e(this,tn,"f");if(!n)throw Error("Could not resolve a `Response` object");return{data:this,response:n,request_id:n.headers.get("request-id"),workspace_id:n.headers.get("anthropic-workspace-id")}}static fromReadableStream(n){let t=new s(null);return t._run(()=>t._fromReadableStream(n)),t}static createMessage(n,t,a,{logger:c}={}){let l=new s(t,{logger:c});for(let d of t.messages)l._addMessageParam(d);return o(l,Ut,{...t,stream:!0},"f"),l._run(()=>l._createMessage(n,{...t,stream:!0},{...a,headers:{...a?.headers,[ft]:"stream"}})),l}_run(n){n().then(()=>{this._emitFinal(),this._emit("end")},e(this,oo,"f"))}_addMessageParam(n){this.messages.push(n)}_addMessage(n,t=!0){if(this.receivedMessages.push(n),t)this._emit("message",n)}async _createMessage(n,t,a){let c=a?.signal,l;if(c){if(c.aborted)this.controller.abort();l=this.controller.abort.bind(this.controller),c.addEventListener("abort",l)}try{e(this,Pe,"m",ao).call(this);let{response:d,data:h}=await n.create({...t,stream:!0},{...a,signal:this.controller.signal}).withResponse();this._connected(d);for await(let f of h)e(this,Pe,"m",co).call(this,f);if(h.controller.signal?.aborted)throw new Ee;e(this,Pe,"m",lo).call(this)}finally{if(c&&l)c.removeEventListener("abort",l)}}_connected(n){if(this.ended)return;o(this,Xs,n,"f"),o(this,Qs,n?.headers.get("request-id"),"f"),o(this,Zs,n?.headers.get("anthropic-workspace-id"),"f"),e(this,Vs,"f").call(this,n),this._emit("connect")}get ended(){return e(this,on,"f")}get errored(){return e(this,Js,"f")}get aborted(){return e(this,Gs,"f")}abort(){this.controller.abort()}on(n,t){return(e(this,We,"f")[n]||(e(this,We,"f")[n]=[])).push({listener:t}),this}off(n,t){let a=e(this,We,"f")[n];if(!a)return this;let c=a.findIndex((l)=>l.listener===t);if(c>=0)a.splice(c,1);return this}once(n,t){return(e(this,We,"f")[n]||(e(this,We,"f")[n]=[])).push({listener:t,once:!0}),this}emitted(n){return new Promise((t,a)=>{if(o(this,ut,!0,"f"),n!=="error")this.once("error",a);this.once(n,t)})}async done(){o(this,ut,!0,"f"),await e(this,nn,"f")}get currentMessage(){return e(this,et,"f")}async finalMessage(){return await this.done(),e(this,Pe,"m",io).call(this)}async finalText(){return await this.done(),e(this,Pe,"m",ac).call(this)}_emit(n,...t){if(e(this,on,"f"))return;if(n==="end")o(this,on,!0,"f"),e(this,Ys,"f").call(this);let a=e(this,We,"f")[n];if(a)e(this,We,"f")[n]=a.filter((c)=>!c.once),a.forEach(({listener:c})=>c(...t));if(n==="abort"){let c=t[0];if(!e(this,ut,"f")&&!a?.length)Promise.reject(c);e(this,rn,"f").call(this,c),e(this,sn,"f").call(this,c),this._emit("end");return}if(n==="error"){let c=t[0];if(!e(this,ut,"f")&&!a?.length)Promise.reject(c);e(this,rn,"f").call(this,c),e(this,sn,"f").call(this,c),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",e(this,Pe,"m",io).call(this))}async _fromReadableStream(n,t){let a=t?.signal,c;if(a){if(a.aborted)this.controller.abort();c=this.controller.abort.bind(this.controller),a.addEventListener("abort",c)}try{e(this,Pe,"m",ao).call(this),this._connected(null);let l=Fe.fromReadableStream(n,this.controller);for await(let d of l)e(this,Pe,"m",co).call(this,d);if(l.controller.signal?.aborted)throw new Ee;e(this,Pe,"m",lo).call(this)}finally{if(a&&c)a.removeEventListener("abort",c)}}[(et=new WeakMap,Ut=new WeakMap,tn=new WeakMap,Vs=new WeakMap,rn=new WeakMap,nn=new WeakMap,Ys=new WeakMap,sn=new WeakMap,We=new WeakMap,on=new WeakMap,Js=new WeakMap,Gs=new WeakMap,ut=new WeakMap,Xs=new WeakMap,Qs=new WeakMap,Zs=new WeakMap,an=new WeakMap,oo=new WeakMap,Pe=new WeakSet,io=function(){if(this.receivedMessages.length===0)throw new u("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ac=function(){if(this.receivedMessages.length===0)throw new u("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter((a)=>a.type==="text").map((a)=>a.text);if(t.length===0)throw new u("stream ended without producing a content block with type=text");return t.join(" ")},ao=function(){if(this.ended)return;o(this,et,void 0,"f")},co=function(t){if(this.ended)return;let a=e(this,Pe,"m",cc).call(this,t);switch(this._emit("streamEvent",t,a),t.type){case"content_block_delta":{let c=a.content.at(-1);switch(t.delta.type){case"text_delta":{if(c.type==="text")this._emit("text",t.delta.text,c.text||"");break}case"citations_delta":{if(c.type==="text")this._emit("citation",t.delta.citation,c.citations??[]);break}case"input_json_delta":{if(uo(c)&&e(this,We,"f").inputJson?.length)this._emit("inputJson",t.delta.partial_json,c.input);break}case"thinking_delta":{if(c.type==="thinking")this._emit("thinking",t.delta.thinking,c.thinking);break}case"signature_delta":{if(c.type==="thinking")this._emit("signature",c.signature);break}default:xt(t.delta)}break}case"message_stop":{this._addMessageParam(a),this._addMessage(no(a,e(this,Ut,"f"),{logger:e(this,an,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",a.content.at(-1));break}case"message_start":{o(this,et,a,"f");break}case"content_block_start":case"message_delta":break}},lo=function(){if(this.ended)throw new u("stream has ended, this shouldn't happen");let t=e(this,et,"f");if(!t)throw new u("request ended without sending any chunks");return o(this,et,void 0,"f"),no(t,e(this,Ut,"f"),{logger:e(this,an,"f")})},cc=function(t){let a=e(this,et,"f");if(t.type==="message_start"){if(a)throw new u(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!a)throw new u(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return a;case"message_delta":if(a.stop_reason=t.delta.stop_reason,a.stop_sequence=t.delta.stop_sequence,a.stop_details=t.delta.stop_details,a.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null)a.container=t.delta.container;if(t.usage.input_tokens!=null)a.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)a.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)a.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)a.usage.server_tool_use=t.usage.server_tool_use;if(t.usage.output_tokens_details!=null)a.usage.output_tokens_details=t.usage.output_tokens_details;return a;case"content_block_start":return a.content.push({...t.content_block}),a;case"content_block_delta":{let c=a.content.at(t.index);switch(t.delta.type){case"text_delta":{if(c?.type==="text")a.content[t.index]={...c,text:(c.text||"")+t.delta.text};break}case"citations_delta":{if(c?.type==="text")a.content[t.index]={...c,citations:[...c.citations??[],t.delta.citation]};break}case"input_json_delta":{if(c&&uo(c)){let l=(c[Je]||"")+t.delta.partial_json;a.content[t.index]=bs(c,l)}break}case"thinking_delta":{if(c?.type==="thinking")a.content[t.index]={...c,thinking:c.thinking+t.delta.thinking};break}case"signature_delta":{if(c?.type==="thinking")a.content[t.index]={...c,signature:t.delta.signature};break}default:xt(t.delta)}return a}case"content_block_stop":{let c=a.content.at(t.index);if(c&&uo(c)&&Je in c)Object.defineProperty(c,"input",{value:c.input,enumerable:!0,configurable:!0,writable:!0});return a}}},Symbol.asyncIterator)](){let n=[],t=[],a=!1;return this.on("streamEvent",(c)=>{let l=t.shift();if(l)l.resolve(c);else n.push(c)}),this.on("end",()=>{a=!0;for(let c of t)c.resolve(void 0);t.length=0}),this.on("abort",(c)=>{a=!0;for(let l of t)l.reject(c);t.length=0}),this.on("error",(c)=>{a=!0;for(let l of t)l.reject(c);t.length=0}),{next:async()=>{if(!n.length){if(a)return{value:void 0,done:!0};return new Promise((l,d)=>t.push({resolve:l,reject:d})).then((l)=>l?{value:l,done:!1}:{value:void 0,done:!0})}return{value:n.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Fe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return s})();class cn extends A{create(s,n){let{user_profile_id:t,workspace_id:a,...c}=s;return this._client.post("/v1/messages/batches",{body:c,...n,headers:p([{...t!=null?{"anthropic-user-profile-id":t}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}retrieve(s,n={},t){let{workspace_id:a}=n??{};return this._client.get(m`/v1/messages/batches/${s}`,{...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}list(s={},n){let{workspace_id:t,...a}=s??{};return this._client.getAPIList("/v1/messages/batches",ie,{query:a,...n,headers:p([{...t!=null?{"anthropic-workspace-id":t}:void 0},n?.headers])})}delete(s,n={},t){let{workspace_id:a}=n??{};return this._client.delete(m`/v1/messages/batches/${s}`,{...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}cancel(s,n={},t){let{workspace_id:a}=n??{};return this._client.post(m`/v1/messages/batches/${s}/cancel`,{...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}async results(s,n={},t){let a=await this.retrieve(s,n,t);if(!a.results_url)throw new u(`No batch \`results_url\`; Has it finished processing? ${a.processing_status} - ${a.id}`);let{workspace_id:c}=n??{};return this._client.get(a.results_url,{...t,headers:p([{Accept:"application/binary",...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((l,d)=>ws.fromResponse(d.response,d.controller))}}var ln=(()=>{class s extends A{constructor(){super(...arguments);this.batches=new cn(this._client)}create(n,t){let{user_profile_id:a,workspace_id:c,...l}=n;if(l.model in uc)console.warn(`The model '${l.model}' is deprecated and will reach end-of-life on ${uc[l.model]}
|
|
12
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Nu.includes(l.model)&&l.thinking&&l.thinking.type==="enabled")console.warn(`Using Claude with ${l.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 d=t?.timeout??this._client._options.timeout;if(!l.stream&&d==null){let f=ys[l.model]??void 0;d=this._client.calculateNonstreamingTimeout(l.max_tokens,f)}let h=Jn(l.tools,l.messages);return this._client.post("/v1/messages",{body:l,timeout:d??600000,...t,headers:p([{...a!=null?{"anthropic-user-profile-id":a}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},h,t?.headers]),stream:n.stream??!1})}parse(n,t){return this.create(n,t).then((a)=>so(a,n,{logger:this._client.logger??console}))}stream(n,t){return lc.createMessage(this,n,t,{logger:this._client.logger??console})}countTokens(n,t){let{user_profile_id:a,workspace_id:c,...l}=n;return this._client.post("/v1/messages/count_tokens",{body:l,...t,headers:p([{...a!=null?{"anthropic-user-profile-id":a}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}return s.Batches=cn,s})(),uc={},Nu=["claude-mythos-preview","claude-opus-4-6"];class jt extends A{retrieve(s,n={},t){let{betas:a,workspace_id:c}=n??{};return this._client.get(m`/v1/models/${s}`,{...t,headers:p([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s={},n){let{betas:t,workspace_id:a,...c}=s??{};return this._client.getAPIList("/v1/models",ie,{query:c,...n,headers:p([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}}class un extends A{create(s,n,t){let{workspace_id:a,...c}=n;return this._client.post(m`/v1/skills/${s}/versions`,Re({body:c,...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])},this._client,!1))}retrieve(s,n,t){let{skill_id:a,workspace_id:c}=n;return this._client.get(m`/v1/skills/${a}/versions/${s}`,{...t,headers:p([{...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s,n={},t){let{workspace_id:a,...c}=n??{};return this._client.getAPIList(m`/v1/skills/${s}/versions`,C,{query:c,...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}delete(s,n,t){let{skill_id:a,workspace_id:c}=n;return this._client.delete(m`/v1/skills/${a}/versions/${s}`,{...t,headers:p([{...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}var pn=(()=>{class s extends A{constructor(){super(...arguments);this.versions=new un(this._client)}create(n,t){let{workspace_id:a,...c}=n;return this._client.post("/v1/skills",Re({body:c,...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])},this._client,!1))}retrieve(n,t={},a){let{workspace_id:c}=t??{};return this._client.get(m`/v1/skills/${n}`,{...a,headers:p([{...c!=null?{"anthropic-workspace-id":c}:void 0},a?.headers])})}list(n={},t){let{workspace_id:a,...c}=n??{};return this._client.getAPIList("/v1/skills",C,{query:c,...t,headers:p([{...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}delete(n,t={},a){let{workspace_id:c}=t??{};return this._client.delete(m`/v1/skills/${n}`,{...a,headers:p([{...c!=null?{"anthropic-workspace-id":c}:void 0},a?.headers])})}}return s.Versions=un,s})();var ho,fo,si,dc,Fu="\\n\\nHuman:",Hu="\\n\\nAssistant:",Du=(()=>{class s{get credentials(){return this._authState.provider}constructor({baseURL:n=R("ANTHROPIC_BASE_URL"),apiKey:t,authToken:a,webhookKey:c=R("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...l}={}){if(ho.add(this),this._requestAuthFlags=new WeakMap,si.set(this,void 0),t===void 0)t=l.profile!=null?null:R("ANTHROPIC_API_KEY")??null;if(a===void 0)a=l.profile!=null?null:R("ANTHROPIC_AUTH_TOKEN")??null;if(l.profile!=null&&(l.credentials!=null||l.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let d={apiKey:t,authToken:a,webhookKey:c,...l,baseURL:n||"https://api.anthropic.com"};if(!d.dangerouslyAllowBrowser&&Io())throw new u(`It looks like you're running in a browser-like environment.
|
|
13
|
-
|
|
14
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
15
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
16
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
17
|
-
|
|
18
|
-
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
19
|
-
`);this.baseURL=d.baseURL,this._baseURLIsExplicit=l.__baseURLIsExplicit??!!n,this.timeout=d.timeout??fo.DEFAULT_TIMEOUT,this.logger=d.logger??console,this.logLevel=Ir,this.logLevel=kn(d.logLevel,"ClientOptions.logLevel",T(this))??kn(R("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",T(this))??Ir,this.fetchOptions=d.fetchOptions,this.maxRetries=Pn("maxRetries",d.maxRetries??2),this.fetch=d.fetch??Mo(),o(this,si,Lo,"f"),this.middleware=[...d.middleware??[]];let h=R("ANTHROPIC_CUSTOM_HEADERS");if(h){let g={};for(let x of h.split(`
|
|
20
|
-
`)){let _=x.indexOf(":");if(_>=0)g[x.substring(0,_).trim()]=x.substring(_+1).trim()}d.defaultHeaders={...g,...d.defaultHeaders}}let f=l.__auth;if(delete d.__auth,delete d.__baseURLIsExplicit,this._options=d,this.apiKey=typeof t==="string"?t:null,this.authToken=a,this.webhookKey=c,f){if(this._authState=f,!this._baseURLIsExplicit&&f.baseURL)this.baseURL=f.baseURL}else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let g=d.credentials??null;if(g)this._authState.provider=g,this._authState.tokenCache=this._makeTokenCache(g);else if(d.config!=null){let x=Si(d.config,this._credentialResolverOptions());this._authState.provider=x.provider,this._authState.tokenCache=this._makeTokenCache(x.provider),this._authState.extraHeaders=x.extraHeaders,this._applyCredentialBaseURL(x.baseURL)}else if(d.profile!=null)this._authState.resolution=this._resolveDefaultCredentials(d.profile);else if(this._shouldResolveDefaultCredentials())this._authState.resolution=this._resolveDefaultCredentials()}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(n){if(!n)return;let t=n.replace(/\/+$/,"");if(this._authState.baseURL=t,!this._baseURLIsExplicit)this.baseURL=t}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:(n)=>{T(this).debug("credential cache write failed (best-effort)",n)},onSafetyWarning:(n)=>{T(this).warn(n)}}}_credentialsFetch(){return xi(this.fetch,this.middleware,void 0,this)}_makeTokenCache(n){return new yi(n,(t)=>{T(this).debug("advisory token refresh failed; serving cached token",t)})}withOptions(n){let t="credentials"in n||"config"in n||"profile"in n,a="apiKey"in n||"authToken"in n||t,c={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...n,__auth:a?void 0:this._authState,__baseURLIsExplicit:"baseURL"in n?!0:this._baseURLIsExplicit};return new this.constructor(c)}async _resolveDefaultCredentials(n){try{let t=await ia(this._credentialResolverOptions(),n);if(t)this._authState.provider=t.provider,this._authState.tokenCache=this._makeTokenCache(t.provider),this._authState.extraHeaders=t.extraHeaders,this._applyCredentialBaseURL(t.baseURL);else if(n!=null)throw new u(`Profile "${n}" could not be resolved (no <config_dir>/configs/${n}.json found).`)}catch(t){this._authState.error=t}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:n,nulls:t}){if(n.get("x-api-key")||n.get("authorization"))return;if(this._authState.error)throw this._authState.error;if(this._authState.tokenCache||this._authState.resolution)return;if(this.apiKey&&n.get("x-api-key"))return;if(t.has("x-api-key"))return;if(this.authToken&&n.get("authorization"))return;if(t.has("authorization"))return;throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}_authFlags(n){let t=this._requestAuthFlags.get(n);if(!t)t={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(n,t);return t}async authHeaders(n){if(this._authState.resolution)await this._authState.resolution;if(this._authState.error)return;if(this._authState.tokenCache&&this.apiKey==null){let t=await this._authState.tokenCache.getToken();return this._authFlags(n).usedTokenCache=!0,p([{Authorization:`Bearer ${t}`}])}return p([await this.apiKeyAuth(n),await this.bearerAuth(n)])}async apiKeyAuth(n){if(this.apiKey==null)return;return p([{"X-Api-Key":this.apiKey}])}async bearerAuth(n){if(this.authToken==null)return;return p([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(n){return qo(n)}getUserAgent(){return`Anthropic/JS ${Ae}`}makeStatusError(n,t,a,c){return Z.generate(n,t,a,c)}buildURL(n,t,a){let c=!e(this,ho,"m",dc).call(this)&&a||this.baseURL,l=ri(n)?new URL(n):new URL(c+(c.endsWith("/")&&n.startsWith("/")?n.slice(1):n)),d=this.defaultQuery(),h=Object.fromEntries(l.searchParams);if(!Eo(d)||!Eo(h))t={...h,...d,...t};if(typeof t==="object"&&t&&!Array.isArray(t))l.search=this.stringifyQuery(t);return l.toString()}_calculateNonstreamingTimeout(n){if(3600*n/128000>600)throw new u("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(n){}async prepareRequest(n,{url:t,options:a}){if(this._authState.tokenCache&&this.apiKey==null){let c=n.headers instanceof Headers?n.headers:new Headers(n.headers);for(let[d,h]of Object.entries(this._authState.extraHeaders))if(!c.has(d))c.set(d,h);let l=c.get("anthropic-beta")?.split(",").map((d)=>d.trim());if(!l?.includes(rt))c.set("anthropic-beta",[...l??[],rt].join(","));n.headers=c}}backendMiddleware(){return[]}get(n,t){return this.methodRequest("get",n,t)}post(n,t){return this.methodRequest("post",n,t)}patch(n,t){return this.methodRequest("patch",n,t)}put(n,t){return this.methodRequest("put",n,t)}delete(n,t){return this.methodRequest("delete",n,t)}methodRequest(n,t,a){return this.request(Promise.resolve(a).then((c)=>({method:n,path:t,...c})))}request(n,t=null){return new qn(this,this.makeRequest(n,t,void 0))}async makeRequest(n,t,a){let c=await n,l=Pn("maxRetries",c.maxRetries??this.maxRetries);if(this.isStreamBody(c.body))l=0;if(t==null)t=l,this._requestAuthFlags.delete(c);await this.prepareOptions(c);let{req:d,url:h,timeout:f}=await this.buildRequest(c,{retryCount:l-t}),g="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),x=a===void 0?"":`, retryOf: ${a}`,_=Date.now();if(c.signal?.aborted)throw new Ee;let k=new AbortController,w=await this.fetchWithTimeout(h,d,f,k,c,{requestLogID:g,retryOfRequestLogID:a}).catch(Lt),v=Date.now();if(w instanceof globalThis.Error){Ne(k);let I=`retrying, ${t} attempts remaining`;if(c.signal?.aborted)throw new Ee;let b=ze(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):"")),N=this.middleware.length>0||!!c.middleware?.length||this.backendMiddleware().length>0;if(N&&!b&&!ua(w))throw T(this).info(`[${g}] middleware error (not retryable)`),Ze(T(this),`[${g}] middleware error (not retryable)`,{retryOfRequestLogID:a,url:h,durationMs:v-_,message:w.message}),w;if(t)return T(this).info(`[${g}] connection ${b?"timed out":"failed"} - ${I}`),Ze(T(this),`[${g}] connection ${b?"timed out":"failed"} (${I})`,{retryOfRequestLogID:a,url:h,durationMs:v-_,message:w.message}),this.retryRequest(c,t,a??g);if(T(this).info(`[${g}] connection ${b?"timed out":"failed"} - error; no more retries left`),Ze(T(this),`[${g}] connection ${b?"timed out":"failed"} (error; no more retries left)`,{retryOfRequestLogID:a,url:h,durationMs:v-_,message:w.message}),b)throw new yn;if(N&&!vi(w))throw w;throw new wt({cause:w})}let O=[...w.headers.entries()].filter(([I])=>I==="request-id"||I==="anthropic-workspace-id").map(([I,b])=>", "+I+": "+JSON.stringify(b)).join(""),S=`[${g}${x}${O}] ${d.method} ${h} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${v-_}ms`;if(!w.ok){let I=await this.shouldRetry(w,c);if(t&&I){let H=`retrying, ${t} attempts remaining`;return await No(w.body),Ne(k),T(this).info(`${S} - ${H}`),Ze(T(this),`[${g}] response error (${H})`,{retryOfRequestLogID:a,url:w.url,status:w.status,headers:w.headers,durationMs:v-_}),this.retryRequest(c,t,a??g,w.headers)}let b=I?"error; no more retries left":"error; not retryable";T(this).info(`${S} - ${b}`);let N=await w.text().catch((H)=>Lt(H).message),L=Tn(N),F=L?void 0:N;throw Ze(T(this),`[${g}] response error (${b})`,{retryOfRequestLogID:a,url:w.url,status:w.status,headers:w.headers,message:F,durationMs:Date.now()-_}),Ne(k),this.makeStatusError(w.status,L,F,w.headers)}return T(this).info(S),Ze(T(this),`[${g}] response start`,{retryOfRequestLogID:a,url:w.url,status:w.status,headers:w.headers,durationMs:v-_}),Oo(w.body??w,k),{response:w,options:c,controller:k,requestLogID:g,retryOfRequestLogID:a,startTime:_}}getAPIList(n,t,a){return this.requestAPIList(t,a&&"then"in a?a.then((c)=>({method:"get",path:n,...c})):{method:"get",path:n,...a})}requestAPIList(n,t){let a=this.makeRequest(t,null,void 0);return new da(this,a,n)}async fetchWithTimeout(n,t,a,c,l,d){let{signal:h,method:f,...g}=t||{},x=this._makeAbort(c);if(h)h.addEventListener("abort",x,{once:!0}),Co(c,h,x);let _=globalThis.ReadableStream&&g.body instanceof globalThis.ReadableStream||typeof g.body==="object"&&g.body!==null&&Symbol.asyncIterator in g.body,k={signal:c.signal,..._?{duplex:"half"}:{},method:"GET",...g};if(f)k.method=f.toUpperCase();let w=this.fetch,v=async(N,L)=>{let F=setTimeout(x,a);try{return await w.call(void 0,N,L)}finally{clearTimeout(F)}},O=l===void 0?v:async(N,L={})=>{let F=typeof N==="string"?N:N instanceof URL?N.href:N.url;if(L.headers=L.headers instanceof Headers?L.headers:new Headers(L.headers),await this.prepareRequest(L,{url:F,options:l}),d)Ze(T(this),`[${d.requestLogID}] sending request`,{retryOfRequestLogID:d.retryOfRequestLogID,method:L.method,url:F,options:l,headers:L.headers});return v(N,L)},S=l?.middleware,I=this.backendMiddleware(),b=S?.length||I.length?[...this.middleware,...S??[],...I]:this.middleware;return await xi(O,b,l,this)(n,k)}async shouldRetry(n,t){let a=this._authFlags(t);if(n.status===401&&this._authState.tokenCache&&a.usedTokenCache&&!a.didRefreshFor401)return a.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let c=n.headers.get("x-should-retry");if(c==="true")return!0;if(c==="false")return!1;if(n.status===408)return!0;if(n.status===409)return!0;if(n.status===429)return!0;if(n.status>=500)return!0;return!1}async retryRequest(n,t,a,c){let l,d=c?.get("retry-after-ms");if(d){let f=parseFloat(d);if(!Number.isNaN(f))l=f}let h=c?.get("retry-after");if(h&&!l){let f=parseFloat(h);if(!Number.isNaN(f))l=f*1000;else l=Date.parse(h)-Date.now()}if(l===void 0||!(l>0&&l<=2147483647)){let f=n.maxRetries??this.maxRetries;l=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Ce(l,n.signal??void 0),this.makeRequest(n,t-1,a)}calculateDefaultRetryTimeoutMillis(n,t){let l=t-n,d=Math.min(0.5*Math.pow(2,l),8),h=1-Math.random()*0.25;return d*h*1000}calculateNonstreamingTimeout(n,t){if(3600000*n/128000>600000||t!=null&&n>t)throw new u("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(n,{retryCount:t=0}={}){let a={...n},{method:c,path:l,query:d,defaultBaseURL:h}=a;if(this._authState.resolution)await this._authState.resolution;if(!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL)this.baseURL=this._authState.baseURL;let f=this.buildURL(l,d,h);if("timeout"in a)Pn("timeout",a.timeout);a.timeout=a.timeout??this.timeout;let{bodyHeaders:g,body:x}=this.buildBody({options:a}),_=await this.buildHeaders({options:n,method:c,bodyHeaders:g,retryCount:t,timeout:a.timeout});return{req:{method:c,headers:_,...a.signal&&{signal:a.signal},...globalThis.ReadableStream&&x instanceof globalThis.ReadableStream&&{duplex:"half"},...x&&{body:x},...this.fetchOptions??{},...a.fetchOptions??{}},url:f,timeout:a.timeout}}async buildHeaders({options:n,method:t,bodyHeaders:a,retryCount:c,timeout:l}){let d=p([{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(c),"X-Stainless-Timeout":String(Math.trunc(l/1000)),...qt(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(n),this._options.defaultHeaders,a,n.headers]);return this.validateHeaders(d),d.values}_makeAbort(n){return()=>n.abort()}buildBody({options:{body:n,headers:t}}){if(!n)return{bodyHeaders:void 0,body:void 0};let a=p([t]);if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof DataView||typeof n==="string"&&a.values.has("content-type")||globalThis.Blob&&n instanceof globalThis.Blob||n instanceof FormData||n instanceof URLSearchParams||globalThis.ReadableStream&&n instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:n};else if(this.isStreamBody(n))return{bodyHeaders:void 0,body:Nn(n)};else if(typeof n==="object"&&a.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(n)};else return e(this,si,"f").call(this,{body:n,headers:a})}isStreamBody(n){if(globalThis.ReadableStream&&n instanceof globalThis.ReadableStream)return!0;return typeof n==="object"&&n!==null&&((Symbol.asyncIterator in n)||(Symbol.iterator in n)&&("next"in n)&&typeof n.next==="function")}}return fo=s,si=new WeakMap,ho=new WeakSet,dc=function(){return this.baseURL!=="https://api.anthropic.com"},s.Anthropic=fo,s.DEFAULT_TIMEOUT=600000,s.AnthropicError=u,s.APIError=Z,s.APIConnectionError=wt,s.APIConnectionTimeoutError=yn,s.APIUserAbortError=Ee,s.NotFoundError=xn,s.ConflictError=vn,s.RateLimitError=An,s.BadRequestError=bn,s.AuthenticationError=Sn,s.InternalServerError=En,s.PermissionDeniedError=wn,s.UnprocessableEntityError=_n,s.toFile=Ci,s.HUMAN_PROMPT=Fu,s.AI_PROMPT=Hu,s})(),ai=(()=>{class s extends Du{constructor(){super(...arguments);this.completions=new Bt(this),this.messages=new ln(this),this.models=new jt(this),this.files=new Wt(this),this.skills=new pn(this),this.beta=new en(this)}}return s.Completions=Bt,s.Messages=ln,s.Models=jt,s.Files=Wt,s.Skills=pn,s.Beta=en,s})();var Bu=function(s,n){if(typeof s==="string"&&/^\.\.?\//.test(s))return s.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,a,c,l,d){return a?n?".jsx":".js":c&&(!l||!d)?t:c+l+"."+d.toLowerCase()+"js"});return s},Wu=null,Uu=null,ju=null,po=(s)=>import(Bu(s)),qu="node:fs",Ku="node:os",zu="node:path";if(typeof process<"u"&&(process.versions?.node||process.versions?.bun))po(qu).then((s)=>{Wu=s.existsSync}),po(Ku).then((s)=>{Uu=s.homedir}),po(zu).then((s)=>{ju=s.join});var xo="ANTHROPIC_AUTH_TOKEN",ei="ANTHROPIC_OAUTH_TOKEN",ti="ANTHROPIC_API_KEY",dn="ANTHROPIC_FEDERATION_RULE_ID",mn="ANTHROPIC_ORGANIZATION_ID",hn="ANTHROPIC_SERVICE_ACCOUNT_ID",fn="ANTHROPIC_IDENTITY_TOKEN_FILE",gn="ANTHROPIC_WORKSPACE_ID";function hc(s,n){if(s)return s;if(P("PI_CACHE_RETENTION",n)==="long")return"long";return"short"}function Vu(s,n,t){let a=hc(n,t);if(a==="none")return{retention:a};let c=a==="long"&&On(s).supportsLongCacheRetention?"1h":void 0;return{retention:a,cacheControl:{type:"ephemeral",...c&&{ttl:c}}}}var Yu="2.1.280",Ju=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],Gu=new Map(Ju.map((s)=>[s.toLowerCase(),s])),yo=(s)=>Gu.get(s.toLowerCase())??s,Xu=(s,n)=>{if(n&&n.length>0){let t=s.toLowerCase(),a=n.find((c)=>c.name.toLowerCase()===t);if(a)return a.name}return s};function Qu(s){if(!s.some((c)=>c.type==="image"))return y(s.map((c)=>c.text).join(`
|
|
21
|
-
`));let t=s.map((c)=>{if(c.type==="text")return{type:"text",text:y(c.text)};return{type:"image",source:{type:"base64",media_type:c.mimeType,data:c.data}}});if(!t.some((c)=>c.type==="text"))t.unshift({type:"text",text:"(see attached image)"});return t}var Zu="fine-grained-tool-streaming-2025-05-14",ed="interleaved-thinking-2025-05-14",td="server-side-fallback-2026-07-01",rd="mid-conversation-output-config-2026-07-01",nd="thinking-binding-controls-2026-08-01",sd="inline-tools-2026-09-15",id={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function od(s){return(s.compat?.allowedFallbackModels?.length??0)>0}function On(s){let n=s.provider==="openrouter"||s.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:s.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:s.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:s.compat?.sendSessionAffinityHeaders??n,sessionAffinityFormat:s.compat?.sessionAffinityFormat??(n?"openrouter":void 0),supportsCacheControlOnTools:s.compat?.supportsCacheControlOnTools??!0,supportsTemperature:s.compat?.supportsTemperature??!0,allowEmptySignature:s.compat?.allowEmptySignature??!1,supportsStrictTools:s.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:s.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:s.compat?.supportsMidConvoToolChanges??!1}}function ad(...s){let n={};for(let t of s)if(t)Object.assign(n,t);return n}function mo(...s){return ad({"User-Agent":ee()},...s)}function go(s,n){if(!s)return!1;let t=n.toLowerCase();for(let[a,c]of Object.entries(s))if(a.toLowerCase()===t&&c!==null&&c.trim().length>0)return!0;return!1}function fc(s,n){return!!s||go(n,"authorization")||go(n,"x-api-key")||go(n,"cf-aig-authorization")}function pc(s,n,t){if(!fc(n,t))throw Error(`No API key for provider: ${s}`)}class In extends ai{_shouldResolveDefaultCredentials(){return!1}}function mc(s,n,t,a){if(s.provider!=="anthropic"||fc(n,t))return;let c=P(dn,a),l=P(mn,a),d=P(fn,a);if(!c||!l||!d)return;return{organization_id:l,workspace_id:P(gn,a),authentication:{type:"oidc_federation",federation_rule_id:c,service_account_id:P(hn,a),identity_token:{source:"file",path:d}}}}var ci,cd=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function _c(s){if(!s.event&&s.data.length===0)return null;let n={event:s.event,data:s.data.join(`
|
|
22
|
-
`),raw:[...s.raw]};return s.event=null,s.data=[],s.raw=[],n}function wo(s,n){if(s==="")return _c(n);if(n.raw.push(s),s.startsWith(":"))return null;let t=s.indexOf(":"),a=t===-1?s:s.slice(0,t),c=t===-1?"":s.slice(t+1);if(c.startsWith(" "))c=c.slice(1);if(a==="event")n.event=c;else if(a==="data")n.data.push(c);return null}function ld(s){let n=s.indexOf("\r"),t=s.indexOf(`
|
|
23
|
-
`);if(n===-1)return t;if(t===-1)return n;return Math.min(n,t)}function li(s){let n=ld(s);if(n===-1)return null;let t=n+1;if(s[n]==="\r"&&s[t]===`
|
|
24
|
-
`)t+=1;return{line:s.slice(0,n),rest:s.slice(t)}}async function*ud(s,n){let t=s.getReader(),a=new TextDecoder,c={event:null,data:[],raw:[]},l="";try{while(!0){if(n?.aborted)throw Error("Request was aborted");let{value:f,done:g}=await t.read();if(g)break;l+=a.decode(f,{stream:!0});let x=li(l);while(x){l=x.rest;let _=wo(x.line,c);if(_)yield _;x=li(l)}}l+=a.decode();let d=li(l);while(d){l=d.rest;let f=wo(d.line,c);if(f)yield f;d=li(l)}if(l.length>0){let f=wo(l,c);if(f)yield f}let h=_c(c);if(h)yield h}finally{t.releaseLock()}}async function*dd(s,n){if(!s.body)throw Error("Attempted to iterate over an Anthropic response with no body");let t=!1,a=!1;for await(let c of ud(s.body,n)){if(c.event==="error")throw Error(c.data);if(!cd.has(c.event??""))continue;try{let l=Qr(c.data);if(l.type==="message_start")t=!0;else if(l.type==="message_stop")a=!0;yield l}catch(l){let d=l instanceof Error?l.message:String(l);throw Error(`Could not parse Anthropic SSE event ${c.event}: ${d}; data=${c.data}; raw=${c.raw.join("\\n")}`)}}if(t&&!a)throw Error("Anthropic stream ended before message_stop")}var Xt=(s,n,t)=>{let a=new M,c=re(n,On(s).supportsMidConvoSystemMessages),l=oe(c.messages);return(async()=>{let d=s.compat?.supportsMidConvoEffort?t?.effort??"high":void 0,h={role:"assistant",content:[],api:s.api,provider:s.provider,model:s.id,...d===void 0?{}:{providerThinkingLevel:d},usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let f,g,x=s,_;if(t?.client)f=t.client,g=!1;else{let S=t?.apiKey,I=mc(s,S,t?.headers,t?.env);if(!I)pc(s.provider,S,t?.headers);let b;if(s.provider==="github-copilot"){let Y=_t(c.messages);b=At({messages:c.messages,hasImages:Y})}let L=hc(t?.cacheRetention,t?.env)==="none"?void 0:t?.sessionId,F=pd(s,S,t?.headers,t?.fetch,b,L,I);f=F.client,g=F.isOAuthToken}let k={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},w=!1,v;for(;;){t?.signal?.throwIfAborted();let S=_d(s,c,g,t,w),I=S.params,b=await t?.onPayload?.(I,s);if(b!==void 0)I={...b,stream:!0};try{v=await se(()=>f.beta.messages.create(I,k).asResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});break}catch(N){if(t?.signal?.aborted||w||!S.hasPreferredStrictTools||!(N instanceof ai.APIError)||N.status!==400||N.type!=="invalid_request_error"||!["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("].some((L)=>N.message.includes(L)))throw N;w=!0,ke(h,{type:"anthropic_strict_tools_fallback",timestamp:Date.now(),error:{message:N.message},details:{reason:"strict_tool_limits_exceeded"}})}}await t?.onResponse?.({status:v.status,headers:j(v.headers)},s),a.push({type:"start",partial:h});let O=h.content;for await(let S of dd(v,t?.signal))if(await t?.onProviderStreamEvent?.(S,s),S.type==="message_start"){h.responseId=S.message.id;let I=S.message.input_transformations;if(Array.isArray(I))_=I;let b=S.message.model;if(b!==s.id)h.responseModel=b;let N=b===s.id?void 0:s.compat?.allowedFallbackModels?.find((L)=>L.provider===s.provider&&L.model===b)?.cost;x=N?{...s,id:b,cost:N}:s,h.usage.input=S.message.usage.input_tokens||0,h.usage.output=S.message.usage.output_tokens||0,h.usage.cacheRead=S.message.usage.cache_read_input_tokens||0,h.usage.cacheWrite=S.message.usage.cache_creation_input_tokens||0,h.usage.cacheWrite1h=S.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,h.usage.totalTokens=h.usage.input+h.usage.output+h.usage.cacheRead+h.usage.cacheWrite,Q(x,h.usage)}else if(S.type==="content_block_start"){if(S.content_block.type==="fallback"){if(h.content.length>0)throw Error("Anthropic performed an unsupported mid-output model fallback");continue}if(S.content_block.type==="text"){let I={type:"text",text:S.content_block.text??"",index:S.index};h.content.push(I),a.push({type:"text_start",contentIndex:h.content.length-1,partial:h})}else if(S.content_block.type==="thinking"){let I={type:"thinking",thinking:S.content_block.thinking??"",thinkingSignature:S.content_block.signature??"",index:S.index};h.content.push(I),a.push({type:"thinking_start",contentIndex:h.content.length-1,partial:h})}else if(S.content_block.type==="redacted_thinking"){let I={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:S.content_block.data,redacted:!0,index:S.index};h.content.push(I),a.push({type:"thinking_start",contentIndex:h.content.length-1,partial:h})}else if(S.content_block.type==="tool_use"){let I={type:"toolCall",id:S.content_block.id,name:g?Xu(S.content_block.name,l):S.content_block.name,arguments:S.content_block.input??{},partialJson:"",index:S.index};h.content.push(I),a.push({type:"toolcall_start",contentIndex:h.content.length-1,partial:h})}}else if(S.type==="content_block_delta"){if(S.delta.type==="text_delta"){let I=O.findIndex((N)=>N.index===S.index),b=O[I];if(b&&b.type==="text")b.text+=S.delta.text,a.push({type:"text_delta",contentIndex:I,delta:S.delta.text,partial:h})}else if(S.delta.type==="thinking_delta"){let I=O.findIndex((N)=>N.index===S.index),b=O[I];if(b&&b.type==="thinking")b.thinking+=S.delta.thinking,a.push({type:"thinking_delta",contentIndex:I,delta:S.delta.thinking,partial:h})}else if(S.delta.type==="input_json_delta"){let I=O.findIndex((N)=>N.index===S.index),b=O[I];if(b&&b.type==="toolCall")b.partialJson+=S.delta.partial_json,b.arguments=W(b.partialJson),a.push({type:"toolcall_delta",contentIndex:I,delta:S.delta.partial_json,partial:h})}else if(S.delta.type==="signature_delta"){let I=O.findIndex((N)=>N.index===S.index),b=O[I];if(b&&b.type==="thinking")b.thinkingSignature=b.thinkingSignature||"",b.thinkingSignature+=S.delta.signature}}else if(S.type==="content_block_stop"){let I=O.findIndex((N)=>N.index===S.index),b=O[I];if(b){if(delete b.index,b.type==="text")a.push({type:"text_end",contentIndex:I,content:b.text,partial:h});else if(b.type==="thinking")a.push({type:"thinking_end",contentIndex:I,content:b.thinking,partial:h});else if(b.type==="toolCall")b.arguments=W(b.partialJson),delete b.partialJson,a.push({type:"toolcall_end",contentIndex:I,toolCall:b,partial:h})}}else if(S.type==="message_delta"){let I=S.input_transformations;if(Array.isArray(I))_=I;if(S.delta.stop_reason){h.rawStopReason=S.delta.stop_reason;let b=Rd(S.delta.stop_reason,S.delta.stop_details);if(h.stopReason=b.stopReason,b.errorMessage)h.errorMessage=b.errorMessage}if(S.usage){if(S.usage.input_tokens!=null)h.usage.input=S.usage.input_tokens;if(S.usage.output_tokens!=null)h.usage.output=S.usage.output_tokens;if(S.usage.cache_read_input_tokens!=null)h.usage.cacheRead=S.usage.cache_read_input_tokens;if(S.usage.cache_creation_input_tokens!=null)h.usage.cacheWrite=S.usage.cache_creation_input_tokens;let b=S.usage.cache_creation;if(b?.ephemeral_1h_input_tokens!=null)h.usage.cacheWrite1h=b.ephemeral_1h_input_tokens;let N=S.usage.output_tokens_details?.thinking_tokens;if(N!=null)h.usage.reasoning=N}h.usage.totalTokens=h.usage.input+h.usage.output+h.usage.cacheRead+h.usage.cacheWrite,Q(x,h.usage)}if(t?.signal?.aborted)throw Error("Request was aborted");if(h.stopReason==="pending")throw Error("Anthropic stream ended without a stop reason");if(h.stopReason==="aborted"||h.stopReason==="error")throw Error(h.errorMessage||"An unknown error occurred");if(_&&_.length>0)ke(h,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:_.map((S)=>({type:S.type??void 0,path:S.path??void 0,reason:S.reason??void 0}))}});a.push({type:"done",reason:h.stopReason,message:h}),a.end()}catch(f){for(let g of h.content)delete g.index,delete g.partialJson;h.stopReason=t?.signal?.aborted?"aborted":"error",h.errorMessage=f instanceof Error?f.message:JSON.stringify(f),a.push({type:"error",reason:h.stopReason,error:h}),a.end()}})(),a};function hd(s,n){let t=n?s.thinkingLevelMap?.[n]:void 0;if(typeof t==="string")return t;switch(n){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var vo=(s,n,t)=>{if(!mc(s,t?.apiKey,t?.headers,t?.env))pc(s.provider,t?.apiKey,t?.headers);let a={...K(s,n,t,t?.apiKey),toolChoice:t?.toolChoice};if(!t?.reasoning)return Xt(s,n,{...a,thinkingEnabled:!1});if(s.compat?.forceAdaptiveThinking===!0){let d=hd(s,t.reasoning);return Xt(s,n,{...a,thinkingEnabled:!0,effort:d})}let c=Dr(a.maxTokens,s.maxTokens,t.reasoning,t.thinkingBudgets),l=Zt(s,n,c.maxTokens);return Xt(s,n,{...a,maxTokens:l,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(c.thinkingBudget,Math.max(0,l-1024))})};function fd(s){return s.includes("sk-ant-oat")}function pd(s,n,t,a,c,l,d){if(s.provider==="github-copilot")return{client:new In({apiKey:null,authToken:n??null,baseURL:s.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:mo({accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},s.headers,c,t)}),isOAuthToken:!1};if(n&&fd(n))return{client:new In({apiKey:null,authToken:n,baseURL:s.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:mo({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${Yu}`,"x-app":"cli"},s.headers,t)}),isOAuthToken:!0};let h=On(s),f={};if(l&&h.sendSessionAffinityHeaders){let _=h.sessionAffinityFormat==="openrouter"?"x-session-id":"x-session-affinity";f[_]=l}let g=mo({accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},f,s.headers,t);if(d){let _=JSON.stringify([s.baseUrl,d]);if(ci?.key!==_||ci.fetch!==a){let k=new In({apiKey:null,authToken:null,config:d,baseURL:s.baseUrl,dangerouslyAllowBrowser:!0,fetch:a});ci={key:_,fetch:a,client:k}}return{client:ci.client.withOptions({defaultHeaders:g}),isOAuthToken:!1}}return{client:new In({apiKey:n??null,authToken:null,baseURL:s.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:g}),isOAuthToken:!1}}function md(s,n,t,a,c){let l;for(let h of[s.headers,c?.headers])for(let[f,g]of Object.entries(h??{}))if(f.toLowerCase()==="anthropic-beta")l=g;if(l===null)return[];if(l!==void 0)return[...new Set(l.split(",").map((h)=>h.trim()).filter((h)=>h.length>0))];let d=[];if(t)d.push("claude-code-20250219","oauth-2025-04-20");if(Sd(s,n))d.push(Zu);if(s.reasoning&&c?.thinkingEnabled===!0&&(c.interleavedThinking??!0)&&s.compat?.forceAdaptiveThinking!==!0)d.push(ed);if(od(s))d.push(td);if(s.compat?.supportsMidConvoEffort===!0)d.push(rd,nd);if(a)d.push(sd);return[...new Set(d)]}function _d(s,n,t,a,c=!1){let{cacheControl:l}=Vu(s,a?.cacheRetention,a?.env),d=On(s),h=me(n.messages),f=h?U(h):"",g=ge(n.messages,s,gd),x=h?g.slice(1):g,_=!1,k=(F,Y)=>{let H=Ad(F,t,d.supportsEagerToolInputStreaming,d.supportsStrictTools,Y,c);if(H.some((J,B)=>{let q=F[B].constrainedSampling;return J.strict===!0&&q&&q.type==="json_schema"&&q.strict==="prefer"}))_=!0;return H},w=h?.toolsAdded??[],v=d.supportsMidConvoSystemMessages&&d.supportsMidConvoToolChanges&&w.length>0,O=yd(x,t,l,d.allowEmptySignature,s.compat?.supportsMidConvoEffort===!0?s.provider:void 0,v?k:void 0),S=a?.effort??"high",I=md(s,n,t,v,a),b={model:s.id,messages:s.compat?.supportsMidConvoEffort===!0?kd(O,S):O.messages,max_tokens:a?.maxTokens??s.maxTokens,stream:!0,...I.length>0?{betas:I}:{}};if(t){if(b.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...l?{cache_control:l}:{}}],f)b.system.push({type:"text",text:y(f),...l?{cache_control:l}:{}})}else if(f)b.system=[{type:"text",text:y(f),...l?{cache_control:l}:{}}];if(a?.temperature!==void 0&&!a?.thinkingEnabled&&s.compat?.supportsMidConvoEffort!==!0&&d.supportsTemperature)b.temperature=a.temperature;let N=d.supportsCacheControlOnTools?l:void 0;if(v)b.tools=[...k(w,N),id];else{let F=oe(n.messages);if(F.length>0)b.tools=k(F,N)}if(s.compat?.supportsMidConvoEffort===!0)b.thinking={type:"adaptive",display:a?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},b.output_config={effort:"high"};else if(s.reasoning){if(a?.thinkingEnabled){let F=a.thinkingDisplay??"summarized";if(s.compat?.forceAdaptiveThinking===!0){if(b.thinking={type:"adaptive",display:F},a.effort)b.output_config={effort:a.effort}}else b.thinking={type:"enabled",budget_tokens:a.thinkingBudgetTokens||1024,display:F}}else if(a?.thinkingEnabled===!1&&s.thinkingLevelMap?.off!==null)b.thinking={type:"disabled"}}if(a?.metadata){let F=a.metadata.user_id;if(typeof F==="string")b.metadata={user_id:F}}if(a?.toolChoice)if(typeof a.toolChoice==="string")b.tool_choice={type:a.toolChoice};else b.tool_choice=a.toolChoice;let L=s.compat?.allowedFallbackModels;if(L&&L.length>0)b.fallbacks=L.map((F)=>({model:F.model}));return{params:b,hasPreferredStrictTools:_}}function gd(s){return s.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function wd(s){return{type:"tool_result",tool_use_id:s.toolCallId,content:Qu(s.content),is_error:s.isError}}function yd(s,n,t,a=!1,c,l){let d=[],h=new Map,f=[],g=()=>{d.push(...f),f.length=0};for(let x=0;x<s.length;x++){let _=s[x];if(_.role==="system"){let k=Le(_),w=[];if(k.length>0)w.push({type:"text",text:y(k)});if(l){let v=_.toolsAdded??[],O=new Set(v.map((S)=>S.name));for(let S of _.toolsRemoved??[]){if(O.has(S.name))continue;w.push({type:"tool_removal",tool:{type:"tool_reference",name:n?yo(S.name):S.name}})}for(let S of l(v))w.push({type:"tool_addition",tool:{type:"tool_definition",definition:S}})}if(w.length>0)f.push({role:"system",content:w})}else if(_.role==="user")if(typeof _.content==="string"){if(_.content.trim().length>0)d.push({role:"user",content:y(_.content)})}else{let w=_.content.map((v)=>{if(v.type==="text")return{type:"text",text:y(v.text)};else return{type:"image",source:{type:"base64",media_type:v.mimeType,data:v.data}}}).filter((v)=>{if(v.type==="text")return v.text.trim().length>0;return!0});if(w.length===0)continue;d.push({role:"user",content:w})}else if(_.role==="assistant"){g();let k=[];for(let v of _.content)if(v.type==="text"){if(v.text.trim().length===0)continue;k.push({type:"text",text:y(v.text)})}else if(v.type==="thinking"){if(v.redacted){k.push({type:"redacted_thinking",data:v.thinkingSignature});continue}let O=v.thinkingSignature,S=!!O&&O.trim().length>0;if(v.thinking.trim().length===0&&!S)continue;if(!S)k.push(a?{type:"thinking",thinking:y(v.thinking),signature:""}:{type:"text",text:y(v.thinking)});else k.push({type:"thinking",thinking:y(v.thinking),signature:O})}else if(v.type==="toolCall")k.push({type:"tool_use",id:v.id,name:n?yo(v.name):v.name,input:v.arguments??{}});if(k.length===0)continue;let w=d.length;if(d.push({role:"assistant",content:k}),c!==void 0&&_.api==="anthropic-messages"&&_.provider===c&&bd(_.providerThinkingLevel))h.set(w,_.providerThinkingLevel)}else if(_.role==="toolResult"){let k=[],w=x;while(w<s.length&&s[w].role==="toolResult")k.push(wd(s[w])),w++;x=w-1,d.push({role:"user",content:k})}}if(g(),t&&d.length>0){let x=d[d.length-1];if(x.role==="user"||x.role==="system"){if(Array.isArray(x.content)){let _=x.content[x.content.length-1];if(_&&(_.type==="text"||_.type==="image"||_.type==="tool_result"||_.type==="tool_addition"||_.type==="tool_removal"))_.cache_control=t}else if(typeof x.content==="string")x.content=[{type:"text",text:x.content,cache_control:t}]}}return{messages:d,assistantLevels:h}}function bd(s){return s==="low"||s==="medium"||s==="high"||s==="xhigh"||s==="max"}function kd(s,n){let t=[];for(let a=0;a<s.messages.length;a++){let c=s.assistantLevels.get(a);if(c!==void 0)t.push({role:"system",content:[],output_config:{effort:c}});t.push(s.messages[a])}return t.push({role:"system",content:[],output_config:{effort:n}}),t}function Sd(s,n){return oe(n.messages).length>0&&!On(s).supportsEagerToolInputStreaming}var vd=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),xd=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),Ed=(s,n)=>{if(vd.has(s))return!0;if(s==="minItems")return n!==0&&n!==1;if(s==="format")return typeof n!=="string"||!xd.has(n);return!1};function Ad(s,n,t,a,c,l=!1){if(!s)return[];return s.map((d,h)=>{let f=d.constrainedSampling,g=l&&f&&f.type==="json_schema"&&f.strict==="prefer"?void 0:pe(d,a,Ed),x=fe(d,g),_=x,k={type:"object",properties:_.properties??{},required:_.required??[]},w=g===!0?{...x,...k}:k;return{name:n?yo(d.name):d.name,description:d.description,...t?{eager_input_streaming:!0}:{},...g===!0?{strict:!0}:{},input_schema:w,...c&&h===s.length-1?{cache_control:c}:{}}})}function Rd(s,n){switch(s){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:n?.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",errorMessage:"Provider stopped with: sensitive"};default:throw Error(`Unhandled stop reason: ${s}`)}}
|
|
25
|
-
export{xo,ei,ti,dn,mn,hn,fn,gn,Xt,vo};
|