clawdi 0.14.74 → 0.14.76

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/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import{createRequire as Z_e}from"node:module";var z_e=Object.create;var{getProto
4
4
  `,"ascii"),oS=iS("sha256").update(lbe).digest("hex")});import dbe from"events";import Wr from"fs";import{EventEmitter as qI}from"node:events";import WW from"node:stream";import{StringDecoder as pbe}from"node:string_decoder";import JW from"node:path";import Rp from"node:fs";import{dirname as Abe,parse as Rbe}from"path";import{EventEmitter as Tbe}from"events";import RI from"assert";import{Buffer as cu}from"buffer";import*as gW from"zlib";import jbe from"zlib";import{posix as wp}from"node:path";import{basename as cSe}from"node:path";import DS from"fs";import _s from"fs";import kW from"path";import{win32 as SSe}from"node:path";import xW from"path";import c9 from"node:fs";import USe from"node:assert";import{randomBytes as u9}from"node:crypto";import Ke from"node:fs";import An from"node:path";import d9 from"fs";import HS from"node:fs";import Rh from"node:path";import ki from"node:fs";import WSe from"node:fs/promises";import NS from"node:path";import{join as S9}from"node:path";import Si from"node:fs";import E9 from"node:path";function OSe(e,t,n){let r=t,i=t?t.next:e.head,o=new XI(n,r,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function DSe(e,t){e.tail=new XI(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function TSe(e,t){e.head=new XI(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var cbe,ube=(e,t)=>{for(var n in t)cbe(e,n,{get:t[n],enumerable:!0})},dW,mbe=(e)=>!!e&&typeof e=="object"&&(e instanceof pu||e instanceof WW||fbe(e)||gbe(e)),fbe=(e)=>!!e&&typeof e=="object"&&e instanceof qI&&typeof e.pipe=="function"&&e.pipe!==WW.Writable.prototype.pipe,gbe=(e)=>!!e&&typeof e=="object"&&e instanceof qI&&typeof e.write=="function"&&typeof e.end=="function",ua,da,ml,sS,lh,aS,pW,lS,mW,Eo,vp,Dn,ch,kp,Tn,Ar,jn,Yx,cS,dr,pn,Xx,Qx,fW,eI,hs,tI,uS,uh,eu,bi,dh=(e)=>Promise.resolve().then(e),hbe=(e)=>e(),ybe=(e)=>e==="end"||e==="finish"||e==="prefinish",vbe=(e)=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,wbe=(e)=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),KW=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[kp](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},_be,bbe=(e)=>!!e.objectMode,Sbe=(e)=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",pu,kbe,Sl,Co,ph,dt,nI,ga,rI,EI,AI,Eh,dS,Pp,Cp,iI,Ep,kl,Po,yl,ys,Ap,oI,fa,mh,sI,bS,tu,SS,lu,WI,Ebe,MS,GW,Pbe,Cbe=(e)=>!!e.sync&&!!e.file,$be=(e)=>!e.sync&&!!e.file,xbe=(e)=>!!e.sync&&!e.file,Ibe=(e)=>!e.sync&&!e.file,Obe=(e)=>!!e.file,Dbe=(e)=>Pbe.get(e)||e,KI=(e={})=>{if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){let i=Dbe(n);t[i]=r}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t},Dh=(e,t,n,r,i)=>Object.assign((o=[],s,a)=>{Array.isArray(o)&&(s=o,o={}),typeof s=="function"&&(a=s,s=void 0),s=s?Array.from(s):[];let l=KI(o);if(i?.(l,s),Cbe(l)){if(typeof a=="function")throw TypeError("callback not supported for sync tar functions");return e(l,s)}else if($be(l)){let c=t(l,s);return a?c.then(()=>a(),a):c}else if(xbe(l)){if(typeof a=="function")throw TypeError("callback not supported for sync tar functions");return n(l,s)}else if(Ibe(l)){if(typeof a=="function")throw TypeError("callback only supported with file option");return r(l,s)}throw Error("impossible options??")},{syncFile:e,asyncFile:t,syncNoFile:n,asyncNoFile:r,validate:i}),Nbe,Ss,Mbe,hW,Lbe=(e)=>e,aI,uu,pS,lI,GI,ZW,Ube,Fbe,YW,zbe,Hbe,XW,Bbe,Vbe,qbe=(e,t)=>{if(Number.isSafeInteger(e))e<0?Kbe(e,t):Wbe(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},Wbe=(e,t)=>{t[0]=128;for(var n=t.length;n>1;n--)t[n-1]=e&255,e=Math.floor(e/256)},Kbe=(e,t)=>{t[0]=255;var n=!1;e=e*-1;for(var r=t.length;r>1;r--){var i=e&255;e=Math.floor(e/256),n?t[r-1]=QW(i):i===0?t[r-1]=0:(n=!0,t[r-1]=e9(i))}},Gbe=(e)=>{let t=e[0],n=t===128?Zbe(e.subarray(1,e.length)):t===255?Jbe(e):null;if(n===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(n))throw Error("parsed number outside of javascript safe integer range");return n},Jbe=(e)=>{for(var t=e.length,n=0,r=!1,i=t-1;i>-1;i--){var o=Number(e[i]),s;r?s=QW(o):o===0?s=o:(r=!0,s=e9(o)),s!==0&&(n-=s*Math.pow(256,t-i-1))}return n},Zbe=(e)=>{for(var t=e.length,n=0,r=t-1;r>-1;r--){var i=Number(e[r]);i!==0&&(n+=i*Math.pow(256,t-r-1))}return n},QW=(e)=>(255^e)&255,e9=(e)=>(255^e)+1&255,Ybe,kS=(e)=>LS.has(e),Xbe=(e)=>JI.has(e),t9,LS,JI,Qbe=(e)=>e===void 0||e<0?void 0:e,du=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(e,t=0,n,r){Buffer.isBuffer(e)?this.decode(e,t||0,n,r):e&&this.#n(e)}decode(e,t,n,r){if(t||(t=0),!e||!(e.length>=t+512))throw Error("need 512 bytes for header");let i=nu(e,t+156,1),o=t9.has(i),s=o?n:void 0,a=o?r:void 0;if(this.path=s?.path??nu(e,t,100),this.mode=s?.mode??a?.mode??vl(e,t+100,8),this.uid=s?.uid??a?.uid??vl(e,t+108,8),this.gid=s?.gid??a?.gid??vl(e,t+116,8),this.size=Qbe(s?.size??a?.size??vl(e,t+124,12)),this.mtime=s?.mtime??a?.mtime??cI(e,t+136,12),this.cksum=vl(e,t+148,12),a&&this.#n(a,!0),s&&this.#n(s),kS(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=nu(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=s?.uname??a?.uname??nu(e,t+265,32),this.gname=s?.gname??a?.gname??nu(e,t+297,32),this.devmaj=s?.devmaj??a?.devmaj??vl(e,t+329,8)??0,this.devmin=s?.devmin??a?.devmin??vl(e,t+337,8)??0,e[t+475]!==0){let c=nu(e,t+345,155);this.path=c+"/"+this.path}else{let c=nu(e,t+345,130);c&&(this.path=c+"/"+this.path),this.atime=n?.atime??r?.atime??cI(e,t+476,12),this.ctime=n?.ctime??r?.ctime??cI(e,t+488,12)}let l=256;for(let c=t;c<t+148;c++)l+=e[c];for(let c=t+156;c<t+512;c++)l+=e[c];this.cksumValid=l===this.cksum,this.cksum===void 0&&l===256&&(this.nullBlock=!0)}#n(e,t=!1){Object.assign(this,Object.fromEntries(Object.entries(e).filter(([n,r])=>!(r==null||n==="size"&&Number(r)<0||n==="path"&&t||n==="linkpath"&&t||n==="global"))))}encode(e,t=0){if(e||(e=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(e.length>=t+512))throw Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,r=eSe(this.path||"",n),i=r[0],o=r[1];this.needPax=!!r[2],this.needPax=ru(e,t,100,i)||this.needPax,this.needPax=wl(e,t+100,8,this.mode)||this.needPax,this.needPax=wl(e,t+108,8,this.uid)||this.needPax,this.needPax=wl(e,t+116,8,this.gid)||this.needPax,this.needPax=wl(e,t+124,12,this.size)||this.needPax,this.needPax=uI(e,t+136,12,this.mtime)||this.needPax,e[t+156]=Number(this.#e.codePointAt(0)),this.needPax=ru(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=ru(e,t+265,32,this.uname)||this.needPax,this.needPax=ru(e,t+297,32,this.gname)||this.needPax,this.needPax=wl(e,t+329,8,this.devmaj)||this.needPax,this.needPax=wl(e,t+337,8,this.devmin)||this.needPax,this.needPax=ru(e,t+345,n,o)||this.needPax,e[t+475]!==0?this.needPax=ru(e,t+345,155,o)||this.needPax:(this.needPax=ru(e,t+345,130,o)||this.needPax,this.needPax=uI(e,t+476,12,this.atime)||this.needPax,this.needPax=uI(e,t+488,12,this.ctime)||this.needPax);let s=256;for(let a=t;a<t+148;a++)s+=e[a];for(let a=t+156;a<t+512;a++)s+=e[a];return this.cksum=s,wl(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:LS.get(this.#e)}get typeKey(){return this.#e}set type(e){let t=String(JI.get(e));if(kS(t)||t==="Unsupported")this.#e=t;else if(kS(e))this.#e=e;else throw TypeError("invalid entry type: "+e)}},eSe=(e,t)=>{let n=e,r="",i,o=wp.parse(e).root||".";if(Buffer.byteLength(n)<100)i=[n,r,!1];else{r=wp.dirname(n),n=wp.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(r)<=t?i=[n,r,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(r)<=t?i=[n.slice(0,99),r,!0]:(n=wp.join(wp.basename(r),n),r=wp.dirname(r));while(r!==o&&i===void 0);i||(i=[e.slice(0,99),"",!0])}return i},nu=(e,t,n)=>e.subarray(t,t+n).toString("utf8").replace(/\0.*/,""),cI=(e,t,n)=>tSe(vl(e,t,n)),tSe=(e)=>e===void 0?void 0:new Date(e*1000),vl=(e,t,n)=>Number(e[t])&128?Gbe(e.subarray(t,t+n)):rSe(e,t,n),nSe=(e)=>isNaN(e)?void 0:e,rSe=(e,t,n)=>nSe(parseInt(e.subarray(t,t+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),iSe,wl=(e,t,n,r)=>r===void 0?!1:r>iSe[n]||r<0?(qbe(r,e.subarray(t,t+n)),!0):(oSe(e,t,n,r),!1),oSe=(e,t,n,r)=>e.write(sSe(r,n),t,n,"ascii"),sSe=(e,t)=>aSe(Math.floor(e).toString(8),t),aSe=(e,t)=>(e.length===t-1?e:Array(t-e.length-1).join("0")+e+" ")+"\x00",uI=(e,t,n,r)=>r===void 0?!1:wl(e,t,n,r.getTime()/1000),lSe,ru=(e,t,n,r)=>r===void 0?!1:(e.write(r+lSe,t,n,"utf8"),r.length!==Buffer.byteLength(r)||r.length>n),OS=class e{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,n=!1){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=n,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(t),r=512*Math.ceil(1+n/512),i=Buffer.allocUnsafe(r);for(let o=0;o<512;o++)i[o]=0;new du({path:("PaxHeader/"+cSe(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(t,512,n,"utf8");for(let o=n+512;o<i.length;o++)i[o]=0;return i}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let n=this[t],r=n instanceof Date?n.getTime()/1000:n,i=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+r+`
5
5
  `,o=Buffer.byteLength(i),s=Math.floor(Math.log(o)/Math.log(10))+1;return o+s>=Math.pow(10,s)&&(s+=1),s+o+i}static parse(t,n,r=!1){return new e(uSe(dSe(t),n),r)}},uSe=(e,t)=>t?Object.assign({},t,e):e,dSe=(e)=>e.replace(/\n$/,"").split(`
6
6
  `).reduce(pSe,Object.create(null)),pSe=(e,t)=>{let n=parseInt(t,10);if(n!==Buffer.byteLength(t)+1)return e;t=t.slice((n+" ").length);let r=t.split("="),i=r.shift();if(!i)return e;let o=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),s=r.join("=").replace(/\0.*/,"");switch(o){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":e[o]=s;break;case"ctime":case"atime":case"mtime":e[o]=new Date(Number(s)*1000);break;case"size":let a=+s;a>=0&&(e[o]=a);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":e[o]=+s;break}return e},mSe,Ne,fSe,US=(e,t,n,r={})=>{e.file&&(r.file=e.file),e.cwd&&(r.cwd=e.cwd),r.code=n instanceof Error&&n.code||t,r.tarCode=t,!e.strict&&r.recoverable!==!1?(n instanceof Error&&(r=Object.assign(n,r),n=n.message),e.emit("warn",t,n,r)):n instanceof Error?e.emit("error",Object.assign(n,r)):e.emit("error",Object.assign(Error(`${t}: ${n}`),r))},gSe=1048576,PI,CI,hSe,Wi,iu,pa,dI,yW,vs,fh,fl,vW,Ut,ma,gl,pI,ou,rn,mS,fS,mI,wW,_W,gh,fI,gS,_p,ws,hS,su,yS,vS,bW,ySe=1000,hh,gI,SW,vSe=()=>!0,Oh,Ah=(e)=>{let t=e.length-1,n=-1;for(;t>-1&&e.charAt(t)==="/";)n=t,t--;return n===-1?e:e.slice(0,n)},wSe=(e)=>{let t=e.onReadEntry;e.onReadEntry=t?(n)=>{t(n),n.resume()}:(n)=>n.resume()},n9=(e,t)=>{let n=new Map(t.map((s)=>[Ah(s),!0])),r=e.filter,i=100,o=(s,a="",l=0)=>{if(l>=i)return n.set(s,!1),!1;let c=a||Rbe(s).root||".",u;if(s===c)u=!1;else{let d=n.get(s);u=d!==void 0?d:o(Abe(s),c,l+1)}return n.set(s,u),u};e.filter=r?(s,a)=>r(s,a)&&o(Ah(s)):(s)=>o(Ah(s))},_Se=(e)=>{let t=new Oh(e),n=e.file,r;try{r=Rp.openSync(n,"r");let i=Rp.fstatSync(r),o=e.maxReadSize||16777216;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=Rp.readSync(r,s,0,i.size,0);t.end(a===s.byteLength?s:s.subarray(0,a))}else{let s=0,a=Buffer.allocUnsafe(o);for(;s<i.size;){let l=Rp.readSync(r,a,0,o,s);if(l===0)break;s+=l,t.write(a.subarray(0,l))}t.end()}}finally{if(typeof r=="number")try{Rp.closeSync(r)}catch{}}},bSe=(e,t)=>{let n=new Oh(e),r=e.maxReadSize||16777216,i=e.file;return new Promise((o,s)=>{n.on("error",s),n.on("end",o),Rp.stat(i,(a,l)=>{if(a)s(a);else{let c=new WI(i,{readSize:r,size:l.size});c.on("error",s),c.pipe(n)}})})},El,r9=(e,t,n)=>(e&=4095,n&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e),kSe,EW,ZI=(e)=>{let t="",n=EW(e);for(;kSe(e)||n.root;){let r=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":n.root;e=e.slice(r.length),t+=r,n=EW(e)}return[t,e]},FS,YI,ESe,ASe,AW=(e)=>FS.reduce((t,n)=>t.split(n).join(ESe.get(n)),e),RSe=(e)=>YI.reduce((t,n)=>t.split(n).join(ASe.get(n)),e),i9=(e,t)=>t?(e=Ne(e).replace(/^\.(\/|$)/,""),Ah(t)+"/"+e):Ne(e),PSe=16777216,RW,PW,CW,$I,$W,yh,ES,xI,AS,II,OI,DI,TI,_l,TS,jI,hI,bs,o9,CSe,$Se,xSe=(e)=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",ISe,XI=class{list;next;prev;value;constructor(e,t,n,r){this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},IW=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},OW,RS,vh,Ao,wh,hl,au,_h,wS,Ro,yI,PS,DW,NI,MI,CS,$S,TW,vI,xS,s9,wI,zS,QI,jSe=(e,t)=>{let n=new QI(e),r=new GW(e.file,{mode:e.mode||438});n.pipe(r),a9(n,t)},NSe=(e,t)=>{let n=new zS(e),r=new MS(e.file,{mode:e.mode||438});n.pipe(r);let i=new Promise((o,s)=>{r.on("error",s),r.on("close",o),n.on("error",s)});return l9(n,t).catch((o)=>n.emit("error",o)),i},a9=(e,t)=>{t.forEach((n)=>{n.charAt(0)==="@"?El({file:JW.resolve(e.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:(r)=>e.add(r)}):e.add(n)}),e.end()},l9=async(e,t)=>{for(let n of t)n.charAt(0)==="@"?await El({file:JW.resolve(String(e.cwd),n.slice(1)),noResume:!0,onReadEntry:(r)=>{e.add(r)}}):e.add(n);e.end()},MSe=(e,t)=>{let n=new QI(e);return a9(n,t),n},LSe=(e,t)=>{let n=new zS(e);return l9(n,t).catch((r)=>n.emit("error",r)),n},eO,FSe,p9,m9,jW,f9,g9,h9,zSe,HSe=524288,BSe,NW,y9,LI=(e,t,n)=>{try{return HS.lchownSync(e,t,n)}catch(r){if(r?.code!=="ENOENT")throw r}},jS=(e,t,n,r)=>{HS.lchown(e,t,n,(i)=>{r(i&&i?.code!=="ENOENT"?i:null)})},VSe=(e,t,n,r,i)=>{if(t.isDirectory())v9(Rh.resolve(e,t.name),n,r,(o)=>{if(o)return i(o);let s=Rh.resolve(e,t.name);jS(s,n,r,i)});else{let o=Rh.resolve(e,t.name);jS(o,n,r,i)}},v9=(e,t,n,r)=>{HS.readdir(e,{withFileTypes:!0},(i,o)=>{if(i){if(i.code==="ENOENT")return r();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return r(i)}if(i||!o.length)return jS(e,t,n,r);let s=o.length,a=null,l=(c)=>{if(!a){if(c)return r(a=c);if(--s===0)return jS(e,t,n,r)}};for(let c of o)VSe(e,c,t,n,l)})},qSe=(e,t,n,r)=>{t.isDirectory()&&w9(Rh.resolve(e,t.name),n,r),LI(Rh.resolve(e,t.name),n,r)},w9=(e,t,n)=>{let r;try{r=HS.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return LI(e,t,n);throw o}for(let i of r)qSe(e,i,t,n);return LI(e,t,n)},_9,BS,KSe=(e,t)=>{ki.stat(e,(n,r)=>{(n||!r.isDirectory())&&(n=new _9(e,n?.code||"ENOTDIR")),t(n)})},GSe=(e,t,n)=>{e=Ne(e);let r=t.umask??18,i=t.mode|448,o=(i&r)!==0,s=t.uid,a=t.gid,l=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),c=t.preserve,u=t.unlink,d=Ne(t.cwd),p=(f,g)=>{f?n(f):g&&l?v9(g,s,a,(v)=>p(v)):o?ki.chmod(e,i,n):n()};if(e===d)return KSe(e,p);if(c)return WSe.mkdir(e,{mode:i,recursive:!0}).then((f)=>p(null,f??void 0),p);let m=Ne(NS.relative(d,e)).split("/");UI(d,m,i,u,d,void 0,p)},UI=(e,t,n,r,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),l=Ne(NS.resolve(e+"/"+a));ki.mkdir(l,n,b9(l,t,n,r,i,o,s))},b9=(e,t,n,r,i,o,s)=>(a)=>{a?ki.lstat(e,(l,c)=>{if(l)l.path=l.path&&Ne(l.path),s(l);else if(c.isDirectory())UI(e,t,n,r,i,o,s);else if(r)ki.unlink(e,(u)=>{if(u)return s(u);ki.mkdir(e,n,b9(e,t,n,r,i,o,s))});else{if(c.isSymbolicLink())return s(new BS(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,UI(e,t,n,r,i,o,s))},JSe=(e)=>{let t=!1,n;try{t=ki.statSync(e).isDirectory()}catch(r){n=r?.code}finally{if(!t)throw new _9(e,n??"ENOTDIR")}},ZSe=(e,t)=>{e=Ne(e);let n=t.umask??18,r=t.mode|448,i=(r&n)!==0,o=t.uid,s=t.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==t.processUid||s!==t.processGid),l=t.preserve,c=t.unlink,u=Ne(t.cwd),d=(f)=>{f&&a&&w9(f,o,s),i&&ki.chmodSync(e,r)};if(e===u)return JSe(u),d();if(l)return d(ki.mkdirSync(e,{mode:r,recursive:!0})??void 0);let p=Ne(NS.relative(u,e)).split("/"),m;for(let f=p.shift(),g=u;f&&(g+="/"+f);f=p.shift()){g=Ne(NS.resolve(g));try{ki.mkdirSync(g,r),m=m||g}catch{let v=ki.lstatSync(g);if(v.isDirectory())continue;if(c){ki.unlinkSync(g),ki.mkdirSync(g,r),m=m||g;continue}else if(v.isSymbolicLink())return new BS(g,g+"/"+p.join("/"))}}return d(m)},_I,MW=1e4,bp,YSe=(e)=>{bp.has(e)?bp.delete(e):_I[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),bp.add(e);let t=_I[e],n=bp.size-MW;if(n>MW/10){for(let r of bp)if(bp.delete(r),delete _I[r],--n<=0)break}return t},XSe,QSe,eke=(e)=>e.split("/").slice(0,-1).reduce((t,n)=>{let r=t.at(-1);return r!==void 0&&(n=S9(r,n)),t.push(n||"/"),t},[]),tke=class{#e=new Map;#n=new Map;#r=new Set;reserve(e,t){e=QSe?["win32 parallelization disabled"]:e.map((r)=>Ah(S9(YSe(r))));let n=new Set(e.map((r)=>eke(r)).reduce((r,i)=>r.concat(i)));this.#n.set(t,{dirs:n,paths:e});for(let r of e){let i=this.#e.get(r);i?i.push(t):this.#e.set(r,[t])}for(let r of n){let i=this.#e.get(r);if(!i)this.#e.set(r,[new Set([t])]);else{let o=i.at(-1);o instanceof Set?o.add(t):i.push(new Set([t]))}}return this.#i(t)}#o(e){let t=this.#n.get(e);if(!t)throw Error("function does not have any path reservations");return{paths:t.paths.map((n)=>this.#e.get(n)),dirs:[...t.dirs].map((n)=>this.#e.get(n))}}check(e){let{paths:t,dirs:n}=this.#o(e);return t.every((r)=>r&&r[0]===e)&&n.every((r)=>r&&r[0]instanceof Set&&r[0].has(e))}#i(e){return this.#r.has(e)||!this.check(e)?!1:(this.#r.add(e),e(()=>this.#t(e)),!0)}#t(e){if(!this.#r.has(e))return!1;let t=this.#n.get(e);if(!t)throw Error("invalid reservation");let{paths:n,dirs:r}=t,i=new Set;for(let o of n){let s=this.#e.get(o);if(!s||s?.[0]!==e)continue;let a=s[1];if(!a){this.#e.delete(o);continue}if(s.shift(),typeof a=="function")i.add(a);else for(let l of a)i.add(l)}for(let o of r){let s=this.#e.get(o),a=s?.[0];if(!(!s||!(a instanceof Set)))if(a.size===1&&s.length===1){this.#e.delete(o);continue}else if(a.size===1){s.shift();let l=s[0];typeof l=="function"&&i.add(l)}else a.delete(e)}return this.#r.delete(e),i.forEach((o)=>this.#i(o)),!0}},nke=()=>process.umask(),LW,FI,UW,zI,Ki,HI,BI,IS,FW,zW,kh,HW,BW,bI,bl,Nn,_S,VW,Sp,SI,kI,VI,Ph,Ch,$h,xh,rke,Ih,ike=1024,oke=(e,t)=>{if(!Ih)return Ke.unlink(e,t);let n=e+".DELETE."+u9(16).toString("hex");Ke.rename(e,n,(r)=>{if(r)return t(r);Ke.unlink(n,t)})},ske=(e)=>{if(!Ih)return Ke.unlinkSync(e);let t=e+".DELETE."+u9(16).toString("hex");Ke.renameSync(e,t),Ke.unlinkSync(t)},qW=(e,t,n)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:n,tO,bh=(e)=>{try{return[null,e()]}catch(t){return[t,null]}},k9,ake=(e)=>{let t=new k9(e),n=e.file,r=c9.statSync(n),i=e.maxReadSize||16777216;new Ebe(n,{readSize:i,size:r.size}).pipe(t)},lke=(e,t)=>{let n=new tO(e),r=e.maxReadSize||16777216,i=e.file;return new Promise((o,s)=>{n.on("error",s),n.on("close",o),c9.stat(i,(a,l)=>{if(a)s(a);else{let c=new WI(i,{readSize:r,size:l.size});c.on("error",s),c.pipe(n)}})})},Th,cke=(e,t)=>{let n=new QI(e),r=!0,i,o;try{try{i=Si.openSync(e.file,"r+")}catch(l){if(l?.code==="ENOENT")i=Si.openSync(e.file,"w+");else throw l}let s=Si.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let u=0,d=0;u<512;u+=d){if(d=Si.readSync(i,a,u,a.length-u,o+u),o===0&&a[0]===31&&a[1]===139)throw Error("cannot append to compressed archives");if(!d)break e}let l=new du(a);if(!l.cksumValid)break;let c=512*Math.ceil((l.size||0)/512);if(o+c+512>s.size)break;o+=c,e.mtimeCache&&l.mtime&&e.mtimeCache.set(String(l.path),l.mtime)}r=!1,uke(e,n,o,i,t)}finally{if(r)try{Si.closeSync(i)}catch{}}},uke=(e,t,n,r,i)=>{let o=new GW(e.file,{fd:r,start:n});t.pipe(o),pke(t,i)},dke=(e,t)=>{t=Array.from(t);let n=new zS(e),r=(i,o,s)=>{let a=(p,m)=>{p?Si.close(i,(f)=>s(p)):s(null,m)},l=0;if(o===0)return a(null,0);let c=0,u=Buffer.alloc(512),d=(p,m)=>{if(p||m===void 0)return a(p);if(c+=m,c<512&&m)return Si.read(i,u,c,u.length-c,l+c,d);if(l===0&&u[0]===31&&u[1]===139)return a(Error("cannot append to compressed archives"));if(c<512)return a(null,l);let f=new du(u);if(!f.cksumValid)return a(null,l);let g=512*Math.ceil((f.size??0)/512);if(l+g+512>o||(l+=g+512,l>=o))return a(null,l);e.mtimeCache&&f.mtime&&e.mtimeCache.set(String(f.path),f.mtime),c=0,Si.read(i,u,0,512,l,d)};Si.read(i,u,0,512,l,d)};return new Promise((i,o)=>{n.on("error",o);let s="r+",a=(l,c)=>{if(l&&l.code==="ENOENT"&&s==="r+")return s="w+",Si.open(e.file,s,a);if(l||!c)return o(l);Si.fstat(c,(u,d)=>{if(u)return Si.close(c,()=>o(u));r(c,d.size,(p,m)=>{if(p)return o(p);let f=new MS(e.file,{fd:c,start:m});n.pipe(f),f.on("error",o),f.on("close",i),mke(n,t)})})};Si.open(e.file,s,a)})},pke=(e,t)=>{t.forEach((n)=>{n.charAt(0)==="@"?El({file:E9.resolve(e.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:(r)=>e.add(r)}):e.add(n)}),e.end()},mke=async(e,t)=>{for(let n of t)n.charAt(0)==="@"?await El({file:E9.resolve(String(e.cwd),n.slice(1)),noResume:!0,onReadEntry:(r)=>e.add(r)}):e.add(n);e.end()},Sh,Fyt,fke=(e)=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(n,r)=>t(n,r)&&!((e.mtimeCache?.get(n)??r.mtime??0)>(r.mtime??0)):(n,r)=>!((e.mtimeCache?.get(n)??r.mtime??0)>(r.mtime??0))};var nO=b(()=>{cbe=Object.defineProperty,dW=typeof process=="object"&&process?process:{stdout:null,stderr:null},ua=Symbol("EOF"),da=Symbol("maybeEmitEnd"),ml=Symbol("emittedEnd"),sS=Symbol("emittingEnd"),lh=Symbol("emittedError"),aS=Symbol("closed"),pW=Symbol("read"),lS=Symbol("flush"),mW=Symbol("flushChunk"),Eo=Symbol("encoding"),vp=Symbol("decoder"),Dn=Symbol("flowing"),ch=Symbol("paused"),kp=Symbol("resume"),Tn=Symbol("buffer"),Ar=Symbol("pipes"),jn=Symbol("bufferLength"),Yx=Symbol("bufferPush"),cS=Symbol("bufferShift"),dr=Symbol("objectMode"),pn=Symbol("destroyed"),Xx=Symbol("error"),Qx=Symbol("emitData"),fW=Symbol("emitEnd"),eI=Symbol("emitEnd2"),hs=Symbol("async"),tI=Symbol("abort"),uS=Symbol("aborted"),uh=Symbol("signal"),eu=Symbol("dataListeners"),bi=Symbol("discarded"),_be=class extends KW{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=(r)=>this.dest.emit("error",r),e.on("error",this.proxyErrors)}},pu=class extends qI{[Dn]=!1;[ch]=!1;[Ar]=[];[Tn]=[];[dr];[Eo];[hs];[vp];[ua]=!1;[ml]=!1;[sS]=!1;[aS]=!1;[lh]=null;[jn]=0;[pn]=!1;[uh];[uS]=!1;[eu]=0;[bi]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw TypeError("Encoding and objectMode may not be used together");bbe(t)?(this[dr]=!0,this[Eo]=null):Sbe(t)?(this[Eo]=t.encoding,this[dr]=!1):(this[dr]=!1,this[Eo]=null),this[hs]=!!t.async,this[vp]=this[Eo]?new pbe(this[Eo]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Tn]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ar]});let{signal:n}=t;n&&(this[uh]=n,n.aborted?this[tI]():n.addEventListener("abort",()=>this[tI]()))}get bufferLength(){return this[jn]}get encoding(){return this[Eo]}set encoding(e){throw Error("Encoding must be set at instantiation time")}setEncoding(e){throw Error("Encoding must be set at instantiation time")}get objectMode(){return this[dr]}set objectMode(e){throw Error("objectMode must be set at instantiation time")}get async(){return this[hs]}set async(e){this[hs]=this[hs]||!!e}[tI](){this[uS]=!0,this.emit("abort",this[uh]?.reason),this.destroy(this[uh]?.reason)}get aborted(){return this[uS]}set aborted(e){}write(e,t,n){if(this[uS])return!1;if(this[ua])throw Error("write after end");if(this[pn])return this.emit("error",Object.assign(Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(n=t,t="utf8"),t||(t="utf8");let r=this[hs]?dh:hbe;if(!this[dr]&&!Buffer.isBuffer(e)){if(wbe(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(vbe(e))e=Buffer.from(e);else if(typeof e!="string")throw Error("Non-contiguous data written to non-objectMode stream")}return this[dr]?(this[Dn]&&this[jn]!==0&&this[lS](!0),this[Dn]?this.emit("data",e):this[Yx](e),this[jn]!==0&&this.emit("readable"),n&&r(n),this[Dn]):e.length?(typeof e=="string"&&!(t===this[Eo]&&!this[vp]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[Eo]&&(e=this[vp].write(e)),this[Dn]&&this[jn]!==0&&this[lS](!0),this[Dn]?this.emit("data",e):this[Yx](e),this[jn]!==0&&this.emit("readable"),n&&r(n),this[Dn]):(this[jn]!==0&&this.emit("readable"),n&&r(n),this[Dn])}read(e){if(this[pn])return null;if(this[bi]=!1,this[jn]===0||e===0||e&&e>this[jn])return this[da](),null;this[dr]&&(e=null),this[Tn].length>1&&!this[dr]&&(this[Tn]=[this[Eo]?this[Tn].join(""):Buffer.concat(this[Tn],this[jn])]);let t=this[pW](e||null,this[Tn][0]);return this[da](),t}[pW](e,t){if(this[dr])this[cS]();else{let n=t;e===n.length||e===null?this[cS]():typeof n=="string"?(this[Tn][0]=n.slice(e),t=n.slice(0,e),this[jn]-=e):(this[Tn][0]=n.subarray(e),t=n.subarray(0,e),this[jn]-=e)}return this.emit("data",t),!this[Tn].length&&!this[ua]&&this.emit("drain"),t}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t="utf8"),e!==void 0&&this.write(e,t),n&&this.once("end",n),this[ua]=!0,this.writable=!1,(this[Dn]||!this[ch])&&this[da](),this}[kp](){this[pn]||(!this[eu]&&!this[Ar].length&&(this[bi]=!0),this[ch]=!1,this[Dn]=!0,this.emit("resume"),this[Tn].length?this[lS]():this[ua]?this[da]():this.emit("drain"))}resume(){return this[kp]()}pause(){this[Dn]=!1,this[ch]=!0,this[bi]=!1}get destroyed(){return this[pn]}get flowing(){return this[Dn]}get paused(){return this[ch]}[Yx](e){this[dr]?this[jn]+=1:this[jn]+=e.length,this[Tn].push(e)}[cS](){return this[dr]?this[jn]-=1:this[jn]-=this[Tn][0].length,this[Tn].shift()}[lS](e=!1){do;while(this[mW](this[cS]())&&this[Tn].length);!e&&!this[Tn].length&&!this[ua]&&this.emit("drain")}[mW](e){return this.emit("data",e),this[Dn]}pipe(e,t){if(this[pn])return e;this[bi]=!1;let n=this[ml];return t=t||{},e===dW.stdout||e===dW.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[Ar].push(t.proxyErrors?new _be(this,e,t):new KW(this,e,t)),this[hs]?dh(()=>this[kp]()):this[kp]()),e}unpipe(e){let t=this[Ar].find((n)=>n.dest===e);t&&(this[Ar].length===1?(this[Dn]&&this[eu]===0&&(this[Dn]=!1),this[Ar]=[]):this[Ar].splice(this[Ar].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e==="data")this[bi]=!1,this[eu]++,!this[Ar].length&&!this[Dn]&&this[kp]();else if(e==="readable"&&this[jn]!==0)super.emit("readable");else if(ybe(e)&&this[ml])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[lh]){let r=t;this[hs]?dh(()=>r.call(this,this[lh])):r.call(this,this[lh])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e==="data"&&(this[eu]=this.listeners("data").length,this[eu]===0&&!this[bi]&&!this[Ar].length&&(this[Dn]=!1)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[eu]=0,!this[bi]&&!this[Ar].length&&(this[Dn]=!1)),t}get emittedEnd(){return this[ml]}[da](){!this[sS]&&!this[ml]&&!this[pn]&&this[Tn].length===0&&this[ua]&&(this[sS]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[aS]&&this.emit("close"),this[sS]=!1)}emit(e,...t){let n=t[0];if(e!=="error"&&e!=="close"&&e!==pn&&this[pn])return!1;if(e==="data")return!this[dr]&&!n?!1:this[hs]?(dh(()=>this[Qx](n)),!0):this[Qx](n);if(e==="end")return this[fW]();if(e==="close"){if(this[aS]=!0,!this[ml]&&!this[pn])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[lh]=n,super.emit(Xx,n);let i=!this[uh]||this.listeners("error").length?super.emit("error",n):!1;return this[da](),i}else if(e==="resume"){let i=super.emit("resume");return this[da](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let r=super.emit(e,...t);return this[da](),r}[Qx](e){for(let n of this[Ar])n.dest.write(e)===!1&&this.pause();let t=this[bi]?!1:super.emit("data",e);return this[da](),t}[fW](){return this[ml]?!1:(this[ml]=!0,this.readable=!1,this[hs]?(dh(()=>this[eI]()),!0):this[eI]())}[eI](){if(this[vp]){let t=this[vp].end();if(t){for(let n of this[Ar])n.dest.write(t);this[bi]||super.emit("data",t)}}for(let t of this[Ar])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[dr]||(e.dataLength=0);let t=this.promise();return this.on("data",(n)=>{e.push(n),this[dr]||(e.dataLength+=n.length)}),await t,e}async concat(){if(this[dr])throw Error("cannot concat in objectMode");let e=await this.collect();return this[Eo]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(pn,()=>t(Error("stream destroyed"))),this.on("error",(n)=>t(n)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[bi]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[ua])return t();let r,i,o=(c)=>{this.off("data",s),this.off("end",a),this.off(pn,l),t(),i(c)},s=(c)=>{this.off("error",o),this.off("end",a),this.off(pn,l),this.pause(),r({value:c,done:!!this[ua]})},a=()=>{this.off("error",o),this.off("data",s),this.off(pn,l),t(),r({done:!0,value:void 0})},l=()=>o(Error("stream destroyed"));return new Promise((c,u)=>{i=u,r=c,this.once(pn,l),this.once("error",o),this.once("end",a),this.once("data",s)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[bi]=!1;let e=!1,t=()=>(this.pause(),this.off(Xx,t),this.off(pn,t),this.off("end",t),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return t();let r=this.read();return r===null?t():{done:!1,value:r}};return this.once("end",t),this.once(Xx,t),this.once(pn,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[pn])return e?this.emit("error",e):this.emit(pn),this;this[pn]=!0,this[bi]=!0,this[Tn].length=0,this[jn]=0;let t=this;return typeof t.close=="function"&&!this[aS]&&t.close(),e?this.emit("error",e):this.emit(pn),this}static get isStream(){return mbe}},kbe=Wr.writev,Sl=Symbol("_autoClose"),Co=Symbol("_close"),ph=Symbol("_ended"),dt=Symbol("_fd"),nI=Symbol("_finished"),ga=Symbol("_flags"),rI=Symbol("_flush"),EI=Symbol("_handleChunk"),AI=Symbol("_makeBuf"),Eh=Symbol("_mode"),dS=Symbol("_needDrain"),Pp=Symbol("_onerror"),Cp=Symbol("_onopen"),iI=Symbol("_onread"),Ep=Symbol("_onwrite"),kl=Symbol("_open"),Po=Symbol("_path"),yl=Symbol("_pos"),ys=Symbol("_queue"),Ap=Symbol("_read"),oI=Symbol("_readSize"),fa=Symbol("_reading"),mh=Symbol("_remain"),sI=Symbol("_size"),bS=Symbol("_write"),tu=Symbol("_writing"),SS=Symbol("_defaultFlag"),lu=Symbol("_errored"),WI=class extends pu{[lu]=!1;[dt];[Po];[oI];[fa]=!1;[sI];[mh];[Sl];constructor(e,t){if(t=t||{},super(t),this.readable=!0,this.writable=!1,typeof e!="string")throw TypeError("path must be a string");this[lu]=!1,this[dt]=typeof t.fd=="number"?t.fd:void 0,this[Po]=e,this[oI]=t.readSize||16777216,this[fa]=!1,this[sI]=typeof t.size=="number"?t.size:1/0,this[mh]=this[sI],this[Sl]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[dt]=="number"?this[Ap]():this[kl]()}get fd(){return this[dt]}get path(){return this[Po]}write(){throw TypeError("this is a readable stream")}end(){throw TypeError("this is a readable stream")}[kl](){Wr.open(this[Po],"r",(e,t)=>this[Cp](e,t))}[Cp](e,t){e?this[Pp](e):(this[dt]=t,this.emit("open",t),this[Ap]())}[AI](){return Buffer.allocUnsafe(Math.min(this[oI],this[mh]))}[Ap](){if(!this[fa]){this[fa]=!0;let e=this[AI]();if(e.length===0)return process.nextTick(()=>this[iI](null,0,e));Wr.read(this[dt],e,0,e.length,null,(t,n,r)=>this[iI](t,n,r))}}[iI](e,t,n){this[fa]=!1,e?this[Pp](e):this[EI](t,n)&&this[Ap]()}[Co](){if(this[Sl]&&typeof this[dt]=="number"){let e=this[dt];this[dt]=void 0,Wr.close(e,(t)=>t?this.emit("error",t):this.emit("close"))}}[Pp](e){this[fa]=!0,this[Co](),this.emit("error",e)}[EI](e,t){let n=!1;return this[mh]-=e,e>0&&(n=super.write(e<t.length?t.subarray(0,e):t)),(e===0||this[mh]<=0)&&(n=!1,this[Co](),super.end()),n}emit(e,...t){switch(e){case"prefinish":case"finish":return!1;case"drain":return typeof this[dt]=="number"&&this[Ap](),!1;case"error":return this[lu]?!1:(this[lu]=!0,super.emit(e,...t));default:return super.emit(e,...t)}}},Ebe=class extends WI{[kl](){let e=!0;try{this[Cp](null,Wr.openSync(this[Po],"r")),e=!1}finally{e&&this[Co]()}}[Ap](){let e=!0;try{if(!this[fa]){this[fa]=!0;do{let t=this[AI](),n=t.length===0?0:Wr.readSync(this[dt],t,0,t.length,null);if(!this[EI](n,t))break}while(!0);this[fa]=!1}e=!1}finally{e&&this[Co]()}}[Co](){if(this[Sl]&&typeof this[dt]=="number"){let e=this[dt];this[dt]=void 0,Wr.closeSync(e),this.emit("close")}}},MS=class extends dbe{readable=!1;writable=!0;[lu]=!1;[tu]=!1;[ph]=!1;[ys]=[];[dS]=!1;[Po];[Eh];[Sl];[dt];[SS];[ga];[nI]=!1;[yl];constructor(e,t){t=t||{},super(t),this[Po]=e,this[dt]=typeof t.fd=="number"?t.fd:void 0,this[Eh]=t.mode===void 0?438:t.mode,this[yl]=typeof t.start=="number"?t.start:void 0,this[Sl]=typeof t.autoClose=="boolean"?t.autoClose:!0;let n=this[yl]!==void 0?"r+":"w";this[SS]=t.flags===void 0,this[ga]=t.flags===void 0?n:t.flags,this[dt]===void 0&&this[kl]()}emit(e,...t){if(e==="error"){if(this[lu])return!1;this[lu]=!0}return super.emit(e,...t)}get fd(){return this[dt]}get path(){return this[Po]}[Pp](e){this[Co](),this[tu]=!0,this.emit("error",e)}[kl](){Wr.open(this[Po],this[ga],this[Eh],(e,t)=>this[Cp](e,t))}[Cp](e,t){this[SS]&&this[ga]==="r+"&&e&&e.code==="ENOENT"?(this[ga]="w",this[kl]()):e?this[Pp](e):(this[dt]=t,this.emit("open",t),this[tu]||this[rI]())}end(e,t){return e&&this.write(e,t),this[ph]=!0,!this[tu]&&!this[ys].length&&typeof this[dt]=="number"&&this[Ep](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[ph]?(this.emit("error",Error("write() after end()")),!1):this[dt]===void 0||this[tu]||this[ys].length?(this[ys].push(e),this[dS]=!0,!1):(this[tu]=!0,this[bS](e),!0)}[bS](e){Wr.write(this[dt],e,0,e.length,this[yl],(t,n)=>this[Ep](t,n))}[Ep](e,t){e?this[Pp](e):(this[yl]!==void 0&&typeof t=="number"&&(this[yl]+=t),this[ys].length?this[rI]():(this[tu]=!1,this[ph]&&!this[nI]?(this[nI]=!0,this[Co](),this.emit("finish")):this[dS]&&(this[dS]=!1,this.emit("drain"))))}[rI](){if(this[ys].length===0)this[ph]&&this[Ep](null,0);else if(this[ys].length===1)this[bS](this[ys].pop());else{let e=this[ys];this[ys]=[],kbe(this[dt],e,this[yl],(t,n)=>this[Ep](t,n))}}[Co](){if(this[Sl]&&typeof this[dt]=="number"){let e=this[dt];this[dt]=void 0,Wr.close(e,(t)=>t?this.emit("error",t):this.emit("close"))}}},GW=class extends MS{[kl](){let e;if(this[SS]&&this[ga]==="r+")try{e=Wr.openSync(this[Po],this[ga],this[Eh])}catch(t){if(t?.code==="ENOENT")return this[ga]="w",this[kl]();throw t}else e=Wr.openSync(this[Po],this[ga],this[Eh]);this[Cp](null,e)}[Co](){if(this[Sl]&&typeof this[dt]=="number"){let e=this[dt];this[dt]=void 0,Wr.closeSync(e),this.emit("close")}}[bS](e){let t=!0;try{this[Ep](null,Wr.writeSync(this[dt],e,0,e.length,this[yl])),t=!1}finally{if(t)try{this[Co]()}catch{}}}},Pbe=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),Nbe=jbe.constants||{ZLIB_VERNUM:4736},Ss=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Nbe)),Mbe=cu.concat,hW=Object.getOwnPropertyDescriptor(cu,"concat"),aI=hW?.writable===!0||hW?.set!==void 0?(e)=>{cu.concat=e?Lbe:Mbe}:(e)=>{},uu=Symbol("_superWrite"),pS=class extends Error{code;errno;constructor(e,t){super("zlib: "+e.message,{cause:e}),this.code=e.code,this.errno=e.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+e.message,Error.captureStackTrace(this,t??this.constructor)}get name(){return"ZlibError"}},lI=Symbol("flushFlag"),GI=class extends pu{#e=!1;#n=!1;#r;#o;#i;#t;#s;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(e,t){if(!e||typeof e!="object")throw TypeError("invalid options for ZlibBase constructor");if(super(e),this.#r=e.flush??0,this.#o=e.finishFlush??0,this.#i=e.fullFlushFlag??0,typeof gW[t]!="function")throw TypeError("Compression method not supported: "+t);try{this.#t=new gW[t](e)}catch(n){throw new pS(n,this.constructor)}this.#s=(n)=>{this.#e||(this.#e=!0,this.close(),this.emit("error",n))},this.#t?.on("error",(n)=>this.#s(new pS(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return RI(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#i),this.write(Object.assign(cu.alloc(0),{[lI]:e})))}end(e,t,n){return typeof e=="function"&&(n=e,t=void 0,e=void 0),typeof t=="function"&&(n=t,t=void 0),e&&(t?this.write(e,t):this.write(e)),this.flush(this.#o),this.#n=!0,super.end(n)}get ended(){return this.#n}[uu](e){return super.write(e)}write(e,t,n){if(typeof t=="function"&&(n=t,t="utf8"),typeof e=="string"&&(e=cu.from(e,t)),this.#e)return;RI(this.#t,"zlib binding closed");let r=this.#t._handle,i=r.close;r.close=()=>{};let o=this.#t.close;this.#t.close=()=>{},aI(!0);let s;try{let l=typeof e[lI]=="number"?e[lI]:this.#r;s=this.#t._processChunk(e,l),aI(!1)}catch(l){aI(!1),this.#s(new pS(l,this.write))}finally{this.#t&&(this.#t._handle=r,r.close=i,this.#t.close=o,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",(l)=>this.#s(new pS(l,this.write)));let a;if(s)if(Array.isArray(s)&&s.length>0){let l=s[0];a=this[uu](cu.from(l));for(let c=1;c<s.length;c++)a=this[uu](s[c])}else a=this[uu](cu.from(s));return n&&n(),a}},ZW=class extends GI{#e;#n;constructor(e,t){e=e||{},e.flush=e.flush||Ss.Z_NO_FLUSH,e.finishFlush=e.finishFlush||Ss.Z_FINISH,e.fullFlushFlag=Ss.Z_FULL_FLUSH,super(e,t),this.#e=e.level,this.#n=e.strategy}params(e,t){if(!this.sawError){if(!this.handle)throw Error("cannot switch params when binding is closed");if(!this.handle.params)throw Error("not supported in this implementation");if(this.#e!==e||this.#n!==t){this.flush(Ss.Z_SYNC_FLUSH),RI(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(r,i)=>{typeof r=="function"&&(i=r,r=this.flushFlag),this.flush(r),i?.()};try{this.handle.params(e,t)}finally{this.handle.flush=n}this.handle&&(this.#e=e,this.#n=t)}}}},Ube=class extends ZW{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[uu](e){return this.#e?(this.#e=!1,e[9]=255,super[uu](e)):super[uu](e)}},Fbe=class extends ZW{constructor(e){super(e,"Unzip")}},YW=class extends GI{constructor(e,t){e=e||{},e.flush=e.flush||Ss.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||Ss.BROTLI_OPERATION_FINISH,e.fullFlushFlag=Ss.BROTLI_OPERATION_FLUSH,super(e,t)}},zbe=class extends YW{constructor(e){super(e,"BrotliCompress")}},Hbe=class extends YW{constructor(e){super(e,"BrotliDecompress")}},XW=class extends GI{constructor(e,t){e=e||{},e.flush=e.flush||Ss.ZSTD_e_continue,e.finishFlush=e.finishFlush||Ss.ZSTD_e_end,e.fullFlushFlag=Ss.ZSTD_e_flush,super(e,t)}},Bbe=class extends XW{constructor(e){super(e,"ZstdCompress")}},Vbe=class extends XW{constructor(e){super(e,"ZstdDecompress")}},Ybe={};ube(Ybe,{code:()=>JI,isCode:()=>kS,isName:()=>Xbe,name:()=>LS,normalFsTypes:()=>t9});t9=new Set(["0","","1","2","3","4","5","6","7","D"]),LS=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),JI=new Map(Array.from(LS).map((e)=>[e[1],e[0]])),iSe={12:8589934591,8:2097151},lSe=Array(156).join("\x00"),mSe=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ne=mSe!=="win32"?(e)=>String(e):(e)=>String(e).replaceAll(/\\/g,"/"),fSe=class extends pu{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,n){switch(super({}),this.pause(),this.extended=t,this.globalExtended=n,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw Error("no path provided for tar.ReadEntry");this.path=Ne(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?Ne(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),n&&this.#e(n,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw Error("writing more to entry than is appropriate");let n=this.remain,r=this.blockRemain;return this.remain=Math.max(0,n-t),this.blockRemain=Math.max(0,r-t),this.ignore?!0:n>=t?super.write(e):super.write(e.subarray(0,n))}#e(e,t=!1){e.path&&(e.path=Ne(e.path)),e.linkpath&&(e.linkpath=Ne(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([n,r])=>!(r==null||n==="path"&&t))))}},PI=Buffer.from([31,139]),CI=Buffer.from([40,181,47,253]),hSe=Math.max(PI.length,CI.length),Wi=Symbol("state"),iu=Symbol("writeEntry"),pa=Symbol("readEntry"),dI=Symbol("nextEntry"),yW=Symbol("processEntry"),vs=Symbol("extendedHeader"),fh=Symbol("globalExtendedHeader"),fl=Symbol("meta"),vW=Symbol("emitMeta"),Ut=Symbol("buffer"),ma=Symbol("queue"),gl=Symbol("ended"),pI=Symbol("emittedEnd"),ou=Symbol("emit"),rn=Symbol("unzip"),mS=Symbol("consumeChunk"),fS=Symbol("consumeChunkSub"),mI=Symbol("consumeBody"),wW=Symbol("consumeMeta"),_W=Symbol("consumeHeader"),gh=Symbol("consuming"),fI=Symbol("bufferConcat"),gS=Symbol("maybeEnd"),_p=Symbol("writing"),ws=Symbol("aborted"),hS=Symbol("onDone"),su=Symbol("sawValidEntry"),yS=Symbol("sawNullBlock"),vS=Symbol("sawEOF"),bW=Symbol("closeStream"),hh=Symbol("compressedBytesRead"),gI=Symbol("decompressedBytesRead"),SW=Symbol("checkDecompressionRatio"),Oh=class extends Tbe{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[ma]=[];[Ut];[pa];[iu];[Wi]="begin";[fl]="";[vs];[fh];[gl]=!1;[rn];[ws]=!1;[su];[yS]=!1;[vS]=!1;[_p]=!1;[gh]=!1;[pI]=!1;[hh]=0;[gI]=0;constructor(e={}){super(),this.file=e.file||"",this.on(hS,()=>{(this[Wi]==="begin"||this[su]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(hS,e.ondone):this.on(hS,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxDecompressionRatio=typeof e.maxDecompressionRatio=="number"?e.maxDecompressionRatio:ySe,this.maxMetaEntrySize=e.maxMetaEntrySize||gSe,this.filter=typeof e.filter=="function"?e.filter:vSe;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let n=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:n?!0:void 0,this.on("end",()=>this[bW]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,n={}){US(this,e,t,n)}[_W](e,t){this[su]===void 0&&(this[su]=!1);let n;try{n=new du(e,t,this[vs],this[fh])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(n.nullBlock)this[yS]?(this[vS]=!0,this[Wi]==="begin"&&(this[Wi]="header"),this[ou]("eof")):(this[yS]=!0,this[ou]("nullBlock"));else if(this[yS]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let r=n.type;if(/^(Symbolic)?Link$/.test(r)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let i=this[iu]=new fSe(n,this[vs],this[fh]);if(!this[su])if(i.remain){let o=()=>{i.invalid||(this[su]=!0)};i.on("end",o)}else this[su]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[ou]("ignoredEntry",i),this[Wi]="ignore",i.resume()):i.size>0&&(this[fl]="",i.on("data",(o)=>this[fl]+=o),this[Wi]="meta"):(this[vs]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[ou]("ignoredEntry",i),this[Wi]=i.remain?"ignore":"header",i.resume()):(i.remain?this[Wi]="body":(this[Wi]="header",i.end()),this[pa]?this[ma].push(i):(this[ma].push(i),this[dI]())))}}}[bW](){queueMicrotask(()=>this.emit("close"))}[yW](e){let t=!0;if(!e)this[pa]=void 0,t=!1;else if(Array.isArray(e)){let[n,...r]=e;this.emit(n,...r)}else this[pa]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[dI]()),t=!1);return t}[dI](){do;while(this[yW](this[ma].shift()));if(this[ma].length===0){let e=this[pa];!e||e.flowing||e.size===e.remain?this[_p]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[mI](e,t){let n=this[iu];if(!n)throw Error("attempt to consume body without entry??");let r=n.blockRemain??0,i=r>=e.length&&t===0?e:e.subarray(t,t+r);return n.write(i),n.blockRemain||(this[Wi]="header",this[iu]=void 0,n.end()),i.length}[wW](e,t){let n=this[iu],r=this[mI](e,t);return!this[iu]&&n&&this[vW](n),r}[ou](e,t,n){this[ma].length===0&&!this[pa]?this.emit(e,t,n):this[ma].push([e,t,n])}[vW](e){switch(this[ou]("meta",this[fl]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[vs]=OS.parse(this[fl],this[vs],!1);break;case"GlobalExtendedHeader":this[fh]=OS.parse(this[fl],this[fh],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[vs]??Object.create(null);this[vs]=t,t.path=this[fl].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[vs]||Object.create(null);this[vs]=t,t.linkpath=this[fl].replace(/\0.*/,"");break}default:throw Error("unknown meta: "+e.type)}}abort(e){if(!this[ws]){if(this[rn]){let t=this[rn];t.write=()=>!0,t.end=()=>t,t.emit=()=>!1,t.destroy?.()}this[ws]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}}[SW](e){this[gI]+=e.length;let t=this[gI]/this[hh];return t>this.maxDecompressionRatio?(this.abort(Error(`max decompression ratio exceeded: ${t.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[ws])return n?.(),!1;if((this[rn]===void 0||this.brotli===void 0&&this[rn]===!1)&&e){if(this[Ut]&&(e=Buffer.concat([this[Ut],e]),this[Ut]=void 0),e.length<hSe)return this[Ut]=e,n?.(),!0;for(let s=0;this[rn]===void 0&&s<PI.length;s++)e[s]!==PI[s]&&(this[rn]=!1);let i=!1;if(this[rn]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<CI.length;s++)if(e[s]!==CI[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[rn]===!1&&o)if(e.length<512)if(this[gl])this.brotli=!0;else return this[Ut]=e,n?.(),!0;else try{new du(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[rn]===void 0||this[rn]===!1&&(this.brotli||i)){let s=this[gl];this[gl]=!1,this[rn]=this[rn]===void 0?new Fbe({}):i?new Vbe({}):new Hbe({}),this[rn].on("data",(l)=>{this[SW](l)&&this[mS](l)}),this[rn].on("error",(l)=>{this[ws]||this.abort(l)}),this[rn].on("end",()=>{this[gl]=!0,this[mS]()}),this[_p]=!0,this[hh]+=e.length;let a=!!this[rn][s?"end":"write"](e);return this[_p]=!1,n?.(),a}}this[_p]=!0,this[rn]?(this[hh]+=e.length,this[rn].write(e)):this[mS](e),this[_p]=!1;let r=this[ma].length>0?!1:this[pa]?this[pa].flowing:!0;return!r&&this[ma].length===0&&this[pa]?.once("drain",()=>this.emit("drain")),n?.(),r}[fI](e){e&&!this[ws]&&(this[Ut]=this[Ut]?Buffer.concat([this[Ut],e]):e)}[gS](){if(this[gl]&&!this[pI]&&!this[ws]&&!this[gh]){this[pI]=!0;let e=this[iu];if(e?.blockRemain){let t=this[Ut]?this[Ut].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Ut]&&e.write(this[Ut]),e.end()}this[ou](hS)}}[mS](e){if(this[gh]&&e)this[fI](e);else if(!e&&!this[Ut])this[gS]();else if(e){if(this[gh]=!0,this[Ut]){this[fI](e);let t=this[Ut];this[Ut]=void 0,this[fS](t)}else this[fS](e);for(;this[Ut]&&this[Ut]?.length>=512&&!this[ws]&&!this[vS];){let t=this[Ut];this[Ut]=void 0,this[fS](t)}this[gh]=!1}(!this[Ut]||this[gl])&&this[gS]()}[fS](e){let t=0,n=e.length;for(;t+512<=n&&!this[ws]&&!this[vS];)switch(this[Wi]){case"begin":case"header":this[_W](e,t),t+=512;break;case"ignore":case"body":t+=this[mI](e,t);break;case"meta":t+=this[wW](e,t);break;default:throw Error("invalid state: "+this[Wi])}t<n&&(this[Ut]=this[Ut]?Buffer.concat([e.subarray(t),this[Ut]]):e.subarray(t))}end(e,t,n){return typeof e=="function"&&(n=e,t=void 0,e=void 0),typeof t=="function"&&(n=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t)),n&&this.once("finish",n),this[ws]||(this[rn]?(e&&(this[hh]+=e.length,this[rn].write(e)),this[rn].end()):(this[gl]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[gS]())),this}},El=Dh(_Se,bSe,(e)=>new Oh(e),(e)=>new Oh(e),(e,t)=>{t?.length&&n9(e,t),e.noResume||wSe(e)}),{isAbsolute:kSe,parse:EW}=SSe,FS=["|","<",">","?",":"],YI=FS.map((e)=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),ESe=new Map(FS.map((e,t)=>[e,YI[t]])),ASe=new Map(YI.map((e,t)=>[e,FS[t]])),RW=Symbol("process"),PW=Symbol("file"),CW=Symbol("directory"),$I=Symbol("symlink"),$W=Symbol("hardlink"),yh=Symbol("header"),ES=Symbol("read"),xI=Symbol("lstat"),AS=Symbol("onlstat"),II=Symbol("onread"),OI=Symbol("onreadlink"),DI=Symbol("openfile"),TI=Symbol("onopenfile"),_l=Symbol("close"),TS=Symbol("mode"),jI=Symbol("awaitDrain"),hI=Symbol("ondrain"),bs=Symbol("prefix"),o9=class extends pu{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,t={}){let n=KI(t);super(),this.path=Ne(e),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||PSe,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Ne(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Ne(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let r=!1;if(!this.preservePaths){let[o,s]=ZI(this.path);o&&typeof s=="string"&&(this.path=s,r=o)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=RSe(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=Ne(n.absolute||kW.resolve(this.cwd,e)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let i=this.statCache.get(this.absolute);i?this[AS](i):this[xI]()}warn(e,t,n={}){return US(this,e,t,n)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[xI](){_s.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[AS](t)})}[AS](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=xSe(e),this.emit("stat",e),this[RW]()}[RW](){switch(this.type){case"File":return this[PW]();case"Directory":return this[CW]();case"SymbolicLink":return this[$I]();default:return this.end()}}[TS](e){return r9(e,this.type==="Directory",this.portable)}[bs](e){return i9(e,this.prefix)}[yh](){if(!this.stat)throw Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new du({path:this[bs](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bs](this.linkpath):this.linkpath,mode:this[TS](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new OS({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[bs](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bs](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw Error("failed to encode header");super.write(e)}[CW](){if(!this.stat)throw Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[yh](),this.end()}[$I](){_s.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[OI](t)})}[OI](e){this.linkpath=Ne(e),this[yh](),this.end()}[$W](e){if(!this.stat)throw Error("cannot create link entry without stat");this.type="Link",this.linkpath=Ne(kW.relative(this.cwd,e)),this.stat.size=0,this[yh](),this.end()}[PW](){if(!this.stat)throw Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[$W](t);this.linkCache.set(e,this.absolute)}if(this[yh](),this.stat.size===0)return this.end();this[DI]()}[DI](){_s.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[TI](t)})}[TI](e){if(this.fd=e,this.#e)return this[_l]();if(!this.stat)throw Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[ES]()}[ES](){let{fd:e,buf:t,offset:n,length:r,pos:i}=this;if(e===void 0||t===void 0)throw Error("cannot read file without first opening");_s.read(e,t,n,r,i,(o,s)=>{if(o)return this[_l](()=>this.emit("error",o));this[II](s)})}[_l](e=()=>{}){this.fd!==void 0&&_s.close(this.fd,e)}[II](e){if(e<=0&&this.remain>0){let n=Object.assign(Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[_l](()=>this.emit("error",n))}if(e>this.remain){let n=Object.assign(Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[_l](()=>this.emit("error",n))}if(!this.buf)throw Error("should have created buffer prior to reading");if(e===this.remain)for(let n=e;n<this.length&&e<this.blockRemain;n++)this.buf[n+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(t)?this[hI]():this[jI](()=>this[hI]())}[jI](e){this.once("drain",e)}write(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemain<e.length){let r=Object.assign(Error("writing more data than expected"),{path:this.absolute});return this.emit("error",r)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,n)}[hI](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[_l]((e)=>e?this.emit("error",e):this.end());if(!this.buf)throw Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[ES]()}},CSe=class extends o9{sync=!0;[xI](){this[AS](_s.lstatSync(this.absolute))}[$I](){this[OI](_s.readlinkSync(this.absolute))}[DI](){this[TI](_s.openSync(this.absolute,"r"))}[ES](){let e=!0;try{let{fd:t,buf:n,offset:r,length:i,pos:o}=this;if(t===void 0||n===void 0)throw Error("fd and buf must be set in READ method");let s=_s.readSync(t,n,r,i,o);this[II](s),e=!1}finally{if(e)try{this[_l](()=>{})}catch{}}}[jI](e){e()}[_l](e=()=>{}){this.fd!==void 0&&_s.closeSync(this.fd),e()}},$Se=class extends pu{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,t,n={}){return US(this,e,t,n)}constructor(e,t={}){let n=KI(t);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=e;let{type:r}=e;if(r==="Unsupported")throw Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=Ne(e.path),this.mode=e.mode!==void 0?this[TS](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:n.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?Ne(e.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=ZI(this.path);s&&typeof a=="string"&&(this.path=a,i=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new du({path:this[bs](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bs](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new OS({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[bs](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bs](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw Error("failed to encode header");super.write(o),e.pipe(this)}[bs](e){return i9(e,this.prefix)}[TS](e){return r9(e,this.type==="Directory",this.portable)}write(e,t,n){typeof t=="function"&&(n=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let r=e.length;if(r>this.blockRemain)throw Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(e,n)}end(e,t,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(n=e,t=void 0,e=void 0),typeof t=="function"&&(n=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),n&&this.once("finish",n),e?super.end(e,n):super.end(n),this}},ISe=class e{tail;head;length=0;static create(t=[]){return new e(t)}constructor(t=[]){for(let n of t)this.push(n)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw Error("removing node which does not belong to this list");let{next:n,prev:r}=t;return n&&(n.prev=r),r&&(r.next=n),t===this.head&&(this.head=n),t===this.tail&&(this.tail=r),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,n}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let n=this.head;t.list=this,t.next=n,n&&(n.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let n=this.tail;t.list=this,t.prev=n,n&&(n.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let n=0,r=t.length;n<r;n++)DSe(this,t[n]);return this.length}unshift(...t){for(var n=0,r=t.length;n<r;n++)TSe(this,t[n]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,t}forEach(t,n){n=n||this;for(let r=this.head,i=0;r;i++)t.call(n,r.value,i,this),r=r.next}forEachReverse(t,n){n=n||this;for(let r=this.tail,i=this.length-1;r;i--)t.call(n,r.value,i,this),r=r.prev}get(t){let n=0,r=this.head;for(;r&&n<t;n++)r=r.next;if(n===t&&r)return r.value}getReverse(t){let n=0,r=this.tail;for(;r&&n<t;n++)r=r.prev;if(n===t&&r)return r.value}map(t,n){n=n||this;let r=new e;for(let i=this.head;i;)r.push(t.call(n,i.value,this)),i=i.next;return r}mapReverse(t,n){n=n||this;var r=new e;for(let i=this.tail;i;)r.push(t.call(n,i.value,this)),i=i.prev;return r}reduce(t,n){let r,i=this.head;if(arguments.length>1)r=n;else if(this.head)i=this.head.next,r=this.head.value;else throw TypeError("Reduce of empty list with no initial value");for(var o=0;i;o++)r=t(r,i.value,o),i=i.next;return r}reduceReverse(t,n){let r,i=this.tail;if(arguments.length>1)r=n;else if(this.tail)i=this.tail.prev,r=this.tail.value;else throw TypeError("Reduce of empty list with no initial value");for(let o=this.length-1;i;o--)r=t(r,i.value,o),i=i.prev;return r}toArray(){let t=Array(this.length);for(let n=0,r=this.head;r;n++)t[n]=r.value,r=r.next;return t}toArrayReverse(){let t=Array(this.length);for(let n=0,r=this.tail;r;n++)t[n]=r.value,r=r.prev;return t}slice(t=0,n=this.length){n<0&&(n+=this.length),t<0&&(t+=this.length);let r=new e;if(n<t||n<0)return r;t<0&&(t=0),n>this.length&&(n=this.length);let i=this.head,o=0;for(o=0;i&&o<t;o++)i=i.next;for(;i&&o<n;o++,i=i.next)r.push(i.value);return r}sliceReverse(t=0,n=this.length){n<0&&(n+=this.length),t<0&&(t+=this.length);let r=new e;if(n<t||n<0)return r;t<0&&(t=0),n>this.length&&(n=this.length);let i=this.length,o=this.tail;for(;o&&i>n;i--)o=o.prev;for(;o&&i>t;i--,o=o.prev)r.push(o.value);return r}splice(t,n=0,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let i=this.head;for(let s=0;i&&s<t;s++)i=i.next;let o=[];for(let s=0;i&&s<n;s++)o.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let s of r)i=OSe(this,i,s);return o}reverse(){let t=this.head,n=this.tail;for(let r=t;r;r=r.prev){let i=r.prev;r.prev=r.next,r.next=i}return this.head=n,this.tail=t,this}};OW=Buffer.alloc(1024),RS=Symbol("onStat"),vh=Symbol("ended"),Ao=Symbol("queue"),wh=Symbol("pendingLinks"),hl=Symbol("current"),au=Symbol("process"),_h=Symbol("processing"),wS=Symbol("processJob"),Ro=Symbol("jobs"),yI=Symbol("jobDone"),PS=Symbol("addFSEntry"),DW=Symbol("addTarEntry"),NI=Symbol("stat"),MI=Symbol("readdir"),CS=Symbol("onreaddir"),$S=Symbol("pipe"),TW=Symbol("entry"),vI=Symbol("entryOpt"),xS=Symbol("writeEntryClass"),s9=Symbol("write"),wI=Symbol("ondrain"),zS=class extends pu{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[xS];onWriteEntry;[Ao];[wh]=new Map;[Ro]=0;[_h]=!1;[vh]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=Ne(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[xS]=o9,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli||e.zstd){if((e.gzip?1:0)+(e.brotli?1:0)+(e.zstd?1:0)>1)throw TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new Ube(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new zbe(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new Bbe(e.zstd)),!this.zip)throw Error("impossible");let t=this.zip;t.on("data",(n)=>super.write(n)),t.on("end",()=>super.end()),t.on("drain",()=>this[wI]()),this.on("resume",()=>t.resume())}else this.on("drain",this[wI]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[Ao]=new ISe,this[Ro]=0,this.jobs=Number(e.jobs)||4,this[_h]=!1,this[vh]=!1}[s9](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t=void 0),e&&this.add(e),this[vh]=!0,this[au](),n&&n(),this}write(e){if(this[vh])throw Error("write after end");return typeof e=="string"?this[PS](e):this[DW](e),this.flowing}[DW](e){let t=Ne(xW.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let n=new IW(e.path,t);n.entry=new $Se(e,this[vI](n)),n.entry.on("end",()=>this[yI](n)),this[Ro]+=1,this[Ao].push(n)}this[au]()}[PS](e){let t=Ne(xW.resolve(this.cwd,e));this[Ao].push(new IW(e,t)),this[au]()}[NI](e){e.pending=!0,this[Ro]+=1;let t=this.follow?"stat":"lstat";DS[t](e.absolute,(n,r)=>{e.pending=!1,this[Ro]-=1,n?this.emit("error",n):this[RS](e,r)})}[RS](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[hl])this[wS](e);else{let n=`${t.dev}:${t.ino}`,r=this[wh].get(n);r?r.push(e):this[wh].set(n,[e]),e.pendingLink=!0,e.pending=!0}this[au]()}[MI](e){e.pending=!0,this[Ro]+=1,DS.readdir(e.absolute,(t,n)=>{if(e.pending=!1,this[Ro]-=1,t)return this.emit("error",t);this[CS](e,n)})}[CS](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[au]()}[au](){if(!this[_h]){this[_h]=!0;for(let e=this[Ao].head;e&&this[Ro]<this.jobs;e=e.next)if(this[wS](e.value),e.value.ignore){let t=e.next;this[Ao].removeNode(e),e.next=t}this[_h]=!1,this[vh]&&this[Ao].length===0&&this[Ro]===0&&(this.zip?this.zip.end(OW):(super.write(OW),super.end()))}}get[hl](){return this[Ao]&&this[Ao].head&&this[Ao].head.value}[yI](e){this[Ao].shift(),this[Ro]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let n=`${t.dev}:${t.ino}`,r=this[wh].get(n);if(r){this[wh].delete(n);for(let i of r)i.pending=!1,this[wS](i)}}this[au]()}[wS](e){if(e.pending&&e.pendingLink&&e===this[hl]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[hl]&&!e.piped&&this[$S](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[RS](e,t):this[NI](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[CS](e,t):this[MI](e),!e.readdir)return}if(e.entry=this[TW](e),!e.entry){e.ignore=!0;return}e===this[hl]&&!e.piped&&this[$S](e)}}}[vI](e){return{onwarn:(t,n,r)=>this.warn(t,n,r),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[TW](e){this[Ro]+=1;try{return new this[xS](e.path,this[vI](e)).on("end",()=>this[yI](e)).on("error",(t)=>this.emit("error",t))}catch(t){this.emit("error",t)}}[wI](){this[hl]&&this[hl].entry&&this[hl].entry.resume()}[$S](e){e.piped=!0,e.readdir&&e.readdir.forEach((r)=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[PS](o+r)});let t=e.entry,n=this.zip;if(!t)throw Error("cannot pipe without source");n?t.on("data",(r)=>{n.write(r)||t.pause()}):t.on("data",(r)=>{super.write(r)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,n={}){US(this,e,t,n)}},QI=class extends zS{sync=!0;constructor(e){super(e),this[xS]=CSe}pause(){}resume(){}[NI](e){let t=this.follow?"statSync":"lstatSync";this[RS](e,DS[t](e.absolute))}[MI](e){this[CS](e,DS.readdirSync(e.absolute))}[$S](e){let t=e.entry,n=this.zip;if(e.readdir&&e.readdir.forEach((r)=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[PS](o+r)}),!t)throw Error("Cannot pipe without source");n?t.on("data",(r)=>{n.write(r)}):t.on("data",(r)=>{super[s9](r)})}},eO=Dh(jSe,NSe,MSe,LSe,(e,t)=>{if(!t?.length)throw TypeError("no paths specified to add to archive")}),FSe=process.env.__FAKE_PLATFORM__||process.platform,p9=FSe==="win32",{O_CREAT:m9,O_NOFOLLOW:jW,O_TRUNC:f9,O_WRONLY:g9}=d9.constants,h9=Number(process.env.__FAKE_FS_O_FILENAME__)||d9.constants.UV_FS_O_FILEMAP||0,zSe=p9&&!!h9,BSe=h9|f9|m9|g9,NW=!p9&&typeof jW=="number"?jW|f9|m9|g9:null,y9=NW!==null?()=>NW:zSe?(e)=>e<HSe?BSe:"w":()=>"w",_9=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}},BS=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}},_I=Object.create(null),bp=new Set,XSe=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,QSe=XSe==="win32",LW=Symbol("onEntry"),FI=Symbol("checkFs"),UW=Symbol("checkFs2"),zI=Symbol("isReusable"),Ki=Symbol("makeFs"),HI=Symbol("file"),BI=Symbol("directory"),IS=Symbol("link"),FW=Symbol("symlink"),zW=Symbol("hardlink"),kh=Symbol("ensureNoSymlink"),HW=Symbol("unsupported"),BW=Symbol("checkPath"),bI=Symbol("stripAbsolutePath"),bl=Symbol("mkdir"),Nn=Symbol("onError"),_S=Symbol("pending"),VW=Symbol("pend"),Sp=Symbol("unpend"),SI=Symbol("ended"),kI=Symbol("maybeClose"),VI=Symbol("skip"),Ph=Symbol("doChown"),Ch=Symbol("uid"),$h=Symbol("gid"),xh=Symbol("checkedCwd"),rke=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ih=rke==="win32",tO=class extends Oh{[SI]=!1;[xh]=!1;[_S]=0;reservations=new tke;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[SI]=!0,this[kI]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?process.getuid?.()===0:!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:ike,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||Ih,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Ne(An.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:nke():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",(t)=>this[LW](t))}warn(e,t,n={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(n.recoverable=!1),super.warn(e,t,n)}[kI](){this[SI]&&this[_S]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[bI](e,t){let n=e[t],{type:r}=e;if(!n||this.preservePaths)return!0;let[i,o]=ZI(n),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||Ih&&/^[a-z]:\.\.$/i.test(s[0]??"")){if(t==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:n}),!1;let a=An.posix.dirname(e.path),l=An.posix.normalize(An.posix.join(a,s.join("/")));if(l.startsWith("../")||l==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:n}),!1}return i&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${t}`,{entry:e,[t]:n})),!0}[BW](e){let t=Ne(e.path),n=t.split("/");if(this.strip){if(n.length<this.strip)return!1;if(e.type==="Link"){let r=Ne(String(e.linkpath)).split("/");if(r.length>=this.strip)e.linkpath=r.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),e.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[bI](e,"path")||!this[bI](e,"linkpath"))return!1;if(e.absolute=An.isAbsolute(e.path)?Ne(An.resolve(e.path)):Ne(An.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:Ne(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:r}=An.win32.parse(String(e.absolute));e.absolute=r+AW(String(e.absolute).slice(r.length));let{root:i}=An.win32.parse(e.path);e.path=i+AW(e.path.slice(i.length))}return!0}[LW](e){if(!this[BW](e))return e.resume();switch(USe.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[FI](e);default:return this[HW](e)}}[Nn](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Sp](),t.resume())}[bl](e,t,n){GSe(Ne(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},n)}[Ph](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ch](e){return qW(this.uid,e.uid,this.processUid)}[$h](e){return qW(this.gid,e.gid,this.processGid)}[HI](e,t){let n=typeof e.mode=="number"?e.mode&4095:this.fmode,r=new MS(String(e.absolute),{flags:y9(e.size),mode:n,autoClose:!1});r.on("error",(a)=>{r.fd&&Ke.close(r.fd,()=>{}),r.write=()=>!0,this[Nn](a,e),t()});let i=1,o=(a)=>{if(a){r.fd&&Ke.close(r.fd,()=>{}),this[Nn](a,e),t();return}--i===0&&r.fd!==void 0&&Ke.close(r.fd,(l)=>{l?this[Nn](l,e):this[Sp](),t()})};r.on("finish",()=>{let a=String(e.absolute),l=r.fd;if(typeof l=="number"&&e.mtime&&!this.noMtime){i++;let c=e.atime||new Date,u=e.mtime;Ke.futimes(l,c,u,(d)=>d?Ke.utimes(a,c,u,(p)=>o(p&&d)):o())}if(typeof l=="number"&&this[Ph](e)){i++;let c=this[Ch](e),u=this[$h](e);typeof c=="number"&&typeof u=="number"&&Ke.fchown(l,c,u,(d)=>d?Ke.chown(a,c,u,(p)=>o(p&&d)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",(a)=>{this[Nn](a,e),t()}),e.pipe(s)),s.pipe(r)}[BI](e,t){let n=typeof e.mode=="number"?e.mode&4095:this.dmode;this[bl](String(e.absolute),n,(r)=>{if(r){this[Nn](r,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Sp](),e.resume())};e.mtime&&!this.noMtime&&(i++,Ke.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[Ph](e)&&(i++,Ke.chown(String(e.absolute),Number(this[Ch](e)),Number(this[$h](e)),o)),o()})}[HW](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[FW](e,t){let n=Ne(An.relative(this.cwd,An.resolve(An.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[kh](e,this.cwd,n,()=>this[IS](e,String(e.linkpath),"symlink",t),(r)=>{this[Nn](r,e),t()})}[zW](e,t){let n=Ne(An.resolve(this.cwd,String(e.linkpath))),r=Ne(String(e.linkpath)).split("/");this[kh](e,this.cwd,r,()=>this[IS](e,n,"link",t),(i)=>{this[Nn](i,e),t()})}[kh](e,t,n,r,i){let o=n.shift();if(this.preservePaths||o===void 0)return r();let s=An.resolve(t,o);Ke.lstat(s,(a,l)=>{if(a)return r();if(l?.isSymbolicLink())return i(new BS(s,An.resolve(s,n.join("/"))));this[kh](e,s,n,r,i)})}[VW](){this[_S]++}[Sp](){this[_S]--,this[kI]()}[VI](e){this[Sp](),e.resume()}[zI](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!Ih}[FI](e){this[VW]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,(n)=>this[UW](e,n))}[UW](e,t){let n=(s)=>{t(s)},r=()=>{this[bl](this.cwd,this.dmode,(s)=>{if(s){this[Nn](s,e),n();return}this[xh]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Ne(An.dirname(String(e.absolute)));if(s!==this.cwd)return this[bl](s,this.dmode,(a)=>{if(a){this[Nn](a,e),n();return}o()})}o()},o=()=>{Ke.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[VI](e),n();return}if(s||this[zI](e,a))return this[Ki](null,e,n);if(a.isDirectory()){if(e.type==="Directory"){let l=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,c=(u)=>this[Ki](u??null,e,n);return l?Ke.chmod(String(e.absolute),Number(e.mode),c):c()}if(e.absolute!==this.cwd)return Ke.rmdir(String(e.absolute),(l)=>this[Ki](l??null,e,n))}if(e.absolute===this.cwd)return this[Ki](null,e,n);oke(String(e.absolute),(l)=>this[Ki](l??null,e,n))})};this[xh]?i():r()}[Ki](e,t,n){if(e){this[Nn](e,t),n();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[HI](t,n);case"Link":return this[zW](t,n);case"SymbolicLink":return this[FW](t,n);case"Directory":case"GNUDumpDir":return this[BI](t,n)}}[IS](e,t,n,r){Ke[n](t,String(e.absolute),(i)=>{i?this[Nn](i,e):(this[Sp](),e.resume()),r()})}},k9=class extends tO{sync=!0;[Ki](e,t){return super[Ki](e,t,()=>{})}[FI](e){if(!this[xh]){let i=this[bl](this.cwd,this.dmode);if(i)return this[Nn](i,e);this[xh]=!0}if(e.absolute!==this.cwd){let i=Ne(An.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[bl](i,this.dmode);if(o)return this[Nn](o,e)}}let[t,n]=bh(()=>Ke.lstatSync(String(e.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(e.mtime??n.mtime)))return this[VI](e);if(t||this[zI](e,n))return this[Ki](null,e);if(n.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(n.mode&4095)!==e.mode,[s]=o?bh(()=>{Ke.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[Ki](s,e)}let[i]=bh(()=>Ke.rmdirSync(String(e.absolute)));this[Ki](i,e)}let[r]=e.absolute===this.cwd?[]:bh(()=>ske(String(e.absolute)));this[Ki](r,e)}[HI](e,t){let n=typeof e.mode=="number"?e.mode&4095:this.fmode,r=(s)=>{let a;try{Ke.closeSync(i)}catch(l){a=l}(s||a)&&this[Nn](s||a,e),t()},i;try{i=Ke.openSync(String(e.absolute),y9(e.size),n)}catch(s){return r(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",(s)=>this[Nn](s,e)),e.pipe(o)),o.on("data",(s)=>{try{Ke.writeSync(i,s,0,s.length)}catch(a){r(a)}}),o.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,l=e.mtime;try{Ke.futimesSync(i,a,l)}catch(c){try{Ke.utimesSync(String(e.absolute),a,l)}catch{s=c}}}if(this[Ph](e)){let a=this[Ch](e),l=this[$h](e);try{Ke.fchownSync(i,Number(a),Number(l))}catch(c){try{Ke.chownSync(String(e.absolute),Number(a),Number(l))}catch{s=s||c}}}r(s)})}[BI](e,t){let n=typeof e.mode=="number"?e.mode&4095:this.dmode,r=this[bl](String(e.absolute),n);if(r){this[Nn](r,e),t();return}if(e.mtime&&!this.noMtime)try{Ke.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[Ph](e))try{Ke.chownSync(String(e.absolute),Number(this[Ch](e)),Number(this[$h](e)))}catch{}t(),e.resume()}[bl](e,t){try{return ZSe(Ne(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(n){return n}}[kh](e,t,n,r,i){if(this.preservePaths||n.length===0)return r();let o=t;for(let s of n){o=An.resolve(o,s);let[a,l]=bh(()=>Ke.lstatSync(o));if(a)return r();if(l.isSymbolicLink())return i(new BS(o,An.resolve(t,n.join("/"))))}r()}[IS](e,t,n,r){let i=`${n}Sync`;try{Ke[i](t,String(e.absolute)),r(),e.resume()}catch(o){return this[Nn](o,e)}}},Th=Dh(ake,lke,(e)=>new k9(e),(e)=>new tO(e),(e,t)=>{t?.length&&n9(e,t)}),Sh=Dh(cke,dke,()=>{throw TypeError("file is required")},()=>{throw TypeError("file is required")},(e,t)=>{if(!Obe(e))throw TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw TypeError("cannot append to compressed archives");if(!t?.length)throw TypeError("no paths specified to add/replace")}),Fyt=Dh(Sh.syncFile,Sh.asyncFile,Sh.syncNoFile,Sh.asyncNoFile,(e,t=[])=>{Sh.validate?.(e,t),fke(e)})});var R9=()=>{};function P9(e){return Array.from(e.trim()).length}var rO=2,iO=500;var oO=200,C9="^[A-Za-z0-9][A-Za-z0-9._-]{0,199}(/[A-Za-z0-9][A-Za-z0-9._-]{0,199}){0,3}$",$9;var x9=b(()=>{$9=["download","content","install"]});var VS=b(()=>{R9();x9()});function yke(e){let t=e.split("/");return t.length>1&&hke.has(t[t.length-1]??"")}function Xt(e){return e.length<=oO&&gke.test(e)&&!yke(e)}function mu(e){if(!Xt(e))throw new qS(e)}function $p(e){let n=e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[^a-z0-9]+|[^a-z0-9]+$/g,"").substring(0,oO)||"unnamed-skill";return mu(n),n}var gke,hke,qS;var $o=b(()=>{VS();gke=new RegExp(C9),hke=new Set($9);qS=class qS extends Error{constructor(e){super(`Invalid skill_key: ${JSON.stringify(e)}`);this.name="SkillKeyValidationError"}}});import{createHash as vke}from"node:crypto";import{existsSync as sO,lstatSync as wke,mkdirSync as I9,mkdtempSync as _ke,realpathSync as bke,renameSync as aO,rmSync as O9}from"node:fs";import{lstat as D9,readdir as Ske,realpath as WS}from"node:fs/promises";import{basename as T9,dirname as lO,isAbsolute as kke,join as KS,relative as Eke,resolve as Ake}from"node:path";import{createGunzip as Rke,gunzipSync as Pke}from"node:zlib";function uO(e){return e==="File"||e==="OldFile"||e==="ContiguousFile"}function Cke(e){return uO(e)||e==="Directory"}function j9(e){return e.split(/[\\/]/).some((t)=>t.toLowerCase().startsWith(".clawdi-managed"))}function N9(e){let t=e.limits??GS,n="fileCount"in t?t.fileCount:void 0,r=e.resourceLabel??"Skill archive",i=0,o=0,s=0;return(a,l)=>{if(e.filter&&!e.filter(a,l))return!1;if(a.includes("..")||a.startsWith("/"))return!1;if(!e.allowReservedManagementPaths&&j9(a))throw Error(`${r} contains reserved management metadata`);let c="type"in l?l.type:void 0;if(!Cke(c))throw Error(`${r} contains an unsupported entry type`);if(i+=1,i>t.entryCount)throw Error(`${r} exceeds ${t.entryCount} entries`);let u=l.size;if(!Number.isSafeInteger(u)||u<0)throw Error(`${r} contains an invalid entry size`);if(u>t.entryBytes)throw Error(`${r} entry exceeds ${t.entryBytes} bytes`);if(uO(c)){if(o+=1,n!==void 0&&o>n)throw Error(`${r} exceeds ${n} files`)}if(s+=u,s>t.totalEntryBytes)throw Error(`${r} exceeds ${t.totalEntryBytes} total entry bytes`);return!0}}function xo(e,t,n={}){let r=n.limits??GS,i=n.resourceLabel??"Skill archive";return $ke(t,r.expandedTarBytes,i).then(()=>new Promise((o,s)=>{let a=Th({cwd:e,gzip:!0,filter:N9(n)});a.on("close",()=>o()),a.on("error",s),a.end(t)}))}function M9(e,t,n={}){let r=n.limits??GS,i=n.resourceLabel??"Skill archive",o;try{o=Pke(t,{maxOutputLength:r.expandedTarBytes})}catch(a){throw Error(`${i} is invalid or exceeds ${r.expandedTarBytes} expanded tar bytes`,{cause:a})}Th({cwd:e,sync:!0,filter:N9(n)}).end(o)}function $ke(e,t=GS.expandedTarBytes,n="Skill archive"){return new Promise((r,i)=>{let o=0,s=!1,a=Rke(),l=(c)=>{if(s)return;s=!0,a.destroy(),i(c)};a.on("error",(c)=>l(c)),a.on("data",(c)=>{if(o+=c.length,o>t)l(Error(`${n} exceeds ${t} expanded tar bytes`))}),a.on("end",()=>{if(s)return;s=!0,r()}),a.end(e)})}async function ha(e,t,n,r,i,o=(s)=>s()){mu(e);let s=Eke(t,n);if(!s||s.startsWith("..")||kke(s))throw Error(`Skill target must be inside skills root: ${n}`);I9(t,{recursive:!0});let a=bke(t),l=lO(a),c=_ke(KS(l,`.${T9(t)}-stage-`)),u=KS(c,e),d=KS(c,".previous"),p=!1;try{if(await xo(c,r),!sO(u)||!wke(u).isDirectory())throw Error(`Skill tarball did not contain expected '${e}/' root entry`);I9(lO(n),{recursive:!0}),o(()=>{let m=!1;if(sO(n))aO(n,d),m=!0;try{i?.(),aO(u,n)}catch(f){if(!m)throw f;try{aO(d,n)}catch(g){p=!0;let v=f instanceof Error?f.message:String(f),w=g instanceof Error?g.message:String(g);throw Error(`Skill install failed: ${v}; restoring the previous version failed: ${w}; previous version retained at ${d}`,{cause:f})}throw f}if(sO(d))O9(d,{recursive:!0,force:!0})})}finally{if(!p)O9(c,{recursive:!0,force:!0})}}async function xke(e,t){let n=await WS(e),r=Array.isArray(t)?t:t!==void 0?[t]:[lO(n)],i=await Promise.all(r.map((u)=>WS(u).catch(()=>u))),o=(u)=>{for(let d of i)if(u===d||u.startsWith(`${d}/`))return!0;return!1},s=[],a=new Set,l=new Set,c=async(u)=>{let d;try{d=await WS(u)}catch{s.push(u);return}if(l.has(d)){s.push(u);return}if(a.has(d))return;l.add(d);let p=await Ske(u,{withFileTypes:!0});try{for(let m of p){if(cO.has(m.name))continue;let f=KS(u,m.name);if(m.isSymbolicLink()){try{let g=await WS(f);if(!o(g)){s.push(f);continue}if((await D9(g)).isDirectory())await c(g)}catch{s.push(f)}continue}if(m.isDirectory())try{if((await D9(f)).isDirectory())await c(f)}catch{}}}finally{l.delete(d),a.add(d)}};return await c(e),s}async function dO(e,t,n){let r=n??T9(e),i=r.split("/").filter(Boolean),o=e;for(let l=0;l<i.length;l++)o=Ake(o,"..");let s=await xke(e,t??o);if(s.length>0)throw Error(`Skill contains symlink(s) pointing outside the agent's skills directory, broken, or cyclic; refusing to upload: ${s.join(", ")}`);let a=[];return await eO({gzip:!0,cwd:o,follow:!0,filter:(l)=>{if(j9(l))throw Error("Skill contains reserved management metadata");return!l.split("/").slice(i.length).some((u)=>cO.has(u))}},[r]).on("data",(l)=>a.push(l)).promise(),Buffer.concat(a)}async function Ike(e,t){let n=t?t.split("/").length:1,r=[],i=El({gzip:!0,onReadEntry:(a)=>{if(!uO(a.type)){a.resume();return}let c=a.path.split("/").slice(n),u=c.join("/");if(!u||c.some((d)=>cO.has(d))){a.resume();return}r.push(a.concat().then((d)=>({relativePath:u,content:Buffer.from(d)})))}});await new Promise((a,l)=>{i.on("end",a),i.on("error",l),i.end(e)});let o=await Promise.all(r);o.sort((a,l)=>Oke(a.relativePath,l.relativePath));let s=vke("sha256");for(let a of o)s.update(a.relativePath),s.update(a.content);return s.digest("hex")}function Oke(e,t){let n=e[Symbol.iterator](),r=t[Symbol.iterator]();while(!0){let i=n.next(),o=r.next();if(i.done||o.done){if(i.done&&o.done)return 0;return i.done?-1:1}let s=i.value.codePointAt(0),a=o.value.codePointAt(0);if(s===void 0||a===void 0)throw Error("Unicode iterator returned an empty code point");if(s!==a)return s<a?-1:1}}async function pr(e,t,n){let r=await dO(e,t,n);return{archive:r,hash:await Ike(r,n)}}async function L9(e,t){let{mkdtempSync:n,writeFileSync:r,mkdirSync:i,rmSync:o}=await import("node:fs"),{tmpdir:s}=await import("node:os"),{join:a}=await import("node:path"),l=n(a(s(),"clawdi-skill-")),c=a(l,e);i(c,{recursive:!0}),r(a(c,"SKILL.md"),t);let u=[];await eO({gzip:!0,cwd:l},[e]).on("data",(p)=>u.push(p)).promise();let d=Buffer.concat(u);return o(l,{recursive:!0,force:!0}),d}var cO,GS;var Kr=b(()=>{nO();$o();cO=new Set(["node_modules",".git",".turbo",".cache","dist","build","out","target","__pycache__",".venv","venv",".pytest_cache",".mypy_cache",".ruff_cache",".tox","coverage",".agents",".cursor",".factory",".openclaw",".hermes",".gbrain",".claude",".codex"]),GS=Object.freeze({entryCount:1024,entryBytes:16777216,totalEntryBytes:33554432,expandedTarBytes:37748736})});import{createHash as U9}from"node:crypto";import{lstatSync as F9,readdirSync as Dke,readFileSync as Tke}from"node:fs";import{join as jke}from"node:path";function Al(e,t){let n=t.resourceLabel??"file tree",r=F9(e);if(!r.isDirectory()||r.isSymbolicLink())throw Error(`${n} root is not a trusted directory`);let i=[],o=new Set,s=0,a=0,l=(c,u)=>{for(let d of Dke(c).sort((p,m)=>Buffer.compare(Buffer.from(p,"utf8"),Buffer.from(m,"utf8")))){let p=u?`${u}/${d}`:d;if(t.exclude?.(p))continue;t.validatePath?.(p);let m=t.collisionKey?.(p);if(m!==void 0){if(o.has(m))throw Error(t.collisionError??`${n} contains a path collision`);o.add(m)}if(s+=1,s>t.limits.entries)throw Error(`${n} exceeds ${t.limits.entries} entries`);let f=jke(c,d),g=F9(f);if(g.isDirectory()&&!g.isSymbolicLink()){l(f,p);continue}if(!g.isFile()||g.isSymbolicLink())throw Error(`${n} contains a non-regular entry`);if(i.length>=t.limits.files)throw Error(`${n} exceeds ${t.limits.files} files`);if(g.size>t.limits.fileBytes)throw Error(`${n} file exceeds ${t.limits.fileBytes} bytes`);if(a+=g.size,a>t.limits.totalBytes)throw Error(`${n} exceeds ${t.limits.totalBytes} total file bytes`);let v=Tke(f);if(v.length!==g.size)throw Error(`${n} changed while reading`);i.push({path:p,mode:(g.mode&73)!==0?33261:33188,bytes:v})}};return l(e,""),i}function xp(e){let t=U9("sha256");for(let n of[...e].sort((r,i)=>Buffer.compare(Buffer.from(r.path,"utf8"),Buffer.from(i.path,"utf8")))){let r=U9("sha256").update(n.bytes).digest("hex");t.update(`${n.mode.toString(8)}\x00${n.path}\x00${n.bytes.length}\x00${r}
7
- `,"utf8")}return`sha256-tree-v1:${t.digest("hex")}`}var jh=()=>{};function H9(e){return xp(Al(e,{limits:Nh,resourceLabel:"managed Skill tree"})).slice(15)}function on(e){return H9(e)}function pO(){return[...z9.keys()]}function Mh(e,t){let n=z9.get(e);if(!n)throw Error(`no bundled hosted skill is registered for ${e}`);let r=n.get(t);if(!r)throw Error(`no bundled hosted skill ${e} version ${t} is registered`);return r}function B9(e,t){if(H9(t)!==e.digest)throw Error(`bundled hosted skill catalog digest mismatch for ${e.id} version ${e.version}`)}var z9,Nh;var Io=b(()=>{jh();z9=new Map([["clawdi",new Map([[1,Object.freeze({id:"clawdi",version:1,assetDirectory:"hosted-versions/1/clawdi",digest:"c612838e760ba65d0f305829d55410cd9521456e802cd168b6f516a9459b5b65"})]])]]),Nh=Object.freeze({entries:1024,files:1024,fileBytes:16777216,totalBytes:33554432})});function V9(e,t){if(typeof e!=="string"||e.length>2048)throw Error(`${t} must be a valid absolute http:// or https:// URL.`);let n=e.trim(),r;try{r=new URL(n)}catch{throw Error(`${t} must be a valid absolute http:// or https:// URL.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw Error(`${t} must use http:// or https://.`);let i=n.indexOf("://")+3,o=n.slice(i).search(/[/?#]/),s=o===-1?n.slice(i):n.slice(i,i+o);if(r.username||r.password||s.includes("@"))throw Error(`${t} must not contain credentials.`);if(!r.hostname||!r.hostname.startsWith("[")&&!r.hostname.split(".").every((c)=>/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(c)))throw Error(`${t} must contain a canonical hostname.`);if(n.includes("?")||n.includes("#"))throw Error(`${t} must not contain a query or fragment.`);let a=n.indexOf("/",i),l=a===-1?"":n.slice(a);return{url:r,rawPath:l}}function Nke(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function q9(e,t){if(e.protocol==="http:"&&!Nke(e.hostname))throw Error(`${t} must use HTTPS except on loopback localhost.`)}function At(e){let{url:n,rawPath:r}=V9(e,"Clawdi Cloud API URL");if(q9(n,"Clawdi Cloud API URL"),r!==""&&r!=="/"||n.pathname!=="/")throw Error("Clawdi Cloud API URL must not contain a non-root path.");return n.origin}function ya(e){let{url:n,rawPath:r}=V9(e,"Hosted deploy API URL");if(q9(n,"Hosted deploy API URL"),!["","/","/v2","/v2/"].includes(r))throw Error("Hosted deploy API URL must use the origin root or the compatible /v2 base.");if(n.pathname!=="/"&&n.pathname!=="/v2"&&n.pathname!=="/v2/")throw Error("Hosted deploy API URL must use the origin root or the compatible /v2 base.");return n.origin}function Ft(e){return new URL(e).origin}function mO(e){return e==="https://cloud-api.clawdi.ai"}import{chmodSync as Mke,lstatSync as K9,mkdirSync as Lke}from"node:fs";import{isAbsolute as Uke,join as Fke,relative as zke,resolve as W9}from"node:path";function G9(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function fu(e,t="trusted directory"){let n;try{n=K9(e)}catch(r){if(G9(r))throw Error(`${t} is missing: ${e}`);throw r}if(!n.isDirectory()||n.isSymbolicLink())throw Error(`${t} is not a real directory: ${e}`)}function Rr(e,t,n={}){let r=W9(e),i=W9(t),o=zke(r,i);if(o.startsWith("..")||Uke(o))throw Error(`directory is outside trusted root ${e}: ${t}`);if(fu(r),!o)return;let s=r;for(let a of o.split("/")){s=Fke(s,a);try{let l=K9(s);if(!l.isDirectory()||l.isSymbolicLink())throw Error(`trusted directory path contains a non-directory: ${s}`)}catch(l){if(!G9(l))throw l;if(Lke(s,n.mode===void 0?void 0:{mode:n.mode}),n.mode!==void 0)Mke(s,n.mode)}}}var Ip=()=>{};import{chmodSync as Hke,closeSync as Bke,existsSync as Vke,fsyncSync as qke,mkdirSync as Wke,openSync as Kke,renameSync as Gke,rmSync as Jke,writeFileSync as Zke}from"node:fs";import{basename as Yke,dirname as Xke,join as Qke}from"node:path";function ie(e,t,n={}){let r=n.mode??at,i=Xke(e);if(n.trustedRoot)Rr(n.trustedRoot,i,{...n.dirMode===void 0?{}:{mode:n.dirMode}});else{let s=Vke(i);if(Wke(i,{recursive:!0,...n.dirMode===void 0?{}:{mode:n.dirMode}}),!s&&n.dirMode!==void 0)Op(i,n.dirMode)}let o=Qke(i,`.${Yke(e)}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);try{if(Zke(o,t,{mode:r}),Op(o,r),n.durable)J9(o);if(Gke(o,e),Op(e,r),n.durable)J9(i)}catch(s){throw Jke(o,{force:!0}),s}}function J9(e){let t=Kke(e,"r");try{qke(t)}finally{Bke(t)}}function Op(e,t){try{Hke(e,t)}catch{}}var at=384,Ge=448;var _t=b(()=>{Ip()});var Q9={};ae(Q9,{CONFIG_KEYS:()=>XS,clearAuth:()=>Fh,clearPendingAuth:()=>Dp,getAuth:()=>we,getClawdiDir:()=>ge,getConfig:()=>Se,getPendingAuth:()=>Es,getStoredAuth:()=>ks,getStoredConfig:()=>Oo,isLoggedIn:()=>Ve,readRecoverablePrivateJson:()=>Rl,setAuth:()=>Uh,setConfig:()=>iEe,setConfigKey:()=>vO,setPendingAuth:()=>_O,unsetConfigKey:()=>wO});import{existsSync as gO,readFileSync as eEe,unlinkSync as Z9}from"node:fs";import{homedir as tEe}from"node:os";import{join as JS}from"node:path";function ZS(){let e=process.env.CLAWDI_HOME;if(e)return e;return JS(process.env.HOME||tEe(),".clawdi")}function YS(){return JS(ZS(),"config.json")}function hO(){return JS(ZS(),"auth.json")}function yO(){return JS(ZS(),"pending-auth.json")}function Y9(e){if(!gO(e))return null;return JSON.parse(eEe(e,"utf-8"))}function X9(){let e=Y9(YS());if(typeof e!=="object"||e===null||Array.isArray(e))return{};let t={...e};if(t.autoUpdate==="true")t.autoUpdate=!0;else if(t.autoUpdate==="false")t.autoUpdate=!1;else if(typeof t.autoUpdate!=="boolean")delete t.autoUpdate;if(typeof t.apiUrl!=="string")delete t.apiUrl;if(typeof t.deployApiUrl!=="string")delete t.deployApiUrl;return t}function Lh(e,t){ie(e,`${JSON.stringify(t,null,2)}
7
+ `,"utf8")}return`sha256-tree-v1:${t.digest("hex")}`}var jh=()=>{};function H9(e){return xp(Al(e,{limits:Nh,resourceLabel:"managed Skill tree"})).slice(15)}function on(e){return H9(e)}function pO(){return[...z9.keys()]}function Mh(e,t){let n=z9.get(e);if(!n)throw Error(`no bundled hosted skill is registered for ${e}`);let r=n.get(t);if(!r)throw Error(`no bundled hosted skill ${e} version ${t} is registered`);return r}function B9(e,t){if(H9(t)!==e.digest)throw Error(`bundled hosted skill catalog digest mismatch for ${e.id} version ${e.version}`)}var z9,Nh;var Io=b(()=>{jh();z9=new Map([["clawdi",new Map([[1,Object.freeze({id:"clawdi",version:1,assetDirectory:"hosted-versions/1/clawdi",digest:"a70f1c53415828ac38d89e325ab976d474e5e6d6c172cb3c812174558261a176"})]])]]),Nh=Object.freeze({entries:1024,files:1024,fileBytes:16777216,totalBytes:33554432})});function V9(e,t){if(typeof e!=="string"||e.length>2048)throw Error(`${t} must be a valid absolute http:// or https:// URL.`);let n=e.trim(),r;try{r=new URL(n)}catch{throw Error(`${t} must be a valid absolute http:// or https:// URL.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw Error(`${t} must use http:// or https://.`);let i=n.indexOf("://")+3,o=n.slice(i).search(/[/?#]/),s=o===-1?n.slice(i):n.slice(i,i+o);if(r.username||r.password||s.includes("@"))throw Error(`${t} must not contain credentials.`);if(!r.hostname||!r.hostname.startsWith("[")&&!r.hostname.split(".").every((c)=>/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(c)))throw Error(`${t} must contain a canonical hostname.`);if(n.includes("?")||n.includes("#"))throw Error(`${t} must not contain a query or fragment.`);let a=n.indexOf("/",i),l=a===-1?"":n.slice(a);return{url:r,rawPath:l}}function Nke(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function q9(e,t){if(e.protocol==="http:"&&!Nke(e.hostname))throw Error(`${t} must use HTTPS except on loopback localhost.`)}function At(e){let{url:n,rawPath:r}=V9(e,"Clawdi Cloud API URL");if(q9(n,"Clawdi Cloud API URL"),r!==""&&r!=="/"||n.pathname!=="/")throw Error("Clawdi Cloud API URL must not contain a non-root path.");return n.origin}function ya(e){let{url:n,rawPath:r}=V9(e,"Hosted deploy API URL");if(q9(n,"Hosted deploy API URL"),!["","/","/v2","/v2/"].includes(r))throw Error("Hosted deploy API URL must use the origin root or the compatible /v2 base.");if(n.pathname!=="/"&&n.pathname!=="/v2"&&n.pathname!=="/v2/")throw Error("Hosted deploy API URL must use the origin root or the compatible /v2 base.");return n.origin}function Ft(e){return new URL(e).origin}function mO(e){return e==="https://cloud-api.clawdi.ai"}import{chmodSync as Mke,lstatSync as K9,mkdirSync as Lke}from"node:fs";import{isAbsolute as Uke,join as Fke,relative as zke,resolve as W9}from"node:path";function G9(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function fu(e,t="trusted directory"){let n;try{n=K9(e)}catch(r){if(G9(r))throw Error(`${t} is missing: ${e}`);throw r}if(!n.isDirectory()||n.isSymbolicLink())throw Error(`${t} is not a real directory: ${e}`)}function Rr(e,t,n={}){let r=W9(e),i=W9(t),o=zke(r,i);if(o.startsWith("..")||Uke(o))throw Error(`directory is outside trusted root ${e}: ${t}`);if(fu(r),!o)return;let s=r;for(let a of o.split("/")){s=Fke(s,a);try{let l=K9(s);if(!l.isDirectory()||l.isSymbolicLink())throw Error(`trusted directory path contains a non-directory: ${s}`)}catch(l){if(!G9(l))throw l;if(Lke(s,n.mode===void 0?void 0:{mode:n.mode}),n.mode!==void 0)Mke(s,n.mode)}}}var Ip=()=>{};import{chmodSync as Hke,closeSync as Bke,existsSync as Vke,fsyncSync as qke,mkdirSync as Wke,openSync as Kke,renameSync as Gke,rmSync as Jke,writeFileSync as Zke}from"node:fs";import{basename as Yke,dirname as Xke,join as Qke}from"node:path";function ie(e,t,n={}){let r=n.mode??at,i=Xke(e);if(n.trustedRoot)Rr(n.trustedRoot,i,{...n.dirMode===void 0?{}:{mode:n.dirMode}});else{let s=Vke(i);if(Wke(i,{recursive:!0,...n.dirMode===void 0?{}:{mode:n.dirMode}}),!s&&n.dirMode!==void 0)Op(i,n.dirMode)}let o=Qke(i,`.${Yke(e)}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);try{if(Zke(o,t,{mode:r}),Op(o,r),n.durable)J9(o);if(Gke(o,e),Op(e,r),n.durable)J9(i)}catch(s){throw Jke(o,{force:!0}),s}}function J9(e){let t=Kke(e,"r");try{qke(t)}finally{Bke(t)}}function Op(e,t){try{Hke(e,t)}catch{}}var at=384,Ge=448;var _t=b(()=>{Ip()});var Q9={};ae(Q9,{CONFIG_KEYS:()=>XS,clearAuth:()=>Fh,clearPendingAuth:()=>Dp,getAuth:()=>we,getClawdiDir:()=>ge,getConfig:()=>Se,getPendingAuth:()=>Es,getStoredAuth:()=>ks,getStoredConfig:()=>Oo,isLoggedIn:()=>Ve,readRecoverablePrivateJson:()=>Rl,setAuth:()=>Uh,setConfig:()=>iEe,setConfigKey:()=>vO,setPendingAuth:()=>_O,unsetConfigKey:()=>wO});import{existsSync as gO,readFileSync as eEe,unlinkSync as Z9}from"node:fs";import{homedir as tEe}from"node:os";import{join as JS}from"node:path";function ZS(){let e=process.env.CLAWDI_HOME;if(e)return e;return JS(process.env.HOME||tEe(),".clawdi")}function YS(){return JS(ZS(),"config.json")}function hO(){return JS(ZS(),"auth.json")}function yO(){return JS(ZS(),"pending-auth.json")}function Y9(e){if(!gO(e))return null;return JSON.parse(eEe(e,"utf-8"))}function X9(){let e=Y9(YS());if(typeof e!=="object"||e===null||Array.isArray(e))return{};let t={...e};if(t.autoUpdate==="true")t.autoUpdate=!0;else if(t.autoUpdate==="false")t.autoUpdate=!1;else if(typeof t.autoUpdate!=="boolean")delete t.autoUpdate;if(typeof t.apiUrl!=="string")delete t.apiUrl;if(typeof t.deployApiUrl!=="string")delete t.deployApiUrl;return t}function Lh(e,t){ie(e,`${JSON.stringify(t,null,2)}
8
8
  `,{mode:at,dirMode:Ge})}function Se(){let e=X9();return{apiUrl:process.env.CLAWDI_API_URL||e.apiUrl||nEe,deployApiUrl:process.env.CLAWDI_DEPLOY_API_URL||e.deployApiUrl||rEe,autoUpdate:e.autoUpdate}}function Oo(){return X9()}function iEe(e){let t={...e,apiUrl:fO("apiUrl",e.apiUrl)};if(e.deployApiUrl!==void 0)t.deployApiUrl=fO("deployApiUrl",e.deployApiUrl);if(e.autoUpdate!==void 0&&typeof e.autoUpdate!=="boolean")throw Error("autoUpdate must be true or false.");Lh(YS(),t)}function vO(e,t){let n=oEe(e,t),r=Oo();Lh(YS(),{...r,[e]:n})}function oEe(e,t){if(e==="autoUpdate"){if(t==="true")return!0;if(t==="false")return!1;throw Error("autoUpdate must be true or false.")}return fO(e,t)}function fO(e,t){return e==="apiUrl"?At(t):ya(t)}function wO(e){let t=Oo();delete t[e],Lh(YS(),t)}function we(){let e=process.env.CLAWDI_AUTH_TOKEN;if(e)return{apiKey:e};return ks()}function ks(){return Rl(hO())}function Uh(e){Lh(hO(),e)}function Fh(){let e=hO();if(gO(e))Z9(e)}function Ve(){return we()!==null}function Es(){return Rl(yO())}function _O(e){Lh(yO(),e)}function Dp(){let e=yO();if(gO(e))Z9(e)}function Rl(e,t=Y9){try{return t(e)}catch{return null}}function ge(){return ZS()}var XS,nEe="https://cloud-api.clawdi.ai",rEe="https://api.clawdi.ai";var Pe=b(()=>{_t();XS=["apiUrl","deployApiUrl","autoUpdate"]});var u5={};ae(u5,{PrivateDirectoryLockTimeoutError:()=>zh,withPrivateDirectoryLock:()=>mr,withPrivateDirectoryLockSync:()=>Rn});import{randomUUID as bO}from"node:crypto";import{chmodSync as t5,mkdirSync as QS,readFileSync as sEe,renameSync as e5,rmSync as ek,statSync as n5}from"node:fs";import{dirname as r5,join as aEe}from"node:path";function Tp(e,t){return e instanceof Error&&"code"in e&&e.code===t}function SO(e){return aEe(e,"owner.json")}function jp(e){try{let t=JSON.parse(sEe(SO(e),"utf8"));if(!t||typeof t!=="object"||Array.isArray(t))return null;let n=t;if(n.schemaVersion!=="clawdi.privateDirectoryLockOwner.v1"||typeof n.pid!=="number"||!Number.isInteger(n.pid)||n.pid<=0||typeof n.acquiredAt!=="string"||!Number.isFinite(Date.parse(n.acquiredAt))||typeof n.token!=="string"||!n.token)return null;return n}catch{return null}}function a5(e){try{return process.kill(e,0),!0}catch(t){return!Tp(t,"ESRCH")}}function lEe(e,t){let n=jp(e);if(n)return t.isProcessAlive(n.pid)?null:{kind:"owner",owner:n};try{let r=n5(e).mtimeMs;return t.now()-r>t.staleMs?{kind:"ownerless",mtimeMs:r}:null}catch(r){if(Tp(r,"ENOENT"))return{kind:"ownerless",mtimeMs:0};throw r}}function cEe(e,t){if(t.kind==="owner"){let n=jp(e);return n?.token===t.owner.token&&n.pid===t.owner.pid&&n.acquiredAt===t.owner.acquiredAt}if(jp(e)!==null)return!1;try{return n5(e).mtimeMs===t.mtimeMs}catch{return!1}}function l5(e,t){let n=lEe(e,t);if(!n)return!1;t.beforeReclaimRename?.();let r=`${e}.stale.${process.pid}.${t.now()}.${bO()}`;try{e5(e,r)}catch(i){if(Tp(i,"ENOENT"))return!0;throw i}if(!cEe(r,n)){try{e5(r,e)}catch(i){if(!Tp(i,"EEXIST"))throw i}return!1}return ek(r,{recursive:!0,force:!0}),!0}function c5(e,t){if(jp(e)?.token!==t)return;ek(e,{recursive:!0,force:!0})}function uEe(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Rn(e,t,n={}){let r=n.timeoutMs??i5,i=n.staleMs??o5,o=n.retryMs??s5,s=n.now??Date.now,a=n.isProcessAlive??a5,l=r5(e);QS(l,{recursive:!0,mode:Ge});try{t5(l,Ge)}catch{}let c=s(),u=bO();for(;;)try{QS(e,{mode:Ge});try{ie(SO(e),`${JSON.stringify({schemaVersion:"clawdi.privateDirectoryLockOwner.v1",pid:process.pid,acquiredAt:new Date(s()).toISOString(),token:u})}
9
9
  `,{mode:at,dirMode:Ge})}catch(p){throw ek(e,{recursive:!0,force:!0}),p}break}catch(p){if(!Tp(p,"EEXIST"))throw p;if(l5(e,{staleMs:i,now:s,isProcessAlive:a,beforeReclaimRename:n.beforeReclaimRename}))continue;if(s()-c>=r)throw Error(`timed out waiting for private lock at ${e}`);uEe(o)}let d={token:u,assertOwned(){if(jp(e)?.token!==u)throw Error(`lost ownership of private lock at ${e}`)}};try{return d.assertOwned(),t(d)}finally{c5(e,u)}}async function mr(e,t,n={}){let r=n.timeoutMs??i5,i=n.staleMs??o5,o=n.retryMs??s5,s=n.now??Date.now,a=n.isProcessAlive??a5,l=r5(e);QS(l,{recursive:!0,mode:Ge});try{t5(l,Ge)}catch{}let c=s(),u=bO();for(;;)try{QS(e,{mode:Ge});try{let p={schemaVersion:"clawdi.privateDirectoryLockOwner.v1",pid:process.pid,acquiredAt:new Date(s()).toISOString(),token:u};ie(SO(e),`${JSON.stringify(p)}
10
10
  `,{mode:at,dirMode:Ge})}catch(p){throw ek(e,{recursive:!0,force:!0}),p}break}catch(p){if(!Tp(p,"EEXIST"))throw p;if(l5(e,{staleMs:i,now:s,isProcessAlive:a,beforeReclaimRename:n.beforeReclaimRename}))continue;if(s()-c>=r)throw new zh(e);await new Promise((m)=>setTimeout(m,o))}let d={token:u,assertOwned(){if(jp(e)?.token!==u)throw Error(`lost ownership of private lock at ${e}`)}};try{return d.assertOwned(),await t(d)}finally{c5(e,u)}}var i5=30000,o5=60000,s5=50,zh;var Do=b(()=>{_t();zh=class zh extends Error{lockDir;constructor(e){super(`timed out waiting for private lock at ${e}`);this.name="PrivateDirectoryLockTimeoutError",this.lockDir=e}}});import{mkdirSync as dEe,readFileSync as pEe,renameSync as d5,rmSync as Hh,statSync as mEe,writeFileSync as fEe}from"node:fs";import{basename as gEe,dirname as p5,join as m5}from"node:path";function f5(e){return m5(e,"owner.json")}function hEe(e,t,n){let r=m5(p5(e),`.${gEe(e)}.${process.pid}.${Date.now()}.tmp`),i=!1;try{fEe(r,t,{mode:n}),d5(r,e),i=!0}finally{if(!i)Hh(r,{force:!0})}}function yEe(e){hEe(f5(e),`${JSON.stringify({schemaVersion:"clawdi.runtimeConvergeLockOwner.v1",pid:process.pid,acquiredAt:new Date().toISOString()})}
@@ -1216,10 +1216,10 @@ WantedBy=default.target
1216
1216
  `:""}${g.message}`}),u.on("close",(g,v)=>{if(d(),!c)m({exit_code:g,signal:v,stdout:s,stderr:a})}),e.stdin!==void 0)u.stdin?.end(e.stdin);else u.stdin?.end()})}function u0(e){return{id:e.id,name:e.name,status:e.status,exclusive_key:e.exclusive_key,command:e.command,cwd:e.cwd,started_at:e.started_at,finished_at:e.finished_at,exit_code:e.exit_code,signal:e.signal,stdout:d0(e.stdout,200),stderr:d0(e.stderr,200)}}function RH(e,t){for(let n of Er(t).split(/\r?\n/)){if(!n)continue;e.push(n)}if(e.length>cie)e.splice(0,e.length-cie)}function d0(e,t){return e.slice(Math.max(0,e.length-t))}function vie(e){return R9e(e??process.cwd())}function wie(){let e={CLAWDI_NO_UPDATE_CHECK:"1",CLAWDI_NO_AUTO_UPDATE:"1"};for(let t of $9e){let n=process.env[t];if(n!==void 0)e[t]=n}return e}function die(e){e.status="cancelled",e.finished_at=new Date().toISOString()}function pie(e,t={termTimeoutMs:fie,killTimeoutMs:gie}){let n={termTimeoutMs:e.termTimeoutMs??t.termTimeoutMs,killTimeoutMs:e.killTimeoutMs??t.killTimeoutMs};for(let[r,i]of[["TERM",n.termTimeoutMs],["KILL",n.killTimeoutMs]])if(!Number.isFinite(i)||i<0)throw Error(`Operation shutdown ${r} timeout must be a non-negative number.`);return n}var cie=1000,P9e=100,uie=4,C9e=60000,fie=5000,gie=1000,xd,$9e;var _ie=b(()=>{Ec();ur();xd=new hie;$9e=["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TEMP","TMP","CI","GITHUB_ACTIONS","CLAWDI_AUTH_TOKEN","CLAWDI_API_URL","CLAWDI_HOME","CLAWDI_STATE_DIR","CLAWDI_AGENT_TYPE","CLAWDI_SERVE_MODE","CLAWDI_SERVE_DEBUG","CLAUDE_CONFIG_DIR","CODEX_HOME","HERMES_HOME","OPENCLAW_STATE_DIR","OPENCLAW_AGENT_ID","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS","BUN_INSTALL"]});import{spawnSync as x9e}from"node:child_process";import{createHash as xH,randomUUID as I9e}from"node:crypto";import{chmodSync as O9e,closeSync as Li,constants as Ot,fstatSync as Ga,fsyncSync as d_,lstatSync as Id,mkdirSync as PH,openSync as Xs,readFileSync as IH,renameSync as D9e,unlinkSync as f_,writeFileSync as T9e}from"node:fs";import{isAbsolute as OH,join as Od,relative as j9e,resolve as kie}from"node:path";function $e(){throw Error("Runtime Vault files could not be synchronized; last good files retained where possible.")}function Eie(e){if(!OH(e)||kie(e)!==e)$e();let t=Xs("/",Ot.O_RDONLY|Ot.O_DIRECTORY);try{for(let n of e.split("/").filter(Boolean)){let r=Xs(`/proc/self/fd/${t}/${n}`,Ot.O_RDONLY|Ot.O_DIRECTORY|Ot.O_NOFOLLOW),i=Ga(r);if(i.uid!==0&&i.uid!==process.geteuid?.()||(i.mode&18)!==0&&(i.mode&512)===0)Li(r),$e();Li(t),t=r}return t}catch{return Li(t),$e()}}function p_(e){if(!OH(e)||kie(e)!==e)$e();let t="/";for(let n of e.split("/").filter(Boolean)){t=Od(t,n),fu(t);let r=Id(t);if(r.uid!==0&&r.uid!==process.geteuid?.()||(r.mode&18)!==0&&(r.mode&512)===0)$e()}}function Ka(e,t){if(!e.connected)return`/proc/self/fd/${e.fd}/${t}`;p_(e.path);let n=Id(e.path),r=Ga(e.fd);if(n.dev!==r.dev||n.ino!==r.ino||n.uid!==process.geteuid?.()||(n.mode&511)!==448)$e();return Od(e.path,t)}function Rc(e,t){let n=Ka(e,t);try{let r=Id(n);if(!r.isFile()||r.nlink!==1||r.uid!==process.geteuid?.()||(r.mode&511)!==384)$e();return!0}catch(r){if(r&&typeof r==="object"&&"code"in r&&r.code==="ENOENT")return!1;return $e()}}function U9e(e,t){if(!Rc(e,t))return null;let n=Xs(Ka(e,t),Ot.O_RDONLY|Ot.O_NOFOLLOW);try{let r=Ga(n);if(!r.isFile()||r.nlink!==1||r.size>16777216)$e();return xH("sha256").update(IH(n)).digest("hex")}finally{Li(n)}}function Aie(e,t,n){if(Rc(e,t)){let o=Xs(Ka(e,t),Ot.O_RDONLY|Ot.O_NOFOLLOW);try{let s=Ga(o);if(!s.isFile()||s.nlink!==1)$e();if(IH(o,"utf8")===n)return}finally{Li(o)}}if(e.connected){ie(Ka(e,t),n,{mode:384,durable:!0,trustedRoot:e.path}),Rc(e,t);return}let r=Ka(e,`.clawdi-${I9e()}`),i;try{i=Xs(r,Ot.O_WRONLY|Ot.O_CREAT|Ot.O_EXCL|Ot.O_NOFOLLOW,384),T9e(i,n),d_(i),Li(i),i=void 0,D9e(r,Ka(e,t)),d_(e.fd)}finally{if(i!==void 0)Li(i);try{f_(r)}catch(o){if(!(o&&typeof o==="object"&&("code"in o)&&o.code==="ENOENT"))$e()}}}function m_(e,t){let n=`${JSON.stringify(t)}
1217
1217
  `;if(e.connected)ie(e.receiptPath,n,{mode:384,dirMode:448,durable:!0,trustedRoot:e.connected.stateRoot});else{if(!e.paths)$e();Ht(e.paths,e.receiptPath,n,{mode:384})}}function Rie(e){let t;try{t=Xs(e,Ot.O_RDONLY|Ot.O_NOFOLLOW)}catch(n){if(n&&typeof n==="object"&&"code"in n&&n.code==="ENOENT")return null;return $e()}try{let n=Ga(t);if(!n.isFile()||n.nlink!==1||n.uid!==process.geteuid?.()||(n.mode&511)!==384||n.size>16777216)$e();let r=L9e.safeParse(JSON.parse(IH(t,"utf8")));if(!r.success)$e();return r.data}finally{Li(t)}}function F9e(e){let t=Rie(e.receiptPath);if(!t)return null;if(t.apiUrl!==e.apiUrl||t.agentId!==e.agentId||t.workspace!==e.workspace||t.userId!==e.connected?.userId||t.machineId!==e.connected?.machineId||t.nativeAgentId!==e.connected?.nativeAgentId)$e();return t}function Pie(e,t){return e.connected?t():zt(t)}function u_(e,t,n){return Pie(e,()=>{let r=Od(e.workspace,".clawdi/vaults");if(e.connected)p_(r);let i=e.connected?Xs(r,Ot.O_RDONLY|Ot.O_DIRECTORY|Ot.O_NOFOLLOW):Eie(r);try{let o=Ga(i);if(o.dev!==t.device||o.ino!==t.inode||o.uid!==process.geteuid?.()||(o.mode&511)!==448)$e();return n({fd:i,path:r,connected:Boolean(e.connected)})}finally{Li(i)}})}function p0(e){let t=(r)=>e.connected?x9e("git",r,{cwd:e.workspace,encoding:"utf8",timeout:5000,maxBuffer:1048576}):de("git",r,e.home,e.workspace,{timeoutMs:5000,maxBufferBytes:1048576}),n=t(["-C",e.workspace,"rev-parse","--show-toplevel"]);if(n.status===0){let r=t(["-C",e.workspace,"ls-files","--",".clawdi/vaults"]);if(r.status!==0||String(r.stdout).trim())$e()}else if(!String(n.stderr).includes("not a git repository"))$e()}function z9e(e){let t=j9e(e.home,e.workspace);if(!e.connected&&(t===".."||t.startsWith("../")||OH(t)))$e();p0(e);let n=Pie(e,()=>{if(e.connected){p_(e.workspace);let o=Od(e.workspace,".clawdi");if(Rr(e.workspace,o,{mode:448}),p_(o),(Id(o).mode&18)!==0)$e();let s=Od(o,"vaults");PH(s,{mode:448}),O9e(s,448);let a=Xs(s,Ot.O_RDONLY|Ot.O_DIRECTORY|Ot.O_NOFOLLOW);try{let l=Ga(a);return{device:l.dev,inode:l.ino}}finally{Li(a)}}let i=Eie(e.workspace);try{try{PH(`/proc/self/fd/${i}/.clawdi`,{mode:448})}catch(s){if(!(s&&typeof s==="object"&&("code"in s)&&s.code==="EEXIST"))throw s}let o=Xs(`/proc/self/fd/${i}/.clawdi`,Ot.O_RDONLY|Ot.O_DIRECTORY|Ot.O_NOFOLLOW);try{let s=Ga(o);if(s.uid!==process.geteuid?.()&&s.uid!==0||(s.mode&18)!==0)$e();PH(`/proc/self/fd/${o}/vaults`,{mode:448});let a=Xs(`/proc/self/fd/${o}/vaults`,Ot.O_RDONLY|Ot.O_DIRECTORY|Ot.O_NOFOLLOW);try{let l=Ga(a);return{device:l.dev,inode:l.ino}}finally{Li(a)}}finally{Li(o)}}finally{Li(i)}}),r={version:1,directory:".clawdi/vaults",...e.connected?{userId:e.connected.userId,machineId:e.connected.machineId,nativeAgentId:e.connected.nativeAgentId}:{},digests:{},apiUrl:e.apiUrl,agentId:e.agentId,workspace:e.workspace,...n,files:[],inventory:[],etag:null};return m_(e,r),r}function $H(e,t){if(t)p0(e),u_(e,t,(n)=>{for(let r of t.files)if(Rc(n,r))f_(Ka(n,r));d_(n.fd)}),m_(e,{...t,files:[],inventory:[],digests:{},etag:null});return"revoked"}function H9e(e,t,n){if(!t)return null;let r=new Set(n.vaults.map((a)=>a.id));if(r.size!==n.vaults.length)$e();let i=t.files.filter((a)=>a!=="index.json"&&a!==".gitignore"&&!r.has(a.slice(0,36)));if(i.length===0)return t;p0(e);let o=t.inventory.filter((a)=>r.has(a.id));u_(e,t,(a)=>{for(let l of i)if(Rc(a,l))f_(Ka(a,l));Aie(a,"index.json",`${JSON.stringify({version:1,agent_id:n.agent_id,user_id:n.user_id,vaults:o},null,2)}
1218
1218
  `),d_(a.fd)});let s={...t,inventory:o,files:t.files.filter((a)=>!i.includes(a)),etag:null};return m_(e,s),s}function B9e(e,t){let n=new Map([[".gitignore",`*
1219
- `]]),r=new Set,i=e.vaults.map((o)=>{if(r.has(o.id))$e();if(r.add(o.id),o.fields===null){let a=t?.inventory.find((l)=>l.id===o.id&&l.revision===o.revision);if(!a)$e();return a}let s=new Map;for(let a of o.fields){let l=s.get(a.section)??[];l.push(a),s.set(a.section,l)}return{id:o.id,name:o.name,slug:o.slug,project_ids:o.project_ids,revision:o.revision,sections:[...s].map(([a,l])=>{let c=xH("sha256").update(a).digest("hex"),u=`${o.id}-${c}.json`;if(new Set(l.map((d)=>d.name)).size!==l.length)$e();return n.set(u,`${JSON.stringify(Object.fromEntries(l.map((d)=>[d.name,d.value])))}
1219
+ `]]),r=new Set,i=e.vaults.map((o)=>{if(r.has(o.id))$e();if(r.add(o.id),o.fields===null){let a=t?.inventory.find((l)=>l.id===o.id&&l.revision===o.revision);if(!a)$e();return{...a,content_version:o.content_version}}let s=new Map;for(let a of o.fields){let l=s.get(a.section)??[];l.push(a),s.set(a.section,l)}return{id:o.id,name:o.name,slug:o.slug,project_ids:o.project_ids,revision:o.revision,content_version:o.content_version,sections:[...s].map(([a,l])=>{let c=xH("sha256").update(a).digest("hex"),u=`${o.id}-${c}.json`;if(new Set(l.map((d)=>d.name)).size!==l.length)$e();return n.set(u,`${JSON.stringify(Object.fromEntries(l.map((d)=>[d.name,d.value])))}
1220
1220
  `),{id:c,name:a,file:u,fields:l.map(({id:d,name:p,references:m})=>({id:d,name:p,references:m,env_name:/^[A-Za-z_][A-Za-z0-9_]*$/.test(p)?p:null}))}})}});if(i.flatMap((o)=>o.sections).reduce((o,s)=>o+s.fields.length,0)>1e4||Buffer.byteLength(JSON.stringify(i))>8388608)$e();return n.set("index.json",`${JSON.stringify({version:1,agent_id:e.agent_id,user_id:e.user_id,vaults:i},null,2)}
1221
1221
  `),{files:n,inventory:i,names:[".gitignore","index.json",...i.flatMap((o)=>o.sections.map((s)=>s.file))]}}async function bie(e){if(!e.body)$e();let t=e.body.getReader(),n=[],r=0;try{for(;;){let{done:o,value:s}=await t.read();if(o)break;if(r+=s.byteLength,r>16777216)$e();n.push(s)}}finally{await t.cancel()}let i=N9e.safeParse(JSON.parse(Buffer.concat(n).toString("utf8")));if(!i.success)$e();return i.data}function Ja(){return process.platform==="linux"||process.platform==="darwin"}function Cie(e){p_(e);let t=Od(e,"vault-file-lock");Rr(e,t,{mode:448});let n=Id(t);if(n.uid!==process.geteuid?.()||(n.mode&511)!==448)$e();let r=Od(t,"writer");try{let i=Id(r);if(!i.isDirectory()||i.isSymbolicLink())$e()}catch(i){if(!(i&&typeof i==="object"&&("code"in i)&&i.code==="ENOENT"))throw i}return r}function Dd(...e){if(!Ja())$e();try{Id(e[0])}catch(t){if(t&&typeof t==="object"&&"code"in t&&t.code==="ENOENT")return;throw t}Rn(Cie(e[1]),()=>V9e(...e),{timeoutMs:0})}function V9e(e,t,n,r,i=!1){let o=Rie(e);if(!o)return;if(!o.userId||!o.machineId)$e();let s=Boolean(r&&o.userId===r.userId&&o.machineId===r.machineId&&o.agentId===r.agentId&&o.workspace===r.workspace&&o.apiUrl===r.apiUrl&&o.nativeAgentId===r.nativeAgentId);if(i?!s:s)return;if($H({apiUrl:o.apiUrl,agentId:o.agentId,workspace:o.workspace,home:n,receiptPath:e,connected:{userId:o.userId,machineId:o.machineId,nativeAgentId:o.nativeAgentId,stateRoot:t}},o),r&&!i)if(o.workspace===r.workspace)ie(e,`${JSON.stringify({...o,...r,files:[],inventory:[],digests:{},etag:null})}
1222
- `,{mode:384,dirMode:448,durable:!0,trustedRoot:t});else f_(e)}async function m0(e){if(e.connected?!Ja():process.platform!=="linux")throw Error("Connected Vault files require macOS or Linux; Hosted requires Linux.");if(!e.connected)return Sie(e);let t=e.connected;try{return await mr(Cie(t.stateRoot),(n)=>Sie({...e,connected:{...t,assertCurrent(){n.assertOwned(),t.assertCurrent()}}}))}catch{return $e()}}async function Sie(e){try{let t={...e,apiUrl:At(e.apiUrl)};t.connected?.assertCurrent();let n=t.connected?.request??fetch;if(!t.connected&&!t.apiKey)$e();let r=t.connected?`?agent_id=${encodeURIComponent(t.agentId)}`:"",i=F9e(t),o=i&&u_(t,i,(g)=>i?.files.every((v)=>U9e(g,v)===i?.digests[v])),s=o?i?.etag:null,a=await n(`${t.apiUrl}/v1/runtime/vaults${r}`,{headers:{...t.connected?{}:{Authorization:`Bearer ${t.apiKey}`},...s?{"If-None-Match":s}:{}},redirect:"error",signal:AbortSignal.timeout(1e4)});if(t.connected?.assertCurrent(),a.status===304){if(!s)$e();return"unchanged"}if(a.status===401||a.status===403)return await a.body?.cancel(),$H(t,i);if(!a.ok)await a.body?.cancel(),$e();let l=await bie(a);if(t.connected?.assertCurrent(),l.agent_id!==t.agentId||t.connected&&l.user_id!==t.connected.userId)$e();i=H9e(t,i,l);let c=await n(`${t.apiUrl}/v1/runtime/vaults/material${r}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{...t.connected?{}:{Authorization:`Bearer ${t.apiKey}`},"Content-Type":"application/json"},body:JSON.stringify({etag:a.headers.get("etag"),revisions:o?Object.fromEntries((i?.inventory??[]).map((g)=>[g.id,g.revision])):{}})});if(t.connected?.assertCurrent(),c.status===401||c.status===403)return await c.body?.cancel(),$H(t,i);if(c.status===409)return await c.body?.cancel(),"deferred";if(!c.ok)await c.body?.cancel(),$e();let u=await bie(c);if(u.agent_id!==t.agentId||u.user_id!==l.user_id||c.headers.get("etag")!==a.headers.get("etag"))$e();t.connected?.assertCurrent();let{files:d,inventory:p,names:m}=B9e(u,o?i:null);if(i)p0(t);i??=z9e(t),u_(t,i,(g)=>{for(let v of d.keys())if(!i?.files.includes(v)&&Rc(g,v))$e()});let f={...i,files:[...new Set([...i.files,...m])],etag:null};return m_(t,f),u_(t,f,(g)=>{for(let v of f.files)Rc(g,v);for(let[v,w]of d)Aie(g,v,w);for(let v of f.files)if(!m.includes(v)&&Rc(g,v))f_(Ka(g,v));d_(g.fd)}),m_(t,{...i,files:m,digests:Object.fromEntries(m.map((g)=>[g,d.has(g)?xH("sha256").update(d.get(g)??"").digest("hex"):i.digests[g]])),inventory:p,etag:a.headers.get("etag")}),"synced"}catch{return $e()}}var N9e,CH,M9e,L9e;var f0=b(()=>{Wt();Do();_t();Ip();et();Wn();N9e=h.object({schema_version:h.literal(1),complete:h.literal(!0),agent_id:h.uuid(),user_id:h.uuid(),vaults:h.array(h.object({id:h.uuid(),name:h.string(),slug:h.string(),project_ids:h.array(h.uuid()).min(1),revision:h.string(),fields:h.array(h.object({id:h.uuid(),section:h.string(),name:h.string(),references:h.array(h.string().startsWith("clawdi://")),value:h.string()})).nullable()})).max(1e4)}),CH=h.string().regex(/^(?:\.gitignore|(?:index|[a-f0-9-]{36}-[a-f0-9]{64})\.json)$/),M9e=h.object({id:h.uuid(),name:h.string(),slug:h.string(),project_ids:h.array(h.uuid()),revision:h.string(),sections:h.array(h.object({id:h.string(),name:h.string(),file:CH,fields:h.array(h.object({id:h.uuid(),name:h.string(),references:h.array(h.string()),env_name:h.string().nullable()}))}))}),L9e=h.object({version:h.literal(1),userId:h.uuid().optional(),machineId:h.string().optional(),nativeAgentId:h.string().optional(),directory:h.literal(".clawdi/vaults"),digests:h.record(CH,h.string().regex(/^[a-f0-9]{64}$/)),apiUrl:h.string(),agentId:h.uuid(),workspace:h.string(),device:h.number(),inode:h.number(),files:h.array(CH),inventory:h.array(M9e),etag:h.string().nullable()}).strict()});import{realpathSync as q9e}from"node:fs";import{homedir as $ie}from"node:os";import{join as xie}from"node:path";import{setTimeout as W9e}from"node:timers/promises";function DH(e,t){if(!Ja()||process.env.CLAWDI_RUNTIME_MODE==="hosted")return;let n=Sj(e),r=n?.vaultWorkspace;if(!n?.userId||!n.machineId||!r||n.userId===we()?.userId||n.machineId!==ju()||t!==void 0&&n.id!==t)return;let i=yr(e);Dd(xie(i,"vault-files.json"),i,process.env.HOME||$ie(),{userId:n.userId,machineId:n.machineId,agentId:n.id,workspace:r.path,nativeAgentId:r.nativeAgentId,apiUrl:r.apiOrigin},!0)}function Iie(e){let{agentType:t,agentId:n,api:r,abort:i,report:o}=e,s=yr(t),a=xie(s,"vault-files.json"),l=process.env.HOME||$ie(),c=ei(t),u=c?.vaultWorkspace,d=c?.userId,p=c?.machineId,m=process.env.CLAWDI_RUNTIME_MODE!=="hosted"&&Ja(),f=null,g=!1,v=!1,w=0,_=0,S=()=>{if(process.env.CLAWDI_RUNTIME_MODE==="hosted"||!Ja())return;try{if(u&&d&&p)v=!0,Dd(a,s,l,{userId:d,machineId:p,agentId:n,workspace:u.path,nativeAgentId:u.nativeAgentId,apiUrl:r.baseUrl},!0),v=!1}catch{o("Owned Vault cleanup is deferred; persistent filesystem conflicts require local repair.",!0)}},k=()=>{let A=ei(t);if(!u||!d||!p||c?.id!==n||we()?.userId!==d||ju()!==p||Ft(Se().apiUrl)!==r.baseUrl||u.apiOrigin!==r.baseUrl||A?.id!==n||A.userId!==d||A.machineId!==p||A.vaultWorkspace?.path!==u.path||A.vaultWorkspace.apiOrigin!==u.apiOrigin||A.vaultWorkspace.nativeAgentId!==u.nativeAgentId||q9e(u.path)!==u.path)throw Error("Vault registration identity changed");ov(t,u.path)};if(process.env.CLAWDI_RUNTIME_MODE==="hosted")m=!1;else if(!Ja())o("Automatic Vault files require macOS or Linux/WSL; native Windows is unsupported.");else try{if(k(),!u||!d||!p)throw Error("Missing binding");Dd(a,s,l,{userId:d,machineId:p,agentId:n,workspace:u.path,nativeAgentId:u.nativeAgentId,apiUrl:r.baseUrl})}catch{m=!1;try{DH(t,n)}catch{o("Owned Vault files need local repair.",!0)}if(c?.id===n&&c.userId===we()?.userId)try{if(u)S();else Dd(a,s,l)}catch{o("Owned Vault files need local repair.",!0)}o(`Vault file sync is disabled. Run clawdi setup --agent ${t} --vault-workspace <path>.`)}return{get enabled(){return m},reconcile:(A=!1)=>{if(A)w=0,_=0;if(!m||i.aborted)return Promise.resolve();if(g=!0,f)return f;return f=(async()=>{while(g&&!i.aborted&&m){g=!1;try{k()}catch{m=!1,S(),o("Vault identity or workspace changed; run setup and restart the daemon.");return}if(Date.now()<w){if(_>0)return;if(await W9e(w-Date.now(),void 0,{signal:i}).catch(()=>{}),i.aborted)return}if(!u||!d||!p)return;try{let R=await m0({apiUrl:r.baseUrl,agentId:n,home:l,workspace:u.path,receiptPath:a,connected:{userId:d,machineId:p,nativeAgentId:u.nativeAgentId,stateRoot:s,assertCurrent(){if(k(),i.aborted)throw Error("Vault sync stopped")},async request(O,M){k();let q=await r.getAccessToken();k();let C=new Headers(M.headers);return C.set("Authorization",`Bearer ${q}`),C.set("X-Clawdi-Machine-Id",p),fetch(O,{...M,headers:C,signal:AbortSignal.any([i,AbortSignal.timeout(1e4)])})}}});o(R==="revoked"?"Vault access was revoked; generated files removed.":null,R==="revoked"),_=0,w=Date.now()+250}catch{try{k()}catch{m=!1,S()}if(_=Math.min(_?_*2:60000,300000),w=Date.now()+_,!i.aborted)o("Vault file sync deferred; last good files retained where possible.",!0)}}})().finally(()=>{if(f=null,v)S()}),f},revoke:S,async finish(){if(await f,v)S();try{k()}catch{S()}}}}var TH=b(()=>{Pe();zu();Jy();f0();Ac()});async function Oie(e,t,n=new Map){if(e.scan)return e.scan(t,n);let r=await e.collect(t);return{coverage:r.coverage,batches:async function*(){yield{sessions:r.sessions,observedLocalSessionIds:r.sessions.map((i)=>i.localSessionId),dedupedCount:r.dedupedCount}}()}}function g0(e){let t=[];if(e.sessions)t.push("sessions");if(e.skills)t.push("skills");if(t.length===0)throw Error(`${e.agentType} has no data modules`);return t}import{createHash as K9e}from"node:crypto";import{chmodSync as G9e,existsSync as J9e,mkdirSync as Z9e,readFileSync as Y9e,renameSync as X9e,writeFileSync as Q9e}from"node:fs";import{join as Tie}from"node:path";function jie(e){let t=JSON.stringify([e.apiOrigin,e.environmentId,e.adapter,e.sourceSessionKey]);return`v2:${K9e("sha256").update(t).digest("hex")}`}function Td(e,t){if(e.version!==2)return;let n=e.sessions[jie(t)];if(!Uie(n))return;return n.api_origin===t.apiOrigin&&n.environment_id===t.environmentId&&n.adapter===t.adapter&&n.source_session_key===t.sourceSessionKey?n:void 0}function e5e(e,t,n){let r=Lie(e);return r.sessions[jie(t)]={api_origin:t.apiOrigin,environment_id:t.environmentId,adapter:t.adapter,source_session_key:t.sourceSessionKey,...n},r}function Jf(e,t){Mie(e5e(Qs(),e,t))}function Nie(e){if(e.length===0)return;let t=Qs(),n=!1;for(let r of e){let i=Td(t,r.fence);if(!i||i.pending!==void 0||i.protocol!==r.protocol||i.local_hash!==r.localHash||i.source_revision===r.sourceRevision)continue;i.source_revision=r.sourceRevision,n=!0}if(n)Mie(t)}function Qs(){let e=Tie(ge(),jH);if(!J9e(e))return h0();try{let t=JSON.parse(Y9e(e,"utf-8"));if(!y0(t)||!y0(t.sessions))return h0();if(t.version===1){let n={};for(let[r,i]of Object.entries(t.sessions))if(Die(i))n[r]=i;return{version:1,sessions:n}}if(t.version===g_){let n={};for(let[r,i]of Object.entries(t.sessions))if(Die(i)||Uie(i))n[r]=i;return{version:g_,sessions:n}}return h0()}catch{return console.log(y.yellow(`⚠ ~/.clawdi/${jH} is corrupted; resetting.`)),h0()}}function Mie(e){let t=ge();Z9e(t,{recursive:!0,mode:448});let n=Tie(t,jH),r=Lie(e),i={};for(let a of Object.keys(r.sessions).sort()){let l=r.sessions[a];if(l)i[a]=l}let o={version:g_,sessions:i},s=`${n}.tmp.${process.pid}`;Q9e(s,`${JSON.stringify(o,null,2)}
1222
+ `,{mode:384,dirMode:448,durable:!0,trustedRoot:t});else f_(e)}async function m0(e){if(e.connected?!Ja():process.platform!=="linux")throw Error("Connected Vault files require macOS or Linux; Hosted requires Linux.");if(!e.connected)return Sie(e);let t=e.connected;try{return await mr(Cie(t.stateRoot),(n)=>Sie({...e,connected:{...t,assertCurrent(){n.assertOwned(),t.assertCurrent()}}}))}catch{return $e()}}async function Sie(e){try{let t={...e,apiUrl:At(e.apiUrl)};t.connected?.assertCurrent();let n=t.connected?.request??fetch;if(!t.connected&&!t.apiKey)$e();let r=t.connected?`?agent_id=${encodeURIComponent(t.agentId)}`:"",i=F9e(t),o=i&&u_(t,i,(g)=>i?.files.every((v)=>U9e(g,v)===i?.digests[v])),s=o&&i?.inventory.every((g)=>g.content_version!==void 0)?i.etag:null,a=await n(`${t.apiUrl}/v1/runtime/vaults${r}`,{headers:{...t.connected?{}:{Authorization:`Bearer ${t.apiKey}`},...s?{"If-None-Match":s}:{}},redirect:"error",signal:AbortSignal.timeout(1e4)});if(t.connected?.assertCurrent(),a.status===304){if(!s)$e();return"unchanged"}if(a.status===401||a.status===403)return await a.body?.cancel(),$H(t,i);if(!a.ok)await a.body?.cancel(),$e();let l=await bie(a);if(t.connected?.assertCurrent(),l.agent_id!==t.agentId||t.connected&&l.user_id!==t.connected.userId)$e();i=H9e(t,i,l);let c=await n(`${t.apiUrl}/v1/runtime/vaults/material${r}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{...t.connected?{}:{Authorization:`Bearer ${t.apiKey}`},"Content-Type":"application/json"},body:JSON.stringify({etag:a.headers.get("etag"),revisions:o?Object.fromEntries((i?.inventory??[]).map((g)=>[g.id,g.revision])):{}})});if(t.connected?.assertCurrent(),c.status===401||c.status===403)return await c.body?.cancel(),$H(t,i);if(c.status===409)return await c.body?.cancel(),"deferred";if(!c.ok)await c.body?.cancel(),$e();let u=await bie(c);if(u.agent_id!==t.agentId||u.user_id!==l.user_id||c.headers.get("etag")!==a.headers.get("etag"))$e();t.connected?.assertCurrent();let{files:d,inventory:p,names:m}=B9e(u,o?i:null);if(i)p0(t);i??=z9e(t),u_(t,i,(g)=>{for(let v of d.keys())if(!i?.files.includes(v)&&Rc(g,v))$e()});let f={...i,files:[...new Set([...i.files,...m])],etag:null};return m_(t,f),u_(t,f,(g)=>{for(let v of f.files)Rc(g,v);for(let[v,w]of d)Aie(g,v,w);for(let v of f.files)if(!m.includes(v)&&Rc(g,v))f_(Ka(g,v));d_(g.fd)}),m_(t,{...i,files:m,digests:Object.fromEntries(m.map((g)=>[g,d.has(g)?xH("sha256").update(d.get(g)??"").digest("hex"):i.digests[g]])),inventory:p,etag:a.headers.get("etag")}),"synced"}catch{return $e()}}var N9e,CH,M9e,L9e;var f0=b(()=>{Wt();Do();_t();Ip();et();Wn();N9e=h.object({schema_version:h.literal(1),complete:h.literal(!0),agent_id:h.uuid(),user_id:h.uuid(),vaults:h.array(h.object({id:h.uuid(),name:h.string(),slug:h.string(),project_ids:h.array(h.uuid()).min(1),revision:h.string(),content_version:h.number().int().nonnegative(),fields:h.array(h.object({id:h.uuid(),section:h.string(),name:h.string(),references:h.array(h.string().startsWith("clawdi://")),value:h.string()})).nullable()})).max(1e4)}),CH=h.string().regex(/^(?:\.gitignore|(?:index|[a-f0-9-]{36}-[a-f0-9]{64})\.json)$/),M9e=h.object({id:h.uuid(),name:h.string(),slug:h.string(),project_ids:h.array(h.uuid()),revision:h.string(),content_version:h.number().int().nonnegative(),sections:h.array(h.object({id:h.string(),name:h.string(),file:CH,fields:h.array(h.object({id:h.uuid(),name:h.string(),references:h.array(h.string()),env_name:h.string().nullable()}))}))}),L9e=h.object({version:h.literal(1),userId:h.uuid().optional(),machineId:h.string().optional(),nativeAgentId:h.string().optional(),directory:h.literal(".clawdi/vaults"),digests:h.record(CH,h.string().regex(/^[a-f0-9]{64}$/)),apiUrl:h.string(),agentId:h.uuid(),workspace:h.string(),device:h.number(),inode:h.number(),files:h.array(CH),inventory:h.array(M9e.partial({content_version:!0})),etag:h.string().nullable()}).strict()});import{realpathSync as q9e}from"node:fs";import{homedir as $ie}from"node:os";import{join as xie}from"node:path";import{setTimeout as W9e}from"node:timers/promises";function DH(e,t){if(!Ja()||process.env.CLAWDI_RUNTIME_MODE==="hosted")return;let n=Sj(e),r=n?.vaultWorkspace;if(!n?.userId||!n.machineId||!r||n.userId===we()?.userId||n.machineId!==ju()||t!==void 0&&n.id!==t)return;let i=yr(e);Dd(xie(i,"vault-files.json"),i,process.env.HOME||$ie(),{userId:n.userId,machineId:n.machineId,agentId:n.id,workspace:r.path,nativeAgentId:r.nativeAgentId,apiUrl:r.apiOrigin},!0)}function Iie(e){let{agentType:t,agentId:n,api:r,abort:i,report:o}=e,s=yr(t),a=xie(s,"vault-files.json"),l=process.env.HOME||$ie(),c=ei(t),u=c?.vaultWorkspace,d=c?.userId,p=c?.machineId,m=process.env.CLAWDI_RUNTIME_MODE!=="hosted"&&Ja(),f=null,g=!1,v=!1,w=0,_=0,S=()=>{if(process.env.CLAWDI_RUNTIME_MODE==="hosted"||!Ja())return;try{if(u&&d&&p)v=!0,Dd(a,s,l,{userId:d,machineId:p,agentId:n,workspace:u.path,nativeAgentId:u.nativeAgentId,apiUrl:r.baseUrl},!0),v=!1}catch{o("Owned Vault cleanup is deferred; persistent filesystem conflicts require local repair.",!0)}},k=()=>{let A=ei(t);if(!u||!d||!p||c?.id!==n||we()?.userId!==d||ju()!==p||Ft(Se().apiUrl)!==r.baseUrl||u.apiOrigin!==r.baseUrl||A?.id!==n||A.userId!==d||A.machineId!==p||A.vaultWorkspace?.path!==u.path||A.vaultWorkspace.apiOrigin!==u.apiOrigin||A.vaultWorkspace.nativeAgentId!==u.nativeAgentId||q9e(u.path)!==u.path)throw Error("Vault registration identity changed");ov(t,u.path)};if(process.env.CLAWDI_RUNTIME_MODE==="hosted")m=!1;else if(!Ja())o("Automatic Vault files require macOS or Linux/WSL; native Windows is unsupported.");else try{if(k(),!u||!d||!p)throw Error("Missing binding");Dd(a,s,l,{userId:d,machineId:p,agentId:n,workspace:u.path,nativeAgentId:u.nativeAgentId,apiUrl:r.baseUrl})}catch{m=!1;try{DH(t,n)}catch{o("Owned Vault files need local repair.",!0)}if(c?.id===n&&c.userId===we()?.userId)try{if(u)S();else Dd(a,s,l)}catch{o("Owned Vault files need local repair.",!0)}o(`Vault file sync is disabled. Run clawdi setup --agent ${t} --vault-workspace <path>.`)}return{get enabled(){return m},reconcile:(A=!1)=>{if(A)w=0,_=0;if(!m||i.aborted)return Promise.resolve();if(g=!0,f)return f;return f=(async()=>{while(g&&!i.aborted&&m){g=!1;try{k()}catch{m=!1,S(),o("Vault identity or workspace changed; run setup and restart the daemon.");return}if(Date.now()<w){if(_>0)return;if(await W9e(w-Date.now(),void 0,{signal:i}).catch(()=>{}),i.aborted)return}if(!u||!d||!p)return;try{let R=await m0({apiUrl:r.baseUrl,agentId:n,home:l,workspace:u.path,receiptPath:a,connected:{userId:d,machineId:p,nativeAgentId:u.nativeAgentId,stateRoot:s,assertCurrent(){if(k(),i.aborted)throw Error("Vault sync stopped")},async request(O,M){k();let q=await r.getAccessToken();k();let C=new Headers(M.headers);return C.set("Authorization",`Bearer ${q}`),C.set("X-Clawdi-Machine-Id",p),fetch(O,{...M,headers:C,signal:AbortSignal.any([i,AbortSignal.timeout(1e4)])})}}});o(R==="revoked"?"Vault access was revoked; generated files removed.":null,R==="revoked"),_=0,w=Date.now()+250}catch{try{k()}catch{m=!1,S()}if(_=Math.min(_?_*2:60000,300000),w=Date.now()+_,!i.aborted)o("Vault file sync deferred; last good files retained where possible.",!0)}}})().finally(()=>{if(f=null,v)S()}),f},revoke:S,async finish(){if(await f,v)S();try{k()}catch{S()}}}}var TH=b(()=>{Pe();zu();Jy();f0();Ac()});async function Oie(e,t,n=new Map){if(e.scan)return e.scan(t,n);let r=await e.collect(t);return{coverage:r.coverage,batches:async function*(){yield{sessions:r.sessions,observedLocalSessionIds:r.sessions.map((i)=>i.localSessionId),dedupedCount:r.dedupedCount}}()}}function g0(e){let t=[];if(e.sessions)t.push("sessions");if(e.skills)t.push("skills");if(t.length===0)throw Error(`${e.agentType} has no data modules`);return t}import{createHash as K9e}from"node:crypto";import{chmodSync as G9e,existsSync as J9e,mkdirSync as Z9e,readFileSync as Y9e,renameSync as X9e,writeFileSync as Q9e}from"node:fs";import{join as Tie}from"node:path";function jie(e){let t=JSON.stringify([e.apiOrigin,e.environmentId,e.adapter,e.sourceSessionKey]);return`v2:${K9e("sha256").update(t).digest("hex")}`}function Td(e,t){if(e.version!==2)return;let n=e.sessions[jie(t)];if(!Uie(n))return;return n.api_origin===t.apiOrigin&&n.environment_id===t.environmentId&&n.adapter===t.adapter&&n.source_session_key===t.sourceSessionKey?n:void 0}function e5e(e,t,n){let r=Lie(e);return r.sessions[jie(t)]={api_origin:t.apiOrigin,environment_id:t.environmentId,adapter:t.adapter,source_session_key:t.sourceSessionKey,...n},r}function Jf(e,t){Mie(e5e(Qs(),e,t))}function Nie(e){if(e.length===0)return;let t=Qs(),n=!1;for(let r of e){let i=Td(t,r.fence);if(!i||i.pending!==void 0||i.protocol!==r.protocol||i.local_hash!==r.localHash||i.source_revision===r.sourceRevision)continue;i.source_revision=r.sourceRevision,n=!0}if(n)Mie(t)}function Qs(){let e=Tie(ge(),jH);if(!J9e(e))return h0();try{let t=JSON.parse(Y9e(e,"utf-8"));if(!y0(t)||!y0(t.sessions))return h0();if(t.version===1){let n={};for(let[r,i]of Object.entries(t.sessions))if(Die(i))n[r]=i;return{version:1,sessions:n}}if(t.version===g_){let n={};for(let[r,i]of Object.entries(t.sessions))if(Die(i)||Uie(i))n[r]=i;return{version:g_,sessions:n}}return h0()}catch{return console.log(y.yellow(`⚠ ~/.clawdi/${jH} is corrupted; resetting.`)),h0()}}function Mie(e){let t=ge();Z9e(t,{recursive:!0,mode:448});let n=Tie(t,jH),r=Lie(e),i={};for(let a of Object.keys(r.sessions).sort()){let l=r.sessions[a];if(l)i[a]=l}let o={version:g_,sessions:i},s=`${n}.tmp.${process.pid}`;Q9e(s,`${JSON.stringify(o,null,2)}
1223
1223
  `,{mode:384}),X9e(s,n);try{G9e(n,384)}catch{}}function Lie(e){return e.version===2?e:{version:g_,sessions:{...e.sessions}}}function h0(){return{version:g_,sessions:{}}}function y0(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Die(e){return y0(e)&&typeof e.hash==="string"}function Uie(e){if(!y0(e))return!1;return typeof e.api_origin==="string"&&typeof e.environment_id==="string"&&typeof e.adapter==="string"&&typeof e.source_session_key==="string"&&(e.protocol==="snapshot-v1"||e.protocol==="events-v1")&&(e.source_revision===void 0||typeof e.source_revision==="string")}var jH="sessions-lock.json",g_=2;var v0=b(()=>{Re();Pe()});import{createHash as zie,randomUUID as MH}from"node:crypto";async function _0(e,t){if(await t.contentProtocol()==="snapshot-v1")return"snapshot-v1";return await qie(e)===null?"snapshot-v1":"events-v1"}function Zf(e,t){if(t==="snapshot-v1"){let i=Buffer.from(JSON.stringify(e.messages),"utf-8");return{protocol:t,localHash:Wie(i),snapshotBytes:i}}let n=e.events;if(!n)throw Error(`${e.localSessionId} has no events-v1 content`);c5e(n);let r=Zx(oS,n);return{protocol:t,localHash:r,events:n,finalEventHead:r}}function Yf(e,t){return{apiOrigin:Ft(e.baseUrl),environmentId:t.environmentId,adapter:t.adapter,sourceSessionKey:t.sourceSessionKey}}function b0(e,t,n=Qs()){let r=Td(n,e);return r?.local_hash===t.localHash?r.blocked?.message??null:null}function S0(e){return e.sourceRevision?{source_revision:e.sourceRevision}:{}}function k0(e,t,n){Jf(e,{protocol:n.protocol,local_hash:n.localHash,...S0(t),...n.protocol==="snapshot-v1"?{snapshot_hash:n.localHash}:{}})}async function E0(e){if(e.plan.protocol==="snapshot-v1")return i5e(e);return o5e(e)}async function i5e(e){let t=e.plan.snapshotBytes;if(!t)throw Error("snapshot-v1 plan is missing bytes");if(t.length>t5e)return LH(e,{code:"legacy_session_too_large",sizeBytes:t.length,message:`${e.session.localSessionId} exceeds the legacy 50 MiB session limit`});let n=!1;if(e.needsSnapshotContent)try{let r=await e.api.uploadSessionContent(e.session.localSessionId,t,`${e.session.localSessionId}.json`,{environmentId:e.fence.environmentId,expectedContentHash:e.plan.localHash});if(r.content_hash!==e.plan.localHash)throw Error(`server stored hash ${r.content_hash}, expected ${e.plan.localHash}`);n=!0}catch(r){if(r instanceof ee&&r.status===413)return LH(e,{code:"legacy_session_too_large",sizeBytes:t.length,message:`${e.session.localSessionId} was rejected by the legacy session size limit`});throw r}return Jf(e.fence,{protocol:"snapshot-v1",local_hash:e.plan.localHash,...S0(e.session),snapshot_hash:e.plan.localHash}),{status:"synced",uploaded:n,localHash:e.plan.localHash}}async function o5e(e){let t=e.plan.events,n=e.plan.finalEventHead;if(!t||n===void 0)throw Error("events-v1 plan is incomplete");let r=await qie(e.api);if(r===null)throw Error("events-v1 capability disappeared after session negotiation");let i,o=!1;for(let s=0;s<r5e;s++){let a=await e.api.getSessionEventHead(e.session.localSessionId,e.fence.environmentId),l={protocol:a.protocol,generation:a.generation,revision:a.revision,count:a.count,head_hash:a.head_hash};if(l.count===t.length&&l.head_hash===n&&l.generation)return NH(e,l),{status:"synced",uploaded:o,localHash:n};try{if(i??=l5e(t),l.protocol==="events-v1"&&l.generation!==null&&l.count<t.length&&i[l.count]===l.head_hash){let u=await s5e(e,l,t,i,r);return o=o||u.uploaded,NH(e,u.head),{status:"synced",uploaded:o,localHash:n}}let c=await a5e(e,l,t,i,r);return o=o||c.uploaded,NH(e,c.head),{status:"synced",uploaded:o,localHash:n}}catch(c){if(c instanceof w0)return LH(e,{code:"event_too_large",sizeBytes:c.sizeBytes,message:c.message});if(!(c instanceof ee)||c.status!==409)throw c}}throw Error(`${e.session.localSessionId} event head changed during every retry`)}async function s5e(e,t,n,r,i){if(!t.generation)throw Error("cannot append without a generation");let o=t,s=Hie(n.slice(t.count),t.count,i,r);for(let a of s){let l=a.startSeq+a.events.length,c={kind:"append",generation:t.generation,base_generation:t.generation,base_revision:o.revision,base_count:a.startSeq,base_head_hash:a.baseHead,final_count:l,final_head_hash:a.resultHead},u=u5e(e.fence,c)??MH();Bie(e,{...c,append_id:u});let d=await e.api.appendSessionEvents({localSessionId:e.session.localSessionId,environmentId:e.fence.environmentId,appendId:u,generation:t.generation,baseRevision:o.revision,baseCount:a.startSeq,baseHeadHash:a.baseHead,finalCount:l,finalHeadHash:a.resultHead,contentHash:a.contentHash,file:a.bytes});UH(d,{generation:t.generation,revision:o.revision+1,count:l,headHash:a.resultHead}),o={protocol:"events-v1",generation:d.generation,revision:d.revision,count:d.count,head_hash:d.head_hash}}return{head:o,uploaded:s.length>0}}async function a5e(e,t,n,r,i){let o=e.plan.finalEventHead;if(!o)throw Error("events-v1 plan is missing final head");let s={kind:"rewrite",base_generation:t.generation,base_revision:t.revision,base_count:t.count,base_head_hash:t.head_hash,final_count:n.length,final_head_hash:o},l=Vie(e.fence,s)??{...s,append_id:MH(),generation:MH()};Bie(e,l);let c={append_id:l.append_id,base_generation:t.generation,base_revision:t.revision,base_count:t.count,base_head_hash:t.head_hash,final_count:n.length,final_head_hash:o},u=await e.api.stageSessionEventGeneration(e.session.localSessionId,{environment_id:e.fence.environmentId,generation:l.generation,append_id:l.append_id,base_generation:t.generation,base_revision:t.revision,base_count:t.count,base_head_hash:t.head_hash,final_count:n.length,final_head_hash:o});if(u.generation!==l.generation)throw Error(`server staged generation ${u.generation}, expected ${l.generation}`);if(u.status==="committed"){let m=await e.api.commitSessionEventGeneration(e.session.localSessionId,l.generation,c);return UH(m,{generation:l.generation,revision:t.revision+1,count:n.length,headHash:o}),{head:{protocol:"events-v1",generation:m.generation,revision:m.revision,count:m.count,head_hash:m.head_hash},uploaded:!1}}let d=Hie(n,0,i,r);for(let m of d){let f=await e.api.uploadSessionEventGenerationChunk({localSessionId:e.session.localSessionId,generation:l.generation,startSeq:m.startSeq,baseHeadHash:m.baseHead,contentHash:m.contentHash,file:m.bytes});if(f.generation!==l.generation||f.start_seq!==m.startSeq||f.end_seq!==m.startSeq+m.events.length-1||f.count!==m.events.length||f.content_hash!==m.contentHash||f.result_head_hash!==m.resultHead)throw Error("server event chunk receipt does not match uploaded bytes")}let p=await e.api.commitSessionEventGeneration(e.session.localSessionId,l.generation,c);return UH(p,{generation:l.generation,revision:t.revision+1,count:n.length,headHash:o}),{head:{protocol:"events-v1",generation:p.generation,revision:p.revision,count:p.count,head_hash:p.head_hash},uploaded:d.length>0}}function Hie(e,t,n,r){let i=[],o=0;while(o<e.length){let s=o,a=0,l=[];while(o<e.length){let f=`${dn(e[o])}
1224
1224
  `,g=Buffer.byteLength(f,"ascii");if(g>n.maxBytes)throw new w0(t+o,g,n.maxBytes);if(o>s&&a+g>n.targetBytes)break;l.push(f),a+=g,o+=1}let c=t+s,u=e.slice(s,o),d=Buffer.from(l.join(""),"ascii");if(d.length>n.maxBytes)throw new w0(c,d.length,n.maxBytes);let p=r[c],m=r[c+u.length];if(!p||!m)throw Error("events-v1 chunk head index is incomplete");i.push({startSeq:c,events:u,bytes:d,contentHash:Wie(d),baseHead:p,resultHead:m})}return i}function l5e(e){let t=[oS],n=oS;for(let r of e)n=Zx(n,[r]),t.push(n);return t}function c5e(e){for(let t=0;t<e.length;t++){let n=e[t];if(!n||n.seq!==t)throw Error("events-v1 seq must be continuous from zero");let r=zie("sha256").update(dn({source:n.source,type:n.type}),"ascii").digest("hex");if(n.event_id!==r)throw Error(`events-v1 event_id mismatch at seq ${t}`)}}function NH(e,t){if(!t.generation)throw Error("events-v1 success is missing generation");Jf(e.fence,{protocol:"events-v1",local_hash:e.plan.localHash,...S0(e.session),event_generation:t.generation,event_revision:t.revision,event_count:t.count,event_head_hash:t.head_hash})}function Bie(e,t){let n=Td(Qs(),e.fence);Jf(e.fence,{protocol:"events-v1",local_hash:e.plan.localHash,...n?.source_revision?{source_revision:n.source_revision}:{},...n?.event_generation?{event_generation:n.event_generation}:{},...n?.event_revision===void 0?{}:{event_revision:n.event_revision},...n?.event_count===void 0?{}:{event_count:n.event_count},...n?.event_head_hash?{event_head_hash:n.event_head_hash}:{},pending:t})}function u5e(e,t){return Vie(e,t)?.append_id??null}function Vie(e,t){let n=Td(Qs(),e)?.pending;if(!n)return null;return n.kind===t.kind&&(t.generation===void 0||n.generation===t.generation)&&n.base_generation===t.base_generation&&n.base_revision===t.base_revision&&n.base_count===t.base_count&&n.base_head_hash===t.base_head_hash&&n.final_count===t.final_count&&n.final_head_hash===t.final_head_hash?n:null}function LH(e,t){return Jf(e.fence,{protocol:e.plan.protocol,local_hash:e.plan.localHash,...S0(e.session),...e.plan.protocol==="snapshot-v1"?{snapshot_hash:e.plan.localHash}:{},blocked:{code:t.code,content_hash:e.plan.localHash,size_bytes:t.sizeBytes,message:t.message,blocked_at:new Date().toISOString()}}),{status:"blocked",uploaded:!1,localHash:e.plan.localHash,message:t.message}}function UH(e,t){if(e.generation!==t.generation||e.revision!==t.revision||e.count!==t.count||e.head_hash!==t.headHash)throw Error("server event receipt does not match the expected committed head")}async function qie(e){let t=Fie.get(e);if(!t)t=e.getSessionUploadCapabilities().then((n)=>{if(!n?.protocols.includes("events-v1"))return null;let r=Math.min(n5e,Math.max(1,n.event_chunk_max_bytes));return{targetBytes:Math.min(r,4194304,Math.max(1048576,n.event_chunk_target_bytes)),maxBytes:r}}),Fie.set(e,t);return t}function Wie(e){return zie("sha256").update(e).digest("hex")}var t5e=52428800,n5e=8388608,r5e=3,Fie,w0;var FH=b(()=>{Fe();ca();v0();Fie=new WeakMap;w0=class w0 extends Error{seq;sizeBytes;constructor(e,t,n){super(`events-v1 event ${e} is ${t} bytes and exceeds the ${n} byte chunk limit`);this.seq=e;this.sizeBytes=t;this.name="EventTooLargeError"}}});import{existsSync as d5e,readFileSync as p5e}from"node:fs";import{join as Kie}from"node:path";function Nd(){return Kie(ge(),`${zH}.lock`)}function Gie(){return Kie(ge(),zH)}function Md(e,t){return`${e}:${t}`}function HH(e,t,n){return[e,t,n].map((r)=>encodeURIComponent(r)).join(":")}function Xf(e,t){return[e,t].map((n)=>encodeURIComponent(n)).join(":")}function BH(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/,"");if(!Xt(t))throw Error("Invalid materialized Skill path");return t}async function Ld(e,t,n){return(await pr(e,t,n)).hash}function ui(){let e=Gie();if(!d5e(e))return A0();try{let t=JSON.parse(p5e(e,"utf-8"));if(!jd(t))return A0();if(t.version!==1&&t.version!==2&&t.version!==3&&t.version!==4&&t.version!==Za)return A0();let n=m5e(t.skills);if(t.version===1||t.version===2)return{version:Za,skills:n,claims:{},materializations:{}};return{version:Za,skills:n,claims:Yie(t.claims),materializations:t.version===4||t.version===Za?Xie(t.materializations):{}}}catch{return console.log(y.yellow(`⚠ ~/.clawdi/${zH} is corrupted; resetting.`)),A0()}}function Jie(e){Rn(Nd(),(t)=>{let n=ui(),r=n.claims,i=n.materializations,o=e.version===Za?Yie(e.claims):{},s=e.version===Za?Xie(e.materializations):{};t.assertOwned(),Ud({version:Za,skills:e.skills,claims:{...o,...r},materializations:{...s,...i}})})}function Ud(e){let t={};for(let o of Object.keys(e.skills).sort()){let s=e.skills[o];if(s)t[o]=s}let n={};for(let o of Object.keys(e.claims).sort()){let s=e.claims[o];if(s)n[o]=s}let r={};for(let o of Object.keys(e.materializations).sort()){let s=e.materializations[o];if(s)r[o]=s}let i={version:Za,skills:t,claims:n,materializations:r};ie(Gie(),`${JSON.stringify(i,null,2)}
1225
1225
  `,{mode:at,dirMode:Ge})}function Fd(e,t,n){let r=ui(),i=new Map;for(let l of Object.values(r.claims))if(l.agent_type===e&&l.agent_id===t&&l.project_id===n)i.set(l.skill_key,l.hash);let o=new Map;for(let[l,c]of Object.entries(r.skills))if(!l.includes(":"))o.set(l,c.hash);let s=`${e}:`,a=`${e}:${n}:`;for(let[l,c]of Object.entries(r.skills))if(l.startsWith(s)&&!l.startsWith(a))o.set(l.slice(s.length),c.hash);for(let[l,c]of Object.entries(r.skills))if(l.startsWith(a))o.set(l.slice(a.length),c.hash);return{claims:i,legacyBaselines:o}}function Pc(e,t){return Object.values(ui().claims).filter((n)=>n.agent_type===e&&n.agent_id===t).map((n)=>({...n}))}function zd(e){if(Qie(e),e.hash.length===0)throw Error("Skill projection claim hash must not be empty");Rn(Nd(),(t)=>{let n=ui(),r=HH(e.agentId,e.projectId,e.skillKey);n.claims[r]={agent_type:e.agentType,agent_id:e.agentId,project_id:e.projectId,skill_key:e.skillKey,hash:e.hash},n.skills[Md(e.agentType,e.skillKey)]={hash:e.hash},t.assertOwned(),Ud(n)})}function ea(e){return Qie(e),Rn(Nd(),(t)=>{let n=ui(),r=HH(e.agentId,e.projectId,e.skillKey),i=n.claims[r];if(!i||i.agent_type!==e.agentType||i.agent_id!==e.agentId||i.project_id!==e.projectId||i.skill_key!==e.skillKey)return!1;delete n.claims[r];let o=Md(e.agentType,e.skillKey);if(n.skills[o]?.hash===i.hash)delete n.skills[o];return t.assertOwned(),Ud(n),!0})}function ao(e){I0(e);let t=Xf(e.agentType,e.localSkillKey),n=ui().materializations[t];if(!n||n.agent_type!==e.agentType||n.local_skill_key!==e.localSkillKey)return null;return{...n}}function R0(e){let t=ao(e);return Boolean(t&&t.source_project_id===e.sourceProjectId&&t.source_skill_key===e.sourceSkillKey&&t.content_hash===e.contentHash&&(e.reconcileAgentId===void 0||t.reconcile_agent_id===e.reconcileAgentId))}function P0(e){if(I0(e),!e.sourceProjectId)throw Error("Source Project ID is required");if(!Xt(e.sourceSkillKey))throw Error("Invalid source Project Skill key");if(!e.contentHash)throw Error("Materialized Skill hash is required");if(e.reconcileAgentId!==void 0&&!e.reconcileAgentId)throw Error("Reconcile Agent ID must not be empty");Rn(Nd(),(t)=>{let n=ui(),r=Xf(e.agentType,e.localSkillKey);n.materializations[r]={agent_type:e.agentType,local_skill_key:e.localSkillKey,source_project_id:e.sourceProjectId,source_skill_key:e.sourceSkillKey,content_hash:e.contentHash,...e.reconcileAgentId?{reconcile_agent_id:e.reconcileAgentId}:{}},t.assertOwned(),Ud(n)})}async function C0(e,t){let n=ao(e);P0(e);try{await t()}catch(r){throw Rn(Nd(),(i)=>{let o=ui(),s=Xf(e.agentType,e.localSkillKey),a=o.materializations[s];if(a?.source_project_id===e.sourceProjectId&&a.source_skill_key===e.sourceSkillKey&&a.content_hash===e.contentHash&&a.reconcile_agent_id===e.reconcileAgentId){if(n)o.materializations[s]=n;else delete o.materializations[s];i.assertOwned(),Ud(o)}}),r}}function Zie(e,t){return Object.values(ui().materializations).filter((n)=>n.agent_type===e&&n.reconcile_agent_id===t).map((n)=>({...n}))}function $0(e){return I0(e),Rn(Nd(),(t)=>{let n=ui(),r=Xf(e.agentType,e.localSkillKey),i=n.materializations[r];if(!i||i.agent_type!==e.agentType||i.local_skill_key!==e.localSkillKey)return!1;return delete n.materializations[r],t.assertOwned(),Ud(n),!0})}function x0(e){return I0(e),Rn(Nd(),(t)=>{let n=ui(),r=Xf(e.agentType,e.localSkillKey),i=n.materializations[r];if(!i||i.agent_type!==e.agentType||i.local_skill_key!==e.localSkillKey||i.source_project_id!==e.sourceProjectId||i.source_skill_key!==e.sourceSkillKey||i.content_hash!==e.contentHash||i.reconcile_agent_id!==e.reconcileAgentId)return!1;return delete n.materializations[r],t.assertOwned(),Ud(n),!0})}function jd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function m5e(e){if(!jd(e))return{};let t={};for(let[n,r]of Object.entries(e))if(jd(r)&&typeof r.hash==="string"&&r.hash.length>0)t[n]={hash:r.hash};return t}function Yie(e){if(!jd(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!jd(r))continue;if(typeof r.agent_type!=="string"||r.agent_type.length===0||typeof r.agent_id!=="string"||r.agent_id.length===0||typeof r.project_id!=="string"||r.project_id.length===0||typeof r.skill_key!=="string"||!Xt(r.skill_key)||typeof r.hash!=="string"||r.hash.length===0)continue;if(n!==HH(r.agent_id,r.project_id,r.skill_key))continue;t[n]={agent_type:r.agent_type,agent_id:r.agent_id,project_id:r.project_id,skill_key:r.skill_key,hash:r.hash}}return t}function Xie(e){if(!jd(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!jd(r))continue;if(typeof r.agent_type!=="string"||r.agent_type.length===0||typeof r.local_skill_key!=="string"||!Xt(r.local_skill_key)||typeof r.source_project_id!=="string"||r.source_project_id.length===0||typeof r.source_skill_key!=="string"||!Xt(r.source_skill_key)||typeof r.content_hash!=="string"||r.content_hash.length===0)continue;if(n!==Xf(r.agent_type,r.local_skill_key))continue;t[n]={agent_type:r.agent_type,local_skill_key:r.local_skill_key,source_project_id:r.source_project_id,source_skill_key:r.source_skill_key,content_hash:r.content_hash,...typeof r.reconcile_agent_id==="string"&&r.reconcile_agent_id.length>0?{reconcile_agent_id:r.reconcile_agent_id}:{}}}return t}function Qie(e){if(e.agentType.length===0)throw Error("Skill projection Agent type is required");if(e.agentId.length===0)throw Error("Skill projection Agent ID is required");if(e.projectId.length===0)throw Error("Skill projection Project ID is required");if(!Xt(e.skillKey))throw Error("Invalid Skill projection key")}function I0(e){if(!e.agentType)throw Error("Materialized Skill Agent type is required");if(!Xt(e.localSkillKey))throw Error("Invalid materialized Skill key")}function A0(){return{version:Za,skills:{},claims:{},materializations:{}}}var zH="skills-lock.json",Za=5;var Qf=b(()=>{Re();Pe();Do();_t();$o();Kr()});import{existsSync as VH}from"node:fs";import{mkdtemp as f5e,rm as g5e}from"node:fs/promises";import{tmpdir as h5e}from"node:os";import{dirname as noe,join as O0}from"node:path";function eoe(e,t,n){return{agentType:e,localSkillKey:n.skill_key,sourceProjectId:n.project_id,sourceSkillKey:n.skill_key,contentHash:n.content_hash,reconcileAgentId:t}}function toe(e,t,n){return{agentType:e,localSkillKey:n.local_skill_key,sourceProjectId:n.source_project_id,sourceSkillKey:n.source_skill_key,contentHash:n.content_hash,reconcileAgentId:t}}async function v5e(e,t){let n=noe(e.path(t.localSkillKey));if(!VH(O0(n,"SKILL.md")))throw Error(`Project Skill ${t.localSkillKey} is missing from this Agent`);let r=await pr(n,void 0,t.localSkillKey);if(r.hash!==t.contentHash)throw Error(`Project Skill ${t.localSkillKey} was changed locally. Move or rename it, then try again.`);return r.archive}function w5e(e,t,n){let r=new URL(n.archive_url);if(r.origin!==new URL(e.baseUrl).origin||r.search||r.hash)throw Error(`Project Skill ${n.skill_key} has an invalid download address`);let i=`/v1/runtime/project-skill-archives/${t}/${n.project_id}/${n.skill_id}/${n.content_hash}/`;if(!r.pathname.startsWith(i)||!r.pathname.endsWith(`/${n.skill_key}.tar.gz`))throw Error(`Project Skill ${n.skill_key} has an invalid download identity`);return r}async function _5e(e,t,n){let r=await fetch(w5e(e,t,n),{headers:{Authorization:`Bearer ${await e.getAccessToken()}`,Accept:"application/gzip"},redirect:"error"});if(!r.ok)throw Error(`Project Skill ${n.skill_key} download failed (${r.status})`);let i=await Ta(r,y5e,{resourceLabel:"Project Skill archive",limitLabel:"25 MB"}),o=await f5e(O0(h5e(),"clawdi-project-reconcile-"));try{await xo(o,i);let s=O0(o,n.skill_key);if(!VH(O0(s,"SKILL.md")))throw Error(`Project Skill ${n.skill_key} archive is invalid`);let a=await pr(s,o,n.skill_key);if(a.hash!==n.content_hash)throw Error(`Project Skill ${n.skill_key} download failed its identity check`);return a.archive}finally{await g5e(o,{recursive:!0,force:!0})}}async function roe(e){Z(await e.api.PUT("/v1/runtime/project-skill-capability",{params:{query:{environment_id:e.agentId}},body:{project_skill_reconcile_version:1}}));let t=Z(await e.api.GET("/v1/runtime/project-skills",{params:{query:{environment_id:e.agentId}}}));if(t.agent_id!==e.agentId)throw Error("Project Skill inventory Agent mismatch");let n=new Map;for(let c of t.skills??[]){if(n.has(c.skill_key))throw Error(`Skill ${c.skill_key} comes from more than one linked Project`);n.set(c.skill_key,c)}let r=new Set(await e.skills.listKeys()),i=Zie(e.agentType,e.agentId),o=new Map,s=new Set;for(let c of i){let u=toe(e.agentType,e.agentId,c);if(!VH(e.skills.path(c.local_skill_key))){s.add(c.local_skill_key);continue}o.set(c.local_skill_key,{input:u,archive:await v5e(e.skills,u)})}let a=new Map;for(let c of[...n.values()].sort((u,d)=>u.skill_key.localeCompare(d.skill_key))){let u=eoe(e.agentType,e.agentId,c),d=ao({agentType:e.agentType,localSkillKey:c.skill_key});if(!d&&r.has(c.skill_key))throw Error(`Skill ${c.skill_key} already exists in this Agent's Workspace. Move or rename it, then try again.`);if(d&&d.reconcile_agent_id!==e.agentId)throw Error(`Skill ${c.skill_key} already exists in this Agent's Workspace. Move or rename it, then try again.`);if(!s.has(c.skill_key)&&R0(u))continue;a.set(c.skill_key,await _5e(e.api,e.agentId,c))}for(let c of i){if(!s.has(c.local_skill_key))continue;x0(toe(e.agentType,e.agentId,c))}let l=[];try{for(let[c,u]of[...a].sort(([d],[p])=>d.localeCompare(p))){let d=n.get(c);if(!d)throw Error("Project Skill inventory changed during reconcile");let p=eoe(e.agentType,e.agentId,d),m=o.get(c);if(await C0(p,()=>e.skills.writeArchive(c,u)),l.push({kind:"installed",input:p,...m?{prior:m}:{}}),await Ld(noe(e.skills.path(c)),void 0,c)!==d.content_hash)throw Error(`Project Skill ${c} did not install with the expected content`)}for(let c of[...o.values()].sort((u,d)=>u.input.localSkillKey.localeCompare(d.input.localSkillKey))){if(n.has(c.input.localSkillKey))continue;if(await e.skills.remove(c.input.localSkillKey),l.push({kind:"removed",prior:c}),!x0(c.input))throw Error(`Project Skill ${c.input.localSkillKey} ownership changed during reconcile`)}}catch(c){let u=[];for(let d of l.reverse())try{if(d.kind==="removed")await e.skills.writeArchive(d.prior.input.localSkillKey,d.prior.archive),P0(d.prior.input);else if(d.prior)await e.skills.writeArchive(d.prior.input.localSkillKey,d.prior.archive),P0(d.prior.input);else await e.skills.remove(d.input.localSkillKey),x0(d.input)}catch(p){u.push(p instanceof Error?p.message:String(p))}if(u.length>0)throw Error(`Project Skill update failed and rollback needs attention: ${u.join("; ")}`,{cause:c});throw c}}var y5e=26214400;var ioe=b(()=>{Fe();gf();Qf();Kr()});import{existsSync as aoe,mkdirSync as b5e,readFileSync as S5e}from"node:fs";import{rename as k5e,writeFile as E5e}from"node:fs/promises";import{dirname as A5e,join as R5e}from"node:path";function ooe(e){return R5e(yr(e),"queue.jsonl")}function C5e(e){let t=A5e(e);if(!aoe(t))b5e(t,{recursive:!0})}function soe(e,t){if(e.kind==="skill_push")return{...e,version:t};if(e.kind==="skill_delete")return{...e,version:t};if(e.kind==="session_push")return{...e,version:t};throw Error(`unreachable queue-item kind: ${JSON.stringify(e)}`)}function $5e(e){if(typeof e!=="object"||e===null)return!1;let t=e;if(typeof t.kind!=="string")return!1;if(typeof t.enqueued_at!=="string")return!1;if(typeof t.attempts!=="number")return!1;if(t.version!==void 0&&typeof t.version!=="number")return!1;if(t.kind==="skill_push"||t.kind==="skill_delete"){if(typeof t.skill_key!=="string")return!1;if(t.kind==="skill_push"&&typeof t.new_hash!=="string")return!1;if(!Xt(t.skill_key))return!1;if(t.agent_id!==void 0&&typeof t.agent_id!=="string")return!1;if(t.project_id!==void 0&&typeof t.project_id!=="string")return!1;if(t.agent_id===""||t.project_id==="")return!1;if(t.kind==="skill_delete"&&(typeof t.agent_id!=="string"||typeof t.project_id!=="string"))return!1;return!0}if(t.kind==="session_push"){if(typeof t.local_session_id!=="string")return!1;if(typeof t.content_hash!=="string")return!1;if(t.api_origin!==void 0&&typeof t.api_origin!=="string")return!1;if(t.environment_id!==void 0&&typeof t.environment_id!=="string")return!1;if(t.adapter!==void 0&&!x5e(t.adapter))return!1;if(t.source_session_key!==void 0&&typeof t.source_session_key!=="string")return!1;return!0}return!1}class qH{items=[];highWater=0;droppedCount=0;nextVersion=1;maxItems;agentType;onEvict;writeChain=Promise.resolve();flushActive=!1;itemWaiters=new Set;capacityWaiters=new Set;pendingBlob=null;persistPath;constructor(e){this.agentType=e.agentType,this.maxItems=e.maxItems??P5e,this.onEvict=e.onEvict,this.persistPath=ooe(this.agentType)}load(){let e=ooe(this.agentType);if(!aoe(e)){this.items=[];return}let t=S5e(e,"utf-8").split(`
@@ -1505,7 +1505,7 @@ const managedSocketMetadata = (creds) => {
1505
1505
  `:null,revision:G4(n)}}function kQe(e){if(e===null)return G4({});try{let t=JSON.parse(e);if(!t||typeof t!=="object"||Array.isArray(t))return null;let n={};for(let[r,i]of Object.entries(t)){if(typeof i!=="string")return null;n[r]=i}return G4(n)}catch{return null}}function EQe(e,t){let n=Cue(t);if(e.content===null)return FC(n,{force:!0}),null;pc(t,n,e.content,{mode:384,dirMode:448}),Y4(n),z_(t.managedSecretRoot);try{Pue(n,384)}catch{}return n}function $ue(e,t,n){let r=Cue(n),i=yQe(r)?vQe(r,"utf-8"):null,o=SQe(e,t);return{path:EQe(o,n),changed:i!==o.content,material:o,previousRevision:kQe(i)}}function AQe(e){return YR(e.egressProfiles)}function RQe(e){let t=new Set,n=Array.isArray(e.egressProfiles?.profiles)?e.egressProfiles.profiles:[];for(let r of n){let i=U(r);if(i?.owner==="provider-projection")zC(r,t);if(i?.owner==="mcp-projection")zC(r,t);if(i?.owner==="clawdi-native-channels")PQe(i,t)}return[...t].sort()}function PQe(e,t){let n=U(e.rewrite);if(!n)return;let r=U(n.pathReplace),i=yt(r?.replacementSecretRef);if(i)t.add(i);let o=U(n.setHeaders);if(!o)return;for(let s of Object.values(o)){let a=U(s);if(a?.type!=="secretRef")continue;let l=yt(a.secretRef);if(l)t.add(l)}}function zC(e,t){if(!e||typeof e!=="object")return;if(Array.isArray(e)){for(let n of e)zC(n,t);return}for(let[n,r]of Object.entries(e)){if(typeof r==="string"&&(n==="secretRef"||n.endsWith("SecretRef")))t.add(r);zC(r,t)}}var kg=b(()=>{Ko();pf();Fn();fc();et();hr()});import{createHash as CQe}from"node:crypto";import{chmodSync as Iue,chownSync as BC,existsSync as $Qe,lstatSync as xue,mkdirSync as Oue,readFileSync as xQe,rmSync as X4}from"node:fs";import{resolve as IQe}from"node:path";function Due(e,t){Oue(e,{recursive:!0});let n=xue(e);if(!n.isDirectory()||n.isSymbolicLink())throw Error(`hosted CLAWDI_HOME must be a real directory: ${e}`);if(Mn())BC(e,t.uid,t.gid);if(Iue(e,FO),n=xue(e),(n.mode&511)!==FO||n.uid!==t.uid||n.gid!==t.gid)throw Error(`hosted CLAWDI_HOME ownership or mode is invalid: ${e}`)}function Tue(e){Oue(e,{recursive:!0}),Y4(e);try{Iue(e,448)}catch{}}function jue(e){return X4(e.egressProfileBundle,{force:!0}),null}function Nue(e,t){if(e&&t?.status!=="ready")throw Error(`required egress engine is not ready: ${t?.error??"status unavailable"}`)}function Mue(e,t){if(pc(t,t.egressProfileBundle,`${JSON.stringify(e,null,2)}
1506
1506
  `,{mode:416,dirMode:457}),Mn())BC(t.egressProfileBundle,0,gu());return t.egressProfileBundle}function Lue(e){let t=OQe(),n=xQe(t,"utf-8");if(pc(e,e.egressAddon,n,{mode:416,dirMode:457}),Mn())BC(e.egressAddon,0,gu());return{path:e.egressAddon,sha256:TQe(n)}}function Uue(e){return X4(e.egressAddon,{force:!0}),null}function OQe(){let e=IQe(Ff(),"egress-addon","clawdi_egress_addon.py");if($Qe(e))return e;throw Error("packaged egress addon is missing")}function Fue(e){if(!e.program)return X4(e.paths.egressTransparentEnv,{force:!0}),null;let t={CLAWDI_RUNTIME_USER:e.runtimeUser,CLAWDI_RUNTIME_UID:String(e.runtimeUid),CLAWDI_RUNTIME_GID:String(e.runtimeGid),CLAWDI_EGRESS_UID:String(e.egressUid),CLAWDI_EGRESS_GID:String(e.egressGid),CLAWDI_EGRESS_TRANSPARENT_PORT:String(e.program.transparentPort),CLAWDI_EGRESS_NFT_TABLE:Vh,CLAWDI_EGRESS_PROFILE_BUNDLE:e.program.profileBundlePath,CLAWDI_EGRESS_SECRET_FILE:e.program.secretFilePath??"",CLAWDI_EGRESS_CA_DIR:e.paths.egressCaDir,CLAWDI_EGRESS_CA_CERT:e.paths.egressCaCert,CLAWDI_EGRESS_SYSTEM_CA_BUNDLE:e.program.systemCaBundle,CLAWDI_EGRESS_TRANSPORT_VERSION:Lp,CLAWDI_EGRESS_ENGINE_TYPE:"mitmproxy",CLAWDI_EGRESS_ENGINE_VERSION:e.program.engine.version,CLAWDI_EGRESS_ENGINE_URL:e.program.engine.url,CLAWDI_EGRESS_ENGINE_SHA256:e.program.engine.sha256,CLAWDI_EGRESS_ENGINE_BINARY_PATH:e.paths.egressServiceBinary,CLAWDI_EGRESS_ADDON_PATH:e.program.addonPath,CLAWDI_EGRESS_ADDON_SHA256:e.program.addonSha256},n=Object.entries(t).sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>`${r}=${DQe(i)}`);if(pc(e.paths,e.paths.egressTransparentEnv,`${n.join(`
1507
1507
  `)}
1508
- `,{mode:416,dirMode:457}),Mn())BC(e.paths.egressTransparentEnv,0,e.egressGid);return e.paths.egressTransparentEnv}function DQe(e){if(/[\r\n]/.test(e))throw Error("runtime environment files only support single-line values");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function TQe(e){return CQe("sha256").update(e).digest("hex")}var zue=b(()=>{Ec();kg();Fn();an();et();Up()});import{existsSync as jQe,readFileSync as NQe}from"node:fs";import{join as MQe}from"node:path";function Q4(e){let t=e.projection?.mcp;if(t===void 0)return{servers:{}};return{servers:iP.parse(t).servers}}function Hue(e,t,n,r,i){let o=Bue(e,t,n,i);for(let s of[...o.runtimes].sort((a,l)=>a.name===l.name?0:a.name==="hermes"?-1:1)){if(s.mutations.length===0)continue;if(s.name==="hermes"){if(!s.commandPath||!sn(s.commandPath)||!i)throw Error("could not mutate managed Hermes MCP servers: runtime is unavailable");let a={...s.native.servers};for(let l of s.mutations)if(l.kind==="remove")delete a[l.serverName];else a[l.serverName]=l.server;Vt(i,"mcp_servers",Object.keys(a).length>0?a:void 0);continue}if(!s.commandPath||!sn(s.commandPath))throw Error("could not mutate managed OpenClaw MCP servers: runtime is unavailable");for(let a of s.mutations){let l=a.kind==="remove"?["mcp","unset",a.serverName]:["mcp","set",a.serverName,JSON.stringify(a.server)];As(s.commandPath,l,"",o.home,r)}}}function Bue(e,t,n,r=null){let i=Q4(e),o=mc(e,t),s=LQe.map((a)=>{let l=e.runtimes[a]?.enabled===!0?i.servers:{},c=n.get(a),u=c?.commandPath??Zs(a,o),d=Boolean(u&&sn(u));if(a==="hermes"&&Object.keys(l).length>0&&!d)throw Error("could not inspect managed Hermes MCP servers: runtime is unavailable");let p=a==="openclaw"||d?FQe(a,o,u,r):{servers:{}},m=new Set(Object.entries(p.servers).flatMap(([v,w])=>UQe(v,w)?[v]:[]));for(let v of Object.keys(l).sort())if(Object.hasOwn(p.servers,v)&&!m.has(v))throw Error(`refusing to replace unmanaged ${a} MCP server ${v}`);let f=[];for(let v of[...m].sort())if(!Object.hasOwn(l,v)&&Object.hasOwn(p.servers,v))f.push({kind:"remove",serverName:v});for(let[v,w]of Object.entries(l).sort(([_],[S])=>_.localeCompare(S))){let _=zQe(v,w);if(!Ks(p.servers[v],_))f.push({kind:"set",serverName:v,server:_})}if(f.some((v)=>v.kind==="set")&&(!c?.enabled||c.status==="install_failed"))throw Error(`could not apply managed ${a} MCP servers: runtime is unavailable`);return{name:a,native:p,mutations:f,commandPath:u}});return{home:o,runtimes:s}}function UQe(e,t){if(!Ze(t)||!Ze(t.headers))return!1;return Object.entries(t.headers).some(([n,r])=>typeof r==="string"&&r.endsWith(XR(e,n)))}function FQe(e,t,n,r){if(e==="hermes"){if(!n||!r)throw Error("Hermes config command is unavailable");let c=fr(r,"mcp_servers");if(!c.exists)return{servers:{}};if(!Ze(c.value))throw Error("Hermes config field mcp_servers must be an object");return{servers:c.value}}let i=MQe(t,".openclaw","openclaw.json");if(!jQe(i))return{servers:{}};let o=NQe(i,"utf-8"),s;try{s=JSON.parse(o)}catch(c){throw Error(`${e} config is invalid: ${c instanceof Error?c.message:String(c)}`)}if(!Ze(s))throw Error(`${e} config must be an object`);if(s.mcpServers!==void 0)throw Error("openclaw config uses unsupported legacy field mcpServers; canonical MCP state is mcp.servers");let a=s.mcp;if(a!==void 0&&!Ze(a))throw Error("openclaw config field mcp must be an object");let l=Ze(a)?a.servers:void 0;if(l===void 0)return{servers:{}};if(!Ze(l))throw Error("openclaw config field mcp.servers must be an object");return{servers:l}}function zQe(e,t){return{url:t.url,transport:t.transport,headers:Object.fromEntries(Object.entries(t.headers).map(([n,r])=>[n,typeof r==="string"?r:`${r.prefix}${XR(e,n)}`]))}}function Vue(e,t,n,r){Bue(e,t,n,r)}var LQe;var VC=b(()=>{Is();ff();oo();yf();Fn();et();LQe=["openclaw","hermes"]});import{existsSync as HQe,readFileSync as BQe}from"node:fs";import{join as e6}from"node:path";function Eg(e){return[qC,"## Clawdi managed locale","",`Use \`${e.language}\` as the default response language unless the user explicitly requests another language.`,`Interpret ambiguous dates and times in \`${e.timezone}\` unless the user specifies another timezone.`,H_].join(`
1508
+ `,{mode:416,dirMode:457}),Mn())BC(e.paths.egressTransparentEnv,0,e.egressGid);return e.paths.egressTransparentEnv}function DQe(e){if(/[\r\n]/.test(e))throw Error("runtime environment files only support single-line values");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function TQe(e){return CQe("sha256").update(e).digest("hex")}var zue=b(()=>{Ec();kg();Fn();an();et();Up()});import{existsSync as jQe,readFileSync as NQe}from"node:fs";import{join as MQe}from"node:path";function Q4(e){let t=e.projection?.mcp;if(t===void 0)return{servers:{}};return{servers:iP.parse(t).servers}}function Hue(e,t,n,r,i){let o=Bue(e,t,n,i);for(let s of[...o.runtimes].sort((a,l)=>a.name===l.name?0:a.name==="hermes"?-1:1)){if(s.mutations.length===0)continue;if(s.name==="hermes"){if(!s.commandPath||!sn(s.commandPath)||!i)throw Error("could not mutate managed Hermes MCP servers: runtime is unavailable");let a={...s.native.servers};for(let l of s.mutations)if(l.kind==="remove")delete a[l.serverName];else a[l.serverName]=l.server;Vt(i,"mcp_servers",Object.keys(a).length>0?a:void 0);continue}if(!s.commandPath||!sn(s.commandPath))throw Error("could not mutate managed OpenClaw MCP servers: runtime is unavailable");for(let a of s.mutations){let l=a.kind==="remove"?["mcp","unset",a.serverName]:["mcp","set",a.serverName,JSON.stringify(a.server)];As(s.commandPath,l,"",o.home,r)}}}function Bue(e,t,n,r=null){let i=Q4(e),o=mc(e,t),s=LQe.map((a)=>{let l=e.runtimes[a]?.enabled===!0?i.servers:{},c=n.get(a),u=c?.commandPath??Zs(a,o),d=Boolean(u&&sn(u));if(a==="hermes"&&Object.keys(l).length>0&&!d)throw Error("could not inspect managed Hermes MCP servers: runtime is unavailable");let p=a==="openclaw"||d?FQe(a,o,u,r):{servers:{}},m=new Set(Object.entries(p.servers).flatMap(([v,w])=>UQe(v,w)?[v]:[]));for(let v of Object.keys(l).sort())if(Object.hasOwn(p.servers,v)&&!m.has(v))throw Error(`refusing to replace unmanaged ${a} MCP server ${v}`);let f=[];for(let v of[...m].sort())if(!Object.hasOwn(l,v)&&Object.hasOwn(p.servers,v))f.push({kind:"remove",serverName:v});for(let[v,w]of Object.entries(l).sort(([_],[S])=>_.localeCompare(S))){let _=zQe(a,v,w);if(!Ks(p.servers[v],_))f.push({kind:"set",serverName:v,server:_})}if(f.some((v)=>v.kind==="set")&&(!c?.enabled||c.status==="install_failed"))throw Error(`could not apply managed ${a} MCP servers: runtime is unavailable`);return{name:a,native:p,mutations:f,commandPath:u}});return{home:o,runtimes:s}}function UQe(e,t){if(!Ze(t)||!Ze(t.headers))return!1;return Object.entries(t.headers).some(([n,r])=>typeof r==="string"&&r.endsWith(XR(e,n)))}function FQe(e,t,n,r){if(e==="hermes"){if(!n||!r)throw Error("Hermes config command is unavailable");let c=fr(r,"mcp_servers");if(!c.exists)return{servers:{}};if(!Ze(c.value))throw Error("Hermes config field mcp_servers must be an object");return{servers:c.value}}let i=MQe(t,".openclaw","openclaw.json");if(!jQe(i))return{servers:{}};let o=NQe(i,"utf-8"),s;try{s=JSON.parse(o)}catch(c){throw Error(`${e} config is invalid: ${c instanceof Error?c.message:String(c)}`)}if(!Ze(s))throw Error(`${e} config must be an object`);if(s.mcpServers!==void 0)throw Error("openclaw config uses unsupported legacy field mcpServers; canonical MCP state is mcp.servers");let a=s.mcp;if(a!==void 0&&!Ze(a))throw Error("openclaw config field mcp must be an object");let l=Ze(a)?a.servers:void 0;if(l===void 0)return{servers:{}};if(!Ze(l))throw Error("openclaw config field mcp.servers must be an object");return{servers:l}}function zQe(e,t,n){return{...e==="openclaw"?{requestTimeoutMs:420000}:{},url:n.url,transport:n.transport,headers:Object.fromEntries(Object.entries(n.headers).map(([r,i])=>[r,typeof i==="string"?i:`${i.prefix}${XR(t,r)}`]))}}function Vue(e,t,n,r){Bue(e,t,n,r)}var LQe;var VC=b(()=>{Is();ff();oo();yf();Fn();et();LQe=["openclaw","hermes"]});import{existsSync as HQe,readFileSync as BQe}from"node:fs";import{join as e6}from"node:path";function Eg(e){return[qC,"## Clawdi managed locale","",`Use \`${e.language}\` as the default response language unless the user explicitly requests another language.`,`Interpret ambiguous dates and times in \`${e.timezone}\` unless the user specifies another timezone.`,H_].join(`
1509
1509
  `)}function WC(e,t){let n=HQe(e)?BQe(e,"utf-8"):"",r=n.indexOf(qC),i=n.indexOf(H_),o=r!==-1,s=i!==-1;if(o!==s||o&&i<r)throw Error(`managed locale block markers are malformed in ${e}`);if(o&&(n.indexOf(qC,r+qC.length)!==-1||n.indexOf(H_,i+H_.length)!==-1))throw Error(`managed locale block markers are duplicated in ${e}`);let a;if(o&&s){let l=i+H_.length;a=`${n.slice(0,r)}${t}${n.slice(l)}`}else{let l=n.length===0?"":n.endsWith(`
1510
1510
  `)?`
1511
1511
  `:`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawdi",
3
- "version": "0.14.74",
3
+ "version": "0.14.76",
4
4
  "description": "The best home for all your AI agents. Run them in the cloud or connect your own—with their context and tools in one place.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -44,6 +44,10 @@ It preserves metadata; find the exact ID before changing it.
44
44
  - Use `session_list` to browse recent sessions or filter by time, Agent, or Project.
45
45
  - Use `session_search` to find past agent conversations by keyword and obtain session UUIDs.
46
46
  - Use `session_get` to read a session by UUID or Clawdi share URL.
47
+ - Use `session_share_create` to publish an immutable snapshot only when the user explicitly asks
48
+ to share a Session, part of it, or one Assistant response.
49
+ - Use `session_share_list` to inspect active links and obtain their exact IDs and kinds.
50
+ - Use `session_share_revoke` to stop sharing one exact link only when the user asks.
47
51
 
48
52
  Call `session_get` when the user provides a Clawdi share URL or session UUID and wants its
49
53
  contents. For a request to open a specific unnamed past conversation, use `session_search`
@@ -51,6 +55,13 @@ to find the UUID and then read the selected match.
51
55
 
52
56
  Do NOT call WebFetch on `cloud.clawdi.ai/s/...` URLs — `session_get` is the right tool and avoids the WebFetch permission prompt.
53
57
 
58
+ For `session_share_create`, omit `position` for the full `session` scope. For `through` or
59
+ `response`, use the stable message `position` returned by `session_get` or `session_search`,
60
+ never a filtered array index; `response` must target an Assistant message. Public snapshots
61
+ include only the existing safe user/Assistant projection, never reasoning, system/developer
62
+ messages, hidden events, or tool activity. Before revoking, use `session_share_list` unless the
63
+ user already supplied the exact `share_id` and `kind`; never infer a link ID or kind.
64
+
54
65
  CLI fallback: `clawdi session search "query" --json`, then `clawdi session read <cloud-session-id> --json`.
55
66
  `session list` is local; `session export <cloud-session-id>` exports owner Markdown without
56
67
  publishing. Publish only with user authorization: `session share <cloud-session-id> --yes`.
@@ -117,18 +128,22 @@ their bound Project, and field deletion is rejected when a Vault is attached to
117
128
  Projects. Whole-Vault deletion, attach/detach, and credential profiles remain
118
129
  foreground operator workflows; never bypass that boundary through raw HTTP or daemon RPC.
119
130
 
120
- ### Request missing credentials
131
+ ### Request new or updated credentials
121
132
 
122
133
  Use `vault_request_create` with exact `project_id`, `vault_id`, canonical `slug`, optional
123
- `section`, and a batch of environment field names in `fields`. A Vault is a key bundle:
124
- request related keys together under one link. Supplied or already-pending fields are rejected.
134
+ `section`, and a batch of Vault field names in `fields`. A Vault is a key bundle:
135
+ request related new and existing keys together under one link. Include existing keys only
136
+ when the user authorized updating them; do not delete them first. Existing Vault values
137
+ remain unchanged until successful submission and are never shown or prefilled. Overlapping pending requests
138
+ are rejected; a change to any requested field conflicts with the entire batch.
125
139
  Show the returned `url` unchanged to the user; do not ask them to paste secrets into chat.
126
140
  Opening the link does not consume it. Saving all requested fields consumes it once.
127
141
 
128
142
  Check `vault_request_status` with its `request_id` after the user finishes. `pending` is not
129
143
  a secret value; `supplied` means the exact references are ready. On `expired` or `conflict`,
130
- inspect the Vault and request only still-missing fields; never replace an existing value to
131
- retry. If creation times out, use `vault_get` to find recent request IDs before retrying.
144
+ inspect current Vault metadata and reassess the authorized fields before creating a fresh
145
+ request; do not blindly retry an overwrite. If creation times out, use `vault_get` to find
146
+ recent request IDs before retrying.
132
147
  If submission times out, inspect status before repeating a mutation.
133
148
 
134
149
  ### Save and refresh credentials locally
@@ -146,9 +161,12 @@ edit, move or commit them. Hosted agents must not invoke/install the tenant Claw
146
161
  Connected operators configure delivery with `clawdi setup --agent <type> --vault-workspace <path>`;
147
162
  that changes only the Vault destination, never every repository scanned by the daemon.
148
163
 
149
- After a credential request is supplied, wait for the expected fields in index metadata before
150
- claiming delivery. If delivery is unavailable, report that state and any missing workspace
151
- binding instead of inventing a destination. Preserve unrelated local configuration.
164
+ After `vault_request_status` reports `supplied`, match its Vault ID, section and field names
165
+ in the index and require the local Vault `content_version` to be at least the status
166
+ `content_version`. The API requires this counter; existing names alone do not prove delivery.
167
+ If the owned index is incomplete or behind, wait for runtime reconciliation and report
168
+ unverified delivery. Do not read secret values to check freshness. Report missing workspace bindings instead of inventing a
169
+ destination. Preserve unrelated local configuration.
152
170
 
153
171
  ### Optional CLI environment files
154
172
 
@@ -11,7 +11,8 @@ Use Clawdi Cloud tools through the `clawdi` MCP server. Treat the live tool sche
11
11
 
12
12
  Third-party tool routing below applies unchanged in Hosted. Do not inspect, run, or suggest
13
13
  Clawdi host-management commands such as `clawdi setup`, `clawdi wallet`, `clawdi vault`, or
14
- `clawdi ai-provider`.
14
+ `clawdi ai-provider`. Do not use any `clawdi` CLI command as a Cloud capability fallback;
15
+ use the Clawdi MCP tools exposed to the Hosted runtime.
15
16
 
16
17
  ## Context Routing
17
18
 
@@ -46,11 +47,23 @@ already supplied the exact memory ID; never infer which stored item to mutate.
46
47
  - Use `session_list` to browse recent sessions or filter by time, Agent, or Project.
47
48
  - Use `session_search` to find past agent conversations by keyword and obtain session UUIDs.
48
49
  - Use `session_get` to read a session by UUID or Clawdi share URL.
50
+ - Use `session_share_create` to publish an immutable snapshot only when the user explicitly asks
51
+ to share a Session, part of it, or one Assistant response.
52
+ - Use `session_share_list` to inspect active links and obtain their exact IDs and kinds.
53
+ - Use `session_share_revoke` to stop sharing one exact link only when the user asks.
49
54
 
50
55
  Call `session_get` when the user provides a Clawdi share URL or session UUID and wants its
51
56
  contents. Use `session_search` to locate a requested unnamed conversation. Do not use a
52
57
  generic web fetcher for Clawdi share URLs.
53
58
 
59
+ For `session_share_create`, omit `position` for the full `session` scope. For `through` or
60
+ `response`, use the stable message `position` returned by `session_get` or `session_search`,
61
+ never a filtered array index; `response` must target an Assistant message. Public snapshots
62
+ include only the existing safe user/Assistant projection, never reasoning, system/developer
63
+ messages, hidden events, or tool activity. Before revoking, use `session_share_list` unless the
64
+ user already supplied the exact `share_id` and `kind`; never infer a link ID or kind. Hosted
65
+ Session sharing uses these MCP tools only, not CLI commands.
66
+
54
67
  ## Projects
55
68
 
56
69
  - `project_current_get` — Read the runtime-bound Project.
@@ -100,18 +113,22 @@ own Workspace (the runtime-bound Project). Field deletion is rejected when a Vau
100
113
  attached to multiple Projects. Whole-Vault deletion, attach/detach, and credential profiles remain
101
114
  unavailable through Agent MCP; do not bypass that boundary through raw HTTP.
102
115
 
103
- ### Request missing credentials
116
+ ### Request new or updated credentials
104
117
 
105
118
  Use `vault_request_create` with exact `project_id`, `vault_id`, canonical `slug`, optional
106
- `section`, and a batch of environment field names in `fields`. A Vault is a key bundle:
107
- request related keys together under one link. Supplied or already-pending fields are rejected.
119
+ `section`, and a batch of Vault field names in `fields`. A Vault is a key bundle:
120
+ request related new and existing keys together under one link. Include existing keys only
121
+ when the user authorized updating them; do not delete them first. Existing Vault values
122
+ remain unchanged until successful submission and are never shown or prefilled. Overlapping pending requests
123
+ are rejected; a change to any requested field conflicts with the entire batch.
108
124
  Show the returned `url` unchanged to the user; do not ask them to paste secrets into chat.
109
125
  Opening the link does not consume it. Saving all requested fields consumes it once.
110
126
 
111
127
  Check `vault_request_status` with its `request_id` after the user finishes. `pending` is not
112
128
  a secret value; `supplied` means the exact references are ready. On `expired` or `conflict`,
113
- inspect the Vault and request only still-missing fields; never replace an existing value to
114
- retry. If creation times out, use `vault_get` to find recent request IDs before retrying.
129
+ inspect current Vault metadata and reassess the authorized fields before creating a fresh
130
+ request; do not blindly retry an overwrite. If creation times out, use `vault_get` to find
131
+ recent request IDs before retrying.
115
132
  If submission times out, inspect status before repeating a mutation.
116
133
 
117
134
  ### Use runtime-supplied credentials
@@ -131,10 +148,12 @@ unrelated configuration in its `.clawdi` parent. Connected installations use thi
131
148
  layout on macOS/Linux only after an explicit workspace binding; do not assume an arbitrary
132
149
  repo is bound. Files remain readable by authorized programs running as the same user.
133
150
 
134
- After a credential request is supplied, inspect index metadata for the requested fields.
135
- Pending requests are metadata only, never empty pseudo-secrets. If delivery is delayed,
136
- report that state without claiming the credentials are saved. Runtime refreshes files;
137
- already-running processes must explicitly reload them. Offline delivery retains last good
151
+ After `vault_request_status` reports `supplied`, match its Vault ID, section and field names
152
+ in the index and require the local Vault `content_version` to be at least the status
153
+ `content_version`. The API requires this counter; existing names alone do not prove delivery.
154
+ If the owned index is incomplete or behind, wait for runtime reconciliation and report
155
+ unverified delivery. Do not read secret values to check freshness. Pending requests are metadata only, never empty pseudo-secrets.
156
+ Runtime refreshes files; already-running processes must explicitly reload them. Offline delivery retains last good
138
157
  files; confirmed access removal removes generated files. Authorized code can read these
139
158
  files, so do not claim that subsequent plaintext exposure is impossible.
140
159