@bkm016/basalt 0.1.12 → 0.1.14
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/README.md +3 -2
- package/chunk-03wzwnn6.js +2 -0
- package/{chunk-7jezts2n.js → chunk-06s9pr82.js} +2 -2
- package/{chunk-eyrtbbdd.js → chunk-0crbhhna.js} +1 -1
- package/{chunk-kpe7pnhy.js → chunk-0rasqm8y.js} +4 -4
- package/chunk-1w4nh5t6.js +5 -0
- package/{chunk-02d3x4mj.js → chunk-2eaehpp6.js} +3 -3
- package/{chunk-jj4hqbrx.js → chunk-30dxcr91.js} +3 -3
- package/{chunk-nw1xpt3s.js → chunk-343jsm46.js} +2 -2
- package/{chunk-bk4rpnm8.js → chunk-37ndxehw.js} +2 -2
- package/chunk-38g4jd6v.js +5 -0
- package/{chunk-0fc9apfn.js → chunk-39mh7h58.js} +23 -23
- package/{chunk-6mges89p.js → chunk-44a7f5ta.js} +5 -5
- package/chunk-44b9yx79.js +2 -0
- package/{chunk-jn5pqy5v.js → chunk-46vy2m29.js} +1 -1
- package/{chunk-2kxnw7vs.js → chunk-4f6p4n7k.js} +2 -2
- package/chunk-4w8j6n7z.js +2 -0
- package/{chunk-qs8zzg50.js → chunk-4yxd2kg1.js} +2 -2
- package/{chunk-ksk49hv0.js → chunk-59hg9a84.js} +1 -1
- package/chunk-62ebm0bn.js +2 -0
- package/chunk-6ef085c1.js +20 -0
- package/chunk-6hx9y86d.js +3 -0
- package/chunk-73t051r6.js +2 -0
- package/{chunk-1h34mzh7.js → chunk-7mgkpn94.js} +7 -7
- package/{chunk-w0rr66z7.js → chunk-81x8r8w4.js} +1 -1
- package/chunk-86yr2c0r.js +3 -0
- package/{chunk-ypqjfv3a.js → chunk-8np9b2y8.js} +2 -2
- package/{chunk-hbnmymaq.js → chunk-9ew8cap5.js} +2 -2
- package/chunk-9v3b7jjv.js +2 -0
- package/{chunk-01nve4qy.js → chunk-9vam83py.js} +1 -1
- package/chunk-9xjecw6c.js +2 -0
- package/{chunk-6sz5q3df.js → chunk-b2wpj81x.js} +2 -2
- package/chunk-b516bp7n.js +3 -0
- package/chunk-bjvv3403.js +2 -0
- package/{chunk-hc300148.js → chunk-c8g9jjqs.js} +2 -2
- package/chunk-cs91rmbf.js +18 -0
- package/chunk-drett6hb.js +2 -0
- package/{chunk-fy82qxa1.js → chunk-edcf97ka.js} +1 -1
- package/chunk-en7z6ne5.js +3 -0
- package/{chunk-p2pmdbt2.js → chunk-evnqkyt7.js} +12 -12
- package/{chunk-8mezk0cb.js → chunk-g2etemv5.js} +2 -2
- package/{chunk-n0ybj4h9.js → chunk-g5p9mj1r.js} +2 -2
- package/{chunk-eq4wqxzt.js → chunk-ge38dhv9.js} +2 -2
- package/chunk-hggam3je.js +2 -0
- package/chunk-k38jaz6c.js +7 -0
- package/{chunk-qfcr5g35.js → chunk-kcn05erf.js} +3 -3
- package/{chunk-rwks9zaw.js → chunk-m5km74eq.js} +2 -2
- package/{chunk-jpnf71q7.js → chunk-mfb3dgs8.js} +2 -2
- package/{chunk-vjne04dp.js → chunk-mh4bjtfs.js} +4 -4
- package/chunk-nysatg77.js +4161 -0
- package/chunk-p886jr17.js +25 -0
- package/{chunk-82v8jh1h.js → chunk-pdt65s31.js} +2 -2
- package/chunk-pjgt1bdx.js +3 -0
- package/{chunk-tvm4zmgj.js → chunk-pyj6avd5.js} +2 -2
- package/chunk-qd2enpr2.js +3 -0
- package/{chunk-cbgpymt4.js → chunk-qe76naq9.js} +1 -1
- package/{chunk-ntks40jd.js → chunk-qjnx4fsn.js} +5 -5
- package/{chunk-fhxy6y34.js → chunk-qs161f2q.js} +2 -2
- package/{chunk-v7wcchy2.js → chunk-rghqprav.js} +1 -1
- package/chunk-t33bm5aa.js +2 -0
- package/{chunk-nrsd810j.js → chunk-tfhp09nj.js} +2 -2
- package/chunk-vd5332ps.js +2 -0
- package/{chunk-3pf1d62g.js → chunk-vqm94hz2.js} +2 -2
- package/{chunk-85v69h91.js → chunk-w55cnj0f.js} +2 -2
- package/{chunk-1zj3zvw5.js → chunk-wnd3y4c0.js} +4 -4
- package/{chunk-stj493dn.js → chunk-xafx1p7z.js} +2 -2
- package/{chunk-9as0p561.js → chunk-xf7zw32f.js} +14 -14
- package/chunk-xk3t5ves.js +482 -0
- package/{chunk-5wnmbc1b.js → chunk-xq74x4gc.js} +2 -2
- package/chunk-y0274xr2.js +7 -0
- package/{chunk-ejjem0tc.js → chunk-z9p6s986.js} +6 -6
- package/chunk-zcwz44db.js +2 -0
- package/{chunk-w6f2r052.js → chunk-zhyzhekt.js} +1 -1
- package/compiled.js +85 -12
- package/package.json +1 -1
- package/ui-test-worker.js +65 -65
- package/web/chunk-15g9pnzy.js +1 -0
- package/web/{chunk-4f6a8dsk.js → chunk-17wwzrp4.js} +1 -1
- package/web/chunk-19tkjg9w.js +1 -0
- package/web/chunk-1y387f45.js +1 -0
- package/web/{chunk-30aeb767.js → chunk-25sn840r.js} +2 -2
- package/web/chunk-26sp6jre.js +1 -0
- package/web/{chunk-81s15c2e.js → chunk-2c7kxr4v.js} +2 -2
- package/web/{chunk-wvrs986a.js → chunk-2gsf89vs.js} +3 -3
- package/web/{chunk-3qxxrwsp.js → chunk-2gvz70wr.js} +10 -10
- package/web/chunk-2s3my1jn.js +1 -0
- package/web/{chunk-ar6jnhm5.js → chunk-32dh0hft.js} +1 -1
- package/web/{chunk-3rkkp6ed.js → chunk-3haw3wcw.js} +5 -5
- package/web/{chunk-hn8m1vsg.js → chunk-3rxhs9qm.js} +7 -7
- package/web/chunk-410qdvmv.js +1 -0
- package/web/chunk-4qehf2xx.js +2 -0
- package/web/{chunk-qdd3bx8q.js → chunk-51b8n5e1.js} +1 -1
- package/web/chunk-54mgncq3.js +1 -0
- package/web/{chunk-r6kk4vp1.js → chunk-59g6rrew.js} +4 -4
- package/web/{chunk-7tkgbbf9.js → chunk-5d9veaef.js} +2 -2
- package/web/chunk-6481wt3t.js +1 -0
- package/web/chunk-6ehecat3.js +1 -0
- package/web/chunk-6m8hq6ph.js +1 -0
- package/web/chunk-73941p08.js +1 -0
- package/web/{chunk-aeymdtm1.js → chunk-783s8jds.js} +3 -3
- package/web/{chunk-g4zm0crw.js → chunk-78m018ya.js} +1 -1
- package/web/chunk-797bh7z6.js +39 -0
- package/web/{chunk-hva7xyne.js → chunk-7hpqrfgg.js} +2 -2
- package/web/{chunk-enwfd8d5.js → chunk-7kywe73f.js} +2 -2
- package/web/chunk-7qq1ypvj.js +1 -0
- package/web/{chunk-xbyrgyy0.js → chunk-7wzszsf5.js} +2 -2
- package/web/{chunk-aa46mrgh.js → chunk-7zfqppsx.js} +2 -2
- package/web/{chunk-d73zkc4q.js → chunk-8sr9w61v.js} +3 -3
- package/web/{chunk-v34mr9ky.js → chunk-8ttp8fh3.js} +6 -6
- package/web/chunk-8zg89764.js +1 -0
- package/web/{chunk-2cyzaqjy.js → chunk-988e9wx6.js} +3 -3
- package/web/{chunk-k4dnjf8n.js → chunk-9h0f3gar.js} +3 -3
- package/web/chunk-9vr6hpmk.js +34 -0
- package/web/chunk-9vrp249f.js +2 -0
- package/web/{chunk-td83xf12.js → chunk-a205cj09.js} +2 -2
- package/web/{chunk-gkmaryr4.js → chunk-ahn2frbt.js} +1 -1
- package/web/{chunk-5g8md2wg.js → chunk-aknsydan.js} +5 -5
- package/web/chunk-at0xtfhy.js +1 -0
- package/web/chunk-bahccwb9.js +1 -0
- package/web/{chunk-rdr6wt22.js → chunk-c7fqrs8j.js} +4 -4
- package/web/chunk-d3hyf9yd.js +1 -0
- package/web/chunk-dcegr80c.js +1 -0
- package/web/{chunk-act3rr85.js → chunk-dwtatme7.js} +1 -1
- package/web/{chunk-5np514v5.js → chunk-ex8rmqn1.js} +12 -12
- package/web/{chunk-g488hxx0.js → chunk-faskbfjf.js} +3 -3
- package/web/chunk-feanedhx.js +1 -0
- package/web/{chunk-e94pd9rr.js → chunk-ffywf5w5.js} +10 -10
- package/web/chunk-fx3d48e6.js +1 -0
- package/web/{chunk-ncfzmf2g.js → chunk-g3szt4c4.js} +1 -1
- package/web/chunk-g7bcntpm.js +1 -0
- package/web/chunk-gr1tjqbd.js +1 -0
- package/web/{chunk-bygwbpvq.js → chunk-hbwxtbq3.js} +2 -2
- package/web/{chunk-gten0rpx.js → chunk-hdtvrh0f.js} +2 -2
- package/web/chunk-j031r08w.js +1 -0
- package/web/{chunk-d57fm7k0.js → chunk-j6wcszxq.js} +2 -2
- package/web/{chunk-885kpj14.js → chunk-jdx7qp2w.js} +2 -2
- package/web/chunk-jge7nn3s.js +1 -0
- package/web/chunk-jy8zat04.js +1 -0
- package/web/{chunk-7vgh17es.js → chunk-jzge034r.js} +1 -1
- package/web/{chunk-fj753yzt.js → chunk-k4qrqmdk.js} +2 -2
- package/web/chunk-k8s7kye3.js +1 -0
- package/web/{chunk-2jfesv7m.js → chunk-k9fyqrhp.js} +2 -2
- package/web/chunk-k9zn1n6d.js +1 -0
- package/web/chunk-kg3tksv7.js +1 -0
- package/web/chunk-kk5rw81s.js +2 -0
- package/web/{chunk-xpecre7w.js → chunk-kpmd893m.js} +4 -4
- package/web/chunk-md9j949p.js +1 -0
- package/web/{chunk-jeafmjsm.js → chunk-mn2wv9ye.js} +6 -6
- package/web/{chunk-dndd757x.js → chunk-mv7jgmnb.js} +3 -3
- package/web/{chunk-c3fty2c2.js → chunk-mvm68qtt.js} +7 -7
- package/web/chunk-nbcpbqq4.js +1 -0
- package/web/{chunk-b99k8q22.js → chunk-nfpff7yf.js} +8 -8
- package/web/chunk-nk7jkpam.js +1 -0
- package/web/chunk-nmvt1rn3.js +1 -0
- package/web/chunk-npw1s1h2.js +1 -0
- package/web/chunk-npyrdsf8.css +1 -0
- package/web/chunk-nzzxv84v.js +8 -0
- package/web/{chunk-n9v14vyd.js → chunk-p4pqtybm.js} +22 -22
- package/web/{chunk-jyf7a7yp.js → chunk-p79c7aak.js} +1 -1
- package/web/{chunk-6jb2zyp6.js → chunk-pafw34vg.js} +2 -2
- package/web/{chunk-y2rzeb4v.js → chunk-pf65cank.js} +2 -2
- package/web/{chunk-d1btrqmw.js → chunk-ppa21760.js} +1 -1
- package/web/{chunk-60mym60n.js → chunk-ptpkv0te.js} +1 -1
- package/web/{chunk-yjs6jmdb.js → chunk-qcdej581.js} +3 -3
- package/web/{chunk-q1zxvjhs.js → chunk-qftcdcps.js} +2 -2
- package/web/{chunk-4wwd3pfz.js → chunk-qv1w36ja.js} +2 -2
- package/web/chunk-r8p741qj.js +2 -0
- package/web/chunk-rcexbkjj.js +1 -0
- package/web/{chunk-kerfb21g.js → chunk-rjakb64x.js} +1 -1
- package/web/{chunk-k0cg4n2k.js → chunk-s0xy00v5.js} +2 -2
- package/web/{chunk-ym7kv2hs.js → chunk-s2ps0ct5.js} +1 -1
- package/web/{chunk-h24ybwp6.js → chunk-s45g7fp6.js} +1 -1
- package/web/{chunk-pjpre6de.js → chunk-s70aj1v5.js} +6 -6
- package/web/chunk-say8bvkc.js +1 -0
- package/web/{chunk-qh62nkem.js → chunk-sd3cdqcm.js} +2 -2
- package/web/{chunk-6f2sz84q.js → chunk-sgkevxdf.js} +2 -2
- package/web/chunk-sjffrcq9.js +1 -0
- package/web/{chunk-19zd0tye.js → chunk-snaepr87.js} +8 -8
- package/web/{chunk-3n9ypydh.js → chunk-tdzh6nsz.js} +2 -2
- package/web/{chunk-wqzbxzk3.js → chunk-tjd8qp87.js} +1 -1
- package/web/chunk-tncc9e57.js +1 -0
- package/web/chunk-ty2rmwda.js +1142 -0
- package/web/chunk-v22hp18w.js +1 -0
- package/web/chunk-ve9dz857.js +2 -0
- package/web/{chunk-80z8s8zb.js → chunk-vg346gxc.js} +2 -2
- package/web/{chunk-hqxc9m07.js → chunk-vpegzgzb.js} +10 -10
- package/web/{chunk-pzg25qqe.js → chunk-vvvd3grf.js} +2 -2
- package/web/{chunk-qp3tjhaq.js → chunk-vwv6pqy7.js} +1 -1
- package/web/{chunk-3psgr0q8.js → chunk-vxm7n7w6.js} +20 -20
- package/web/{chunk-h754ntg7.js → chunk-w5q7978e.js} +1 -1
- package/web/{chunk-xvfeq8v2.js → chunk-we4mhfmq.js} +12 -12
- package/web/{chunk-8539865x.js → chunk-wfgrdabk.js} +1 -1
- package/web/{chunk-sdr5wa4z.js → chunk-wkhj4hsw.js} +4 -4
- package/web/{chunk-7ksg3ccg.js → chunk-wspk8qbg.js} +2 -2
- package/web/{chunk-hxbfkdjd.js → chunk-xf1hnpme.js} +1 -1
- package/web/{chunk-v1hfbjz9.js → chunk-xhqvzmfj.js} +5 -5
- package/web/chunk-xq70hgre.js +1 -0
- package/web/chunk-xtss82z2.js +1 -0
- package/web/{chunk-yf8ykk4v.js → chunk-y3tb6410.js} +3 -3
- package/web/{chunk-7v85yvb2.js → chunk-y6mcxfm0.js} +1 -1
- package/web/{chunk-7adsmqv6.js → chunk-ya696bfe.js} +2 -2
- package/web/{chunk-w9gnqkez.js → chunk-ysw5fs45.js} +3 -3
- package/web/chunk-zkq1xknc.js +1 -0
- package/web/chunk-zkv025s5.js +1 -0
- package/web/{chunk-8cnjd0f2.js → chunk-zpzvz973.js} +28 -28
- package/web/{chunk-b5zf1hs3.js → chunk-zsat72qd.js} +120 -120
- package/web/chunk-zx3h7v72.js +1 -0
- package/web/index.html +1 -1
- package/worker.js +1 -1
- package/chunk-1xfv4bd7.js +0 -2
- package/chunk-2fyjph3f.js +0 -2
- package/chunk-37zystxb.js +0 -25
- package/chunk-3k627vf2.js +0 -3
- package/chunk-4gtgqcct.js +0 -5
- package/chunk-7er5pz7s.js +0 -479
- package/chunk-7g5smgjj.js +0 -2
- package/chunk-7m3jagqn.js +0 -2
- package/chunk-9c4gdg1q.js +0 -3
- package/chunk-b2bxqeb4.js +0 -2
- package/chunk-bpw6q7g0.js +0 -3
- package/chunk-bwawt15q.js +0 -3
- package/chunk-cdw03j4t.js +0 -20
- package/chunk-ch1r3ted.js +0 -2
- package/chunk-cmwdjes8.js +0 -18
- package/chunk-db7ws33a.js +0 -7
- package/chunk-e1x629v0.js +0 -5
- package/chunk-j64dc767.js +0 -3
- package/chunk-m4bg1apa.js +0 -7
- package/chunk-nhm9z3d8.js +0 -2
- package/chunk-pnspvnyd.js +0 -2
- package/chunk-qnkrrwmg.js +0 -2
- package/chunk-r4gm8ngh.js +0 -2
- package/chunk-rks90mh1.js +0 -2
- package/chunk-t7te60m7.js +0 -2
- package/chunk-tv52xajf.js +0 -2
- package/chunk-wqqjzsjt.js +0 -3983
- package/chunk-xef4642x.js +0 -3
- package/web/chunk-04drx71p.js +0 -1
- package/web/chunk-0mdf1qja.js +0 -1
- package/web/chunk-0rdgt4jb.css +0 -1
- package/web/chunk-1m0kp0g3.js +0 -8
- package/web/chunk-3j2tcphs.js +0 -1
- package/web/chunk-3k9h7a73.js +0 -1142
- package/web/chunk-3m1bb2fw.js +0 -1
- package/web/chunk-55nvm2mj.js +0 -1
- package/web/chunk-5dkqfnh7.js +0 -2
- package/web/chunk-7ky5nrrr.js +0 -1
- package/web/chunk-8sdjgv3k.js +0 -1
- package/web/chunk-9bxtzwtc.js +0 -1
- package/web/chunk-9jy8nc4r.js +0 -1
- package/web/chunk-aebrw6cv.js +0 -39
- package/web/chunk-bcjgzwef.js +0 -1
- package/web/chunk-bra33pt0.js +0 -2
- package/web/chunk-cxpnj495.js +0 -2
- package/web/chunk-d94t9z70.js +0 -1
- package/web/chunk-de29pe57.js +0 -1
- package/web/chunk-e68jw0bg.js +0 -1
- package/web/chunk-fr4fft89.js +0 -1
- package/web/chunk-gckmcef6.js +0 -1
- package/web/chunk-gnb09wmx.js +0 -1
- package/web/chunk-gx340asc.js +0 -1
- package/web/chunk-hrgqc1vr.js +0 -1
- package/web/chunk-j9c8fa82.js +0 -1
- package/web/chunk-jz5mmp64.js +0 -1
- package/web/chunk-kxeaj44h.js +0 -1
- package/web/chunk-m0136xav.js +0 -1
- package/web/chunk-m1rdyvb5.js +0 -1
- package/web/chunk-m6vyvgm5.js +0 -1
- package/web/chunk-mxkbmgcv.js +0 -2
- package/web/chunk-my0ec787.js +0 -1
- package/web/chunk-mzzaet63.js +0 -1
- package/web/chunk-nkpdd9hw.js +0 -1
- package/web/chunk-ny436sqg.js +0 -1
- package/web/chunk-pbp1p5ex.js +0 -1
- package/web/chunk-ph75hddv.js +0 -1
- package/web/chunk-phdfyqaa.js +0 -1
- package/web/chunk-phxa5krt.js +0 -1
- package/web/chunk-r4zbw4zj.js +0 -2
- package/web/chunk-ry4ycah9.js +0 -1
- package/web/chunk-sqm16fat.js +0 -1
- package/web/chunk-tj1fn8v2.js +0 -1
- package/web/chunk-v0wtk059.js +0 -34
- package/web/chunk-v1qt3gq4.js +0 -1
- package/web/chunk-v854w9yn.js +0 -1
- package/web/chunk-ve56gxq0.js +0 -1
- package/web/chunk-w573ym17.js +0 -1
- package/web/chunk-x0mjydtp.js +0 -1
- package/web/chunk-zhybh04p.js +0 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
`);if(r[r.length-1]==="")r.pop();return r}function
|
|
2
|
+
import{Do,Et,ct,P,Un,Uo}from"./chunk-vd5332ps.js";import{o,e,u,Bt,At,I,he,R,No,Ur,$t}from"./chunk-pjgt1bdx.js";import*as S from"fs/promises";import*as ne from"fs";import*as O from"path";import*as $e from"child_process";import*as at from"crypto";import*as lt from"readline";function D(a){if(a.inputSchema.type!=="object")throw Error(`JSON schema for tool "${a.name}" must be an object, but got ${a.inputSchema.type}`);return{type:"custom",name:a.name,input_schema:a.inputSchema,description:a.description,run:a.run,parse:(r)=>r,...a.close?{close:a.close}:{}}}var C=ct.promises,J=448,yt=384;function ae(a,r){let t=P.relative(a,r);return t===""||!t.startsWith(".."+P.sep)&&t!==".."&&!P.isAbsolute(t)}async function Ee(a,r){for(let t of a)if(ae(await X(P.resolve(t)),r))return t;return}var wt=40;function Z(a){let r=a?.code;return typeof r==="string"?r:void 0}async function X(a){let r=[],t=a,i=0;for(;;){let n;try{n=await C.realpath(t)}catch(s){let c;try{c=(await C.lstat(t)).isSymbolicLink()}catch(l){let f=Z(l);if(f!=="ENOENT"&&f!=="ENOTDIR")throw l;let h=P.dirname(t);if(h===t)throw l;r.push(P.basename(t)),t=h;continue}if(!c)throw s;if(++i>wt)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});t=P.resolve(P.dirname(t),await C.readlink(t));continue}return r.length?P.join(n,...r.reverse()):n}}async function Ae(a,r,t){let i=t?.allowedRoots??[],n=await X(P.resolve(a)),s;try{s=await X(P.resolve(n,r))}catch(l){throw new R(q(l,`path ${JSON.stringify(r)}`))}if(ae(n,s)||await Ee(i,s)!==void 0)return s;let c=i.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new R(`path ${JSON.stringify(r)} is outside ${c}`)}async function be(a,r){let t=P.dirname(a),i=P.join(t,`.tmp-${process.pid}-${Et.randomUUID()}`),n=await C.stat(a).then((c)=>c.mode&511,()=>{return}),s;try{if(s=await C.open(i,"wx",yt),n!==void 0)await s.chmod(n);await s.writeFile(r,"utf-8"),await s.sync(),await s.close(),s=void 0,await C.rename(i,a)}catch(c){if(s)await s.close().catch(()=>{});throw await C.unlink(i).catch(()=>{}),c}}function q(a,r){let t=Z(a);switch(t){case"ENOENT":return`${r}: no such file or directory`;case"EACCES":case"EPERM":return`${r}: permission denied`;case"ENOTDIR":return`${r}: not a directory`;case"EISDIR":return`${r}: is a directory`;case"ELOOP":return`${r}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${r}: file name too long`;case"ENOSPC":return`${r}: no space left on device`;case"EMFILE":case"ENFILE":return`${r}: too many open files`;default:return`${r}: ${t!==void 0?`i/o error (${t})`:"i/o error"}`}}var k=ct.promises,_t=Uo.promisify(Do.execFile);async function gt(a){let{client:r,sessionId:t}=a;if(!r)return async()=>{};let i=I(r),n=a.session;if(!n){if(t===void 0)return async()=>{};i.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),n=await r.beta.sessions.retrieve(t)}let s=P.resolve(a.workdir,"skills"),c=[];for(let l of n.agent.skills)try{let f=await r.beta.skills.versions.retrieve(l.version,{skill_id:l.skill_id}),h=P.basename(f.name.trim());if(h===""||h==="."||h==="..")h=l.skill_id;let d=P.resolve(s,h);if(d!==s&&!d.startsWith(s+P.sep)){i.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:f.name});continue}let m=await r.beta.skills.versions.download(f.id,{skill_id:l.skill_id});await k.rm(d,{recursive:!0,force:!0}),await k.mkdir(d,{recursive:!0,mode:J}),c.push(d),await Ce(m,d),i.info("downloaded skill",{component:"agent-tool-context",skill_id:l.skill_id,version:f.id,dest:d})}catch(f){i.warn("failed to download skill",{component:"agent-tool-context",skill_id:l.skill_id,error:String(f)})}return async()=>{for(let l of c)await k.rm(l,{recursive:!0,force:!0}).catch((f)=>{i.warn("failed to clean up skill",{component:"agent-tool-context",dest:l,error:String(f)})})}}function St(a){for(let r of a){let t=r.trim();if(!t)continue;if(P.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new u(`refusing to extract unsafe archive member: ${t}`)}}var Me="skill archive listing is inconsistent; refusing to extract",bt={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function xe(a){let r=a.split(`
|
|
3
|
+
`);if(r[r.length-1]==="")r.pop();return r}function Ot(a,r){return/^[\x20-\x7E]+$/.test(r)&&!/[\\^#]/.test(r)&&!(a==="unzip"&&r.startsWith("-"))}function Mt(a,r,t){let i=xe(r),n=xe(t);if(i.length!==n.length)throw new u(Me);let s=[],c=[];return i.forEach((l,f)=>{if(bt[a].has(n[f].charAt(0))){s.push(l);return}if(!Ot(a,l))throw new u(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(l)}`);c.push(l)}),{plain:s,special:c}}async function De(a){for(let r of await k.readdir(a,{withFileTypes:!0}))if(r.isDirectory())await De(P.join(a,r.name));else if(!r.isFile())throw new u(Me)}async function Oe(a,r){try{let{stdout:t}=await _t(a,r);return t}catch(t){if(Z(t)==="ENOENT")throw new u(`skill extraction requires the \`${a}\` command, but it was not found on PATH`);throw t}}function vt(a){let r,t=!1;for(let i of a){let n=i.trim().split("/").filter((c)=>c!==""&&c!==".");if(n.length===0)continue;let s=n[0];if(r===void 0)r=s;else if(s!==r)return"";if(n.length>1)t=!0}return r!==void 0&&t?r:""}async function Ce(a,r){let t=P.join(r,`.skill-archive-${process.pid}-${Date.now()}`);if(!a.body)throw new u("skill download response had no body");await Un.promises.pipeline(Un.Readable.fromWeb(a.body),ct.createWriteStream(t));let i=P.join(P.dirname(r),`.skill-stage-${process.pid}-${Date.now()}`),n=P.join(P.dirname(r),`.skill-exclude-${process.pid}-${Date.now()}`);try{let s=await It(t,4),c=s.length>=4&&s[0]===80&&s[1]===75&&s[2]===3&&s[3]===4,l=c?"unzip":"tar",f=await Oe(l,c?["-Z1",t]:["-tf",t]),h=await Oe(l,c?["-Z","--h","--t",t]:["-tvf",t]),{plain:d,special:m}=Mt(l,f,h);St([...d,...m]);let _=vt(d);if(await k.mkdir(i,{recursive:!0,mode:J}),d.length>0)await Oe(l,await kt(l,t,i,m,n));await De(i);let E=_?P.join(i,_):i,x=await k.readdir(E).catch((M)=>{throw Z(M)==="ENOENT"?new u(Me):M});for(let M of x)await k.rename(P.join(E,M),P.join(r,M))}finally{await k.rm(t,{force:!0}),await k.rm(n,{force:!0}),await k.rm(i,{recursive:!0,force:!0})}}async function kt(a,r,t,i,n){let s=i.map((c)=>c.replace(/[*?[\\]/g,"\\$&"));if(a==="unzip")return["-oq",r,"-d",t,...s.length>0?["-x",...s]:[]];if(s.length===0)return["-xf",r,"-C",t];return await k.writeFile(n,s.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{flag:"wx",mode:384}),["-xf",r,"-C",t,"-X",n]}async function
|
|
6
|
-
${a}`,"utf-8").digest("hex")}var qt=30000,zt=100,Gt=20,Ht=16,Kt=32,Vt=8,Xt=50;class
|
|
7
|
-
${t.memoryStoreId}`);for await(let[i,n]of e(this,
|
|
8
|
-
`),ie=102400,tr=2000,rr=200;class dt extends u{constructor(a){super(`bash command timed out after ${a}ms`);this.name="BashTimeoutError",this.timeoutMs=a}}var ir=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,nr=
|
|
5
|
+
`,{flag:"wx",mode:384}),["-xf",r,"-C",t,"-X",n]}async function It(a,r){let t=await k.open(a,"r");try{let i=Buffer.alloc(r),{bytesRead:n}=await t.read(i,0,r,0);return i.subarray(0,n)}finally{await t.close()}}var g=ct.promises,z=ct.constants,Ue=448,Rt=384,Nt=448,ke=z.O_NOFOLLOW??0,Tt=z.O_NONBLOCK??0,y=(()=>{class a extends Error{constructor(r,t){super(`path ${JSON.stringify(t)} ${r}`);this.name="FileStoreError",this.reason=r,this.relPath=t}}return a.ESCAPES_ROOT="escapes the store root",a.IS_A_SYMLINK="is a symlink",a.NOT_A_FILE="is not a regular file",a.NOT_A_DIRECTORY="is not a directory",a.NOT_UTF8="is not valid utf-8",a.MOVE_DESTINATION_EXISTS="already exists",a})();function Ie(a){return a.startsWith("/")&&!a.split("/").includes("..")}var ve=(()=>{class a{constructor(r,t,i=!1){this.hashes=new Map,this.rootPath=r,this.removedOnDispose=t,this.decoder=i?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(r,t){if(!Lt())throw Error("FileStore requires O_NOFOLLOW support on this platform");let i=!1;try{await g.lstat(r)}catch(n){if(n.code!=="ENOENT")throw n;i=!0}return new a(P.resolve(r),i,t?.utf8??!1)}async createRoot(){await xt(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await g.rm(this.rootPath,{recursive:!0,force:!0})}async put(r,t,i){let n=r.replace(/\\/g,"/");if(n.endsWith("/")||n.endsWith("/.")||n===""||n===".")throw new y(y.NOT_A_FILE,r);let s=this.resolveUnderRoot(r),c=typeof t==="string"?Bt(t):t;this.requireUtf8(r,c),await Fe(this.rootPath,P.dirname(s)),await Dt(s,c,i?.executable??!1)}async get(r){let t=this.resolveUnderRoot(r),i;try{i=await je(r,t)}catch(s){if(s.code==="ENOENT")return null;throw s}let n;try{let s=await i.readFile();n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}finally{await i.close()}return this.requireUtf8(r,n),n}async ls(r="/"){let t=this.resolveUnderRoot(r);return new Set((await Pe(this.rootPath,r,t)).map(([i])=>i))}async findSymlinks(r="/"){let t=this.resolveUnderRoot(r);return Ft(this.rootPath,r,t)}async hashtree(r="/"){let t=this.resolveUnderRoot(r),i=ce.nowNs(),n=Object.create(null);for(let[s,c]of await Pe(this.rootPath,r,t)){let l=await this.hashViaCache(s,c,i);if(l!==null)n[s]=l}return n}async hashFile(r){let t=this.resolveUnderRoot(r),i;try{i=await g.lstat(t,{bigint:!0})}catch(s){if(s.code==="ENOENT")return null;throw s}if(i.isSymbolicLink())throw new y(y.IS_A_SYMLINK,r);if(!i.isFile())throw new y(y.NOT_A_FILE,r);let n=P.relative(this.rootPath,t).split(P.sep).join("/");return this.hashViaCache(n,t,ce.nowNs())}async move(r,t){let i=this.resolveUnderRoot(r),n=this.resolveUnderRoot(t);if(i===this.rootPath||n===this.rootPath)return;if(await g.stat(n).then(()=>!0,()=>!1))throw new y(y.MOVE_DESTINATION_EXISTS,t);await Fe(this.rootPath,P.dirname(n)),await g.rename(i,n)}async remove(r){let t=this.resolveUnderRoot(r);if(t===this.rootPath)return;let i;try{i=await g.lstat(t,{bigint:!0})}catch(n){if(n.code==="ENOENT")return;throw n}if(i.isDirectory())await g.rm(t,{recursive:!0,force:!0});else try{await g.unlink(t)}catch(n){if(n.code!=="ENOENT")throw n}}resolveUnderRoot(r){let t=r.replace(/\\/g,"/").replace(/^\/+/,""),i=t.split("/").filter((n)=>n!==""&&n!==".");if(P.posix.isAbsolute(t)||i.includes(".."))throw new y(y.ESCAPES_ROOT,r);return i.length===0?this.rootPath:P.join(this.rootPath,...i)}requireUtf8(r,t){if(!this.decoder)return;try{this.decoder.decode(t)}catch{throw new y(y.NOT_UTF8,r)}}async hashViaCache(r,t,i){let n;try{n=await g.lstat(t,{bigint:!0})}catch(l){if(l.code==="ENOENT")return null;throw l}if(!n.isFile())return null;let s=this.hashes.get(r),c;if(s!==void 0&&Wt(s,n))c=s.sha;else try{c=await ce.hashFile(t)}catch(l){let f=l.code;if(f==="ENOENT"||l instanceof y)return null;if(f==="ELOOP"||f==="EMLINK")return null;throw l}if(Ut(n,i))this.hashes.set(r,{mtimeNs:n.mtimeNs,ctimeNs:n.ctimeNs,size:n.size,sha:c});return c}}return a.isPathLegal=Ie,a})();function Lt(){return ke!==0}async function xt(a){let r=[],t=a;for(;;){try{await g.stat(t);break}catch(n){let s=n.code;if(s!=="ENOENT"&&s!=="ENOTDIR"&&s!=="ELOOP")throw n}r.push(t);let i=P.dirname(t);if(i===t)break;t=i}for(let i of r.reverse())try{await g.mkdir(i,{mode:Ue})}catch(n){if(n.code!=="EEXIST")throw n}}async function Fe(a,r){let t=P.relative(a,r);if(t==="")return;let i=a;for(let n of t.split(P.sep)){i=P.join(i,n);try{await g.mkdir(i,{mode:Ue})}catch(s){if(s.code!=="EEXIST")throw s}}}async function Dt(a,r,t){let i=t?Nt:Rt,n=P.join(P.dirname(a),`.fs-${Et.randomBytes(8).toString("hex")}.tmp`),s;try{s=await g.open(n,z.O_WRONLY|z.O_CREAT|z.O_EXCL|ke,i),await s.writeFile(r),await s.close(),s=void 0,await g.rename(n,a)}catch(c){if(s)await s.close().catch(()=>{});throw await g.unlink(n).catch(()=>{}),c}}async function je(a,r){let t;try{t=await g.open(r,z.O_RDONLY|ke|Tt)}catch(i){let n=i.code;if(n==="ELOOP"||n==="EMLINK")throw new y(y.IS_A_SYMLINK,a);throw i}try{if(!(await t.stat()).isFile())throw new y(y.NOT_A_FILE,a)}catch(i){throw await t.close().catch(()=>{}),i}return t}async function Ct(a){let r=Et.createHash("sha256"),t=await je(P.basename(a),a),i=new Uint8Array(1048576);try{for(;;){let{bytesRead:n}=await t.read(i,0,i.length);if(n===0)break;r.update(i.subarray(0,n))}}finally{await t.close()}return r.digest("hex")}async function Pe(a,r,t){if(!await Pt(r,t))return[];let i=[];return await Be(t,(n,s)=>{if(s.isFile())i.push([P.relative(a,n).split(P.sep).join("/"),n])}),i.sort(),i}async function Ft(a,r,t){let i=(c)=>P.relative(a,c).split(P.sep).join("/"),n;try{n=await g.lstat(t,{bigint:!0})}catch(c){let l=c.code;if(l==="ENOENT"||l==="ENOTDIR")return new Set;throw c}if(n.isSymbolicLink())return new Set([i(t)]);if(!n.isDirectory())throw new y(y.NOT_A_DIRECTORY,r);let s=new Set;return await Be(t,(c,l)=>{if(l.isSymbolicLink())s.add(i(c))}),s}async function Pt(a,r){let t;try{t=await g.lstat(r,{bigint:!0})}catch(i){let n=i.code;if(n==="ENOENT"||n==="ENOTDIR")return!1;throw i}if(!t.isDirectory())throw new y(y.NOT_A_DIRECTORY,a);return!0}async function Be(a,r){let t=[a];while(t.length){let i=t.pop(),n;try{n=await g.readdir(i,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of n){let c=P.join(i,s.name);if(r(c,s),s.isDirectory()&&!s.isSymbolicLink())t.push(c)}}}function Wt(a,r){return r.mtimeNs===a.mtimeNs&&r.ctimeNs===a.ctimeNs&&r.size===a.size}function Ut(a,r){return(a.mtimeNs>a.ctimeNs?a.mtimeNs:a.ctimeNs)<r-ce.timestampTrustMarginNs}var jt=2000000000n,ce={hashFile:Ct,timestampTrustMarginNs:jt,nowNs:()=>BigInt(Date.now())*1000000n},Ye=ve,We=Symbol.asyncDispose;if(We)Object.defineProperty(ve.prototype,We,{value:ve.prototype.dispose,configurable:!0,writable:!0});var w,T,le,Q,fe,p,G,de,L,qe,me,ze,Ge,Re,Ne,He,Ke,Te,Ve,Xe,ue,pe,Je,Ze,Yt=30000,K=".anthropic-memory-store",et=1;function Qe(a){return Et.createHash("sha256").update(`version ${et}
|
|
6
|
+
${a}`,"utf-8").digest("hex")}var qt=30000,zt=100,Gt=20,Ht=16,Kt=32,Vt=8,Xt=50;class F extends u{constructor(a,r){super(a);if(this.name="SessionMemoryError",r!==void 0)this.cause=r}}class tt{constructor(a,r,t){this.mode=a,this.cap=r,this.waiveWindow=t,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){if(this.attempted>=this.cap)return this.capped++,!1;return this.attempted++,!0}}var Jt=(()=>{class a{constructor(r,t){w.add(this),T.set(this,void 0),le.set(this,void 0),Q.set(this,void 0),fe.set(this,void 0),p.set(this,void 0),G.set(this,void 0),de.set(this,!1),L.set(this,[]),o(this,T,r,"f"),o(this,le,t.workdir,"f"),o(this,Q,t.syncIntervalMs??No,"f"),Ur(e(this,Q,"f"),"syncIntervalMs"),o(this,fe,t.syncDeletions??"enabled","f"),o(this,p,I(r),"f"),o(this,G,Date.now(),"f")}get roots(){return e(this,L,"f").map((r)=>r.files.root().path)}get readOnlyRoots(){return e(this,L,"f").filter((r)=>r.readOnly).map((r)=>r.files.root().path)}async download(r){for(let t of r.resources){if(t.type!=="memory_store")continue;let i=e(this,w,"m",qe).call(this,t),n;try{if(n={memoryStoreId:t.memory_store_id,files:await Ye.open(i,{utf8:!0}),readOnly:t.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!n.files.root().removedOnDispose)throw new F(`something already exists at the memory store's path: ${i} (memory_store_id=${t.memory_store_id}); it must not exist when the session starts`);try{await n.files.createRoot()}catch(s){if(!H(s))throw s;throw new F(`cannot create the memory store's folder: ${i} (memory_store_id=${t.memory_store_id}): ${s}; the worker host must make this mount path writable`,s)}await e(this,w,"m",Ne).call(this,n),e(this,p,"f").info("downloaded memories",{count:n.baseline.size,memory_store_id:n.memoryStoreId,dest:n.files.root().path}),e(this,L,"f").push(n)}catch(s){if(n)await n.files.dispose().catch(()=>{});if(s instanceof F)throw s;throw new F(`failed to download memory store memory_store_id=${t.memory_store_id}: ${s}`,s)}}o(this,G,Date.now(),"f")}async finish(){if(e(this,de,"f"))throw new u("finish() was already called: it is the session's last sync and runs once");o(this,de,!0,"f"),await this.syncAll(!0)}async syncAll(r){await Promise.all(e(this,L,"f").map((t)=>e(this,w,"m",ze).call(this,t,r))),o(this,G,Date.now(),"f")}async syncIfDue(){if(Date.now()-e(this,G,"f")<e(this,Q,"f"))return;await this.syncAll(!1)}async flushWrites(r){await Promise.all(e(this,L,"f").map((t)=>e(this,w,"m",Ge).call(this,t,r)))}async dispose(){for(let r of e(this,L,"f")){let t=r.files.root();try{let i=await e(this,w,"m",me).call(this,r);if(!i.markerOk&&Object.keys(i.files).length>0){e(this,p,"f").warn(`${i.distrustReason}; leaving the memory store folder on disk`,{root:t.path,memory_store_id:r.memoryStoreId});continue}await r.files.dispose()}catch(i){if(!(i instanceof y)&&!H(i))throw i;e(this,p,"f").warn("failed to remove the memory store folder",{root:r.files.root().path,memory_store_id:r.memoryStoreId,error:String(i)});continue}if(t.removedOnDispose)e(this,p,"f").info("removed memory store dir",{dest:t.path,memory_store_id:r.memoryStoreId})}}}return T=new WeakMap,le=new WeakMap,Q=new WeakMap,fe=new WeakMap,p=new WeakMap,G=new WeakMap,de=new WeakMap,L=new WeakMap,w=new WeakSet,qe=function(t){if(t.mount_path){if(!Ie(t.mount_path))throw new F(`memory store mount_path is not a clean absolute path: ${JSON.stringify(t.mount_path)} (memory_store_id=${t.memory_store_id})`);return t.mount_path}return P.join(e(this,le,"f"),"memory",t.name||t.memory_store_id)},me=async function(t){let i=await t.files.hashtree(),n=i[K];if(delete i[K],n===Qe(t.memoryStoreId))return{files:i,markerOk:!0,distrustReason:null};return{files:i,markerOk:!1,distrustReason:n!==void 0?"the marker file does not match this store":"the marker file is gone"}},ze=async function(t,i){try{let n=await e(this,w,"m",me).call(this,t),s=n.files;if(!n.markerOk){if(Object.keys(s).length>0){e(this,p,"f").warn(`${n.distrustReason}; leaving the memory store folder as found and not syncing`,{root:t.files.root().path,memory_store_id:t.memoryStoreId});return}await e(this,w,"m",Re).call(this,t,"the folder or its marker is gone");return}if(Object.keys(s).length===0&&t.baseline.size>1){await e(this,w,"m",Re).call(this,t,"every memory file is gone at once");return}let c=new Map;for await(let[m,_]of e(this,w,"m",ue).call(this,t.memoryStoreId))c.set(m,_);let l=new tt(e(this,fe,"f"),Math.max(Vt,Math.min(Xt,Math.floor(t.baseline.size/4))),i),f=[],h=new Map,d=[...new Set([...c.keys(),...Object.keys(s),...t.baseline.keys()])].sort();for(let m of d){let _=c.get(m),E=s[m],x=t.baseline.get(m),M;if(E===void 0&&x!==void 0&&_!==void 0&&_.content_sha256===x&&!t.readOnly)M=await e(this,w,"m",Je).call(this,t,m,_,x,l);else M=await e(this,w,"m",He).call(this,t,m,_,E,f);if(M!==void 0)h.set(m,M)}if(t.baseline=h,await e(this,w,"m",Ve).call(this,t,f),l.suppressed>0)e(this,p,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:l.suppressed,memory_store_id:t.memoryStoreId});if(l.capped>0)e(this,p,"f").warn(`delete cap reached: ${l.mode==="log_only"?"would send":"sent"} ${l.attempted} deletes, held ${l.capped} for later syncs`,{memory_store_id:t.memoryStoreId})}catch(n){e(this,p,"f").warn("memory sync failed",{memory_store_id:t.memoryStoreId,error:String(n)})}},Ge=async function(t,i){let n=new Map,s=new Set,c=async()=>{if(t.readOnly)return;let l=await e(this,w,"m",me).call(this,t);if(!l.markerOk){e(this,p,"f").warn(`${l.distrustReason}; not uploading anything from the memory store folder`,{root:t.files.root().path,memory_store_id:t.memoryStoreId});return}for(let[d,m]of Object.entries(l.files))if(m!==t.baseline.get(d)&&t.refusedShas.get(d)!==m)n.set(d,m),s.add(d);if(n.size===0||i?.aborted)return;let f=new Map;for await(let[d,m]of e(this,w,"m",ue).call(this,t.memoryStoreId)){if(i?.aborted)return;f.set(d,m)}let h=[];for(let d of[...n.keys()].sort()){let m=n.get(d),_=t.baseline.get(d),E=f.get(d);if(E!==void 0&&E.content_sha256===m){t.baseline.set(d,E.content_sha256),s.delete(d);continue}if(E!==void 0&&E.content_sha256!==_){e(this,p,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:d,memory_store_id:t.memoryStoreId}),s.delete(d);continue}h.push([d,m,E])}await e(this,w,"m",Xe).call(this,t,h,s,i)};try{if(await Zt(c(),i),i?.aborted&&s.size>0)e(this,p,"f").warn(`memory flush cut off part-way; ${s.size} of ${n.size} changed files had not finished uploading`,{memory_store_id:t.memoryStoreId})}catch(l){e(this,p,"f").warn("memory flush failed",{memory_store_id:t.memoryStoreId,error:String(l)})}},Re=async function(t,i){e(this,p,"f").warn(`${i}; re-downloading the memory store folder instead of syncing`,{root:t.files.root().path,memory_store_id:t.memoryStoreId}),await t.files.createRoot(),await e(this,w,"m",Ne).call(this,t)},Ne=async function(t){t.baseline=new Map,t.pendingDeletes.clear(),await t.files.put(K,`version ${et}
|
|
7
|
+
${t.memoryStoreId}`);for await(let[i,n]of e(this,w,"m",ue).call(this,t.memoryStoreId,"full"))if(await e(this,w,"m",Te).call(this,t,i,n.content??""))t.baseline.set(i,n.content_sha256)},He=async function(t,i,n,s,c){let l=t.baseline.get(i);if(s!==void 0)t.pendingDeletes.delete(i);if(!n){if(s===void 0){t.pendingDeletes.delete(i);return}if(l!==void 0){if(s===l){let _=await e(this,w,"m",Ke).call(this,t,i,l);if(_===void 0)return;if(_===l)return l;s=_}if(t.readOnly)e(this,p,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:i,memory_store_id:t.memoryStoreId});else if(t.refusedShas.get(i)!==s)e(this,p,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:i,memory_store_id:t.memoryStoreId})}if(t.readOnly)return;if(t.refusedShas.get(i)===s)return;return await e(this,w,"m",pe).call(this,t,i,s,void 0)}let f=n.content_sha256,h=f!==l,d=s!==void 0&&s!==l&&s!==f,m=!t.readOnly&&d;if(s===void 0&&l!==void 0){if(h)e(this,p,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:i,memory_store_id:t.memoryStoreId}),t.pendingDeletes.delete(i),c.push([i,n]);return l}if(h){if(s===f)return f;if(d)e(this,p,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:i,memory_store_id:t.memoryStoreId});return c.push([i,n]),l}if(m){if(t.refusedShas.get(i)===s)return f;return await e(this,w,"m",pe).call(this,t,i,s,n)??f}return f},Ke=async function(t,i,n){let s;try{s=await t.files.hashFile(i)}catch(c){if(!(c instanceof y)&&!H(c))throw c;return n}if(s===null)return;if(s!==n)return s;try{await t.files.remove(i)}catch(c){if(!(c instanceof y)&&!H(c))throw c;return e(this,p,"f").warn("failed to remove memory deleted remotely",{path:i,memory_store_id:t.memoryStoreId,error:String(c)}),n}return},Te=async function(t,i,n){try{await t.files.put(i,n)}catch(s){if(!(s instanceof y)&&!H(s))throw s;return e(this,p,"f").warn("failed to write memory",{path:i,memory_store_id:t.memoryStoreId,error:String(s)}),!1}return!0},Ve=async function(t,i){if(i.length===0)return;let n=async(l,f)=>{let h;try{h=await e(this,T,"f").beta.memoryStores.memories.retrieve(f.id,{memory_store_id:t.memoryStoreId,view:"full"})}catch(d){if(he(d,404))return;e(this,p,"f").warn("failed to fetch memory content",{path:l,memory_store_id:t.memoryStoreId,error:String(d)});return}if(await e(this,w,"m",Te).call(this,t,l,h.content??""))t.baseline.set(l,h.content_sha256)},s=i[Symbol.iterator](),c=async()=>{for(let[l,f]of s)await n(l,f)};await Promise.all(Array.from({length:Math.min(Ht,i.length)},c))},Xe=async function(t,i,n,s){let c=i[Symbol.iterator](),l=async()=>{for(let[f,h,d]of c){if(s?.aborted)return;let m=await e(this,w,"m",pe).call(this,t,f,h,d);if(n.delete(f),m!==void 0)t.baseline.set(f,m)}};await Promise.all(Array.from({length:Math.min(Kt,i.length)},l))},ue=async function*(t,i="basic"){let n=i==="basic"?zt:Gt;for await(let s of e(this,T,"f").beta.memoryStores.memories.list(t,{view:i,limit:n})){if(s.type!=="memory")continue;let c=s.path.replace(/^\/+/,"");if(c===K){e(this,p,"f").warn("the server listed the reserved marker path; skipping",{path:s.path,memory_store_id:t});continue}yield[c,s]}},pe=async function r(t,i,n,s){try{let c=await t.files.get(i);if(c===null)return;let l=At(c),f=s?await e(this,T,"f").beta.memoryStores.memories.update(s.id,{memory_store_id:t.memoryStoreId,content:l,precondition:{type:"content_sha256",content_sha256:s.content_sha256}}):await e(this,T,"f").beta.memoryStores.memories.create(t.memoryStoreId,{path:"/"+i,content:l});return t.refusedShas.delete(i),f.content_sha256}catch(c){if(s&&he(c,404))return await e(this,w,"m",r).call(this,t,i,n,void 0);let l=c instanceof y||he(c,400)||he(c,413);if(s&&he(c,409))e(this,p,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:i,memory_store_id:t.memoryStoreId});else if(l&&n!==void 0)t.refusedShas.set(i,n),e(this,p,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:i,memory_store_id:t.memoryStoreId,rejection:String(c)});else e(this,p,"f").warn("failed to upload memory",{path:i,memory_store_id:t.memoryStoreId,error:String(c)});return}},Je=async function(t,i,n,s,c){if(c.mode==="disabled")return c.suppressed++,s;let l=t.pendingDeletes.get(i);if(l===void 0)l=Date.now(),t.pendingDeletes.set(i,l);if(!c.waiveWindow&&Date.now()-l<qt)return s;let f,h;try{f=await t.files.hashFile(K)===Qe(t.memoryStoreId),h=await t.files.hashFile(i)===null}catch(m){if(!(m instanceof y)&&!H(m))throw m;f=h=!1}if(!f)return s;if(!h)return t.pendingDeletes.delete(i),s;if(!c.takeSlot())return s;if(c.mode==="log_only")return e(this,p,"f").info("log-only: sync would delete this memory on the server",{path:i,memory_store_id:t.memoryStoreId}),s;let d=await e(this,w,"m",Ze).call(this,t,i,n,s);if(d===void 0)t.pendingDeletes.delete(i);return d},Ze=async function(t,i,n,s){try{await e(this,T,"f").beta.memoryStores.memories.delete(n.id,{memory_store_id:t.memoryStoreId,expected_content_sha256:s})}catch(c){if(he(c,404))return;if(he(c,409)||he(c,412))e(this,p,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:i,memory_store_id:t.memoryStoreId});else e(this,p,"f").warn("failed to delete memory",{path:i,memory_store_id:t.memoryStoreId,error:String(c)});return s}e(this,p,"f").info("propagated local deletion",{path:i,memory_store_id:t.memoryStoreId});return},a})();function H(a){return typeof a==="object"&&a!==null&&typeof a.code==="string"}async function Zt(a,r){if(!r){await a;return}let t,i=new Promise((n)=>{if(t=n,r.aborted)n()});r.addEventListener("abort",t,{once:!0});try{await Promise.race([a,i])}finally{r.removeEventListener("abort",t)}}var ye,b,v,ee,W,N,Le,we,te,_e,ge,U,j,V,B,re,A,rt,it,nt=102400,ft=120000,Qt=262144,er=65536,ot=Buffer.from(`
|
|
8
|
+
`),ie=102400,tr=2000,rr=200;class dt extends u{constructor(a){super(`bash command timed out after ${a}ms`);this.name="BashTimeoutError",this.timeoutMs=a}}var ir=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,nr=S.glob;function ht(a){return a===void 0?Qt:a}function Y(a){if(a===void 0)return;throw new u("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function Xr(a){return[ar(a),cr(a),dr(a),hr(a),ur(a),pr(a)]}async function oe(a,r){return Y(a.unrestrictedPaths),Ae(a.workdir,r,{allowedRoots:a.allowedRoots??[]})}function mt(a,r){return Ee(a.readOnlyRoots??[],r)}function or(){let a={};for(let[r,t]of Object.entries(process.env)){if(r.startsWith("ANTHROPIC_"))continue;a[r]=t}return a}var sr=(()=>{class a{constructor(r,t=or()){ye.add(this),b.set(this,void 0),v.set(this,""),ee.set(this,!1),W.set(this,!1),N.set(this,null),o(this,b,$e.spawn("/bin/bash",["--noprofile","--norc"],{cwd:r,env:{...t,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),e(this,b,"f").stdout.setEncoding("utf8"),e(this,b,"f").stderr.setEncoding("utf8"),e(this,b,"f").stdout.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,b,"f").stderr.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,b,"f").once("close",()=>{o(this,W,!0,"f");let i=e(this,N,"f");o(this,N,null,"f"),i?.resolve()})}get closed(){return e(this,W,"f")}async exec(r,t={}){if(e(this,W,"f"))throw new u("bash session terminated");let i=t.timeoutMs??ft,n=t.signal;n?.throwIfAborted(),o(this,v,"","f"),o(this,ee,!1,"f");let s=`__ANT_CMD_${at.randomUUID()}_DONE__`,c=`${s.slice(0,8)}''${s.slice(8)}`,l=`{ ${r}
|
|
9
9
|
} </dev/null 2>&1; printf '\\n${c}%d\\n' $?
|
|
10
|
-
`;if(e(this,
|
|
11
|
-
${
|
|
10
|
+
`;if(e(this,b,"f").stdin.write(l),e(this,v,"f").indexOf(s)<0){let{promise:E,resolve:x}=$t();o(this,N,{sentinel:s,resolve:x},"f");let M,se;try{await Promise.race([E,new Promise((pt,Se)=>{M=setTimeout(()=>Se(new dt(i)),i)}),new Promise((pt,Se)=>{if(!n)return;se=()=>Se(n.reason),n.addEventListener("abort",se,{once:!0})})])}finally{if(M)clearTimeout(M);if(se&&n)n.removeEventListener("abort",se);o(this,N,null,"f")}}let f=e(this,v,"f").indexOf(s);if(f<0)throw new u("bash session terminated");let d=e(this,v,"f").slice(f+s.length).match(/^(-?\d+)/),m=d?parseInt(d[1],10):-1,_=e(this,v,"f").slice(0,f).replace(ir,"").replace(/\n+$/,"");if(e(this,ee,"f"))_=`[output truncated]
|
|
11
|
+
${_}`;return{output:_,exitCode:m}}close(){if(e(this,W,"f"))return;o(this,W,!0,"f");let r=e(this,N,"f");o(this,N,null,"f"),r?.resolve(),e(this,b,"f").stdout.destroy(),e(this,b,"f").stderr.destroy(),e(this,b,"f").stdin.destroy();try{process.kill(-e(this,b,"f").pid,"SIGKILL")}catch{e(this,b,"f").kill("SIGKILL")}e(this,b,"f").unref()}}return b=new WeakMap,v=new WeakMap,ee=new WeakMap,W=new WeakMap,N=new WeakMap,ye=new WeakSet,Le=function(t){if(o(this,v,e(this,v,"f")+t,"f"),e(this,v,"f").length>nt)o(this,v,e(this,v,"f").slice(e(this,v,"f").length-nt),"f"),o(this,ee,!0,"f");if(e(this,N,"f")&&e(this,v,"f").indexOf(e(this,N,"f").sentinel)>=0){let i=e(this,N,"f");o(this,N,null,"f"),i.resolve()}},a})();function ar(a){Y(a.unrestrictedPaths);let r,t=Promise.resolve();return D({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:i,restart:n,timeout_ms:s},c)=>{let l=t,f=$t();t=f.promise;try{await l}catch{}try{if(n)r?.close(),r=void 0;if(!i){if(n)return"bash session restarted";throw new R("bash: command is required")}r??(r=new sr(a.workdir,a.env));try{let{output:h,exitCode:d}=await r.exec(i,{timeoutMs:s??ft,signal:c?.signal});if(d!==0)throw new R(h||`exit ${d}`);return h}catch(h){if(h instanceof R)throw h;throw r.close(),r=void 0,new R(`bash: ${h instanceof Error?h.message:String(h)}`)}}finally{f.resolve()}},close:()=>{r?.close(),r=void 0}})}function cr(a){return Y(a.unrestrictedPaths),D({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:r,view_range:t})=>{if(!r)throw new R("read: file_path is required");let i=await oe(a,r);if(t?.length&&t.length!==2)throw new R("read: view_range must be [start_line, end_line]");let n;try{let d=await S.stat(i);if(!d.isFile())throw new R(`read: ${r} is not a regular file`);let m=ht(a.maxFileBytes);if(m!==null&&d.size>m){if(!t?.length)throw new R(`read: ${r} is ${d.size} bytes, exceeds ${m}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[_,E]=t;return await lr(i,r,_,E,m)}n=await S.readFile(i,"utf8")}catch(d){if(d instanceof R)throw d;throw new R(`read: ${q(d,r)}`)}if(!t?.length)return n;let[s,c]=t,l=n.split(`
|
|
12
12
|
`),f=Math.max(0,s-1),h=c>0?c:l.length;return l.slice(f,h).join(`
|
|
13
|
-
`)}})}async function lr(a,r,t,i,n){let s=new fr(r,t,i,n);if(s.rangeIsEmpty())return"";let c=ne.createReadStream(a,{highWaterMark:er});try{for await(let l of c)if(s.collectFrom(l),s.rangeIsCollected())break}finally{c.destroy()}return s.text()}var fr=(()=>{class a{constructor(r,t,i,n){we.add(this),te.set(this,void 0),_e.set(this,void 0),ge.set(this,void 0),U.set(this,void 0),j.set(this,void 0),V.set(this,void 0),B.set(this,0),re.set(this,[]),
|
|
14
|
-
`)}})}function pr(a){return Y(a.unrestrictedPaths),
|
|
15
|
-
[output truncated at ${ie} bytes]`);if(d===0)return n(l);if(d===1)return n("no matches");s(new
|
|
16
|
-
`)}async function
|
|
13
|
+
`)}})}async function lr(a,r,t,i,n){let s=new fr(r,t,i,n);if(s.rangeIsEmpty())return"";let c=ne.createReadStream(a,{highWaterMark:er});try{for await(let l of c)if(s.collectFrom(l),s.rangeIsCollected())break}finally{c.destroy()}return s.text()}var fr=(()=>{class a{constructor(r,t,i,n){we.add(this),te.set(this,void 0),_e.set(this,void 0),ge.set(this,void 0),U.set(this,void 0),j.set(this,void 0),V.set(this,void 0),B.set(this,0),re.set(this,[]),A.set(this,0),o(this,te,r,"f"),o(this,_e,t,"f"),o(this,ge,i,"f"),o(this,U,Math.max(0,t-1),"f"),o(this,j,i>0?i:1/0,"f"),o(this,V,n,"f")}rangeIsEmpty(){return e(this,j,"f")<=e(this,U,"f")}rangeIsCollected(){return e(this,B,"f")>=e(this,j,"f")}collectFrom(r){var t;let i=0;while(i<r.length&&!this.rangeIsCollected()){let n=r.indexOf(10,i),s=n<0?r.length:n;if(e(this,B,"f")>=e(this,U,"f"))e(this,we,"m",rt).call(this,r.subarray(i,s),n>=0);if(n<0)break;o(this,B,(t=e(this,B,"f"),t++,t),"f"),i=n+1}}text(){return Buffer.concat(e(this,re,"f"),e(this,A,"f")).toString("utf8")}}return te=new WeakMap,_e=new WeakMap,ge=new WeakMap,U=new WeakMap,j=new WeakMap,V=new WeakMap,B=new WeakMap,re=new WeakMap,A=new WeakMap,we=new WeakSet,rt=function(t,i){if(e(this,re,"f").push(t),o(this,A,e(this,A,"f")+t.length,"f"),i&&e(this,B,"f")+1<e(this,j,"f"))e(this,re,"f").push(ot),o(this,A,e(this,A,"f")+ot.length,"f");if(e(this,A,"f")>e(this,V,"f"))throw e(this,we,"m",it).call(this)},it=function(){if(e(this,j,"f")-e(this,U,"f")===1)return new R(`read: line ${e(this,U,"f")+1} of ${e(this,te,"f")} alone exceeds ${e(this,V,"f")}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`);return new R(`read: view_range [${e(this,_e,"f")}, ${e(this,ge,"f")}] of ${e(this,te,"f")} exceeds ${e(this,V,"f")}-byte limit. Narrow the view_range to read a smaller portion.`)},a})();function dr(a){return Y(a.unrestrictedPaths),D({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:r,content:t})=>{if(!r)throw new R("write: file_path is required");let i=await oe(a,r),n=await mt(a,i);if(n!==void 0)throw new R(`write: ${r} is inside read-only directory ${n}`);try{await S.mkdir(O.dirname(i),{recursive:!0,mode:J}),await be(i,t??"")}catch(s){throw new R(`write: ${q(s,r)}`)}return`wrote ${Buffer.byteLength(t??"")} bytes to ${r}`}})}function hr(a){return Y(a.unrestrictedPaths),D({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:r,old_string:t,new_string:i,replace_all:n})=>{if(!r)throw new R("edit: file_path is required");if(!t)throw new R("edit: old_string is required");let s=await oe(a,r),c=await mt(a,s);if(c!==void 0)throw new R(`edit: ${r} is inside read-only directory ${c}`);let l;try{let d=await S.stat(s);if(!d.isFile())throw new R(`edit: ${r} is not a regular file`);let m=ht(a.maxFileBytes);if(m!==null&&d.size>m)throw new R(`edit: ${r} is ${d.size} bytes, exceeds ${m}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);l=await S.readFile(s,"utf8")}catch(d){if(d instanceof R)throw d;throw new R(`edit: ${q(d,r)}`)}let f=l.split(t).length-1;if(f===0)throw new R(`edit: old_string not found in ${r}`);let h;if(n)h=l.split(t).join(i);else{if(f>1)throw new R(`edit: old_string appears ${f} times in ${r} (must be unique)`);h=l.replace(t,()=>i)}try{await be(s,h)}catch(d){throw new R(`edit: write: ${q(d,r)}`)}return`edited ${r} (${n?f:1} replacement(s))`}})}function mr(a){return a.split(/[\\/{},]/).includes("..")}function ur(a){return Y(a.unrestrictedPaths),D({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:r,path:t})=>{if(!r)throw new R("glob: pattern is required");if(O.isAbsolute(r))throw new R("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(mr(r))throw new R('glob: ".." is not permitted in the pattern');let i=t?await oe(a,t):O.resolve(a.workdir),n=t?i:await X(i),s=[],c=ut;try{for await(let l of nr(r,{cwd:i,withFileTypes:!0,exclude:(f)=>f.name===".git"||f.name==="node_modules"})){if(c--<=0)break;if(!l.isFile())continue;let f=O.join(l.parentPath,l.name),h;try{h=await S.realpath(f)}catch{continue}if(!ae(n,h))continue;let d=0;try{d=(await S.stat(f)).mtimeMs}catch{}s.push({path:f,mtime:d})}}catch(l){throw new R(`glob: ${l instanceof Error?l.message:String(l)}`)}if(s.length===0)return"no matches";return s.sort((l,f)=>f.mtime-l.mtime),s.slice(0,rr).map((l)=>l.path).join(`
|
|
14
|
+
`)}})}function pr(a){return Y(a.unrestrictedPaths),D({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:r,path:t},i)=>{if(!r)throw new R("grep: pattern is required");let n=O.resolve(a.workdir);if(t)n=await oe(a,t);let s=await Sr();return s?yr(s,r,n,i?.signal):wr(r,n,i?.signal)}})}function yr(a,r,t,i){return new Promise((n,s)=>{let c=$e.spawn(a,["-n","--no-heading","-e",r,"--",t],{...i?{signal:i}:{}}),l="",f="",h=!1;c.stdout.on("data",(d)=>{if(h)return;if(l+=d,l.length>ie)h=!0,l=l.slice(0,ie),c.kill("SIGKILL")}),c.stderr.on("data",(d)=>f+=d),c.on("close",(d)=>{if(i?.aborted)return s(new R("grep: aborted"));if(h)return n(l+`
|
|
15
|
+
[output truncated at ${ie} bytes]`);if(d===0)return n(l);if(d===1)return n("no matches");s(new R(`grep: rg failed: ${f||`exit ${d}`}`))}),c.on("error",(d)=>{if(i?.aborted)return s(new R("grep: aborted"));s(new R(`grep: rg failed: ${d.message}`))})})}async function wr(a,r,t){let i;try{i=new RegExp(a)}catch(f){throw new R(`grep: invalid regex: ${f instanceof Error?f.message:String(f)}`)}let n=[],s=ie,c=(f)=>{if(s-=f.length+1,s<0)return n.push(`[output truncated at ${ie} bytes]`),!1;return n.push(f),!0};if((await S.stat(r).catch(()=>null))?.isFile())await st(r,i,c);else await gr(r,"",(f)=>st(O.join(r,f),i,c),t);if(t?.aborted)throw new R("grep: aborted");if(n.length===0)return"no matches";return n.join(`
|
|
16
|
+
`)}async function st(a,r,t){let i=ne.createReadStream(a,{encoding:"utf8"}),n=lt.createInterface({input:i,crlfDelay:1/0}),s=0;try{for await(let c of n){if(s++,c.length>tr)continue;if(r.test(c)&&!t(`${a}:${s}:${c}`))return!1}}catch{}finally{i.destroy()}return!0}var _r=40,ut=50000;async function gr(a,r,t,i){let n=ut;async function s(c,l){if(l>_r)return!0;if(i?.aborted)return!1;let f;try{f=await S.readdir(O.join(a,c),{withFileTypes:!0})}catch{return!0}for(let h of f){if(h.name===".git"||h.name==="node_modules")continue;if(n--<=0)return!1;if(i?.aborted)return!1;let d=c?O.join(c,h.name):h.name;if(h.isDirectory()){if(!await s(d,l+1))return!1}else if(h.isFile()){if(await t(d)===!1)return!1}}return!0}await s(r,0)}async function Sr(){let a=(process.env.PATH??"").split(O.delimiter);for(let r of a){let t=O.join(r,"rg");try{return await S.access(t,ne.constants.X_OK),t}catch{}}return null}export{Yt as MEMORY_FLUSH_TIMEOUT_MS,F as SessionMemoryError,Jt as SessionMemoryStores,Xr as betaAgentToolset20260401,gt as setupSkills};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var A=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],I=["content-type","cache-control","allow"];function p(e){let r=e.path;if(!r?.startsWith("/api/")||/[\\\r\n#]/.test(r))throw Error("request path must start with /api/");let n=new URL(r,"http://basalt.internal");if(n.origin!=="http://basalt.internal"||!n.pathname.startsWith("/api/"))throw Error("request path must stay within /api/");let o=e.method??"GET";if(!A.includes(o))throw Error("Unsupported request method");if(e.body!==void 0&&(!e.body||typeof e.body!=="object"||Array.isArray(e.body)))throw Error("request body must be a JSON object");if(e.body!==void 0&&(o==="GET"||o==="HEAD"))throw Error("GET and HEAD requests cannot have a body");let s=e.timeoutMs??1e4;if(!Number.isSafeInteger(s)||s<1||s>60000)throw Error("timeoutMs must be an integer between 1 and 60000");return{url:n,method:o,timeoutMs:s}}function g(e){let r={};for(let n of I){let o=e.headers.get(n);if(o)r[n]=o.slice(0,500)}return r}async function M(e,r){let n=e.getReader();r(()=>n.cancel());let o=[],s=0,i=!1;while(!0){let t=await n.read();if(t.done)break;let d=20480-s;if(o.push(t.value.subarray(0,d)),s+=Math.min(t.value.length,d),t.value.length>d){i=!0,await n.cancel();break}}let u=new Uint8Array(s),c=0;for(let t of o)u.set(t,c),c+=t.length;return{text:new TextDecoder().decode(u,{stream:i}),truncated:i}}async function
|
|
3
|
-
export{
|
|
2
|
+
var A=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],I=["content-type","cache-control","allow"];function p(e){let r=e.path;if(!r?.startsWith("/api/")||/[\\\r\n#]/.test(r))throw Error("request path must start with /api/");let n=new URL(r,"http://basalt.internal");if(n.origin!=="http://basalt.internal"||!n.pathname.startsWith("/api/"))throw Error("request path must stay within /api/");let o=e.method??"GET";if(!A.includes(o))throw Error("Unsupported request method");if(e.body!==void 0&&(!e.body||typeof e.body!=="object"||Array.isArray(e.body)))throw Error("request body must be a JSON object");if(e.body!==void 0&&(o==="GET"||o==="HEAD"))throw Error("GET and HEAD requests cannot have a body");let s=e.timeoutMs??1e4;if(!Number.isSafeInteger(s)||s<1||s>60000)throw Error("timeoutMs must be an integer between 1 and 60000");return{url:n,method:o,timeoutMs:s}}function g(e){let r={};for(let n of I){let o=e.headers.get(n);if(o)r[n]=o.slice(0,500)}return r}async function M(e,r){let n=e.getReader();r(()=>n.cancel());let o=[],s=0,i=!1;while(!0){let t=await n.read();if(t.done)break;let d=20480-s;if(o.push(t.value.subarray(0,d)),s+=Math.min(t.value.length,d),t.value.length>d){i=!0,await n.cancel();break}}let u=new Uint8Array(s),c=0;for(let t of o)u.set(t,c),c+=t.length;return{text:new TextDecoder().decode(u,{stream:i}),truncated:i}}async function tr(e,r,n){let{url:o,method:s,timeoutMs:i}=p(r),u=e.http;if(!u)throw Error("HTTP API is not attached; start the Basalt server first");let c=new AbortController,t=n?AbortSignal.any([n,c.signal]):c.signal;t.throwIfAborted();let d,b=()=>{d?.().catch(()=>{})},E=async()=>{let h=r.body!==void 0,a=await u.request(new Request(o.toString(),{method:s,headers:h?{"content-type":"application/json"}:void 0,body:h?JSON.stringify(r.body):void 0,signal:t}));if(t.aborted)throw await a.body?.cancel(),Error("API request cancelled");let m=a.body?await M(a.body,(T)=>{d=T}):{text:"",truncated:!1};return{status:a.status,headers:g(a),body:m.text,truncated:m.truncated}},f,l,y=new Promise((h,a)=>{if(l=()=>{a(Error("API request cancelled")),b()},t.addEventListener("abort",l,{once:!0}),t.aborted)l()}),w=new Promise((h,a)=>{f=setTimeout(()=>{a(Error(`API request timed out after ${i}ms`)),c.abort(),b()},i)});try{return await Promise.race([E(),y,w])}finally{if(clearTimeout(f),l)t.removeEventListener("abort",l)}}
|
|
3
|
+
export{tr};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var f=new Set;function
|
|
3
|
-
export{
|
|
2
|
+
var f=new Set;function eo(r){return f.add(r),()=>{f.delete(r)}}function ts(r){let t=[];for(let s of f)try{s(r)}catch(e){t.push(e)}if(t.length>0)throw AggregateError(t,"Failed to cleanup session resources")}var a=(1n<<41n)-1n,u=-1,n;function rn(r){let t=r??Date.now();if(!Number.isInteger(t)||t<0||t>281474976710655)throw RangeError("UUIDv7 timestamp must be an integer between 0 and 281474976710655");let s=r===void 0?Math.max(t,u):r;if(r===void 0)u=s;let e=new Uint8Array(16);if(globalThis.crypto.getRandomValues(e),n===void 0)n=BigInt(e[1])<<32n|BigInt(e[2])<<24n|BigInt(e[3])<<16n|BigInt(e[4])<<8n|BigInt(e[5]);else{if(n===a)throw RangeError("UUIDv7 generator sequence exhausted");n++}let c=BigInt(s);for(let o=5;o>=0;o--)e[o]=Number(c>>BigInt((5-o)*8))&255;e[6]=112|Number(n>>37n&0x0fn),e[7]=Number(n>>29n&0xffn),e[8]=128|Number(n>>23n&0x3fn),e[9]=Number(n>>15n&0xffn),e[10]=Number(n>>7n&0xffn),e[11]=Number((n&0x7fn)<<1n)|e[11]&1;let i=Array.from(e,(o)=>o.toString(16).padStart(2,"0"));return`${i.slice(0,4).join("")}-${i.slice(4,6).join("")}-${i.slice(6,8).join("")}-${i.slice(8,10).join("")}-${i.slice(10).join("")}`}
|
|
3
|
+
export{eo,ts,rn};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{p}from"./chunk-
|
|
3
|
-
export{
|
|
2
|
+
import{p}from"./chunk-qd2enpr2.js";var n=null;function c(e){if(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)return;if(n===null){n=new Map;try{let{readFileSync:t}=p("fs"),s=t("/proc/self/environ","utf-8");for(let r of s.split("\x00")){let o=r.indexOf("=");if(o>0)n.set(r.slice(0,o),r.slice(o+1))}}catch{}}return n.get(e)}function _(e,t){return t?.[e]||(typeof process<"u"?process.env[e]:void 0)||c(e)||void 0}
|
|
3
|
+
export{_};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{S}from"./chunk-xf7zw32f.js";import{G}from"./chunk-38g4jd6v.js";import{_}from"./chunk-ge38dhv9.js";import{Tt,Pt}from"./chunk-xafx1p7z.js";import{Ke}from"./chunk-86yr2c0r.js";import{rt}from"./chunk-06s9pr82.js";import{oe}from"./chunk-pyj6avd5.js";import{ue}from"./chunk-vqm94hz2.js";import{be,Hr,qr,fe,nr,Re,dt,X,Wo,Ho,Se}from"./chunk-qs161f2q.js";import{w}from"./chunk-b516bp7n.js";import{V,J}from"./chunk-8np9b2y8.js";import{Q}from"./chunk-tfhp09nj.js";import{W,De,se,xe,ve,Y,K}from"./chunk-z9p6s986.js";import{U}from"./chunk-4yxd2kg1.js";function ee(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,u]of Object.entries(e))if(s.toLowerCase()===t&&u!==null&&u.trim().length>0)return!0;return!1}function ae(e,n,t){if(n)return n;if(ee(t,"authorization")||ee(t,"cf-aig-authorization"))return"unused";throw Error(`No API key for provider: ${e}`)}function ye(e){for(let n of e){if(n.role==="toolResult")return!0;if(n.role==="assistant"){if(n.content.some((t)=>t.type==="toolCall"))return!0}}return!1}function te(e){return e.type==="text"}function ke(e){return e.type==="thinking"}function Te(e){return e.type==="toolCall"}function _e(e){return e.type==="image"}function Ae(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ce(e){return(e.id===void 0||e.id===null||typeof e.id==="string")&&(e.format===void 0||typeof e.format==="string")&&(e.index===void 0||typeof e.index==="number")}function N(e){if(!Ae(e)||!Ce(e))return!1;switch(e.type){case"reasoning.summary":return typeof e.summary==="string";case"reasoning.encrypted":return typeof e.data==="string";case"reasoning.text":return typeof e.text==="string"&&(e.signature===void 0||e.signature===null||typeof e.signature==="string");default:return!1}}function Me(e){if(!e)return;try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every(N)?n:void 0}catch{return}}function Ie(e){if(!e)return;try{let n=JSON.parse(e);return N(n)&&n.type==="reasoning.encrypted"&&typeof n.id==="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function ne(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Ee(e,n){let t=e[e.length-1];if(n.type==="reasoning.text"&&t?.type==="reasoning.text"){t.text+=n.text,t.signature||=n.signature,ne(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,ne(t,n);return}e.push({...n})}var we=["reasoning","reasoning_content","reasoning_text"];function Fe(e){return we.includes(e)}function le(e,n){if(e)return e;if(_("PI_CACHE_RETENTION",n)==="long")return"long";return"short"}var Oe=(e,n,t)=>{let s=new U,u=se(n,D(e).supportsMidConvoSystemMessages);return(async()=>{let r={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},k,g=(R)=>{if(k!==void 0)R.thinkingSignature=JSON.stringify(k)};try{let R=ae(e.provider,t?.apiKey,t?.headers),a=D(e),T=Re(xe(u.messages),a.supportsOpenAIGrammarTools),p=le(t?.cacheRetention,t?.env),d=p==="none"?void 0:t?.sessionId,o=Be(e,u,R,t?.headers,t?.fetch,d,a),f=Pe(e,u,t,a,p,T),h=await t?.onPayload?.(f,e);if(h!==void 0)f=h;let C={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:M,response:P}=await ue(()=>o.chat.completions.create(f,C).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:P.status,headers:Q(P.headers)},e),s.push({type:"start",partial:r});let O=null,F=null,A=!1,b=new Map,L=new Map,l=r.content,I=(i)=>l.indexOf(i),j=(i)=>{let c=i.customInput?.property;if(c===void 0)return"";let x=i.arguments[c];return typeof x==="string"?x:""},H=(i,c,x)=>{let m=i.customInput;if(!m)return;let E=qr(m.jsonBuffer,m.property,c,x);return i.arguments={[m.property]:c},E},ge=(i)=>{let c=I(i);if(c===-1)return;if(i.type==="text")s.push({type:"text_end",contentIndex:c,content:i.text,partial:r});else if(i.type==="thinking")g(i),s.push({type:"thinking_end",contentIndex:c,content:i.thinking,partial:r});else if(i.type==="toolCall"){if(i.customInput){let x=H(i,j(i),!0);if(x!==void 0)s.push({type:"toolcall_delta",contentIndex:c,delta:x,partial:r})}else i.arguments=G(i.partialArgs);delete i.partialArgs,delete i.customInput,delete i.streamIndex,s.push({type:"toolcall_end",contentIndex:c,toolCall:i,partial:r})}},de=()=>{if(!O)O={type:"text",text:""},l.push(O),s.push({type:"text_start",contentIndex:I(O),partial:r});return O},Z=(i)=>{if(!F)F={type:"thinking",thinking:"",thinkingSignature:i},l.push(F),s.push({type:"thinking_start",contentIndex:I(F),partial:r});return F},he=(i)=>{let c=typeof i.index==="number"?i.index:void 0,x=i.function?.name??i.custom?.name??"",m=c!==void 0?b.get(c):void 0;if(!m&&i.id)m=L.get(i.id);if(!m){let E=i.custom&&!i.function?T.get(x)??"input":void 0,B=E!==void 0;if(m={type:"toolCall",id:i.id||"",name:x,arguments:B?{[E]:""}:{},partialArgs:B?void 0:"",customInput:B?{property:E,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:c},c!==void 0)b.set(c,m);if(i.id)L.set(i.id,m);l.push(m),s.push({type:"toolcall_start",contentIndex:I(m),partial:r})}if(c!==void 0&&m.streamIndex===void 0)m.streamIndex=c,b.set(c,m);if(i.id)L.set(i.id,m);if(!m.name&&x)m.name=x;if(i.custom&&!i.function&&!m.customInput){let E=T.get(m.name)??"input";m.arguments={[E]:""},m.customInput={property:E,jsonBuffer:{input:"",started:!1,closed:!1}},delete m.partialArgs}return m};for await(let i of M){if(await t?.onProviderStreamEvent?.(i,e),!i||typeof i!=="object")continue;if(r.responseId||=i.id,typeof i.model==="string"&&i.model.length>0&&i.model!==e.id)r.responseModel||=i.model;if(i.usage)r.usage=ie(i.usage,e);let c=Array.isArray(i.choices)?i.choices[0]:void 0;if(!c)continue;if(!i.usage&&c.usage)r.usage=ie(c.usage,e);if(c.finish_reason){r.rawStopReason=c.finish_reason;let x=Ve(c.finish_reason);if(r.stopReason=x.stopReason,x.errorMessage)r.errorMessage=x.errorMessage;A=!0}if(c.delta){if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){let y=de();y.text+=c.delta.content,s.push({type:"text_delta",contentIndex:I(y),delta:c.delta.content,partial:r})}let x=["reasoning_content","reasoning","reasoning_text"],m=c.delta,E=null;for(let y of x){let v=m[y];if(typeof v==="string"&&v.length>0){E=y;break}}if(E){let y=m[E];if(typeof y==="string"&&y.length>0){let v=e.provider==="opencode-go"&&E==="reasoning"?"reasoning_content":E,q=Z(v);q.thinking+=y,s.push({type:"thinking_delta",contentIndex:I(q),delta:y,partial:r})}}if(c?.delta?.tool_calls)for(let y of c.delta.tool_calls){let v=he(y);if(!v.id&&y.id)v.id=y.id,L.set(y.id,v);let q=y.function?.name??y.custom?.name;if(!v.name&&q)v.name=q;let z="";if(y.function?.arguments)z=y.function.arguments,v.partialArgs=(v.partialArgs??"")+y.function.arguments,v.arguments=G(v.partialArgs);else if(y.custom?.input){let me=j(v)+y.custom.input;z=H(v,me,!1)??""}s.push({type:"toolcall_delta",contentIndex:I(v),delta:z,partial:r})}let B=c.delta.reasoning_details;if(Array.isArray(B))for(let y of B){if(!N(y))continue;Z(""),k??=[],Ee(k,y)}}}for(let i of l)ge(i);if(t?.signal?.aborted)throw Error("Request was aborted");if(r.stopReason==="aborted")throw Error("Request was aborted");if(!A&&!a.supportsFinishReason)r.stopReason=r.content.some((i)=>i.type==="toolCall")?"toolUse":"stop";if(r.stopReason==="error")throw Error(r.errorMessage||"Provider returned an error stop reason");if(a.supportsFinishReason&&!A||r.stopReason==="pending")throw Error("Stream ended without finish_reason");s.push({type:"done",reason:r.stopReason,message:r}),s.end()}catch(R){for(let T of r.content){if(T.type==="thinking")g(T);delete T.index,delete T.partialArgs,delete T.customInput,delete T.streamIndex}r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=J(V(R));let a=R?.error?.metadata?.raw;if(a&&!r.errorMessage.includes(String(a)))r.errorMessage+=`
|
|
3
|
+
${a}`;s.push({type:"error",reason:r.stopReason,error:r}),s.end()}})(),s},yt=(e,n,t)=>{ae(e.provider,t?.apiKey,t?.headers);let s={...X(e,n,t,t?.apiKey),toolChoice:t?.toolChoice},u=t?.reasoning?K(e,t.reasoning):void 0;return Oe(e,n,{...s,reasoningEffort:u==="off"?void 0:u,thinkingBudgets:t?.thinkingBudgets})};function Be(e,n,t,s,u,r,k=D(e)){let g={"User-Agent":oe(),...e.headers};if(e.provider==="github-copilot"){let R=Tt(n.messages),a=Pt({messages:n.messages,hasImages:R});Object.assign(g,a)}if(r&&k.sendSessionAffinityHeaders)if(k.sessionAffinityFormat==="openrouter")g["x-session-id"]=r;else{if(k.sessionAffinityFormat==="openai")g.session_id=r;g["x-client-request-id"]=r,g["x-session-affinity"]=r}if(s)Object.assign(g,s);return new S({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:u,defaultHeaders:g})}function Pe(e,n,t,s=D(e),u=le(t?.cacheRetention,t?.env),r=Re(xe(n.messages),s.supportsOpenAIGrammarTools)){let k=ve(n.messages,s.supportsMidConvoSystemMessages===!0&&s.supportsMidConvoToolAdditions===!0),g=Je(e,n,s,{grammarToolInputProperties:r}),R=Ge(s,u),a={model:e.id,messages:g,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&u!=="none"||u==="long"&&s.supportsLongCacheRetention?Ke(t?.sessionId):void 0,prompt_cache_retention:u==="long"&&s.supportsLongCacheRetention?"24h":void 0};if(s.supportsUsageInStreaming!==!1)a.stream_options={include_usage:!0};if(s.supportsStore)a.store=!1;if(t?.maxTokens)if(s.maxTokensField==="max_tokens")a.max_tokens=t.maxTokens;else a.max_completion_tokens=t.maxTokens;if(t?.temperature!==void 0)a.temperature=t.temperature;if(k.requestTools.length>0){if(a.tools=pe(k.requestTools,s),s.zaiToolStream)a.tool_stream=!0}else if(ye(n.messages))a.tools=[];if(R)Ne(g,a.tools,R);if(t?.toolChoice)a.tool_choice=t.toolChoice;if(s.vllmPriority!==void 0)a.priority=s.vllmPriority;let T=Le(s),p=qe(e,t,a);if(s.thinkingFormat==="zai"&&e.reasoning){let o=a;if(o.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&s.supportsReasoningEffort){let f=e.thinkingLevelMap?.[t.reasoningEffort],h=f===void 0?t.reasoningEffort:f;if(typeof h==="string")o.reasoning_effort=h}}else if(s.thinkingFormat==="qwen"&&e.reasoning){if(a.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&s.supportsReasoningEffort){let o=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;if(typeof o==="string")a.reasoning_effort=o}}else if(s.thinkingFormat==="qwen-chat-template"&&e.reasoning)a.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(s.thinkingFormat==="chat-template"&&e.reasoning){let o=re(e,t,s.chatTemplateKwargs,p);if(o)a.chat_template_kwargs=o}else if(s.thinkingFormat==="baseten"&&e.reasoning){let o=a,f=re(e,t,s.chatTemplateArgs,p);if(f)o.chat_template_args=f;if(s.supportsReasoningEffort){let h=t?.reasoningEffort,C=h?e.thinkingLevelMap?.[h]:e.thinkingLevelMap?.off,M=C===void 0?h:C;if(typeof M==="string")o.reasoning_effort=M}}else if(s.thinkingFormat==="deepseek"&&e.reasoning){if(t?.reasoningEffort)a.thinking={type:"enabled"};else if(e.thinkingLevelMap?.off!==null)a.thinking={type:"disabled"};if(t?.reasoningEffort&&s.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(s.thinkingFormat==="openrouter"&&e.reasoning){let o=a;if(t?.reasoningEffort)o.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort};else if(e.thinkingLevelMap?.off!==null)o.reasoning={effort:e.thinkingLevelMap?.off??"none"}}else if(s.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let o=e.thinkingLevelMap?.[t.reasoningEffort];if(typeof o==="string")a.reasoning={effort:o}}else if(s.thinkingFormat==="together"&&e.reasoning){let o=a;if(o.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&s.supportsReasoningEffort)o.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(s.thinkingFormat==="string-thinking"&&e.reasoning){let o=a;if(t?.reasoningEffort)o.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(e.thinkingLevelMap?.off!==null)o.thinking=e.thinkingLevelMap?.off??"none"}else if(t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort){let o=e.thinkingLevelMap?.off;if(typeof o==="string")a.reasoning_effort=o}if(T&&p!==void 0)Object.assign(a,{[T]:p});if(e.compat?.openRouterRouting)a.provider=e.compat.openRouterRouting;if(e.compat?.vercelGatewayRouting){let o=e.compat.vercelGatewayRouting;if(o.only||o.order){let f={};if(o.only)f.only=o.only;if(o.order)f.order=o.order;a.providerOptions={gateway:f}}}let d=dt(e,t?.reasoningEffort??"off",t?.samplingParams);if(d)Object.assign(a,d);return a}function Le(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return"thinking_token_budget";return}function qe(e,n,t){if(!n?.reasoningEffort||!e.reasoning)return;let s=t.max_tokens??t.max_completion_tokens??e.maxTokens,u=Ho(Wo(n.reasoningEffort,n.thinkingBudgets),s);return u>0?u:void 0}function re(e,n,t,s){let u={};for(let[r,k]of Object.entries(t)){let g=ze(e,n,k,s);if(g!==void 0)u[r]=g}return Object.keys(u).length>0?u:void 0}function ze(e,n,t,s){if(typeof t!=="object"||t===null)return t;let u=n?.reasoningEffort;if(!u&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!u;if(t.$var==="thinking.budget")return s;let r=u?e.thinkingLevelMap?.[u]:e.thinkingLevelMap?.off;return r===void 0?u:typeof r==="string"?r:void 0}function Ge(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none")return;let t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function Ne(e,n,t){je(e,t),He(n,t),$e(e,t)}function je(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){Ue(t,n);return}}function $e(e,n){for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.role==="user"||s.role==="assistant"||s.role==="tool"){if(We(s,n))return}}}function He(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function Ue(e,n){return ce(e,n)}function We(e,n){if(e.role==="user"||e.role==="assistant"||e.role==="tool")return ce(e,n);return!1}function ce(e,n){let t=e.content;if(typeof t==="string"){if(t.length===0)return!1;return e.content=[{type:"text",text:t,cache_control:n}],!0}if(!Array.isArray(t))return!1;for(let s=t.length-1;s>=0;s--){let u=t[s];if(u?.type==="text"){let r=u;return r.cache_control=n,!0}}return!1}function Je(e,n,t,s){let u=se(n,t.supportsMidConvoSystemMessages),r=[],k=(p)=>{if(p.includes("|")){let d=p.indexOf("|"),o=p.slice(0,d).replace(/[^a-zA-Z0-9_-]/g,"_"),f=p.slice(d+1).replace(/[^a-zA-Z0-9_-]/g,"_"),h=f.length>0?`${o}_${f}`:o;if(h.length<=40)return h;let C=rt(p).slice(0,8);return`${o.slice(0,Math.max(1,40-C.length-1))}_${C}`}if(e.provider==="openai")return p.length>40?p.slice(0,40):p;return p},g=Se(u.messages,e,(p)=>k(p)),R=ve(u.messages,t.supportsMidConvoSystemMessages===!0&&t.supportsMidConvoToolAdditions===!0),a=e.reasoning&&t.supportsDeveloperRole?"developer":"system",T=null;for(let p=0;p<g.length;p++){let d=g[p];if(t.requiresAssistantAfterToolResult&&T==="toolResult"&&d.role==="user")r.push({role:"assistant",content:"I have processed the tool results."});if(d.role==="system"){let o=p>0&&R.anchorsAdditions?d.toolsAdded??[]:[];if(o.length>0){let h={role:"system",tools:pe(o,t)};r.push(h)}let f=p===0?W(d):De(d);if(f.length>0)r.push({role:a,content:w(f)})}else if(d.role==="user")if(typeof d.content==="string")r.push({role:"user",content:w(d.content)});else{let o=d.content.filter((f)=>f.type!=="text"||f.text.length>0).map((f)=>{if(f.type==="text")return{type:"text",text:w(f.text)};else return{type:"image_url",image_url:{url:`data:${f.mimeType};base64,${f.data}`}}});if(o.length===0)continue;r.push({role:"user",content:o})}else if(d.role==="assistant"){let o={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},f=d.content.filter(te).filter((l)=>l.text.trim().length>0).map((l)=>({type:"text",text:w(l.text)})),h=f.map((l)=>l.text).join(""),C=d.content.filter(ke),M=d.content.filter(Te),P=C.map((l)=>Me(l.thinkingSignature)).find((l)=>l!==void 0),O=M.map((l)=>Ie(l.thoughtSignature)).filter((l)=>l!==void 0),F=P??(O.length>0?O:void 0),A=C.filter((l)=>l.thinking.trim().length>0);if(A.length>0)if(t.requiresThinkingAsText){let l=A.map((I)=>w(I.thinking)).join(`
|
|
4
|
+
|
|
5
|
+
`);o.content=[{type:"text",text:l},...f]}else{if(h.length>0)o.content=h;if(!F){let l=A[0].thinkingSignature;if(e.provider==="opencode-go"&&l==="reasoning")l="reasoning_content";if(l&&Fe(l))o[l]=A.map((I)=>I.thinking).join(`
|
|
6
|
+
`)}}else if(h.length>0)o.content=h;if(M.length>0)o.tool_calls=M.map((l)=>{let I=s?.grammarToolInputProperties?.get(l.name);if(I!==void 0)return{id:l.id,type:"custom",custom:{name:l.name,input:w(Hr(l.name,l.arguments,I))}};return{id:l.id,type:"function",function:{name:l.name,arguments:JSON.stringify(l.arguments)}}});if(F)o.reasoning_details=F;if(t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&o.reasoning_content===void 0)o.reasoning_content="";let b=o.content;if(!(b!==null&&b!==void 0&&(typeof b==="string"?b.length>0:b.length>0))&&!o.tool_calls)continue;r.push(o)}else if(d.role==="toolResult"){let o=[],f=p;for(;f<g.length&&g[f].role==="toolResult";f++){let h=g[f],C=h.content.filter(te).map((A)=>A.text).join(`
|
|
7
|
+
`),M=h.content.some((A)=>A.type==="image"),O=C.length>0?C:M?"(see attached image)":"(no tool output)",F={role:"tool",content:w(O),tool_call_id:h.toolCallId};if(t.requiresToolResultName&&h.toolName)F.name=h.toolName;if(r.push(F),M&&e.input.includes("image")){for(let A of h.content)if(_e(A))o.push({type:"image_url",image_url:{url:`data:${A.mimeType};base64,${A.data}`}})}}if(p=f-1,o.length>0){if(t.requiresAssistantAfterToolResult)r.push({role:"assistant",content:"I have processed the tool results."});r.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...o]}),T="user"}else T="toolResult";continue}T=d.role}return r}function pe(e,n){return e.map((t)=>{let s=nr(t,n.supportsOpenAIGrammarTools);if(s)return{type:"custom",custom:{name:t.name,description:t.description,format:{type:"grammar",grammar:{syntax:s.format,definition:s.definition}}}};let u=fe(t,n.supportsStrictMode!==!1);return{type:"function",function:{name:t.name,description:t.description,parameters:be(t,u),...n.supportsStrictMode!==!1&&{strict:u??!1}}}})}function ie(e,n){let t=e.prompt_tokens||0,s=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,u=e.prompt_tokens_details?.cache_write_tokens||0,r=Math.max(0,t-s-u),k=e.completion_tokens||0,g={input:r,output:k,cacheRead:s,cacheWrite:u,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:r+k+s+u,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return Y(n,g),g}function Ve(e){if(e===null)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}function Ze(e){let{provider:n,baseUrl:t}=e,s=n==="zai"||n==="zai-coding-cn"||t.includes("api.z.ai")||t.includes("open.bigmodel.cn"),u=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),r=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot."),k=n==="openrouter"||t.includes("openrouter.ai"),g=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),R=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),a=n==="nvidia"||t.includes("integrate.api.nvidia.com"),T=n==="ant-ling"||t.includes("api.ant-ling.com"),p=n==="cerebras"||t.includes("cerebras.ai"),d=n==="deepseek"||t.toLowerCase().includes("deepseek.com"),o=a||p||n==="xai"||t.includes("api.x.ai")||u||t.includes("chutes.ai")||d||s||r||n==="opencode"||t.includes("opencode.ai")||g||R||T,f=t.includes("chutes.ai")||d||r||R||u||a||T||s,h=n==="xai"||t.includes("api.x.ai"),C=k&&(e.id.startsWith("anthropic/")||e.id.startsWith("openai/")),M=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!o,supportsDeveloperRole:C||!o&&!k,supportsReasoningEffort:!h&&!s&&!r&&!u&&!R&&!a&&!T,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:f?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:d,thinkingFormat:d?"deepseek":s?"zai":u?"together":T?"ant-ling":k?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:M,sendSessionAffinityHeaders:k,sessionAffinityFormat:k?"openrouter":"openai",supportsLongCacheRetention:!(u||g||R||a||T)}}function D(e){let n=Ze(e);if(!e.compat)return n;return{supportsStore:e.compat.supportsStore??n.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??n.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??n.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??n.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??n.supportsFinishReason,maxTokensField:e.compat.maxTokensField??n.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??n.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??n.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??n.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??n.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??n.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??n.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??n.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??n.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??n.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??n.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??n.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??n.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??n.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:e.compat.supportsMidConvoSystemMessages??n.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:e.compat.supportsMidConvoToolAdditions??n.supportsMidConvoToolAdditions,cacheControlFormat:e.compat.cacheControlFormat??n.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??n.sendSessionAffinityHeaders,sessionAffinityFormat:e.compat.sessionAffinityFormat??n.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??n.supportsLongCacheRetention,vllmPriority:e.compat.vllmPriority}}export{Je as convertMessages,Oe as stream,yt as streamSimple};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-eq4wqxzt.js";import"./chunk-4gtgqcct.js";import{Tr}from"./chunk-85v69h91.js";import{at,Je,lt}from"./chunk-ntks40jd.js";import{Ge}from"./chunk-bpw6q7g0.js";import{ee}from"./chunk-tvm4zmgj.js";import{Lr}from"./chunk-hc300148.js";import{q,V}from"./chunk-ypqjfv3a.js";import{Te,K}from"./chunk-fhxy6y34.js";import{j}from"./chunk-nrsd810j.js";import{Gn,Kr}from"./chunk-n0ybj4h9.js";import{U,ft,me,re,be,Se,G}from"./chunk-ejjem0tc.js";import{L,Ve,Ht,ke}from"./chunk-qs8zzg50.js";var ve="https://chatgpt.com/backend-api",Re="https://api.openai.com/auth",Ce=0,te=1000,xe=60000,Oe=15000,Ae=3,ue=new Set(["openai","openai-codex","opencode"]),Me=1009,We="websocket_connection_limit_reached",Le="previous_response_not_found",De=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function ne(e){if(e.stopReason==="pending")throw Error("Codex stream ended without a stop reason");if(e.stopReason==="error"||e.stopReason==="aborted")throw Error(e.errorMessage||"An unknown error occurred")}function Ne(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function qe(e,r){if(e===429&&Ne(r))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}function Be(e){let r=e.get("retry-after-ms");if(r!==null){let s=Number(r);if(Number.isFinite(s))return Math.max(0,s)}let t=e.get("retry-after");if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1000);let o=Date.parse(t);if(!Number.isNaN(o))return Math.max(0,o-Date.now());return}class Y extends Error{}function Pe(e,r){let t=r?.maxRetryDelayMs??xe;if(t>0&&e>t)throw new Y(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(t/1000)}s)`);return e}function se(e,r){return new Promise((t,n)=>{if(r?.aborted){n(Error("Request was aborted"));return}let o=setTimeout(t,e);r?.addEventListener("abort",()=>{clearTimeout(o),n(Error("Request was aborted"))})})}function oe(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Ie(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Fe(e){let r=Ie();if(!r||typeof r.zstdCompressSync!=="function")return null;try{let t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:Ae}});return new Uint8Array(t)}catch{return null}}var Ue=(e,r,t)=>{let n=new L,o=re(r,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let i=t?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let u=_t(i),a=Te(be(o.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=t?.cacheRetention==="none"?void 0:t?.sessionId,p=Ge(d),c=$e(e,o,t,p,a),l=await t?.onPayload?.(c,e);if(l!==void 0)c=l;let f=p||Kr(),m=kt(e.headers,t?.headers,u,i,p),b=Tt(e.headers,t?.headers,u,i,f),h=JSON.stringify(c),E=oe(t?.timeoutMs),w=oe(t?.websocketConnectTimeoutMs),v=t?.transport||"auto",T=!1,y=v!=="sse"&&ye(d);if(y)ie(d);if(v!=="sse"&&!y){let S=!1,k=!1,O=!1;while(!0){S=!1;try{if(await St(He(e.baseUrl),c,b,s,n,e,()=>{if(S=!0,!T)T=!0,n.push({type:"start",partial:s})},E,w,d,u,a,t),t?.signal?.aborted)throw Error("Request was aborted");ne(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(R){let N=t?.signal?.aborted,B=!S&&Xe(R),M=Ye(R);if(!N&&M&&!O){O=!0;continue}if(!N&&B&&!k){k=!0;continue}if(N||je(R)&&!B)throw R;if(ke(s,Ht("provider_transport_failure",R,{configuredTransport:v,...S?{}:{fallbackTransport:"sse"},eventsEmitted:S,phase:S?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(h).byteLength})),ot(d,R),S)throw R;ie(d);break}}}let x=Fe(h);if(x)m.set("content-encoding","zstd");let A=x??h,_,D,J=t?.maxRetries??Ce;for(let S=0;S<=J;S++){if(t?.signal?.aborted)throw Error("Request was aborted");try{let k=E!==void 0&&E>0?AbortSignal.timeout(E):void 0,O=Tr([t?.signal,k]);try{_=await(t?.fetch??globalThis.fetch)(de(e.baseUrl),{method:"POST",headers:m,body:A,signal:O.signal})}catch(M){if(k?.aborted&&!t?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${E}ms`);throw M}finally{O.cleanup()}if(await t?.onResponse?.({status:_.status,headers:j(_.headers)},e),_.ok)break;let R=await _.text();if(S<J&&qe(_.status,R)){let M=Be(_.headers),_e=M===void 0?te*2**S:Pe(M,t);await se(_e,t?.signal);continue}let N=new Response(R,{status:_.status,statusText:_.statusText}),B=await Et(N);throw Error(B.friendlyMessage||B.message)}catch(k){if(k instanceof Error){if(k.name==="AbortError"||k.message==="Request was aborted")throw Error("Request was aborted")}if(D=k instanceof Error?k:Error(String(k)),S<J&&!(D instanceof Y)&&!D.message.includes("usage limit")){let O=te*2**S;await se(O,t?.signal);continue}throw D}}if(!_?.ok)throw D??Error("Failed after retries");if(!_.body)throw Error("No response body");if(!T)T=!0,n.push({type:"start",partial:s});if(await Ke(_,s,n,e,a,t),t?.signal?.aborted)throw Error("Request was aborted");ne(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(i){for(let u of s.content)delete u.partialJson,delete u.customInput;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=V(q(i)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Ut=(e,r,t)=>{let n=t?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let o={...K(e,r,t,n),toolChoice:t?.toolChoice},s=t?.reasoning?G(e,t.reasoning):void 0;return Ue(e,r,{...o,reasoningEffort:s==="off"?void 0:s})};function $e(e,r,t,n,o=Te(be(r.messages),e.compat?.supportsOpenAIGrammarTools??!1)){let s=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,u=e.compat?.supportsAdditionalTools??!1,a=e.compat?.supportsToolSearch??!1,d=Se(r.messages,u||a),p=at(e,r,ue,{includeSystemPrompt:!1,grammarToolInputProperties:o,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:u,supportsToolSearch:a,toolOptions:{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i}}),c=me(r.messages),l=c?U(c):"",f={model:e.id,store:!1,stream:!0,instructions:l||"You are a helpful assistant.",input:p,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0)f.temperature=t.temperature;if(t?.serviceTier!==void 0)f.service_tier=t.serviceTier;if(d.requestTools.length>0)f.tools=Je(d.requestTools,{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i});if(t?.reasoningEffort!==void 0){let m=t.reasoningEffort==="none"?e.thinkingLevelMap?.off===void 0?"none":e.thinkingLevelMap.off:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;if(m!==null)f.reasoning={effort:m,summary:t.reasoningSummary??"auto"}}else if(e.reasoning&&e.thinkingLevelMap?.off!==null)f.reasoning={effort:e.thinkingLevelMap?.off??"none"};return f}function ze(e,r){switch(r){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function fe(e,r,t){let n=ze(t,r);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function le(e,r){if(e==="default"&&(r==="flex"||r==="priority"))return r;return e??r}function de(e){let t=(e&&e.trim().length>0?e:ve).replace(/\/+$/,"");if(t.endsWith("/codex/responses"))return t;if(t.endsWith("/codex"))return`${t}/responses`;return`${t}/codex/responses`}function He(e){let r=new URL(de(e));if(r.protocol==="https:")r.protocol="wss:";if(r.protocol==="http:")r.protocol="ws:";return r.toString()}async function Ke(e,r,t,n,o,s){await lt(pe(et(e,s?.signal),r,n,s?.onProviderStreamEvent),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:o,resolveServiceTier:le,applyServiceTierPricing:(i,u)=>fe(i,u,n)})}class W extends Error{code;payload;constructor(e,r){super(e);this.name="CodexApiError",this.code=r?.code,this.payload=r?.payload,this.cause=r?.cause}}class z extends Error{payload;constructor(e,r){super(e);this.name="CodexProtocolError",this.payload=r?.payload,this.cause=r?.cause}}class Z extends Error{constructor(e){super(Ve(e));this.name="ProviderStreamEventCallbackError",this.cause=e}}function je(e){return e instanceof W||e instanceof z||e instanceof Z}function Xe(e){return e instanceof W&&e.code===We}function Ye(e){return e instanceof W&&e.code===Le}function Ze(e){let r=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof r?.code==="string"?r.code:void 0,message:typeof e.message==="string"?e.message:typeof r?.message==="string"?r.message:void 0}}async function*pe(e,r,t,n){for await(let o of e){try{await n?.(o,t)}catch(i){throw new Z(i)}let s=typeof o.type==="string"?o.type:void 0;if(!s)continue;if(s==="error"){let{code:i,message:u}=Ze(o);throw new W(`Codex error: ${u||i||JSON.stringify(o)}`,{code:i,payload:o})}if(s==="response.failed"){let i=o.response,u=i?.error?.code,a=i?.error?.message;throw new W(a||"Codex response failed",{code:u,payload:o})}if(s==="response.done"||s==="response.completed"||s==="response.incomplete"){let i=o.response;if(typeof i?.end_turn==="boolean")r.endTurn=i.end_turn;let u=i?{...i,status:Qe(i.status)}:i;yield{...o,type:"response.completed",response:u};return}yield o}}function Qe(e){if(typeof e!=="string")return;return De.has(e)?e:void 0}async function*et(e,r){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,o="",s=()=>{t.cancel().catch(()=>{})};r?.addEventListener("abort",s,{once:!0});try{while(!0){if(r?.aborted)throw Error("Request was aborted");let{done:i,value:u}=await t.read();if(r?.aborted)throw Error("Request was aborted");if(o+=i?n.decode():n.decode(u,{stream:!0}),i&&o.trim())o+=`
|
|
2
|
+
import"./chunk-ge38dhv9.js";import"./chunk-38g4jd6v.js";import{Ir}from"./chunk-w55cnj0f.js";import{ut,tt,pt}from"./chunk-qjnx4fsn.js";import{Ke}from"./chunk-86yr2c0r.js";import{oe}from"./chunk-pyj6avd5.js";import{Wr}from"./chunk-c8g9jjqs.js";import{Re,X}from"./chunk-qs161f2q.js";import{V,J}from"./chunk-8np9b2y8.js";import{Q}from"./chunk-tfhp09nj.js";import{eo,rn}from"./chunk-g5p9mj1r.js";import{W,bt,ge,se,xe,ve,K}from"./chunk-z9p6s986.js";import{U,Xe,jt,Ie}from"./chunk-4yxd2kg1.js";var Ee="https://chatgpt.com/backend-api",_e="https://api.openai.com/auth",ke=0,ee=1000,Te=60000,Ce=15000,Oe=3,ue=new Set(["openai","openai-codex","opencode"]),Ae=1009,Me="websocket_connection_limit_reached",We="previous_response_not_found",Le=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function te(e){if(e.stopReason==="pending")throw Error("Codex stream ended without a stop reason");if(e.stopReason==="error"||e.stopReason==="aborted")throw Error(e.errorMessage||"An unknown error occurred")}function De(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Ne(e,r){if(e===429&&De(r))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}function qe(e){let r=e.get("retry-after-ms");if(r!==null){let s=Number(r);if(Number.isFinite(s))return Math.max(0,s)}let t=e.get("retry-after");if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1000);let o=Date.parse(t);if(!Number.isNaN(o))return Math.max(0,o-Date.now());return}class j extends Error{}function Be(e,r){let t=r?.maxRetryDelayMs??Te;if(t>0&&e>t)throw new j(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(t/1000)}s)`);return e}function re(e,r){return new Promise((t,n)=>{if(r?.aborted){n(Error("Request was aborted"));return}let o=setTimeout(t,e);r?.addEventListener("abort",()=>{clearTimeout(o),n(Error("Request was aborted"))})})}function ne(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Pe(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Fe(e){let r=Pe();if(!r||typeof r.zstdCompressSync!=="function")return null;try{let t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:Oe}});return new Uint8Array(t)}catch{return null}}var Ue=(e,r,t)=>{let n=new U,o=se(r,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let i=t?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let u=_t(i),a=Re(xe(o.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=t?.cacheRetention==="none"?void 0:t?.sessionId,p=Ke(d),c=$e(e,o,t,p,a),l=await t?.onPayload?.(c,e);if(l!==void 0)c=l;let f=p||rn(),m=kt(e.headers,t?.headers,u,i,p),b=Tt(e.headers,t?.headers,u,i,f),h=JSON.stringify(c),E=ne(t?.timeoutMs),w=ne(t?.websocketConnectTimeoutMs),v=t?.transport||"auto",T=!1,y=v!=="sse"&&me(d);if(y)ie(d);if(v!=="sse"&&!y){let S=!1,k=!1,O=!1;while(!0){S=!1;try{if(await St(Je(e.baseUrl),c,b,s,n,e,()=>{if(S=!0,!T)T=!0,n.push({type:"start",partial:s})},E,w,d,u,a,t),t?.signal?.aborted)throw Error("Request was aborted");te(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(R){let N=t?.signal?.aborted,q=!S&&je(R),M=Ve(R);if(!N&&M&&!O){O=!0;continue}if(!N&&q&&!k){k=!0;continue}if(N||Ge(R)&&!q)throw R;if(Ie(s,jt("provider_transport_failure",R,{configuredTransport:v,...S?{}:{fallbackTransport:"sse"},eventsEmitted:S,phase:S?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(h).byteLength})),ot(d,R),S)throw R;ie(d);break}}}let x=Fe(h);if(x)m.set("content-encoding","zstd");let A=x??h,_,D,z=t?.maxRetries??ke;for(let S=0;S<=z;S++){if(t?.signal?.aborted)throw Error("Request was aborted");try{let k=E!==void 0&&E>0?AbortSignal.timeout(E):void 0,O=Ir([t?.signal,k]);try{_=await(t?.fetch??globalThis.fetch)(de(e.baseUrl),{method:"POST",headers:m,body:A,signal:O.signal})}catch(M){if(k?.aborted&&!t?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${E}ms`);throw M}finally{O.cleanup()}if(await t?.onResponse?.({status:_.status,headers:Q(_.headers)},e),_.ok)break;let R=await _.text();if(S<z&&Ne(_.status,R)){let M=qe(_.headers),Se=M===void 0?ee*2**S:Be(M,t);await re(Se,t?.signal);continue}let N=new Response(R,{status:_.status,statusText:_.statusText}),q=await Et(N);throw Error(q.friendlyMessage||q.message)}catch(k){if(k instanceof Error){if(k.name==="AbortError"||k.message==="Request was aborted")throw Error("Request was aborted")}if(D=k instanceof Error?k:Error(String(k)),S<z&&!(D instanceof j)&&!D.message.includes("usage limit")){let O=ee*2**S;await re(O,t?.signal);continue}throw D}}if(!_?.ok)throw D??Error("Failed after retries");if(!_.body)throw Error("No response body");if(!T)T=!0,n.push({type:"start",partial:s});if(await He(_,s,n,e,a,t),t?.signal?.aborted)throw Error("Request was aborted");te(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(i){for(let u of s.content)delete u.partialJson,delete u.customInput;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=J(V(i)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Ut=(e,r,t)=>{let n=t?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let o={...X(e,r,t,n),toolChoice:t?.toolChoice},s=t?.reasoning?K(e,t.reasoning):void 0;return Ue(e,r,{...o,reasoningEffort:s==="off"?void 0:s})};function $e(e,r,t,n,o=Re(xe(r.messages),e.compat?.supportsOpenAIGrammarTools??!1)){let s=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,u=e.compat?.supportsAdditionalTools??!1,a=e.compat?.supportsToolSearch??!1,d=ve(r.messages,u||a),p=ut(e,r,ue,{includeSystemPrompt:!1,grammarToolInputProperties:o,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:u,supportsToolSearch:a,toolOptions:{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i}}),c=ge(r.messages),l=c?W(c):"",f={model:e.id,store:!1,stream:!0,instructions:l||"You are a helpful assistant.",input:p,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0)f.temperature=t.temperature;if(t?.serviceTier!==void 0)f.service_tier=t.serviceTier;if(d.requestTools.length>0)f.tools=tt(d.requestTools,{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i});if(t?.reasoningEffort!==void 0){let m=t.reasoningEffort==="none"?e.thinkingLevelMap?.off===void 0?"none":e.thinkingLevelMap.off:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;if(m!==null)f.reasoning={effort:m,summary:t.reasoningSummary??"auto"}}else if(e.reasoning&&e.thinkingLevelMap?.off!==null)f.reasoning={effort:e.thinkingLevelMap?.off??"none"};return f}function ze(e,r){switch(r){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function fe(e,r,t){let n=ze(t,r);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function le(e,r){if(e==="default"&&(r==="flex"||r==="priority"))return r;return e??r}function de(e){let t=(e&&e.trim().length>0?e:Ee).replace(/\/+$/,"");if(t.endsWith("/codex/responses"))return t;if(t.endsWith("/codex"))return`${t}/responses`;return`${t}/codex/responses`}function Je(e){let r=new URL(de(e));if(r.protocol==="https:")r.protocol="wss:";if(r.protocol==="http:")r.protocol="ws:";return r.toString()}async function He(e,r,t,n,o,s){await pt(pe(Qe(e,s?.signal),r,n,s?.onProviderStreamEvent),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:o,resolveServiceTier:le,applyServiceTierPricing:(i,u)=>fe(i,u,n)})}class L extends Error{code;payload;constructor(e,r){super(e);this.name="CodexApiError",this.code=r?.code,this.payload=r?.payload,this.cause=r?.cause}}class F extends Error{payload;constructor(e,r){super(e);this.name="CodexProtocolError",this.payload=r?.payload,this.cause=r?.cause}}class Y extends Error{constructor(e){super(Xe(e));this.name="ProviderStreamEventCallbackError",this.cause=e}}function Ge(e){return e instanceof L||e instanceof F||e instanceof Y}function je(e){return e instanceof L&&e.code===Me}function Ve(e){return e instanceof L&&e.code===We}function Ye(e){let r=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof r?.code==="string"?r.code:void 0,message:typeof e.message==="string"?e.message:typeof r?.message==="string"?r.message:void 0}}async function*pe(e,r,t,n){for await(let o of e){try{await n?.(o,t)}catch(i){throw new Y(i)}let s=typeof o.type==="string"?o.type:void 0;if(!s)continue;if(s==="error"){let{code:i,message:u}=Ye(o);throw new L(`Codex error: ${u||i||JSON.stringify(o)}`,{code:i,payload:o})}if(s==="response.failed"){let i=o.response,u=i?.error?.code,a=i?.error?.message;throw new L(a||"Codex response failed",{code:u,payload:o})}if(s==="response.done"||s==="response.completed"||s==="response.incomplete"){let i=o.response;if(typeof i?.end_turn==="boolean")r.endTurn=i.end_turn;let u=i?{...i,status:Ze(i.status)}:i;yield{...o,type:"response.completed",response:u};return}yield o}}function Ze(e){if(typeof e!=="string")return;return Le.has(e)?e:void 0}async function*Qe(e,r){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,o="",s=()=>{t.cancel().catch(()=>{})};r?.addEventListener("abort",s,{once:!0});try{while(!0){if(r?.aborted)throw Error("Request was aborted");let{done:i,value:u}=await t.read();if(r?.aborted)throw Error("Request was aborted");if(o+=i?n.decode():n.decode(u,{stream:!0}),i&&o.trim())o+=`
|
|
3
3
|
|
|
4
4
|
`;let a=o.indexOf(`
|
|
5
5
|
|
|
6
6
|
`);while(a!==-1){let d=o.slice(0,a);o=o.slice(a+2);let p=d.split(`
|
|
7
7
|
`).filter((c)=>c.startsWith("data:")).map((c)=>c.slice(5).trim());if(p.length>0){let c=p.join(`
|
|
8
|
-
`).trim();if(c&&c!=="[DONE]")try{yield JSON.parse(c)}catch(l){throw new
|
|
8
|
+
`).trim();if(c&&c!=="[DONE]")try{yield JSON.parse(c)}catch(l){throw new F(`Invalid Codex SSE JSON: ${Xe(l)}`,{cause:l,payload:c})}}a=o.indexOf(`
|
|
9
9
|
|
|
10
|
-
`)}if(i)break}}finally{r?.removeEventListener("abort",s);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var tt="responses_websockets=2026-02-06",rt=300000,nt=3300000,g=new Map,P=new Map,F=new Set;function Q(e){let r=P.get(e);if(!r)r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},P.set(e,r);return r}function $t(e){let r=P.get(e);return r?{...r}:void 0}function zt(e){if(e){P.delete(e),F.delete(e);return}P.clear(),F.clear()}function st(e){let r=(t)=>{if(t.idleTimer)clearTimeout(t.idleTimer);C(t.socket,1000,"debug_close")};if(e){for(let t of g.get(e)?.values()??[])r(t);g.delete(e);return}for(let t of g.values())for(let n of t.values())r(n);g.clear()}Gn(st);function ye(e){return e?F.has(e):!1}function ie(e){if(!e)return;let r=Q(e);r.sseFallbacks++,r.websocketFallbackActive=ye(e)}function ot(e,r){if(!e)return;F.add(e);let t=Q(e);t.websocketFailures++,t.lastWebSocketError=Ve(r),t.websocketFallbackActive=!0}var H=null;async function it(e){if(!e&&H)return H;if(typeof process<"u"&&process.versions?.bun){let t=class extends WebSocket{constructor(n,o){let s={};if(Array.isArray(o)||typeof o==="string")s={protocols:o};else s={...o};let i=Lr(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...i?{proxy:i.toString()}:{}})}};if(!e)H=t;return t}let r=globalThis.WebSocket;if(typeof r!=="function")return null;return r}class he extends Error{code;reason;wasClean;constructor(e,r){super(e);this.name="WebSocketCloseError",this.code=r?.code,this.reason=r?.reason,this.wasClean=r?.wasClean}}function ct(e){let r=e.readyState;return typeof r==="number"?r:void 0}function I(e){let r=ct(e);return r===void 0||r===1}function ut(e){return Date.now()-e.createdAt>=nt}function C(e,r=1000,t="done"){try{e.close(r,t)}catch{}}function ae(e,r,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;C(t.socket,1000,"idle_timeout");let n=g.get(e);if(n?.get(r)===t)n.delete(r);if(n?.size===0)g.delete(e)},rt)}async function X(e,r,t,n=Oe,o){let s=await it(o);if(!s)throw Error("WebSocket transport is not available in this runtime");let i=j(r);return delete i["OpenAI-Beta"],new Promise((u,a)=>{let d=!1,p,c;try{c=new s(e,{headers:i})}catch(w){a(w instanceof Error?w:Error(String(w)));return}let l=()=>{if(p)clearTimeout(p),p=void 0;c.removeEventListener("open",m),c.removeEventListener("error",b),c.removeEventListener("close",h),t?.removeEventListener("abort",E)},f=(w,v)=>{if(d)return;if(d=!0,l(),v)C(c,1000,v);a(w)},m=()=>{if(d)return;d=!0,l(),u(c)},b=(w)=>{f(we(w))},h=(w)=>{f(ge(w))},E=()=>{f(Error("Request was aborted"),"aborted")};if(c.addEventListener("open",m),c.addEventListener("error",b),c.addEventListener("close",h),t?.addEventListener("abort",E),n>0)p=setTimeout(()=>{f(Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n);if(t?.aborted)E()})}async function dt(e,r,t,n,o,s,i){if(!t){let c=await X(e,r,o,s,i);return{socket:c,reused:!1,release:()=>C(c)}}let u=g.get(t),a=u?.get(n);if(a){if(a.idleTimer)clearTimeout(a.idleTimer),a.idleTimer=void 0;if(!a.busy&&ut(a)){if(C(a.socket,1000,"connection_age_limit"),u?.delete(n),u?.size===0)g.delete(t)}else if(!a.busy&&I(a.socket))return a.busy=!0,{socket:a.socket,entry:a,reused:!0,release:({keep:c}={})=>{if(!c||!I(a.socket)){C(a.socket);let l=g.get(t);if(l?.get(n)===a)l.delete(n);if(l?.size===0)g.delete(t);return}a.busy=!1,ae(t,n,a)}};if(a.busy){let c=await X(e,r,o,s,i);return{socket:c,reused:!1,release:()=>{C(c)}}}if(!I(a.socket)){if(C(a.socket),u?.delete(n),u?.size===0)g.delete(t)}}let d=await X(e,r,o,s,i),p={socket:d,busy:!0,createdAt:Date.now()};if(u=g.get(t),!u)u=new Map,g.set(t,u);return u.set(n,p),{socket:d,entry:p,reused:!1,release:({keep:c}={})=>{if(!c||!I(p.socket)){if(C(p.socket),p.idleTimer)clearTimeout(p.idleTimer);let l=g.get(t);if(l?.get(n)===p)l.delete(n);if(l?.size===0)g.delete(t);return}p.busy=!1,ae(t,n,p)}}}function we(e){if(e&&typeof e==="object"){let r="message"in e?e.message:void 0;if(typeof r==="string"&&r.length>0)return Error(r);let t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t==="object"&&"message"in t){let n=t.message;if(typeof n==="string"&&n.length>0)return Error(n)}}return Error("WebSocket error")}function ge(e){if(e&&typeof e==="object"){let r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,o=typeof r==="number"?` ${r}`:"",s=typeof t==="string"&&t.length>0?` ${t}`:"";if(!s&&r===Me)s=" message too big";return new he(`WebSocket closed${o}${s}`.trim(),{code:typeof r==="number"?r:void 0,reason:typeof t==="string"&&t.length>0?t:void 0,wasClean:typeof n==="boolean"?n:void 0})}return Error("WebSocket closed")}async function pt(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}if(e&&typeof e==="object"&&"arrayBuffer"in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*mt(e,r,t){let n=[],o=null,s=!1,i=null,u=!1,a=()=>{if(!o)return;let f=o;o=null,f()},d=(f)=>{(async()=>{let m=null;try{if(!f||typeof f!=="object"||!("data"in f))return;if(m=await pt(f.data),!m)return;let b=JSON.parse(m),h=typeof b.type==="string"?b.type:"";if(h==="response.completed"||h==="response.done"||h==="response.incomplete")u=!0,s=!0;n.push(b),a()}catch(b){i=new z(`Invalid Codex WebSocket JSON: ${Ve(b)}`,{cause:b,payload:m}),s=!0,a()}})()},p=(f)=>{i=we(f),s=!0,a()},c=(f)=>{if(u){s=!0,a();return}if(!i)i=ge(f);s=!0,a()},l=()=>{i=Error("Request was aborted"),s=!0,a()};e.addEventListener("message",d),e.addEventListener("error",p),e.addEventListener("close",c),r?.addEventListener("abort",l);try{while(!0){if(r?.aborted)throw Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let f;await new Promise((m,b)=>{if(o=m,t!==void 0&&t>0)f=setTimeout(()=>{let h=Error(`WebSocket idle timeout after ${t}ms`);i=h,s=!0,o=null,C(e,1000,"idle_timeout"),b(h)},t)}).finally(()=>{if(f)clearTimeout(f)})}if(i)throw i;if(!u)throw Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",d),e.removeEventListener("error",p),e.removeEventListener("close",c),r?.removeEventListener("abort",l)}}function ce(e){let{input:r,previous_response_id:t,...n}=e;return n}function yt(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}function bt(e,r){return JSON.stringify(ce(e))===JSON.stringify(ce(r))}function ht(e,r){if(!bt(e,r.lastRequestBody))return;let t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;let o=t.slice(0,n.length);if(!yt(o,n))return;return t.slice(n.length)}function wt(e,r){let t=e.continuation;if(!t)return r;let n=ht(r,t);if(!n||!t.lastResponseId)return e.continuation=void 0,r;return{...r,previous_response_id:t.lastResponseId,input:n}}async function*gt(e,r){let t=!1;for await(let n of e){if(!t)t=!0,r();yield n}}async function St(e,r,t,n,o,s,i,u,a,d,p,c,l){let{socket:f,entry:m,reused:b,release:h}=await dt(e,t,d,p,l?.signal,a,l?.env),E=!0,w=l?.transport==="websocket-cached"||l?.transport==="auto",v=r,T=w&&m?wt(m,v):v,y=d?Q(d):void 0;if(y){if(y.requests++,b)y.connectionsReused++;else y.connectionsCreated++;if(w)y.cachedContextRequests++;if(T.store===!0)y.storeTrueRequests++;if(y.lastInputItems=T.input?.length??0,T.previous_response_id)y.deltaRequests++,y.lastDeltaInputItems=T.input?.length??0,y.lastPreviousResponseId=T.previous_response_id;else y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0}try{if(f.send(JSON.stringify({type:"response.create",...T})),await lt(gt(pe(mt(f,l?.signal,u),n,s,l?.onProviderStreamEvent),i),n,o,s,{serviceTier:l?.serviceTier,grammarToolInputProperties:c,resolveServiceTier:le,applyServiceTierPricing:(x,A)=>fe(x,A,s)}),l?.signal?.aborted)E=!1;else if(w&&m&&n.responseId){let x=at(s,ft({messages:[n]}),ue,{includeSystemPrompt:!1,grammarToolInputProperties:c}).filter((A)=>A.type!=="function_call_output"&&A.type!=="custom_tool_call_output");m.continuation={lastRequestBody:v,lastResponseId:n.responseId,lastResponseItems:x}}}catch(x){if(m)m.continuation=void 0;throw E=!1,x}finally{h({keep:E})}}async function Et(e){let r=await e.text(),t=r||e.statusText||"Request failed",n;try{let s=JSON.parse(r)?.error;if(s){let i=s.code||s.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){let u=s.plan_type?` (${s.plan_type.toLowerCase()} plan)`:"",a=s.resets_at?Math.max(0,Math.round((s.resets_at*1000-Date.now())/60000)):void 0,d=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${u}.${d}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function _t(e){try{let r=e.split(".");if(r.length!==3)throw Error("Invalid token");let n=JSON.parse(atob(r[1]))?.[Re]?.chatgpt_account_id;if(!n)throw Error("No account ID in token");return n}catch{throw Error("Failed to extract accountId from token")}}function Ee(e,r,t,n){let o=new Headers({originator:"pi","User-Agent":ee()});for(let[s,i]of Object.entries(e||{}))o.set(s,i);for(let[s,i]of Object.entries(r||{}))if(i===null)o.delete(s);else o.set(s,i);return o.set("Authorization",`Bearer ${n}`),o.set("chatgpt-account-id",t),o}function kt(e,r,t,n,o){let s=Ee(e,r,t,n);if(s.set("OpenAI-Beta","responses=experimental"),s.set("accept","text/event-stream"),s.set("content-type","application/json"),o)s.set("session-id",o),s.set("x-client-request-id",o);return s}function Tt(e,r,t,n,o){let s=Ee(e,r,t,n);return s.delete("accept"),s.delete("content-type"),s.delete("OpenAI-Beta"),s.delete("openai-beta"),s.set("OpenAI-Beta",tt),s.set("x-client-request-id",o),s.set("session-id",o),s}export{st as closeOpenAICodexWebSocketSessions,$t as getOpenAICodexWebSocketDebugStats,zt as resetOpenAICodexWebSocketDebugStats,Ue as stream,Ut as streamSimple};
|
|
10
|
+
`)}if(i)break}}finally{r?.removeEventListener("abort",s);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var et="responses_websockets=2026-02-06",rt=300000,nt=3300000,g=new Map,B=new Map,I=new Set;function Z(e){let r=B.get(e);if(!r)r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},B.set(e,r);return r}function $t(e){let r=B.get(e);return r?{...r}:void 0}function zt(e){if(e){B.delete(e),I.delete(e);return}B.clear(),I.clear()}function st(e){let r=(t)=>{if(t.idleTimer)clearTimeout(t.idleTimer);C(t.socket,1000,"debug_close")};if(e){for(let t of g.get(e)?.values()??[])r(t);g.delete(e);return}for(let t of g.values())for(let n of t.values())r(n);g.clear()}eo(st);function me(e){return e?I.has(e):!1}function ie(e){if(!e)return;let r=Z(e);r.sseFallbacks++,r.websocketFallbackActive=me(e)}function ot(e,r){if(!e)return;I.add(e);let t=Z(e);t.websocketFailures++,t.lastWebSocketError=Xe(r),t.websocketFallbackActive=!0}var H=null;async function it(e){if(!e&&H)return H;if(typeof process<"u"&&process.versions?.bun){let t=class extends WebSocket{constructor(n,o){let s={};if(Array.isArray(o)||typeof o==="string")s={protocols:o};else s={...o};let i=Wr(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...i?{proxy:i.toString()}:{}})}};if(!e)H=t;return t}let r=globalThis.WebSocket;if(typeof r!=="function")return null;return r}class ye extends Error{code;reason;wasClean;constructor(e,r){super(e);this.name="WebSocketCloseError",this.code=r?.code,this.reason=r?.reason,this.wasClean=r?.wasClean}}function at(e){let r=e.readyState;return typeof r==="number"?r:void 0}function P(e){let r=at(e);return r===void 0||r===1}function ct(e){return Date.now()-e.createdAt>=nt}function C(e,r=1000,t="done"){try{e.close(r,t)}catch{}}function ae(e,r,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;C(t.socket,1000,"idle_timeout");let n=g.get(e);if(n?.get(r)===t)n.delete(r);if(n?.size===0)g.delete(e)},rt)}async function G(e,r,t,n=Ce,o){let s=await it(o);if(!s)throw Error("WebSocket transport is not available in this runtime");let i=Q(r);return delete i["OpenAI-Beta"],new Promise((u,a)=>{let d=!1,p,c;try{c=new s(e,{headers:i})}catch(w){a(w instanceof Error?w:Error(String(w)));return}let l=()=>{if(p)clearTimeout(p),p=void 0;c.removeEventListener("open",m),c.removeEventListener("error",b),c.removeEventListener("close",h),t?.removeEventListener("abort",E)},f=(w,v)=>{if(d)return;if(d=!0,l(),v)C(c,1000,v);a(w)},m=()=>{if(d)return;d=!0,l(),u(c)},b=(w)=>{f(be(w))},h=(w)=>{f(he(w))},E=()=>{f(Error("Request was aborted"),"aborted")};if(c.addEventListener("open",m),c.addEventListener("error",b),c.addEventListener("close",h),t?.addEventListener("abort",E),n>0)p=setTimeout(()=>{f(Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n);if(t?.aborted)E()})}async function ft(e,r,t,n,o,s,i){if(!t){let c=await G(e,r,o,s,i);return{socket:c,reused:!1,release:()=>C(c)}}let u=g.get(t),a=u?.get(n);if(a){if(a.idleTimer)clearTimeout(a.idleTimer),a.idleTimer=void 0;if(!a.busy&&ct(a)){if(C(a.socket,1000,"connection_age_limit"),u?.delete(n),u?.size===0)g.delete(t)}else if(!a.busy&&P(a.socket))return a.busy=!0,{socket:a.socket,entry:a,reused:!0,release:({keep:c}={})=>{if(!c||!P(a.socket)){C(a.socket);let l=g.get(t);if(l?.get(n)===a)l.delete(n);if(l?.size===0)g.delete(t);return}a.busy=!1,ae(t,n,a)}};if(a.busy){let c=await G(e,r,o,s,i);return{socket:c,reused:!1,release:()=>{C(c)}}}if(!P(a.socket)){if(C(a.socket),u?.delete(n),u?.size===0)g.delete(t)}}let d=await G(e,r,o,s,i),p={socket:d,busy:!0,createdAt:Date.now()};if(u=g.get(t),!u)u=new Map,g.set(t,u);return u.set(n,p),{socket:d,entry:p,reused:!1,release:({keep:c}={})=>{if(!c||!P(p.socket)){if(C(p.socket),p.idleTimer)clearTimeout(p.idleTimer);let l=g.get(t);if(l?.get(n)===p)l.delete(n);if(l?.size===0)g.delete(t);return}p.busy=!1,ae(t,n,p)}}}function be(e){if(e&&typeof e==="object"){let r="message"in e?e.message:void 0;if(typeof r==="string"&&r.length>0)return Error(r);let t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t==="object"&&"message"in t){let n=t.message;if(typeof n==="string"&&n.length>0)return Error(n)}}return Error("WebSocket error")}function he(e){if(e&&typeof e==="object"){let r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,o=typeof r==="number"?` ${r}`:"",s=typeof t==="string"&&t.length>0?` ${t}`:"";if(!s&&r===Ae)s=" message too big";return new ye(`WebSocket closed${o}${s}`.trim(),{code:typeof r==="number"?r:void 0,reason:typeof t==="string"&&t.length>0?t:void 0,wasClean:typeof n==="boolean"?n:void 0})}return Error("WebSocket closed")}async function lt(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}if(e&&typeof e==="object"&&"arrayBuffer"in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*dt(e,r,t){let n=[],o=null,s=!1,i=null,u=!1,a=()=>{if(!o)return;let f=o;o=null,f()},d=(f)=>{(async()=>{let m=null;try{if(!f||typeof f!=="object"||!("data"in f))return;if(m=await lt(f.data),!m)return;let b=JSON.parse(m),h=typeof b.type==="string"?b.type:"";if(h==="response.completed"||h==="response.done"||h==="response.incomplete")u=!0,s=!0;n.push(b),a()}catch(b){i=new F(`Invalid Codex WebSocket JSON: ${Xe(b)}`,{cause:b,payload:m}),s=!0,a()}})()},p=(f)=>{i=be(f),s=!0,a()},c=(f)=>{if(u){s=!0,a();return}if(!i)i=he(f);s=!0,a()},l=()=>{i=Error("Request was aborted"),s=!0,a()};e.addEventListener("message",d),e.addEventListener("error",p),e.addEventListener("close",c),r?.addEventListener("abort",l);try{while(!0){if(r?.aborted)throw Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let f;await new Promise((m,b)=>{if(o=m,t!==void 0&&t>0)f=setTimeout(()=>{let h=Error(`WebSocket idle timeout after ${t}ms`);i=h,s=!0,o=null,C(e,1000,"idle_timeout"),b(h)},t)}).finally(()=>{if(f)clearTimeout(f)})}if(i)throw i;if(!u)throw Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",d),e.removeEventListener("error",p),e.removeEventListener("close",c),r?.removeEventListener("abort",l)}}function ce(e){let{input:r,previous_response_id:t,...n}=e;return n}function mt(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}function yt(e,r){return JSON.stringify(ce(e))===JSON.stringify(ce(r))}function ht(e,r){if(!yt(e,r.lastRequestBody))return;let t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;let o=t.slice(0,n.length);if(!mt(o,n))return;return t.slice(n.length)}function wt(e,r){let t=e.continuation;if(!t)return r;let n=ht(r,t);if(!n||!t.lastResponseId)return e.continuation=void 0,r;return{...r,previous_response_id:t.lastResponseId,input:n}}async function*gt(e,r){let t=!1;for await(let n of e){if(!t)t=!0,r();yield n}}async function St(e,r,t,n,o,s,i,u,a,d,p,c,l){let{socket:f,entry:m,reused:b,release:h}=await ft(e,t,d,p,l?.signal,a,l?.env),E=!0,w=l?.transport==="websocket-cached"||l?.transport==="auto",v=r,T=w&&m?wt(m,v):v,y=d?Z(d):void 0;if(y){if(y.requests++,b)y.connectionsReused++;else y.connectionsCreated++;if(w)y.cachedContextRequests++;if(T.store===!0)y.storeTrueRequests++;if(y.lastInputItems=T.input?.length??0,T.previous_response_id)y.deltaRequests++,y.lastDeltaInputItems=T.input?.length??0,y.lastPreviousResponseId=T.previous_response_id;else y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0}try{if(f.send(JSON.stringify({type:"response.create",...T})),await pt(gt(pe(dt(f,l?.signal,u),n,s,l?.onProviderStreamEvent),i),n,o,s,{serviceTier:l?.serviceTier,grammarToolInputProperties:c,resolveServiceTier:le,applyServiceTierPricing:(x,A)=>fe(x,A,s)}),l?.signal?.aborted)E=!1;else if(w&&m&&n.responseId){let x=ut(s,bt({messages:[n]}),ue,{includeSystemPrompt:!1,grammarToolInputProperties:c}).filter((A)=>A.type!=="function_call_output"&&A.type!=="custom_tool_call_output");m.continuation={lastRequestBody:v,lastResponseId:n.responseId,lastResponseItems:x}}}catch(x){if(m)m.continuation=void 0;throw E=!1,x}finally{h({keep:E})}}async function Et(e){let r=await e.text(),t=r||e.statusText||"Request failed",n;try{let s=JSON.parse(r)?.error;if(s){let i=s.code||s.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){let u=s.plan_type?` (${s.plan_type.toLowerCase()} plan)`:"",a=s.resets_at?Math.max(0,Math.round((s.resets_at*1000-Date.now())/60000)):void 0,d=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${u}.${d}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function _t(e){try{let r=e.split(".");if(r.length!==3)throw Error("Invalid token");let n=JSON.parse(atob(r[1]))?.[_e]?.chatgpt_account_id;if(!n)throw Error("No account ID in token");return n}catch{throw Error("Failed to extract accountId from token")}}function we(e,r,t,n){let o=new Headers({originator:"pi","User-Agent":oe()});for(let[s,i]of Object.entries(e||{}))o.set(s,i);for(let[s,i]of Object.entries(r||{}))if(i===null)o.delete(s);else o.set(s,i);return o.set("Authorization",`Bearer ${n}`),o.set("chatgpt-account-id",t),o}function kt(e,r,t,n,o){let s=we(e,r,t,n);if(s.set("OpenAI-Beta","responses=experimental"),s.set("accept","text/event-stream"),s.set("content-type","application/json"),o)s.set("session-id",o),s.set("x-client-request-id",o);return s}function Tt(e,r,t,n,o){let s=we(e,r,t,n);return s.delete("accept"),s.delete("content-type"),s.delete("OpenAI-Beta"),s.delete("openai-beta"),s.set("OpenAI-Beta",et),s.set("x-client-request-id",o),s.set("session-id",o),s}export{st as closeOpenAICodexWebSocketSessions,$t as getOpenAICodexWebSocketDebugStats,zt as resetOpenAICodexWebSocketDebugStats,Ue as stream,Ut as streamSimple};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{G}from"./chunk-38g4jd6v.js";import{_}from"./chunk-ge38dhv9.js";import{Q,we}from"./chunk-tfhp09nj.js";import{U,jt,Ie}from"./chunk-4yxd2kg1.js";class u extends Error{code;diagnosticDetails;constructor(r,t,n){super(r);this.name="PiMessagesResponseError",this.code=t,this.diagnosticDetails=n}}function x(r){try{let t=JSON.parse(r),n=t?.error;return t&&typeof n==="object"&&n!==null&&!Array.isArray(n)?t:void 0}catch{return}}function m(r){return r.length>8192?`${r.slice(0,8192)}\u2026`:r}function y(r,t,n){let e=typeof n?.error?.message==="string"?n.error.message:void 0,s=typeof n?.error?.code==="string"?n.error.code:void 0,a=e??t,o=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${a}${o}`}function k(r,t,n,e){let s=x(e),a=typeof s?.error?.code==="string"?s.error.code:void 0;return new u(y(n,e,s),a,{version:1,provider:r.provider,model:r.id,url:t.toString(),status:n.status,statusText:n.statusText,...s?.error===void 0?{}:{error:s.error},...s?{}:{body:m(e)},timestampMs:Date.now()})}function h(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function l(r,t){if(!t)return;Ie(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}function w(r){let t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:h(),stopReason:"pending",timestamp:Date.now()},n=new Map;return(e)=>{switch(e.type){case"done":if(Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.providerThinkingLevel!==void 0)t.providerThinkingLevel=e.providerThinkingLevel;return l(t,e.rewrite),{type:"done",reason:e.reason,message:t};case"error":if(Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),e.providerThinkingLevel!==void 0)t.providerThinkingLevel=e.providerThinkingLevel;return l(t,e.rewrite),{type:"error",reason:e.reason,error:t};case"start":break;case"text_start":t.content[e.contentIndex]={type:"text",text:""};break;case"text_delta":t.content[e.contentIndex].text+=e.delta;break;case"text_end":Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case"thinking_start":t.content[e.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":t.content[e.contentIndex].thinking+=e.delta;break;case"thinking_end":Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case"toolcall_start":t.content[e.contentIndex]={type:"toolCall",id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,"");break;case"toolcall_delta":{let s=`${n.get(e.contentIndex)??""}${e.delta}`;n.set(e.contentIndex,s),t.content[e.contentIndex].arguments=G(s);break}case"toolcall_end":return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:"toolcall_end",contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*b(r){let t=new TextDecoder,n=r.getReader(),e="";try{while(!0){let{done:s,value:a}=await n.read();e+=s?t.decode():t.decode(a,{stream:!0}),e=e.replace(/\r\n/g,`
|
|
3
3
|
`);let o=e.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);while(o!==-1){let c=f(e.slice(0,o));if(c)yield c;e=e.slice(o+2),o=e.indexOf(`
|
|
6
6
|
|
|
7
7
|
`)}if(s)break}if(e.trim()){let s=f(e);if(s)yield s}}finally{n.releaseLock()}}function f(r){let t=r.split(`
|
|
8
|
-
`).find((n)=>n.startsWith("data:"))?.slice(5).trim();return t&&t!=="[DONE]"?JSON.parse(t):void 0}function I(r,t,n){let e=n?"aborted":"error",s={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:h(),stopReason:e,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()};if(!n&&t instanceof u)
|
|
8
|
+
`).find((n)=>n.startsWith("data:"))?.slice(5).trim();return t&&t!=="[DONE]"?JSON.parse(t):void 0}function I(r,t,n){let e=n?"aborted":"error",s={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:h(),stopReason:e,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()};if(!n&&t instanceof u)Ie(s,jt("pi_messages_response_failure",t,t.diagnosticDetails));return{type:"error",reason:e,error:s}}function E(r,t){if(r)return r;return _("PI_CACHE_RETENTION",t)==="long"?"long":void 0}var T=(r,t,n)=>{let e=new U,s=w(r);return(async()=>{try{let a=n?.apiKey;if(!a)throw Error(`No API key provided for provider "${r.provider}"`);let o=new URL(`${r.baseUrl.replace(/\/+$/u,"")}/messages`);if(n?.debug)o.searchParams.set("debug","1");let c={model:r.id,context:t,options:{temperature:n?.temperature,maxTokens:n?.maxTokens,reasoning:n?.reasoning,cacheRetention:E(n?.cacheRetention,n?.env),sessionId:n?.sessionId,toolChoice:n?.toolChoice}},p=await n?.onPayload?.(c,r);if(p!==void 0)c=p;let i=await(n?.fetch??globalThis.fetch)(o,{method:"POST",headers:{authorization:`Bearer ${a}`,accept:"text/event-stream","content-type":"application/json",...we(n?.headers)},body:JSON.stringify(c),signal:n?.signal});if(await n?.onResponse?.({status:i.status,headers:Q(i.headers)},r),!i.ok){let d=await i.text();throw k(r,o,i,d)}if(!i.body)throw Error(`${r.provider} response has no body`);for await(let d of b(i.body)){await n?.onProviderStreamEvent?.(d,r);let g=s(d);if(e.push(g),g.type==="done"||g.type==="error")return}throw Error(`${r.provider} stream ended without a terminal event`)}catch(a){e.push(I(r,a,n?.signal?.aborted??!1))}})(),e},P=(r,t,n)=>{let e=n;return T(r,t,{...n,reasoning:n?.reasoning,toolChoice:n?.toolChoice,debug:e?.debug})};export{u as PiMessagesResponseError,T as stream,P as streamSimple};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{pe,$e,Br,Fr}from"./chunk-xq74x4gc.js";import{V,J}from"./chunk-8np9b2y8.js";var o="OpenAI Decisions",a=128;function f(r){let t=[r.criteria.true?`True means: ${r.criteria.true}`:"",r.criteria.false?`False means: ${r.criteria.false}`:""].filter(Boolean);return t.length>0?`${r.instructions}
|
|
3
3
|
|
|
4
4
|
${t.join(`
|
|
5
|
-
`)}`:r.instructions}function u(r,t){if(t.type==="choice")return{type:"choice",name:r,instructions:t.instructions,choices:Object.entries(t.criteria).map(([e,i])=>i?{value:e,description:i}:{value:e})};if(t.type==="score")return{type:"score",name:r,instructions:t.instructions,levels:t.criteria.map((e)=>({label:e}))};return{type:"predicate",name:r,instructions:f(t)}}function y(r){let t=JSON.stringify(r.state),e=r.images??[];if(e.length===0)return t;if(e.length>a)throw Error(`${o} accepts at most ${a} images, got ${e.length}`);return[{role:"user",content:[{type:"input_text",text:t},...e.map((i)=>({type:"input_image",image_url:`data:${i.mimeType};base64,${i.data}`}))]}]}function b(r,t){if(!Array.isArray(r))throw Error(`${o} returned invalid probabilities for ${t}`);return Object.fromEntries(r.map((e)=>{if(!
|
|
5
|
+
`)}`:r.instructions}function u(r,t){if(t.type==="choice")return{type:"choice",name:r,instructions:t.instructions,choices:Object.entries(t.criteria).map(([e,i])=>i?{value:e,description:i}:{value:e})};if(t.type==="score")return{type:"score",name:r,instructions:t.instructions,levels:t.criteria.map((e)=>({label:e}))};return{type:"predicate",name:r,instructions:f(t)}}function y(r){let t=JSON.stringify(r.state),e=r.images??[];if(e.length===0)return t;if(e.length>a)throw Error(`${o} accepts at most ${a} images, got ${e.length}`);return[{role:"user",content:[{type:"input_text",text:t},...e.map((i)=>({type:"input_image",image_url:`data:${i.mimeType};base64,${i.data}`}))]}]}function b(r,t){if(!Array.isArray(r))throw Error(`${o} returned invalid probabilities for ${t}`);return Object.fromEntries(r.map((e)=>{if(!pe(e)||typeof e.value!=="string")throw Error(`${o} returned invalid probabilities for ${t}`);return[e.value,$e(o,e.probability,`probability for ${t}.${e.value}`)]}))}function l(r,t,e){if(e.type==="refusal")throw Error(`${o} refused to answer ${r}`);if(t.type==="choice"){if(e.type!=="choice"||typeof e.choice!=="string")throw Error(`${o} did not return a choice answer for ${r}`);return{type:"choice",choice:e.choice,probabilities:b(e.probabilities,r),confidence:$e(o,e.confidence,`confidence for ${r}`)}}if(t.type==="score"){if(e.type!=="score")throw Error(`${o} did not return a score answer for ${r}`);return{type:"score",score:$e(o,e.score,`score for ${r}`),confidence:$e(o,e.confidence,`confidence for ${r}`)}}if(e.type!=="predicate")throw Error(`${o} did not return a predicate answer for ${r}`);return{type:"bool",probability:$e(o,e.probability,`probability for ${r}`)}}function w(r,t){if(!Array.isArray(r))throw Error(`${o} returned an unexpected response`);let e=new Map;for(let i of r)if(pe(i)&&typeof i.name==="string")e.set(i.name,i);return Object.fromEntries(Object.entries(t.questions).map(([i,n])=>{let s=e.get(i);if(!s)throw Error(`${o} did not return an answer for ${i}`);return[i,l(i,n,s)]}))}var h=[504];function d(r){if(r.status===504)return`${o} error (504): the request timed out at the gateway. Very large inputs (above roughly 600K tokens) currently exceed its time limit.`;return J(V(r),`${o} error`)}var E=async(r,t,e)=>{let i={api:r.api,provider:r.provider,model:r.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(r.api!=="openai-decisions")throw Error(`Unsupported classifier API: ${r.api}`);let n=await Br(o,new URL("decisions",`${r.baseUrl.replace(/\/+$/u,"")}/`),r,{model:r.id,input:y(t),questions:Object.entries(t.questions).map(([c,p])=>u(c,p))},e,h);if(!pe(n))throw Error(`${o} returned an unexpected response`);let s=Fr(n.usage,r);if(s)i.usage=s;return i.answers=w(n.answers,t),i}catch(n){return i.answers={},i.stopReason=e?.signal?.aborted?"aborted":"error",i.errorMessage=d(n),i}};export{E as classify};
|