@bkm016/basalt 0.1.10 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{chunk-755sy11p.js → chunk-01nve4qy.js} +1 -1
- package/{chunk-jtsve11b.js → chunk-0fc9apfn.js} +9 -9
- package/{chunk-d5j74pcp.js → chunk-1h34mzh7.js} +4 -4
- package/{chunk-fgwda4m0.js → chunk-1xfv4bd7.js} +1 -1
- package/{chunk-mbpb5c7w.js → chunk-2fyjph3f.js} +1 -1
- package/{chunk-13gvs0ax.js → chunk-2kxnw7vs.js} +1 -1
- package/{chunk-95964592.js → chunk-37zystxb.js} +11 -11
- package/{chunk-h1kb8b49.js → chunk-3pf1d62g.js} +2 -2
- package/{chunk-29qrxygd.js → chunk-5wnmbc1b.js} +2 -2
- package/{chunk-c71173py.js → chunk-6mges89p.js} +4 -4
- package/{chunk-d0a1jxk5.js → chunk-6sz5q3df.js} +2 -2
- package/chunk-7er5pz7s.js +479 -0
- package/{chunk-gbjn6d81.js → chunk-7g5smgjj.js} +1 -1
- package/chunk-7m3jagqn.js +2 -0
- package/{chunk-wnzvnskb.js → chunk-85v69h91.js} +2 -2
- package/{chunk-38g3gctw.js → chunk-9c4gdg1q.js} +2 -2
- package/{chunk-en218k4y.js → chunk-cbgpymt4.js} +1 -1
- package/{chunk-a1rb1a48.js → chunk-cdw03j4t.js} +2 -2
- package/chunk-ch1r3ted.js +2 -0
- package/{chunk-dfh9m9n7.js → chunk-db7ws33a.js} +2 -2
- package/{chunk-1n7dat03.js → chunk-ejjem0tc.js} +3 -3
- package/{chunk-c4qr1f41.js → chunk-eq4wqxzt.js} +2 -2
- package/{chunk-zc9ar0r4.js → chunk-eyrtbbdd.js} +1 -1
- package/{chunk-r4ttdkrz.js → chunk-fhxy6y34.js} +2 -2
- package/{chunk-zyyzk5ha.js → chunk-fy82qxa1.js} +1 -1
- package/{chunk-xtq1xpq0.js → chunk-hc300148.js} +1 -1
- package/{chunk-vtqr7dm8.js → chunk-j64dc767.js} +2 -2
- package/{chunk-msm9hmk9.js → chunk-jpnf71q7.js} +2 -2
- package/{chunk-q9f4xb0w.js → chunk-kpe7pnhy.js} +4 -4
- package/{chunk-a98wma9j.js → chunk-ksk49hv0.js} +1 -1
- package/{chunk-bdjr0kfr.js → chunk-m4bg1apa.js} +5 -5
- package/{chunk-dq01v5eq.js → chunk-nhm9z3d8.js} +1 -1
- package/{chunk-30rjf7my.js → chunk-ntks40jd.js} +2 -2
- package/{chunk-a1352w87.js → chunk-nw1xpt3s.js} +1 -1
- package/{chunk-xh444pfn.js → chunk-p2pmdbt2.js} +8 -8
- package/{chunk-hb4f2v34.js → chunk-qfcr5g35.js} +2 -2
- package/{chunk-n2jcx65v.js → chunk-qs8zzg50.js} +2 -2
- package/{chunk-qaeyhe65.js → chunk-r4gm8ngh.js} +1 -1
- package/{chunk-pz2afna8.js → chunk-rks90mh1.js} +1 -1
- package/{chunk-asyr3gnq.js → chunk-rwks9zaw.js} +2 -2
- package/{chunk-v3ee9z3f.js → chunk-t7te60m7.js} +1 -1
- package/{chunk-4dw43syb.js → chunk-tv52xajf.js} +1 -1
- package/{chunk-c0zfefq8.js → chunk-v7wcchy2.js} +1 -1
- package/{chunk-tevejprz.js → chunk-vjne04dp.js} +3 -3
- package/{chunk-ax04trym.js → chunk-w0rr66z7.js} +1 -1
- package/{chunk-gkf5jwvj.js → chunk-w6f2r052.js} +1 -1
- package/{chunk-0mjb3sm3.js → chunk-wqqjzsjt.js} +327 -282
- package/{chunk-c6q04xrd.js → chunk-xef4642x.js} +1 -1
- package/compiled.js +7 -7
- package/package.json +1 -1
- package/ui-test-worker.js +2 -2
- package/web/chunk-04drx71p.js +1 -0
- package/web/chunk-0mdf1qja.js +1 -0
- package/web/chunk-0rdgt4jb.css +1 -0
- package/web/{chunk-nawxgz87.js → chunk-19zd0tye.js} +8 -8
- package/web/chunk-1m0kp0g3.js +8 -0
- package/web/{chunk-07agqp8h.js → chunk-1zwc09e8.js} +2 -2
- package/web/{chunk-fmmrthpa.js → chunk-2cyzaqjy.js} +3 -3
- package/web/{chunk-vasppf6b.js → chunk-2jfesv7m.js} +2 -2
- package/web/{chunk-mykrm8ba.js → chunk-30aeb767.js} +2 -2
- package/web/chunk-3j2tcphs.js +1 -0
- package/web/chunk-3k9h7a73.js +1142 -0
- package/web/chunk-3m1bb2fw.js +1 -0
- package/web/{chunk-88wd49xe.js → chunk-3n9ypydh.js} +2 -2
- package/web/{chunk-sd3xat3r.js → chunk-3psgr0q8.js} +13 -13
- package/web/{chunk-yppgejg7.js → chunk-3qxxrwsp.js} +10 -10
- package/web/{chunk-js6kb05s.js → chunk-3rkkp6ed.js} +6 -6
- package/web/{chunk-tqze6d6b.js → chunk-4f6a8dsk.js} +1 -1
- package/web/{chunk-eqndhs21.js → chunk-4wwd3pfz.js} +2 -2
- package/web/chunk-55nvm2mj.js +1 -0
- package/web/chunk-5dkqfnh7.js +2 -0
- package/web/{chunk-zms6mrqk.js → chunk-5g8md2wg.js} +5 -5
- package/web/{chunk-h5ckjk48.js → chunk-5np514v5.js} +12 -12
- package/web/{chunk-z4bp6p32.js → chunk-60mym60n.js} +1 -1
- package/web/{chunk-bc3ajvfg.js → chunk-6f2sz84q.js} +2 -2
- package/web/{chunk-frnh4zqf.js → chunk-6jb2zyp6.js} +2 -2
- package/web/{chunk-g7dc4hrd.js → chunk-7adsmqv6.js} +1 -1
- package/web/{chunk-g7kz8f7q.js → chunk-7ksg3ccg.js} +5 -5
- package/web/chunk-7ky5nrrr.js +1 -0
- package/web/{chunk-sc63488q.js → chunk-7v85yvb2.js} +1 -1
- package/web/chunk-7vgh17es.js +1 -0
- package/web/chunk-80z8s8zb.js +2 -0
- package/web/{chunk-rxvm70w5.js → chunk-81s15c2e.js} +2 -2
- package/web/{chunk-knm82fw9.js → chunk-8539865x.js} +1 -1
- package/web/{chunk-jccz14ye.js → chunk-885kpj14.js} +2 -2
- package/web/{chunk-26ecc2xh.js → chunk-8cnjd0f2.js} +5 -5
- package/web/chunk-8sdjgv3k.js +1 -0
- package/web/chunk-9bxtzwtc.js +1 -0
- package/web/chunk-9jy8nc4r.js +1 -0
- package/web/{chunk-c57f714b.js → chunk-aa46mrgh.js} +2 -2
- package/web/{chunk-gw8x1g61.js → chunk-act3rr85.js} +1 -1
- package/web/chunk-aebrw6cv.js +39 -0
- package/web/{chunk-j37p0b13.js → chunk-aeymdtm1.js} +3 -3
- package/web/{chunk-8h2x89tw.js → chunk-ar6jnhm5.js} +1 -1
- package/web/{chunk-tfqarvdx.js → chunk-b5zf1hs3.js} +59 -59
- package/web/{chunk-m4fxd5d9.js → chunk-b99k8q22.js} +8 -8
- package/web/chunk-bcjgzwef.js +1 -0
- package/web/{chunk-jke2ev6m.js → chunk-bra33pt0.js} +2 -2
- package/web/{chunk-myd6sc76.js → chunk-bygwbpvq.js} +1 -1
- package/web/{chunk-zse05v6j.js → chunk-c3fty2c2.js} +9 -9
- package/web/chunk-cxpnj495.js +2 -0
- package/web/{chunk-x850q01z.js → chunk-d1btrqmw.js} +1 -1
- package/web/{chunk-qdzy124b.js → chunk-d57fm7k0.js} +2 -2
- package/web/{chunk-j89s11x8.js → chunk-d73zkc4q.js} +4 -4
- package/web/chunk-d94t9z70.js +1 -0
- package/web/chunk-de29pe57.js +1 -0
- package/web/{chunk-rag65pfs.js → chunk-dndd757x.js} +3 -3
- package/web/chunk-e68jw0bg.js +1 -0
- package/web/{chunk-grm2208k.js → chunk-e94pd9rr.js} +13 -13
- package/web/{chunk-zz1qkaar.js → chunk-enwfd8d5.js} +2 -2
- package/web/{chunk-qq6m2my8.js → chunk-fj753yzt.js} +2 -2
- package/web/chunk-fr4fft89.js +1 -0
- package/web/{chunk-5svqfj4g.js → chunk-g488hxx0.js} +3 -3
- package/web/{chunk-0770q5e1.js → chunk-g4zm0crw.js} +1 -1
- package/web/chunk-gckmcef6.js +1 -0
- package/web/{chunk-se4h6wx0.js → chunk-gkmaryr4.js} +1 -1
- package/web/chunk-gnb09wmx.js +1 -0
- package/web/{chunk-6e87m0nm.js → chunk-gten0rpx.js} +2 -2
- package/web/chunk-h24ybwp6.js +1 -0
- package/web/{chunk-z5qn0xev.js → chunk-h754ntg7.js} +2 -2
- package/web/{chunk-tt93zbn4.js → chunk-hn8m1vsg.js} +7 -7
- package/web/{chunk-rh3xb76f.js → chunk-hqxc9m07.js} +10 -10
- package/web/chunk-hrgqc1vr.js +1 -0
- package/web/{chunk-3eexx7y5.js → chunk-hva7xyne.js} +2 -2
- package/web/chunk-hxbfkdjd.js +1 -0
- package/web/chunk-j9c8fa82.js +1 -0
- package/web/{chunk-5v5q13hz.js → chunk-jeafmjsm.js} +2 -2
- package/web/chunk-jyf7a7yp.js +2 -0
- package/web/chunk-jz5mmp64.js +1 -0
- package/web/{chunk-18neka5g.js → chunk-k4dnjf8n.js} +5 -5
- package/web/{chunk-32ty2xfn.js → chunk-kerfb21g.js} +1 -1
- package/web/chunk-kxeaj44h.js +1 -0
- package/web/chunk-m0136xav.js +1 -0
- package/web/chunk-m1rdyvb5.js +1 -0
- package/web/chunk-m6vyvgm5.js +1 -0
- package/web/{chunk-w3zgfhjb.js → chunk-mxkbmgcv.js} +2 -2
- package/web/chunk-my0ec787.js +1 -0
- package/web/{chunk-qy1zx2yw.js → chunk-n9v14vyd.js} +22 -22
- package/web/{chunk-x5g1yy12.js → chunk-ncfzmf2g.js} +1 -1
- package/web/chunk-nkpdd9hw.js +1 -0
- package/web/chunk-ny436sqg.js +1 -0
- package/web/chunk-pbp1p5ex.js +1 -0
- package/web/chunk-ph75hddv.js +1 -0
- package/web/chunk-phdfyqaa.js +1 -0
- package/web/chunk-phxa5krt.js +1 -0
- package/web/{chunk-wrevb4ew.js → chunk-pjpre6de.js} +6 -6
- package/web/{chunk-vvvd3grf.js → chunk-pzg25qqe.js} +2 -2
- package/web/chunk-q1zxvjhs.js +2 -0
- package/web/{chunk-1qh7f5kr.js → chunk-qdd3bx8q.js} +1 -1
- package/web/{chunk-9yfftz38.js → chunk-qp3tjhaq.js} +1 -1
- package/web/chunk-r4zbw4zj.js +2 -0
- package/web/{chunk-1ev0n3n4.js → chunk-r6kk4vp1.js} +2 -2
- package/web/{chunk-n4yzs2q0.js → chunk-rdr6wt22.js} +4 -4
- package/web/chunk-ry4ycah9.js +1 -0
- package/web/{chunk-de40q05r.js → chunk-sdr5wa4z.js} +3 -3
- package/web/chunk-sqm16fat.js +1 -0
- package/web/{chunk-gsw1tv96.js → chunk-td83xf12.js} +1 -1
- package/web/{chunk-t5nvgz7z.js → chunk-v0wtk059.js} +7 -7
- package/web/{chunk-pgwf37s2.js → chunk-v1hfbjz9.js} +5 -5
- package/web/chunk-v1qt3gq4.js +1 -0
- package/web/{chunk-wtvch4ad.js → chunk-v34mr9ky.js} +9 -9
- package/web/chunk-v854w9yn.js +1 -0
- package/web/{chunk-xtn305fd.js → chunk-ve56gxq0.js} +1 -1
- package/web/chunk-w573ym17.js +1 -0
- package/web/{chunk-dv1berk6.js → chunk-w9gnqkez.js} +2 -2
- package/web/{chunk-q4bst4an.js → chunk-wqzbxzk3.js} +1 -1
- package/web/{chunk-rwfmccmh.js → chunk-wvrs986a.js} +4 -4
- package/web/chunk-x0mjydtp.js +1 -0
- package/web/{chunk-awkdw9rw.js → chunk-xbyrgyy0.js} +2 -2
- package/web/{chunk-p55vhns6.js → chunk-xpecre7w.js} +4 -4
- package/web/{chunk-ehtmb6sn.js → chunk-xvfeq8v2.js} +13 -13
- package/web/{chunk-rbqnre6q.js → chunk-yf8ykk4v.js} +4 -4
- package/web/{chunk-sjkg40ay.js → chunk-yjs6jmdb.js} +1 -1
- package/web/chunk-ym7kv2hs.js +1 -0
- package/web/chunk-zhybh04p.js +1 -0
- package/web/index.html +1 -1
- package/worker.js +1 -1
- package/chunk-3mqf9ped.js +0 -479
- package/chunk-7zkswxvk.js +0 -2
- package/chunk-m1eam0s5.js +0 -2
- package/web/chunk-045d3b5d.js +0 -1
- package/web/chunk-12qf1r6m.js +0 -1
- package/web/chunk-1ex3wgms.js +0 -2
- package/web/chunk-2cz7tx8q.js +0 -1
- package/web/chunk-46jnkghq.js +0 -2
- package/web/chunk-4am8j3k3.js +0 -1
- package/web/chunk-5qvmefq2.js +0 -1
- package/web/chunk-5z2n4z9x.css +0 -1
- package/web/chunk-6y55gk1n.js +0 -1
- package/web/chunk-7np1jp3x.js +0 -8
- package/web/chunk-7qq1ypvj.js +0 -1
- package/web/chunk-87e8d1hv.js +0 -1
- package/web/chunk-8y2526ve.js +0 -1
- package/web/chunk-905vw286.js +0 -2
- package/web/chunk-918e5t4x.js +0 -2
- package/web/chunk-96m2m3e8.js +0 -1
- package/web/chunk-9f4zzqbx.js +0 -1
- package/web/chunk-a1n4468c.js +0 -1
- package/web/chunk-arnzrqnm.js +0 -1
- package/web/chunk-b46ws7rf.js +0 -1
- package/web/chunk-bwy3e58v.js +0 -1
- package/web/chunk-d5gshd1a.js +0 -1
- package/web/chunk-dp0k5vhd.js +0 -1
- package/web/chunk-eh7wp62z.js +0 -2
- package/web/chunk-et1hytyv.js +0 -1
- package/web/chunk-f7jpakwh.js +0 -1
- package/web/chunk-f9m9seam.js +0 -1
- package/web/chunk-g2erm7k0.js +0 -1
- package/web/chunk-g3kbn0t2.js +0 -1
- package/web/chunk-ght0t49g.js +0 -1
- package/web/chunk-ghwm7bdj.js +0 -2
- package/web/chunk-h2txs73e.js +0 -39
- package/web/chunk-h3tkacc7.js +0 -1
- package/web/chunk-je78j3vr.js +0 -1
- package/web/chunk-kxdtg9dt.js +0 -1
- package/web/chunk-m9xzt9p7.js +0 -1
- package/web/chunk-ngt1j8py.js +0 -1139
- package/web/chunk-q34as3v6.js +0 -1
- package/web/chunk-qe0bgeda.js +0 -1
- package/web/chunk-sat7zyva.js +0 -1
- package/web/chunk-sk0hpa80.js +0 -1
- package/web/chunk-tvcxrx6h.js +0 -1
- package/web/chunk-tzpnh70q.js +0 -1
- package/web/chunk-vb7g4xg6.js +0 -1
- package/web/chunk-wzfe6jtq.js +0 -1
- package/web/chunk-xh4xn1az.js +0 -1
- package/web/chunk-xk904wqv.js +0 -1
- package/web/chunk-xzwxcxb4.js +0 -1
- package/web/chunk-yekaz74b.js +0 -1
- package/web/chunk-ys2tns0p.js +0 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{So,St,st,w,un,wo}from"./chunk-b2bxqeb4.js";import{o,e,u,Ot,vt,
|
|
3
|
-
`);if(r[r.length-1]==="")r.pop();return r}function Mt(a,r){return/^[\x20-\x7E]+$/.test(r)&&!/[\\^#]/.test(r)&&!(a==="unzip"&&r.startsWith("-"))}function kt(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(!Mt(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
|
|
2
|
+
import{So,St,st,w,un,wo}from"./chunk-b2bxqeb4.js";import{o,e,u,Ot,vt,k,pe,E,Po,Mr,Dt}from"./chunk-j64dc767.js";import*as b from"fs/promises";import*as ne from"fs";import*as v from"path";import*as $e from"child_process";import*as ct from"crypto";import*as lt from"readline";function C(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 F=st.promises,J=448,yt=384;function ae(a,r){let t=w.relative(a,r);return t===""||!t.startsWith(".."+w.sep)&&t!==".."&&!w.isAbsolute(t)}async function Ee(a,r){for(let t of a)if(ae(await X(w.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 F.realpath(t)}catch(s){let c;try{c=(await F.lstat(t)).isSymbolicLink()}catch(l){let f=Z(l);if(f!=="ENOENT"&&f!=="ENOTDIR")throw l;let h=w.dirname(t);if(h===t)throw l;r.push(w.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=w.resolve(w.dirname(t),await F.readlink(t));continue}return r.length?w.join(n,...r.reverse()):n}}async function Ae(a,r,t){let i=t?.allowedRoots??[],n=await X(w.resolve(a)),s;try{s=await X(w.resolve(n,r))}catch(l){throw new E(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 E(`path ${JSON.stringify(r)} is outside ${c}`)}async function be(a,r){let t=w.dirname(a),i=w.join(t,`.tmp-${process.pid}-${St.randomUUID()}`),n=await F.stat(a).then((c)=>c.mode&511,()=>{return}),s;try{if(s=await F.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 F.rename(i,a)}catch(c){if(s)await s.close().catch(()=>{});throw await F.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 N=st.promises,_t=wo.promisify(So.execFile);async function gt(a){let{client:r,sessionId:t}=a;if(!r)return async()=>{};let i=k(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=w.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=w.basename(f.name.trim());if(h===""||h==="."||h==="..")h=l.skill_id;let d=w.resolve(s,h);if(d!==s&&!d.startsWith(s+w.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 N.rm(d,{recursive:!0,force:!0}),await N.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 N.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 Et(a){for(let r of a){let t=r.trim();if(!t)continue;if(w.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 Mt(a,r){return/^[\x20-\x7E]+$/.test(r)&&!/[\\^#]/.test(r)&&!(a==="unzip"&&r.startsWith("-"))}function kt(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(!Mt(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 N.readdir(a,{withFileTypes:!0}))if(r.isDirectory())await De(w.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 It(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=w.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),st.createWriteStream(t));let i=w.join(w.dirname(r),`.skill-stage-${process.pid}-${Date.now()}`),n=w.join(w.dirname(r),`.skill-exclude-${process.pid}-${Date.now()}`);try{let s=await Nt(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}=kt(l,f,h);Et([...d,...m]);let g=It(d);if(await N.mkdir(i,{recursive:!0,mode:J}),d.length>0)await Oe(l,await Rt(l,t,i,m,n));await De(i);let O=g?w.join(i,g):i,D=await N.readdir(O).catch((I)=>{throw Z(I)==="ENOENT"?new u(Me):I});for(let I of D)await N.rename(w.join(O,I),w.join(r,I))}finally{await N.rm(t,{force:!0}),await N.rm(n,{force:!0}),await N.rm(i,{recursive:!0,force:!0})}}async function Rt(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 N.writeFile(n,s.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{flag:"wx",mode:384}),["-xf",r,"-C",t,"-X",n]}async function Nt(a,r){let t=await
|
|
6
|
-
${a}`,"utf-8").digest("hex")}var qt=30000,zt=100,Gt=20,Ht=16,Kt=32,Vt=8,Xt=50;class P 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){_.add(this),L.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),A.set(this,[]),o(this,L,r,"f"),o(this,le,t.workdir,"f"),o(this,Q,t.syncIntervalMs??
|
|
7
|
-
${t.memoryStoreId}`);for await(let[i,n]of e(this,_,"m",me).call(this,t.memoryStoreId,"full"))if(await e(this,_,"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 g=await e(this,_,"m",Ke).call(this,t,i,l);if(g===void 0)return;if(g===l)return l;s=g}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,_,"m",
|
|
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=b.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),M.set(this,void 0),
|
|
5
|
+
`,{flag:"wx",mode:384}),["-xf",r,"-C",t,"-X",n]}async function Nt(a,r){let t=await N.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 S=st.promises,z=st.constants,Ue=448,Tt=384,Lt=448,ke=z.O_NOFOLLOW??0,$t=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(!At())throw Error("FileStore requires O_NOFOLLOW support on this platform");let i=!1;try{await S.lstat(r)}catch(n){if(n.code!=="ENOENT")throw n;i=!0}return new a(w.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 S.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"?Ot(t):t;this.requireUtf8(r,c),await Fe(this.rootPath,w.dirname(s)),await Ct(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 Pt(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 S.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=w.relative(this.rootPath,t).split(w.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 S.stat(n).then(()=>!0,()=>!1))throw new y(y.MOVE_DESTINATION_EXISTS,t);await Fe(this.rootPath,w.dirname(n)),await S.rename(i,n)}async remove(r){let t=this.resolveUnderRoot(r);if(t===this.rootPath)return;let i;try{i=await S.lstat(t,{bigint:!0})}catch(n){if(n.code==="ENOENT")return;throw n}if(i.isDirectory())await S.rm(t,{recursive:!0,force:!0});else try{await S.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(w.posix.isAbsolute(t)||i.includes(".."))throw new y(y.ESCAPES_ROOT,r);return i.length===0?this.rootPath:w.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 S.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&&Ut(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(jt(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 At(){return ke!==0}async function xt(a){let r=[],t=a;for(;;){try{await S.stat(t);break}catch(n){let s=n.code;if(s!=="ENOENT"&&s!=="ENOTDIR"&&s!=="ELOOP")throw n}r.push(t);let i=w.dirname(t);if(i===t)break;t=i}for(let i of r.reverse())try{await S.mkdir(i,{mode:Ue})}catch(n){if(n.code!=="EEXIST")throw n}}async function Fe(a,r){let t=w.relative(a,r);if(t==="")return;let i=a;for(let n of t.split(w.sep)){i=w.join(i,n);try{await S.mkdir(i,{mode:Ue})}catch(s){if(s.code!=="EEXIST")throw s}}}async function Ct(a,r,t){let i=t?Lt:Tt,n=w.join(w.dirname(a),`.fs-${St.randomBytes(8).toString("hex")}.tmp`),s;try{s=await S.open(n,z.O_WRONLY|z.O_CREAT|z.O_EXCL|ke,i),await s.writeFile(r),await s.close(),s=void 0,await S.rename(n,a)}catch(c){if(s)await s.close().catch(()=>{});throw await S.unlink(n).catch(()=>{}),c}}async function je(a,r){let t;try{t=await S.open(r,z.O_RDONLY|ke|$t)}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 Ft(a){let r=St.createHash("sha256"),t=await je(w.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 Wt(r,t))return[];let i=[];return await Be(t,(n,s)=>{if(s.isFile())i.push([w.relative(a,n).split(w.sep).join("/"),n])}),i.sort(),i}async function Pt(a,r,t){let i=(c)=>w.relative(a,c).split(w.sep).join("/"),n;try{n=await S.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 Wt(a,r){let t;try{t=await S.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 S.readdir(i,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of n){let c=w.join(i,s.name);if(r(c,s),s.isDirectory()&&!s.isSymbolicLink())t.push(c)}}}function Ut(a,r){return r.mtimeNs===a.mtimeNs&&r.ctimeNs===a.ctimeNs&&r.size===a.size}function jt(a,r){return(a.mtimeNs>a.ctimeNs?a.mtimeNs:a.ctimeNs)<r-ce.timestampTrustMarginNs}var Bt=2000000000n,ce={hashFile:Ft,timestampTrustMarginNs:Bt,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 _,L,le,Q,fe,p,G,de,A,qe,he,ze,Ge,Re,Ne,He,Ke,Te,Ve,Xe,me,ue,Je,Ze,Yt=30000,K=".anthropic-memory-store",et=1;function Qe(a){return St.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 P 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){_.add(this),L.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),A.set(this,[]),o(this,L,r,"f"),o(this,le,t.workdir,"f"),o(this,Q,t.syncIntervalMs??Po,"f"),Mr(e(this,Q,"f"),"syncIntervalMs"),o(this,fe,t.syncDeletions??"enabled","f"),o(this,p,k(r),"f"),o(this,G,Date.now(),"f")}get roots(){return e(this,A,"f").map((r)=>r.files.root().path)}get readOnlyRoots(){return e(this,A,"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,_,"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 P(`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 P(`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,_,"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,A,"f").push(n)}catch(s){if(n)await n.files.dispose().catch(()=>{});if(s instanceof P)throw s;throw new P(`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,A,"f").map((t)=>e(this,_,"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,A,"f").map((t)=>e(this,_,"m",Ge).call(this,t,r)))}async dispose(){for(let r of e(this,A,"f")){let t=r.files.root();try{let i=await e(this,_,"m",he).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 L=new WeakMap,le=new WeakMap,Q=new WeakMap,fe=new WeakMap,p=new WeakMap,G=new WeakMap,de=new WeakMap,A=new WeakMap,_=new WeakSet,qe=function(t){if(t.mount_path){if(!Ie(t.mount_path))throw new P(`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 w.join(e(this,le,"f"),"memory",t.name||t.memory_store_id)},he=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,_,"m",he).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,_,"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,_,"m",Re).call(this,t,"every memory file is gone at once");return}let c=new Map;for await(let[m,g]of e(this,_,"m",me).call(this,t.memoryStoreId))c.set(m,g);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 g=c.get(m),O=s[m],D=t.baseline.get(m),I;if(O===void 0&&D!==void 0&&g!==void 0&&g.content_sha256===D&&!t.readOnly)I=await e(this,_,"m",Je).call(this,t,m,g,D,l);else I=await e(this,_,"m",He).call(this,t,m,g,O,f);if(I!==void 0)h.set(m,I)}if(t.baseline=h,await e(this,_,"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,_,"m",he).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,_,"m",me).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),g=t.baseline.get(d),O=f.get(d);if(O!==void 0&&O.content_sha256===m){t.baseline.set(d,O.content_sha256),s.delete(d);continue}if(O!==void 0&&O.content_sha256!==g){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,O])}await e(this,_,"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,_,"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,_,"m",me).call(this,t.memoryStoreId,"full"))if(await e(this,_,"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 g=await e(this,_,"m",Ke).call(this,t,i,l);if(g===void 0)return;if(g===l)return l;s=g}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,_,"m",ue).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,_,"m",ue).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,L,"f").beta.memoryStores.memories.retrieve(f.id,{memory_store_id:t.memoryStoreId,view:"full"})}catch(d){if(pe(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,_,"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,_,"m",ue).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))},me=async function*(t,i="basic"){let n=i==="basic"?zt:Gt;for await(let s of e(this,L,"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]}},ue=async function r(t,i,n,s){try{let c=await t.files.get(i);if(c===null)return;let l=vt(c),f=s?await e(this,L,"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,L,"f").beta.memoryStores.memories.create(t.memoryStoreId,{path:"/"+i,content:l});return t.refusedShas.delete(i),f.content_sha256}catch(c){if(s&&pe(c,404))return await e(this,_,"m",r).call(this,t,i,n,void 0);let l=c instanceof y||pe(c,400)||pe(c,413);if(s&&pe(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,_,"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,L,"f").beta.memoryStores.memories.delete(n.id,{memory_store_id:t.memoryStoreId,expected_content_sha256:s})}catch(c){if(pe(c,404))return;if(pe(c,409)||pe(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,M,R,ee,W,T,Le,we,te,_e,ge,U,j,V,B,re,x,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=b.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),M.set(this,void 0),R.set(this,""),ee.set(this,!1),W.set(this,!1),T.set(this,null),o(this,M,$e.spawn("/bin/bash",["--noprofile","--norc"],{cwd:r,env:{...t,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),e(this,M,"f").stdout.setEncoding("utf8"),e(this,M,"f").stderr.setEncoding("utf8"),e(this,M,"f").stdout.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,M,"f").stderr.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,M,"f").once("close",()=>{o(this,W,!0,"f");let i=e(this,T,"f");o(this,T,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,R,"","f"),o(this,ee,!1,"f");let s=`__ANT_CMD_${ct.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,M,"f").stdin.write(l),e(this,
|
|
11
|
-
${g}`;return{output:g,exitCode:m}}close(){if(e(this,W,"f"))return;o(this,W,!0,"f");let r=e(this,
|
|
10
|
+
`;if(e(this,M,"f").stdin.write(l),e(this,R,"f").indexOf(s)<0){let{promise:O,resolve:D}=Dt();o(this,T,{sentinel:s,resolve:D},"f");let I,se;try{await Promise.race([O,new Promise((pt,Se)=>{I=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(I)clearTimeout(I);if(se&&n)n.removeEventListener("abort",se);o(this,T,null,"f")}}let f=e(this,R,"f").indexOf(s);if(f<0)throw new u("bash session terminated");let d=e(this,R,"f").slice(f+s.length).match(/^(-?\d+)/),m=d?parseInt(d[1],10):-1,g=e(this,R,"f").slice(0,f).replace(ir,"").replace(/\n+$/,"");if(e(this,ee,"f"))g=`[output truncated]
|
|
11
|
+
${g}`;return{output:g,exitCode:m}}close(){if(e(this,W,"f"))return;o(this,W,!0,"f");let r=e(this,T,"f");o(this,T,null,"f"),r?.resolve(),e(this,M,"f").stdout.destroy(),e(this,M,"f").stderr.destroy(),e(this,M,"f").stdin.destroy();try{process.kill(-e(this,M,"f").pid,"SIGKILL")}catch{e(this,M,"f").kill("SIGKILL")}e(this,M,"f").unref()}}return M=new WeakMap,R=new WeakMap,ee=new WeakMap,W=new WeakMap,T=new WeakMap,ye=new WeakSet,Le=function(t){if(o(this,R,e(this,R,"f")+t,"f"),e(this,R,"f").length>nt)o(this,R,e(this,R,"f").slice(e(this,R,"f").length-nt),"f"),o(this,ee,!0,"f");if(e(this,T,"f")&&e(this,R,"f").indexOf(e(this,T,"f").sentinel)>=0){let i=e(this,T,"f");o(this,T,null,"f"),i.resolve()}},a})();function ar(a){Y(a.unrestrictedPaths);let r,t=Promise.resolve();return C({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=Dt();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 E("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 E(h||`exit ${d}`);return h}catch(h){if(h instanceof E)throw h;throw r.close(),r=void 0,new E(`bash: ${h instanceof Error?h.message:String(h)}`)}}finally{f.resolve()}},close:()=>{r?.close(),r=void 0}})}function cr(a){return Y(a.unrestrictedPaths),C({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 E("read: file_path is required");let i=await oe(a,r);if(t?.length&&t.length!==2)throw new E("read: view_range must be [start_line, end_line]");let n;try{let d=await b.stat(i);if(!d.isFile())throw new E(`read: ${r} is not a regular file`);let m=ht(a.maxFileBytes);if(m!==null&&d.size>m){if(!t?.length)throw new E(`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[g,O]=t;return await lr(i,r,g,O,m)}n=await b.readFile(i,"utf8")}catch(d){if(d instanceof E)throw d;throw new E(`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
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,[]),x.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,x,"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,x=new WeakMap,we=new WeakSet,rt=function(t,i){if(e(this,re,"f").push(t),o(this,x,e(this,x,"f")+t.length,"f"),i&&e(this,B,"f")+1<e(this,j,"f"))e(this,re,"f").push(ot),o(this,x,e(this,x,"f")+ot.length,"f");if(e(this,x,"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 E(`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 E(`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),C({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 E("write: file_path is required");let i=await oe(a,r),n=await mt(a,i);if(n!==void 0)throw new E(`write: ${r} is inside read-only directory ${n}`);try{await b.mkdir(v.dirname(i),{recursive:!0,mode:J}),await be(i,t??"")}catch(s){throw new E(`write: ${q(s,r)}`)}return`wrote ${Buffer.byteLength(t??"")} bytes to ${r}`}})}function hr(a){return Y(a.unrestrictedPaths),C({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 E("edit: file_path is required");if(!t)throw new E("edit: old_string is required");let s=await oe(a,r),c=await mt(a,s);if(c!==void 0)throw new E(`edit: ${r} is inside read-only directory ${c}`);let l;try{let d=await b.stat(s);if(!d.isFile())throw new E(`edit: ${r} is not a regular file`);let m=ht(a.maxFileBytes);if(m!==null&&d.size>m)throw new E(`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 b.readFile(s,"utf8")}catch(d){if(d instanceof E)throw d;throw new E(`edit: ${q(d,r)}`)}let f=l.split(t).length-1;if(f===0)throw new E(`edit: old_string not found in ${r}`);let h;if(n)h=l.split(t).join(i);else{if(f>1)throw new E(`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 E(`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),C({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 E("glob: pattern is required");if(v.isAbsolute(r))throw new E("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(mr(r))throw new E('glob: ".." is not permitted in the pattern');let i=t?await oe(a,t):v.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=v.join(l.parentPath,l.name),h;try{h=await b.realpath(f)}catch{continue}if(!ae(n,h))continue;let d=0;try{d=(await b.stat(f)).mtimeMs}catch{}s.push({path:f,mtime:d})}}catch(l){throw new E(`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
14
|
`)}})}function pr(a){return Y(a.unrestrictedPaths),C({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 E("grep: pattern is required");let n=v.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 E("grep: aborted"));if(h)return n(l+`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-c4qr1f41.js";import"./chunk-4gtgqcct.js";import{Pr}from"./chunk-wnzvnskb.js";import{at,Je,lt}from"./chunk-30rjf7my.js";import{Ge}from"./chunk-bpw6q7g0.js";import{ee}from"./chunk-tvm4zmgj.js";import{Lr}from"./chunk-xtq1xpq0.js";import{q,V}from"./chunk-ypqjfv3a.js";import{Pe,K}from"./chunk-r4ttdkrz.js";import{j}from"./chunk-nrsd810j.js";import{Gn,Kr}from"./chunk-n0ybj4h9.js";import{U,ft,me,re,be,Se,G}from"./chunk-1n7dat03.js";import{M,Ve,Ht,ke}from"./chunk-n2jcx65v.js";var Te="https://chatgpt.com/backend-api",ve="https://api.openai.com/auth",Re=0,te=1000,Ce=60000,xe=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 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 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 Y extends Error{}function Be(e,r){let t=r?.maxRetryDelayMs??Ce;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]:Oe}});return new Uint8Array(t)}catch{return null}}var Ue=(e,r,t)=>{let n=new M,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=Pe(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),W=Ye(R);if(!N&&W&&!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??Re;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=Pr([t?.signal,k]);try{_=await(t?.fetch??globalThis.fetch)(de(e.baseUrl),{method:"POST",headers:m,body:A,signal:O.signal})}catch(W){if(k?.aborted&&!t?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${E}ms`);throw W}finally{O.cleanup()}if(await t?.onResponse?.({status:_.status,headers:j(_.headers)},e),_.ok)break;let R=await _.text();if(S<J&&Ne(_.status,R)){let W=qe(_.headers),_e=W===void 0?te*2**S:Be(W,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=Pe(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:Te).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 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 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 L||e instanceof z||e instanceof Z}function Xe(e){return e instanceof L&&e.code===Me}function Ye(e){return e instanceof L&&e.code===We}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 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:Qe(i.status)}:i;yield{...o,type:"response.completed",response:u};return}yield o}}function Qe(e){if(typeof e!=="string")return;return Le.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-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+=`
|
|
3
3
|
|
|
4
4
|
`;let a=o.indexOf(`
|
|
5
5
|
|
|
@@ -7,4 +7,4 @@ import"./chunk-c4qr1f41.js";import"./chunk-4gtgqcct.js";import{Pr}from"./chunk-w
|
|
|
7
7
|
`).filter((c)=>c.startsWith("data:")).map((c)=>c.slice(5).trim());if(p.length>0){let c=p.join(`
|
|
8
8
|
`).trim();if(c&&c!=="[DONE]")try{yield JSON.parse(c)}catch(l){throw new z(`Invalid Codex SSE JSON: ${Ve(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=xe,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===Ae)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]))?.[ve]?.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 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};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
class n{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(e){this.incoming.push(e)}dequeue(){if(this.outgoing.length===0)while(this.incoming.length>0)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}}class Xn{queue=new n;waiting=new n;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise((i)=>{this.resolveFinalResult=i})}push(e){if(this.done)return;if(this.isComplete(e))this.done=!0,this.resolveFinalResult(this.extractResult(e));let t=this.waiting.dequeue();if(t)t({value:e,done:!1});else this.queue.enqueue(e)}end(e){if(this.done=!0,e!==void 0)this.resolveFinalResult(e);while(this.waiting.length>0)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){while(!0)if(this.queue.length>0)yield this.queue.dequeue();else if(this.done)return;else{let e=await new Promise((t)=>this.waiting.enqueue(t));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}}class
|
|
3
|
-
export{Xn,
|
|
2
|
+
class n{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(e){this.incoming.push(e)}dequeue(){if(this.outgoing.length===0)while(this.incoming.length>0)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}}class Xn{queue=new n;waiting=new n;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise((i)=>{this.resolveFinalResult=i})}push(e){if(this.done)return;if(this.isComplete(e))this.done=!0,this.resolveFinalResult(this.extractResult(e));let t=this.waiting.dequeue();if(t)t({value:e,done:!1});else this.queue.enqueue(e)}end(e){if(this.done=!0,e!==void 0)this.resolveFinalResult(e);while(this.waiting.length>0)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){while(!0)if(this.queue.length>0)yield this.queue.dequeue();else if(this.done)return;else{let e=await new Promise((t)=>this.waiting.enqueue(t));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}}class L extends Xn{#t=Date.now();#i=performance.now();constructor(){super((e)=>e.type==="done"||e.type==="error",(e)=>{if(e.type==="done")return e.message;else if(e.type==="error")return e.error;throw Error("Unexpected event type for final result")})}push(e){if(e.type==="done")this.#e(e.message);else if(e.type==="error")this.#e(e.error);super.push(e)}end(e){if(e!==void 0)this.#e(e);super.end(e)}#e(e){if(this.done||e.durationMs!==void 0||e.timestamp<this.#t)return;e.durationMs=Math.max(0,Math.round(performance.now()-this.#i))}}function Jn(){return new L}function Ve(e){if(e instanceof Error)return e.message||e.name;if(typeof e==="string")return e;return String(e)}function bi(e){if(!(e instanceof Error))return{name:"ThrownValue",message:Ve(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t==="string"||typeof t==="number"?t:void 0}}function Ht(e,t,i){return{type:e,timestamp:Date.now(),error:bi(t),details:i}}function ke(e,t){e.diagnostics=[...e.diagnostics??[],t]}
|
|
3
|
+
export{Xn,L,Jn,Ve,bi,Ht,ke};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Fe,ot}from"./chunk-a1rb1a48.js";import{We}from"./chunk-e1x629v0.js";import{qe,Ae,L}from"./chunk-tevejprz.js";import{we,X,b,xe,J,Qe,H}from"./chunk-cmwdjes8.js";var{awsEndpointFunctions:Pe,emitWarningIfUnsupportedVersion:Ce,createDefaultUserAgentProvider:ye,NODE_APP_ID_CONFIG_OPTIONS:Te,getAwsRegionExtensionConfiguration:Oe,resolveAwsRegionExtensionConfiguration:De,resolveUserAgentConfig:Re,resolveHostHeaderConfig:ke,getUserAgentPlugin:$e,getHostHeaderPlugin:Ne,getLoggerPlugin:be,getRecursionDetectionPlugin:Ue}=L(),{NoAuthSigner:ze,getHttpAuthSchemeEndpointRuleSetPlugin:He,DefaultIdentityProviderConfig:Ge,getHttpSigningPlugin:Me}=Ae(),{normalizeProvider:K,getSmithyContext:je,ServiceException:Ke,NoOpLogger:Ve,emitWarningIfUnsupportedVersion:Le,loadConfigsForDefaultMode:Be,getDefaultExtensionConfiguration:Ye,resolveDefaultRuntimeConfig:Je,Client:V,makeBuilder:Xe,createAggregatedClient:Ze}=X(),{Command:et}=X();var Kr=et,Vr=V;var{resolveDefaultsModeConfig:tt,loadConfig:h,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:rt,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:nt,NODE_REGION_CONFIG_OPTIONS:st,NODE_REGION_CONFIG_FILE_OPTIONS:it,resolveRegionConfig:ct}=b(),{BinaryDecisionDiagram:at,EndpointCache:dt,decideEndpoint:pt,customEndpointFunctions:ut,resolveEndpointConfig:lt,getEndpointPlugin:ht}=xe(),{parseUrl:Et,getHttpHandlerExtensionConfiguration:gt,resolveHttpHandlerRuntimeConfig:_t,getContentLengthPlugin:mt}=H(),{DEFAULT_RETRY_MODE:xt,NODE_RETRY_MODE_CONFIG_OPTIONS:St,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:ft,resolveRetryConfig:It,getRetryPlugin:vt}=qe(),{TypeRegistry:B,getSchemaSerdePlugin:Pt}=we(),{resolveAwsSdkSigV4Config:Ct,AwsSdkSigV4Signer:At,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:yt}=Fe(),{toUtf8:Tt,fromUtf8:Ot,toBase64:wt,fromBase64:Dt,calculateBodyLength:Rt}=J(),{streamCollector:kt,NodeHttpHandler:$t}=We(),{AwsRestJsonProtocol:Nt}=ot(),{Sha256:bt}=Qe(),Ut=async(e,t,n)=>({operation:je(t).operation,region:await K(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Ft(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function qt(e){return{schemeId:"smithy.api#noAuth"}}var zt=(e)=>{let t=[];switch(e.operation){case"CreateToken":{t.push(qt());break}default:t.push(Ft(e))}return t},Ht=(e)=>{let t=Ct(e);return Object.assign(t,{authSchemePreference:K(e.authSchemePreference??[])})},Gt=(e)=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"}),Mt={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},jt="3.997.47",Kt={version:jt},_="ref",E=-1,x=!0,z="isSet",W="PartitionResult",S="booleanEquals",k="getAttr",G={[_]:"Endpoint"},N={[_]:W},g={},M=[{[_]:"Region"}],j={conditions:[[z,[G]],[z,M],["aws.partition",M,W],[S,[{[_]:"UseFIPS"},x]],[S,[{[_]:"UseDualStack"},x]],[S,[{fn:k,argv:[N,"supportsDualStack"]},x]],[S,[{fn:k,argv:[N,"supportsFIPS"]},x]],["stringEquals",[{fn:k,argv:[N,"name"]},"aws-us-gov"]]],results:[[E],[E,"Invalid Configuration: FIPS and custom endpoint are not supported"],[E,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[G,g],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",g],[E,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",g],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",g],[E,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",g],[E,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",g],[E,"Invalid Configuration: Missing Region"]]},Vt=2,c=1e8,Lt=new Int32Array([-1,1,-1,0,13,3,1,4,c+12,2,5,c+12,3,8,6,4,7,c+11,5,c+9,c+10,4,11,9,6,10,c+8,7,c+6,c+7,5,12,c+5,6,c+4,c+5,3,c+1,14,4,c+2,c+3]),Bt=at.from(Lt,Vt,j.conditions,j.results),Wt=new dt({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Yt=(e,t={})=>Wt.get(e,()=>pt(Bt,{endpointParams:e,logger:t.logger}));ut.aws=Pe;class i extends Ke{static shapeId="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc#SSOOIDCServiceException";constructor(e){super(e);Object.setPrototypeOf(this,i.prototype)}}class f extends i{static shapeId="com.amazonaws.ssooidc#AccessDeniedException";name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e});Object.setPrototypeOf(this,f.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class I extends i{static shapeId="com.amazonaws.ssooidc#AuthorizationPendingException";name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e});Object.setPrototypeOf(this,I.prototype),this.error=e.error,this.error_description=e.error_description}}class v extends i{static shapeId="com.amazonaws.ssooidc#ExpiredTokenException";name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e});Object.setPrototypeOf(this,v.prototype),this.error=e.error,this.error_description=e.error_description}}class P extends i{static shapeId="com.amazonaws.ssooidc#InternalServerException";name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e});Object.setPrototypeOf(this,P.prototype),this.error=e.error,this.error_description=e.error_description}}class C extends i{static shapeId="com.amazonaws.ssooidc#InvalidClientException";name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e});Object.setPrototypeOf(this,C.prototype),this.error=e.error,this.error_description=e.error_description}}class A extends i{static shapeId="com.amazonaws.ssooidc#InvalidGrantException";name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e});Object.setPrototypeOf(this,A.prototype),this.error=e.error,this.error_description=e.error_description}}class y extends i{static shapeId="com.amazonaws.ssooidc#InvalidRequestException";name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,y.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class T extends i{static shapeId="com.amazonaws.ssooidc#InvalidScopeException";name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e});Object.setPrototypeOf(this,T.prototype),this.error=e.error,this.error_description=e.error_description}}class O extends i{static shapeId="com.amazonaws.ssooidc#SlowDownException";name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e});Object.setPrototypeOf(this,O.prototype),this.error=e.error,this.error_description=e.error_description}}class w extends i{static shapeId="com.amazonaws.ssooidc#UnauthorizedClientException";name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e});Object.setPrototypeOf(this,w.prototype),this.error=e.error,this.error_description=e.error_description}}class D extends i{static shapeId="com.amazonaws.ssooidc#UnsupportedGrantTypeException";name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e});Object.setPrototypeOf(this,D.prototype),this.error=e.error,this.error_description=e.error_description}}var Jt="AccessDeniedException",Xt="AuthorizationPendingException",Qt="AccessToken",Zt="ClientSecret",er="CreateToken",tr="CreateTokenRequest",rr="CreateTokenResponse",or="CodeVerifier",nr="ExpiredTokenException",sr="InvalidClientException",ir="InvalidGrantException",cr="InvalidRequestException",ar="InternalServerException",dr="InvalidScopeException",pr="IdToken",ur="RefreshToken",lr="SlowDownException",hr="UnauthorizedClientException",Er="UnsupportedGrantTypeException",gr="accessToken",l="client",_r="clientId",mr="clientSecret",xr="codeVerifier",Sr="code",fr="deviceCode",r="error",Ir="expiresIn",p="error_description",vr="grantType",Pr="http",u="httpError",Cr="idToken",Y="reason",Q="refreshToken",Ar="redirectUri",Z="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",yr="scope",Tr="server",Or="tokenType",o="com.amazonaws.ssooidc",ee=new B(Z),te=[-3,Z,"SSOOIDCServiceException",0,[],[]];ee.registerError(te,i);var a=new B(o),re=[-3,o,Jt,{[r]:l,[u]:400},[r,Y,p],[0,0,0]];a.registerError(re,f);var oe=[-3,o,Xt,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(oe,I);var ne=[-3,o,nr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(ne,v);var se=[-3,o,ar,{[r]:Tr,[u]:500},[r,p],[0,0]];a.registerError(se,P);var ie=[-3,o,sr,{[r]:l,[u]:401},[r,p],[0,0]];a.registerError(ie,C);var ce=[-3,o,ir,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(ce,A);var ae=[-3,o,cr,{[r]:l,[u]:400},[r,Y,p],[0,0,0]];a.registerError(ae,y);var de=[-3,o,dr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(de,T);var pe=[-3,o,lr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(pe,O);var ue=[-3,o,hr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(ue,w);var le=[-3,o,Er,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(le,D);var he=[ee,a],wr=[0,o,Qt,8,0],Dr=[0,o,Zt,8,0],Rr=[0,o,or,8,0],kr=[0,o,pr,8,0],Ee=[0,o,ur,8,0],ge=[3,o,tr,0,[_r,mr,vr,fr,Sr,Q,yr,Ar,xr],[0,[()=>Dr,0],0,0,0,[()=>Ee,0],64,0,[()=>Rr,0]],3],_e=[3,o,rr,0,[gr,Or,Ir,Q,Cr],[[()=>wr,0],0,1,[()=>Ee,0],[()=>kr,0]]],me=[9,o,er,{[Pr]:["POST","/token",200]},()=>ge,()=>_e],$r=(e)=>({apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??Dt,base64Encoder:e?.base64Encoder??wt,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??Yt,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??zt,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new At},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new ze}],logger:e?.logger??new Ve,protocol:e?.protocol??Nt,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:he,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:e?.serviceId??"SSO OIDC",sha256:e?.sha256??bt,urlParser:e?.urlParser??Et,utf8Decoder:e?.utf8Decoder??Ot,utf8Encoder:e?.utf8Encoder??Tt}),Nr=(e)=>{Le(process.version);let t=tt(e),n=()=>t().then(Be),d=$r(e);Ce(process.version);let s={profile:e?.profile,logger:d.logger};return{...d,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??h(yt,s),bodyLengthChecker:e?.bodyLengthChecker??Rt,defaultUserAgentProvider:e?.defaultUserAgentProvider??ye({serviceId:d.serviceId,clientVersion:Kt.version}),maxAttempts:e?.maxAttempts??h(ft,e),region:e?.region??h(st,{...it,...s}),requestHandler:$t.create(e?.requestHandler??n),retryMode:e?.retryMode??h({...St,default:async()=>(await n()).retryMode||xt},e),streamCollector:e?.streamCollector??kt,useDualstackEndpoint:e?.useDualstackEndpoint??h(nt,s),useFipsEndpoint:e?.useFipsEndpoint??h(rt,s),userAgentAppId:e?.userAgentAppId??h(Te,s)}},br=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:n,credentials:d}=e;return{setHttpAuthScheme(s){let m=t.findIndex((R)=>R.schemeId===s.schemeId);if(m===-1)t.push(s);else t.splice(m,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){n=s},httpAuthSchemeProvider(){return n},setCredentials(s){d=s},credentials(){return d}}},Ur=(e)=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}),Fr=(e,t)=>{let n=Object.assign(Oe(e),Ye(e),gt(e),br(e));return t.forEach((d)=>d.configure(n)),Object.assign(e,De(n),Je(n),_t(n),Ur(n))};class U extends V{config;constructor(...[e]){let t=Nr(e||{});super(t);this.initConfig=t;let n=Gt(t),d=Re(n),s=It(d),m=ct(s),R=ke(m),Se=lt(R),fe=Ht(Se),Ie=Fr(fe,e?.extensions||[]);this.config=Ie,this.middlewareStack.use(Pt(this.config)),this.middlewareStack.use($e(this.config)),this.middlewareStack.use(vt(this.config)),this.middlewareStack.use(mt(this.config)),this.middlewareStack.use(Ne(this.config)),this.middlewareStack.use(be(this.config)),this.middlewareStack.use(Ue(this.config)),this.middlewareStack.use(He(this.config,{httpAuthSchemeParametersProvider:Ut,identityProviderConfigProvider:async(ve)=>new Ge({"aws.auth#sigv4":ve.credentials})})),this.middlewareStack.use(Me(this.config))}destroy(){super.destroy()}}var qr=Xe(Mt,"AWSSSOOIDCService","SSOOIDCClient",ht),zr={},Hr=(e,t,n,d)=>[];class F extends qr(zr,Hr,"CreateToken",me){}var Gr={CreateTokenCommand:F};class q extends U{}Ze(Gr,q);var Mr={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},jr={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};var Lr=f,Br=re,Wr=Mr,Yr=I,Jr=oe,Xr=me,Qr=F,Zr=ge,eo=_e,to=v,ro=ne,oo=P,no=se,so=C,io=ie,co=A,ao=ce,po=y,uo=ae,lo=jr,ho=T,Eo=de,go=q,_o=U,mo=i,xo=te,So=O,fo=pe,Io=w,vo=ue,Po=D,Co=le,Ao=he;export{Kr as $Command,Vr as __Client,Lr as AccessDeniedException,Br as AccessDeniedException$,Wr as AccessDeniedExceptionReason,Yr as AuthorizationPendingException,Jr as AuthorizationPendingException$,Xr as CreateToken$,Qr as CreateTokenCommand,Zr as CreateTokenRequest$,eo as CreateTokenResponse$,to as ExpiredTokenException,ro as ExpiredTokenException$,oo as InternalServerException,no as InternalServerException$,so as InvalidClientException,io as InvalidClientException$,co as InvalidGrantException,ao as InvalidGrantException$,po as InvalidRequestException,uo as InvalidRequestException$,lo as InvalidRequestExceptionReason,ho as InvalidScopeException,Eo as InvalidScopeException$,go as SSOOIDC,_o as SSOOIDCClient,mo as SSOOIDCServiceException,xo as SSOOIDCServiceException$,So as SlowDownException,fo as SlowDownException$,Io as UnauthorizedClientException,vo as UnauthorizedClientException$,Po as UnsupportedGrantTypeException,Co as UnsupportedGrantTypeException$,Ao as errorTypeRegistries};
|
|
2
|
+
import{Fe,ot}from"./chunk-cdw03j4t.js";import{We}from"./chunk-e1x629v0.js";import{qe,Ae,O}from"./chunk-vjne04dp.js";import{we,X,b,xe,J,Qe,H}from"./chunk-cmwdjes8.js";var{awsEndpointFunctions:Pe,emitWarningIfUnsupportedVersion:Ce,createDefaultUserAgentProvider:ye,NODE_APP_ID_CONFIG_OPTIONS:Te,getAwsRegionExtensionConfiguration:Oe,resolveAwsRegionExtensionConfiguration:De,resolveUserAgentConfig:Re,resolveHostHeaderConfig:ke,getUserAgentPlugin:$e,getHostHeaderPlugin:Ne,getLoggerPlugin:be,getRecursionDetectionPlugin:Ue}=O(),{NoAuthSigner:ze,getHttpAuthSchemeEndpointRuleSetPlugin:He,DefaultIdentityProviderConfig:Ge,getHttpSigningPlugin:Me}=Ae(),{normalizeProvider:V,getSmithyContext:je,ServiceException:Ke,NoOpLogger:Ve,emitWarningIfUnsupportedVersion:Le,loadConfigsForDefaultMode:Be,getDefaultExtensionConfiguration:Ye,resolveDefaultRuntimeConfig:Je,Client:L,makeBuilder:Xe,createAggregatedClient:Ze}=X(),{Command:et}=X();var Kr=et,Vr=L;var{resolveDefaultsModeConfig:tt,loadConfig:h,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:rt,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:nt,NODE_REGION_CONFIG_OPTIONS:st,NODE_REGION_CONFIG_FILE_OPTIONS:it,resolveRegionConfig:ct}=b(),{BinaryDecisionDiagram:at,EndpointCache:dt,decideEndpoint:pt,customEndpointFunctions:ut,resolveEndpointConfig:lt,getEndpointPlugin:ht}=xe(),{parseUrl:Et,getHttpHandlerExtensionConfiguration:gt,resolveHttpHandlerRuntimeConfig:_t,getContentLengthPlugin:mt}=H(),{DEFAULT_RETRY_MODE:xt,NODE_RETRY_MODE_CONFIG_OPTIONS:St,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:ft,resolveRetryConfig:It,getRetryPlugin:vt}=qe(),{TypeRegistry:B,getSchemaSerdePlugin:Pt}=we(),{resolveAwsSdkSigV4Config:Ct,AwsSdkSigV4Signer:At,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:yt}=Fe(),{toUtf8:Tt,fromUtf8:Ot,toBase64:wt,fromBase64:Dt,calculateBodyLength:Rt}=J(),{streamCollector:kt,NodeHttpHandler:$t}=We(),{AwsRestJsonProtocol:Nt}=ot(),{Sha256:bt}=Qe(),Ut=async(e,t,n)=>({operation:je(t).operation,region:await V(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Ft(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function qt(e){return{schemeId:"smithy.api#noAuth"}}var zt=(e)=>{let t=[];switch(e.operation){case"CreateToken":{t.push(qt());break}default:t.push(Ft(e))}return t},Ht=(e)=>{let t=Ct(e);return Object.assign(t,{authSchemePreference:V(e.authSchemePreference??[])})},Gt=(e)=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"}),Mt={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},jt="3.997.47",Kt={version:jt},_="ref",E=-1,x=!0,G="isSet",W="PartitionResult",S="booleanEquals",N="getAttr",M={[_]:"Endpoint"},U={[_]:W},g={},j=[{[_]:"Region"}],K={conditions:[[G,[M]],[G,j],["aws.partition",j,W],[S,[{[_]:"UseFIPS"},x]],[S,[{[_]:"UseDualStack"},x]],[S,[{fn:N,argv:[U,"supportsDualStack"]},x]],[S,[{fn:N,argv:[U,"supportsFIPS"]},x]],["stringEquals",[{fn:N,argv:[U,"name"]},"aws-us-gov"]]],results:[[E],[E,"Invalid Configuration: FIPS and custom endpoint are not supported"],[E,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[M,g],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",g],[E,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",g],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",g],[E,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",g],[E,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",g],[E,"Invalid Configuration: Missing Region"]]},Vt=2,c=1e8,Lt=new Int32Array([-1,1,-1,0,13,3,1,4,c+12,2,5,c+12,3,8,6,4,7,c+11,5,c+9,c+10,4,11,9,6,10,c+8,7,c+6,c+7,5,12,c+5,6,c+4,c+5,3,c+1,14,4,c+2,c+3]),Bt=at.from(Lt,Vt,K.conditions,K.results),Wt=new dt({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Yt=(e,t={})=>Wt.get(e,()=>pt(Bt,{endpointParams:e,logger:t.logger}));ut.aws=Pe;class i extends Ke{static shapeId="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc#SSOOIDCServiceException";constructor(e){super(e);Object.setPrototypeOf(this,i.prototype)}}class f extends i{static shapeId="com.amazonaws.ssooidc#AccessDeniedException";name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e});Object.setPrototypeOf(this,f.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class I extends i{static shapeId="com.amazonaws.ssooidc#AuthorizationPendingException";name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e});Object.setPrototypeOf(this,I.prototype),this.error=e.error,this.error_description=e.error_description}}class v extends i{static shapeId="com.amazonaws.ssooidc#ExpiredTokenException";name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e});Object.setPrototypeOf(this,v.prototype),this.error=e.error,this.error_description=e.error_description}}class P extends i{static shapeId="com.amazonaws.ssooidc#InternalServerException";name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e});Object.setPrototypeOf(this,P.prototype),this.error=e.error,this.error_description=e.error_description}}class C extends i{static shapeId="com.amazonaws.ssooidc#InvalidClientException";name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e});Object.setPrototypeOf(this,C.prototype),this.error=e.error,this.error_description=e.error_description}}class A extends i{static shapeId="com.amazonaws.ssooidc#InvalidGrantException";name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e});Object.setPrototypeOf(this,A.prototype),this.error=e.error,this.error_description=e.error_description}}class y extends i{static shapeId="com.amazonaws.ssooidc#InvalidRequestException";name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,y.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class T extends i{static shapeId="com.amazonaws.ssooidc#InvalidScopeException";name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e});Object.setPrototypeOf(this,T.prototype),this.error=e.error,this.error_description=e.error_description}}class w extends i{static shapeId="com.amazonaws.ssooidc#SlowDownException";name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e});Object.setPrototypeOf(this,w.prototype),this.error=e.error,this.error_description=e.error_description}}class D extends i{static shapeId="com.amazonaws.ssooidc#UnauthorizedClientException";name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e});Object.setPrototypeOf(this,D.prototype),this.error=e.error,this.error_description=e.error_description}}class R extends i{static shapeId="com.amazonaws.ssooidc#UnsupportedGrantTypeException";name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e});Object.setPrototypeOf(this,R.prototype),this.error=e.error,this.error_description=e.error_description}}var Jt="AccessDeniedException",Xt="AuthorizationPendingException",Qt="AccessToken",Zt="ClientSecret",er="CreateToken",tr="CreateTokenRequest",rr="CreateTokenResponse",or="CodeVerifier",nr="ExpiredTokenException",sr="InvalidClientException",ir="InvalidGrantException",cr="InvalidRequestException",ar="InternalServerException",dr="InvalidScopeException",pr="IdToken",ur="RefreshToken",lr="SlowDownException",hr="UnauthorizedClientException",Er="UnsupportedGrantTypeException",gr="accessToken",l="client",_r="clientId",mr="clientSecret",xr="codeVerifier",Sr="code",fr="deviceCode",r="error",Ir="expiresIn",p="error_description",vr="grantType",Pr="http",u="httpError",Cr="idToken",Y="reason",Q="refreshToken",Ar="redirectUri",Z="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",yr="scope",Tr="server",Or="tokenType",o="com.amazonaws.ssooidc",ee=new B(Z),te=[-3,Z,"SSOOIDCServiceException",0,[],[]];ee.registerError(te,i);var a=new B(o),re=[-3,o,Jt,{[r]:l,[u]:400},[r,Y,p],[0,0,0]];a.registerError(re,f);var oe=[-3,o,Xt,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(oe,I);var ne=[-3,o,nr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(ne,v);var se=[-3,o,ar,{[r]:Tr,[u]:500},[r,p],[0,0]];a.registerError(se,P);var ie=[-3,o,sr,{[r]:l,[u]:401},[r,p],[0,0]];a.registerError(ie,C);var ce=[-3,o,ir,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(ce,A);var ae=[-3,o,cr,{[r]:l,[u]:400},[r,Y,p],[0,0,0]];a.registerError(ae,y);var de=[-3,o,dr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(de,T);var pe=[-3,o,lr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(pe,w);var ue=[-3,o,hr,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(ue,D);var le=[-3,o,Er,{[r]:l,[u]:400},[r,p],[0,0]];a.registerError(le,R);var he=[ee,a],wr=[0,o,Qt,8,0],Dr=[0,o,Zt,8,0],Rr=[0,o,or,8,0],kr=[0,o,pr,8,0],Ee=[0,o,ur,8,0],ge=[3,o,tr,0,[_r,mr,vr,fr,Sr,Q,yr,Ar,xr],[0,[()=>Dr,0],0,0,0,[()=>Ee,0],64,0,[()=>Rr,0]],3],_e=[3,o,rr,0,[gr,Or,Ir,Q,Cr],[[()=>wr,0],0,1,[()=>Ee,0],[()=>kr,0]]],me=[9,o,er,{[Pr]:["POST","/token",200]},()=>ge,()=>_e],$r=(e)=>({apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??Dt,base64Encoder:e?.base64Encoder??wt,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??Yt,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??zt,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new At},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new ze}],logger:e?.logger??new Ve,protocol:e?.protocol??Nt,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:he,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:e?.serviceId??"SSO OIDC",sha256:e?.sha256??bt,urlParser:e?.urlParser??Et,utf8Decoder:e?.utf8Decoder??Ot,utf8Encoder:e?.utf8Encoder??Tt}),Nr=(e)=>{Le(process.version);let t=tt(e),n=()=>t().then(Be),d=$r(e);Ce(process.version);let s={profile:e?.profile,logger:d.logger};return{...d,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??h(yt,s),bodyLengthChecker:e?.bodyLengthChecker??Rt,defaultUserAgentProvider:e?.defaultUserAgentProvider??ye({serviceId:d.serviceId,clientVersion:Kt.version}),maxAttempts:e?.maxAttempts??h(ft,e),region:e?.region??h(st,{...it,...s}),requestHandler:$t.create(e?.requestHandler??n),retryMode:e?.retryMode??h({...St,default:async()=>(await n()).retryMode||xt},e),streamCollector:e?.streamCollector??kt,useDualstackEndpoint:e?.useDualstackEndpoint??h(nt,s),useFipsEndpoint:e?.useFipsEndpoint??h(rt,s),userAgentAppId:e?.userAgentAppId??h(Te,s)}},br=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:n,credentials:d}=e;return{setHttpAuthScheme(s){let m=t.findIndex((k)=>k.schemeId===s.schemeId);if(m===-1)t.push(s);else t.splice(m,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){n=s},httpAuthSchemeProvider(){return n},setCredentials(s){d=s},credentials(){return d}}},Ur=(e)=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}),Fr=(e,t)=>{let n=Object.assign(Oe(e),Ye(e),gt(e),br(e));return t.forEach((d)=>d.configure(n)),Object.assign(e,De(n),Je(n),_t(n),Ur(n))};class F extends L{config;constructor(...[e]){let t=Nr(e||{});super(t);this.initConfig=t;let n=Gt(t),d=Re(n),s=It(d),m=ct(s),k=ke(m),Se=lt(k),fe=Ht(Se),Ie=Fr(fe,e?.extensions||[]);this.config=Ie,this.middlewareStack.use(Pt(this.config)),this.middlewareStack.use($e(this.config)),this.middlewareStack.use(vt(this.config)),this.middlewareStack.use(mt(this.config)),this.middlewareStack.use(Ne(this.config)),this.middlewareStack.use(be(this.config)),this.middlewareStack.use(Ue(this.config)),this.middlewareStack.use(He(this.config,{httpAuthSchemeParametersProvider:Ut,identityProviderConfigProvider:async(ve)=>new Ge({"aws.auth#sigv4":ve.credentials})})),this.middlewareStack.use(Me(this.config))}destroy(){super.destroy()}}var qr=Xe(Mt,"AWSSSOOIDCService","SSOOIDCClient",ht),zr={},Hr=(e,t,n,d)=>[];class q extends qr(zr,Hr,"CreateToken",me){}var Gr={CreateTokenCommand:q};class z extends F{}Ze(Gr,z);var Mr={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},jr={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};var Lr=f,Br=re,Wr=Mr,Yr=I,Jr=oe,Xr=me,Qr=q,Zr=ge,eo=_e,to=v,ro=ne,oo=P,no=se,so=C,io=ie,co=A,ao=ce,po=y,uo=ae,lo=jr,ho=T,Eo=de,go=z,_o=F,mo=i,xo=te,So=w,fo=pe,Io=D,vo=ue,Po=R,Co=le,Ao=he;export{Kr as $Command,Vr as __Client,Lr as AccessDeniedException,Br as AccessDeniedException$,Wr as AccessDeniedExceptionReason,Yr as AuthorizationPendingException,Jr as AuthorizationPendingException$,Xr as CreateToken$,Qr as CreateTokenCommand,Zr as CreateTokenRequest$,eo as CreateTokenResponse$,to as ExpiredTokenException,ro as ExpiredTokenException$,oo as InternalServerException,no as InternalServerException$,so as InvalidClientException,io as InvalidClientException$,co as InvalidGrantException,ao as InvalidGrantException$,po as InvalidRequestException,uo as InvalidRequestException$,lo as InvalidRequestExceptionReason,ho as InvalidScopeException,Eo as InvalidScopeException$,go as SSOOIDC,_o as SSOOIDCClient,mo as SSOOIDCServiceException,xo as SSOOIDCServiceException$,So as SlowDownException,fo as SlowDownException$,Io as UnauthorizedClientException,vo as UnauthorizedClientException$,Po as UnsupportedGrantTypeException,Co as UnsupportedGrantTypeException$,Ao as errorTypeRegistries};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{he,$e,Mt}from"./chunk-
|
|
2
|
+
import{he,$e,Mt}from"./chunk-1h34mzh7.js";export{he as UnauthorizedError,$e as auth,Mt as extractWWWAuthenticateParams};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{W}from"./chunk-4gtgqcct.js";import{
|
|
2
|
+
import{W}from"./chunk-4gtgqcct.js";import{T}from"./chunk-eq4wqxzt.js";import{j,ye}from"./chunk-nrsd810j.js";import{L,Ht,ke}from"./chunk-qs8zzg50.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;ke(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=W(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)ke(s,Ht("pi_messages_response_failure",t,t.diagnosticDetails));return{type:"error",reason:e,error:s}}function E(r,t){if(r)return r;return
|
|
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)ke(s,Ht("pi_messages_response_failure",t,t.diagnosticDetails));return{type:"error",reason:e,error:s}}function E(r,t){if(r)return r;return T("PI_CACHE_RETENTION",t)==="long"?"long":void 0}var R=(r,t,n)=>{let e=new L,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",...ye(n?.headers)},body:JSON.stringify(c),signal:n?.signal});if(await n?.onResponse?.({status:i.status,headers:j(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 R(r,t,{...n,reasoning:n?.reasoning,toolChoice:n?.toolChoice,debug:e?.debug})};export{u as PiMessagesResponseError,R as stream,P as streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{O}from"./chunk-vjne04dp.js";import{b}from"./chunk-cmwdjes8.js";import{i}from"./chunk-bwawt15q.js";var _=i(O()),N=i(b()),Ur="AWS_ACCESS_KEY_ID",Br="AWS_SECRET_ACCESS_KEY",S="AWS_SESSION_TOKEN",C="AWS_CREDENTIAL_EXPIRATION",A="AWS_CREDENTIAL_SCOPE",p="AWS_ACCOUNT_ID",Mn=(e)=>async()=>{e?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let o=process.env[Ur],E=process.env[Br],r=process.env[S],n=process.env[C],s=process.env[A],t=process.env[p];if(o&&E){let c={accessKeyId:o,secretAccessKey:E,...r&&{sessionToken:r},...n&&{expiration:new Date(n)},...s&&{credentialScope:s},...t&&{accountId:t}};return _.setCredentialFeature(c,"CREDENTIALS_ENV_VARS","g"),c}throw new N.CredentialsProviderError("Unable to find environment variable credentials.",{logger:e?.logger})};export{Ur,Br,Mn};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Fe,ot}from"./chunk-
|
|
2
|
+
import{Fe,ot}from"./chunk-cdw03j4t.js";import{We}from"./chunk-e1x629v0.js";import{qe,Ae,O}from"./chunk-vjne04dp.js";import{we,X,b,xe,J,Qe,H}from"./chunk-cmwdjes8.js";var{awsEndpointFunctions:Y,emitWarningIfUnsupportedVersion:Z,createDefaultUserAgentProvider:ee,NODE_APP_ID_CONFIG_OPTIONS:te,getAwsRegionExtensionConfiguration:se,resolveAwsRegionExtensionConfiguration:oe,resolveUserAgentConfig:ne,resolveHostHeaderConfig:re,getUserAgentPlugin:ie,getHostHeaderPlugin:ae,getLoggerPlugin:ce,getRecursionDetectionPlugin:ue}=O(),{NoAuthSigner:de,getHttpAuthSchemeEndpointRuleSetPlugin:pe,DefaultIdentityProviderConfig:le,getHttpSigningPlugin:he}=Ae(),{normalizeProvider:q,getSmithyContext:ge,ServiceException:me,NoOpLogger:Se,emitWarningIfUnsupportedVersion:_e,loadConfigsForDefaultMode:Ee,getDefaultExtensionConfiguration:fe,resolveDefaultRuntimeConfig:Pe,Client:ve,makeBuilder:Re,createAggregatedClient:Ce}=X(),{Command:Es}=X();var{resolveDefaultsModeConfig:Ie,loadConfig:a,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:ye,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:Oe,NODE_REGION_CONFIG_OPTIONS:Te,NODE_REGION_CONFIG_FILE_OPTIONS:Ne,resolveRegionConfig:De}=b(),{BinaryDecisionDiagram:ke,EndpointCache:be,decideEndpoint:$e,customEndpointFunctions:He,resolveEndpointConfig:Ue,getEndpointPlugin:Ge}=xe(),{parseUrl:Me,getHttpHandlerExtensionConfiguration:ze,resolveHttpHandlerRuntimeConfig:je,getContentLengthPlugin:Le}=H(),{DEFAULT_RETRY_MODE:Ke,NODE_RETRY_MODE_CONFIG_OPTIONS:Ve,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:Be,resolveRetryConfig:Ye,getRetryPlugin:Je}=qe(),{TypeRegistry:U,getSchemaSerdePlugin:Xe}=we(),{resolveAwsSdkSigV4Config:Ze,AwsSdkSigV4Signer:et,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:tt}=Fe(),{toUtf8:st,fromUtf8:nt,toBase64:rt,fromBase64:it,calculateBodyLength:at}=J(),{streamCollector:ct,NodeHttpHandler:ut}=We(),{AwsRestJsonProtocol:dt}=ot(),{Sha256:pt}=Qe(),lt=async(e,t,s)=>({operation:ge(t).operation,region:await q(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function ht(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"awsssoportal",region:e.region},propertiesExtractor:(t,s)=>({signingProperties:{config:t,context:s}})}}function gt(e){return{schemeId:"smithy.api#noAuth"}}var mt=(e)=>{let t=[];switch(e.operation){case"GetRoleCredentials":{t.push(gt());break}default:t.push(ht(e))}return t},St=(e)=>{let t=Ze(e);return Object.assign(t,{authSchemePreference:q(e.authSchemePreference??[])})},_t=(e)=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"awsssoportal"}),Et={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},ft="3.997.47",Pt={version:ft},p="ref",c=-1,g=!0,T="isSet",G="PartitionResult",m="booleanEquals",v="getAttr",N={[p]:"Endpoint"},R={[p]:G},d={},D=[{[p]:"Region"}],k={conditions:[[T,[N]],[T,D],["aws.partition",D,G],[m,[{[p]:"UseFIPS"},g]],[m,[{[p]:"UseDualStack"},g]],[m,[{fn:v,argv:[R,"supportsDualStack"]},g]],[m,[{fn:v,argv:[R,"supportsFIPS"]},g]],["stringEquals",[{fn:v,argv:[R,"name"]},"aws-us-gov"]]],results:[[c],[c,"Invalid Configuration: FIPS and custom endpoint are not supported"],[c,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[N,d],["https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",d],[c,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://portal.sso.{Region}.amazonaws.com",d],["https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}",d],[c,"FIPS is enabled but this partition does not support FIPS"],["https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}",d],[c,"DualStack is enabled but this partition does not support DualStack"],["https://portal.sso.{Region}.{PartitionResult#dnsSuffix}",d],[c,"Invalid Configuration: Missing Region"]]},vt=2,n=1e8,Rt=new Int32Array([-1,1,-1,0,13,3,1,4,n+12,2,5,n+12,3,8,6,4,7,n+11,5,n+9,n+10,4,11,9,6,10,n+8,7,n+6,n+7,5,12,n+5,6,n+4,n+5,3,n+1,14,4,n+2,n+3]),xt=ke.from(Rt,vt,k.conditions,k.results),Ct=new be({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),It=(e,t={})=>Ct.get(e,()=>$e(xt,{endpointParams:e,logger:t.logger}));He.aws=Y;class u extends me{static shapeId="smithy.ts.sdk.synthetic.com.amazonaws.sso#SSOServiceException";constructor(e){super(e);Object.setPrototypeOf(this,u.prototype)}}class x extends u{static shapeId="com.amazonaws.sso#InvalidRequestException";name="InvalidRequestException";$fault="client";constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,x.prototype)}}class C extends u{static shapeId="com.amazonaws.sso#ResourceNotFoundException";name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e});Object.setPrototypeOf(this,C.prototype)}}class I extends u{static shapeId="com.amazonaws.sso#TooManyRequestsException";name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e});Object.setPrototypeOf(this,I.prototype)}}class y extends u{static shapeId="com.amazonaws.sso#UnauthorizedException";name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e});Object.setPrototypeOf(this,y.prototype)}}var yt="AccessTokenType",At="GetRoleCredentials",Ot="GetRoleCredentialsRequest",wt="GetRoleCredentialsResponse",Tt="InvalidRequestException",Nt="RoleCredentials",Dt="ResourceNotFoundException",kt="SecretAccessKeyType",bt="SessionTokenType",Ft="TooManyRequestsException",qt="UnauthorizedException",$t="accountId",Ht="accessKeyId",Ut="accessToken",Gt="account_id",S="client",_="error",Mt="expiration",zt="http",E="httpError",jt="httpHeader",F="httpQuery",f="message",Lt="roleCredentials",Kt="roleName",Vt="role_name",M="smithy.ts.sdk.synthetic.com.amazonaws.sso",Bt="secretAccessKey",Wt="sessionToken",Qt="x-amz-sso_bearer_token",r="com.amazonaws.sso",z=new U(M),Yt=[-3,M,"SSOServiceException",0,[],[]];z.registerError(Yt,u);var l=new U(r),Jt=[-3,r,Tt,{[_]:S,[E]:400},[f],[0]];l.registerError(Jt,x);var Xt=[-3,r,Dt,{[_]:S,[E]:404},[f],[0]];l.registerError(Xt,C);var Zt=[-3,r,Ft,{[_]:S,[E]:429},[f],[0]];l.registerError(Zt,I);var es=[-3,r,qt,{[_]:S,[E]:401},[f],[0]];l.registerError(es,y);var ts=[z,l],ss=[0,r,yt,8,0],os=[0,r,kt,8,0],ns=[0,r,bt,8,0],rs=[3,r,Ot,0,[Kt,$t,Ut],[[0,{[F]:Vt}],[0,{[F]:Gt}],[()=>ss,{[jt]:Qt}]],3],is=[3,r,wt,0,[Lt],[[()=>as,0]]],as=[3,r,Nt,0,[Ht,Bt,Wt,Mt],[0,[()=>os,0],[()=>ns,0],1]],cs=[9,r,At,{[zt]:["GET","/federation/credentials",200]},()=>rs,()=>is],us=(e)=>({apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??it,base64Encoder:e?.base64Encoder??rt,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??It,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??mt,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new et},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new de}],logger:e?.logger??new Se,protocol:e?.protocol??dt,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.sso",errorTypeRegistries:ts,version:"2019-06-10",serviceTarget:"SWBPortalService"},serviceId:e?.serviceId??"SSO",sha256:e?.sha256??pt,urlParser:e?.urlParser??Me,utf8Decoder:e?.utf8Decoder??nt,utf8Encoder:e?.utf8Encoder??st}),ds=(e)=>{_e(process.version);let t=Ie(e),s=()=>t().then(Ee),i=us(e);Z(process.version);let o={profile:e?.profile,logger:i.logger};return{...i,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??a(tt,o),bodyLengthChecker:e?.bodyLengthChecker??at,defaultUserAgentProvider:e?.defaultUserAgentProvider??ee({serviceId:i.serviceId,clientVersion:Pt.version}),maxAttempts:e?.maxAttempts??a(Be,e),region:e?.region??a(Te,{...Ne,...o}),requestHandler:ut.create(e?.requestHandler??s),retryMode:e?.retryMode??a({...Ve,default:async()=>(await s()).retryMode||Ke},e),streamCollector:e?.streamCollector??ct,useDualstackEndpoint:e?.useDualstackEndpoint??a(Oe,o),useFipsEndpoint:e?.useFipsEndpoint??a(ye,o),userAgentAppId:e?.userAgentAppId??a(te,o)}},ps=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:s,credentials:i}=e;return{setHttpAuthScheme(o){let h=t.findIndex((P)=>P.schemeId===o.schemeId);if(h===-1)t.push(o);else t.splice(h,1,o)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(o){s=o},httpAuthSchemeProvider(){return s},setCredentials(o){i=o},credentials(){return i}}},ls=(e)=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}),hs=(e,t)=>{let s=Object.assign(se(e),fe(e),ze(e),ps(e));return t.forEach((i)=>i.configure(s)),Object.assign(e,oe(s),Pe(s),je(s),ls(s))};class A extends ve{config;constructor(...[e]){let t=ds(e||{});super(t);this.initConfig=t;let s=_t(t),i=ne(s),o=Ye(i),h=De(o),P=re(h),V=Ue(P),B=St(V),W=hs(B,e?.extensions||[]);this.config=W,this.middlewareStack.use(Xe(this.config)),this.middlewareStack.use(ie(this.config)),this.middlewareStack.use(Je(this.config)),this.middlewareStack.use(Le(this.config)),this.middlewareStack.use(ae(this.config)),this.middlewareStack.use(ce(this.config)),this.middlewareStack.use(ue(this.config)),this.middlewareStack.use(pe(this.config,{httpAuthSchemeParametersProvider:lt,identityProviderConfigProvider:async(Q)=>new le({"aws.auth#sigv4":Q.credentials})})),this.middlewareStack.use(he(this.config))}destroy(){super.destroy()}}var gs=Re(Et,"SWBPortalService","SSOClient",Ge),ms={},Ss=(e,t,s,i)=>[];class w extends gs(ms,Ss,"GetRoleCredentials",cs){}var _s={GetRoleCredentialsCommand:w};class j extends A{}Ce(_s,j);var L=w;var K=A;export{L as GetRoleCredentialsCommand,K as SSOClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{O}from"./chunk-vjne04dp.js";import{b}from"./chunk-cmwdjes8.js";import{i}from"./chunk-bwawt15q.js";var d=i(b());var t=i(b());import{exec as w}from"child_process";import{promisify as P}from"util";var p=i(O()),f=(r,e,o)=>{if(e.Version!==1)throw Error(`Profile ${r} credential_process did not return Version 1.`);if(e.AccessKeyId===void 0||e.SecretAccessKey===void 0)throw Error(`Profile ${r} credential_process returned invalid credentials.`);if(e.Expiration){let l=new Date;if(new Date(e.Expiration)<l)throw Error(`Profile ${r} credential_process returned expired credentials.`)}let s=e.AccountId;if(!s&&o?.[r]?.aws_account_id)s=o[r].aws_account_id;let n={accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,...e.SessionToken&&{sessionToken:e.SessionToken},...e.Expiration&&{expiration:new Date(e.Expiration)},...e.CredentialScope&&{credentialScope:e.CredentialScope},...s&&{accountId:s}};return p.setCredentialFeature(n,"CREDENTIALS_PROCESS","w"),n};var u=async(r,e,o)=>{let s=e[r];if(e[r]){let n=s.credential_process;if(n!==void 0){let l=P(t.externalDataInterceptor?.getTokenRecord?.().exec??w);try{let{stdout:c}=await l(n),a;try{a=JSON.parse(c.trim())}catch{throw Error(`Profile ${r} credential_process returned invalid JSON.`)}return f(r,a,e)}catch(c){throw new t.CredentialsProviderError(c.message,{logger:o})}}else throw new t.CredentialsProviderError(`Profile ${r} did not contain credential_process.`,{logger:o})}else throw new t.CredentialsProviderError(`Profile ${r} could not be found in shared credentials file.`,{logger:o})};var m=(r={})=>async({callerClientConfig:e}={})=>{r.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let o=await d.parseKnownFiles(r);return u(d.getProfileName({profile:r.profile??e?.profile}),o,r.logger)};export{m as fromProcess};
|