@forsion/extend 0.10.13 → 0.10.15
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/CHANGELOG.md +24 -0
- package/SIGNATURE +6 -6
- package/dist/desktop.mjs +67 -63
- package/dist/main.js +161 -73
- package/manifest.json +2 -2
- package/package.json +1 -1
package/dist/desktop.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var ms=null;function Ha(t){ms=t}function Ee(){if(!ms)throw new Error("core host not set (call setCoreHost first)");return ms}var za=new TextEncoder,wf=new TextDecoder("utf-8",{ignoreBOM:!0}),nr=t=>za.encode(t),Ct=t=>wf.decode(t),ei=t=>typeof t=="string"?za.encode(t).length:t.length;function Ba(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function ti(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),n=>n.charCodeAt(0))}async function qa(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ve(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let i=r.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(i),l=>l.charCodeAt(0)),a=JSON.parse(new TextDecoder().decode(s)),o=a.userId??a.sub;return typeof o!="string"&&typeof o!="number"||!String(o).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(o)}`}catch{return null}}function ys(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Ct(ti(e)));return n&&typeof n=="object"?n:null}catch{return null}}function ws(t,e=Date.now()){let n=ys(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Wa(t,e=Date.now()){let n=ys(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var bf=36e5;function ni(t,e=Date.now()){return!!t&&ws(t,e)>=bf}async function ri(t,e,n=8e3,r){if(!t||!e)return null;let i=t.replace(/\/+$/,"");try{let s=await fetch(`${i}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!s.ok)return null;let a=await s.json().catch(()=>null),o=typeof a?.token=="string"?a.token:"";return o&&o!==e?o:null}catch{return null}}var rr=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,Sf=(t,e)=>new Promise((n,r)=>{let i=()=>{clearTimeout(s),r(new Error("Sign-in cancelled."))},s=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);e.aborted?i():e.addEventListener("abort",i,{once:!0})});function Ga(t,e){let n=f=>e.write(JSON.stringify(f,null,2)),r=()=>{let f;try{f=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(f===null)return[];try{let g=JSON.parse(f);return Array.isArray(g.accounts)?g.accounts.filter(p=>p&&typeof p.token=="string"&&p.id===Ve(p.cloudUrl,p.token)):null}catch{return null}},i=(f,g)=>{let p=Ve(f.cloudUrl||"",f.token||"");if(!p||!f.token||!f.cloudUrl)return;let m=r();if(!m)return;let y=m.find(h=>h.id===p),b=ys(f.token),_={...y,id:p,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:g?.username||y?.username||b?.username,nickname:g?.nickname||y?.nickname};JSON.stringify(y)!==JSON.stringify(_)&&n({version:1,accounts:[...m.filter(h=>h.id!==p),_]})},s=()=>{let f=t.readCreds();i(f);let g=Ve(f.cloudUrl,f.token);return(r()??[]).map(({token:p,...m})=>({...m,active:m.id===g}))},a=f=>{let g=r()?.find(p=>p.id===f);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},o=f=>{let g=Ve(f.cloudUrl||"",f.token||""),p=r();g&&p&&n({version:1,accounts:p.filter(m=>m.id!==g)})},l=null;return{rememberForsionAccount:i,forsionAccounts:s,savedForsionAccount:a,forgetForsionAccount:o,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(f,g,p)=>{if(l)throw new Error("A sign-in is already in progress.");if(!f)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;l=m;let y=()=>{if(m.signal.aborted||l!==m)throw new Error("Sign-in cancelled.")};try{let b=f.replace(/\/+$/,""),_;try{_=await fetch(`${b}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(D=>D.json())}catch(D){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${b}:${D?.message||D}`)}if(y(),!_?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let h=_.verification_uri_complete||`${_.verification_uri}?code=${_.user_code}`,T=new URL(`${b}/auth`);T.searchParams.set("logout","1"),T.searchParams.set("app","forsion-desktop"),T.searchParams.set("redirect",h);let v=T.toString();g?.({url:v,userCode:String(_.user_code||"")}),t.openExternal(v);let I=Date.now()+(_.expires_in||600)*1e3,E=(_.interval||2)*1e3;for(;Date.now()<I;){await Sf(E,m.signal),y();let D=null;try{D=await fetch(`${b}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:_.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),D.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let x=await D.json().catch(()=>({status:"pending"}));if(y(),x.status==="approved"&&x.token){let L={cloudUrl:b,token:x.token};return await p(L,y),y(),{token:x.token,cloudUrl:b}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===m&&(l=null)}},readAccounts:()=>r()??[]}}function Nt(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,i;try{r=new URL(n),i=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||i.origin!==r.origin||!i.pathname.startsWith("/api/")?null:i.toString()}function ir(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function Ze(t,e,n,r,i=6e4){let s=await(t.fetch??fetch)(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token&&!t.fetch?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(i)}),a=await s.json().catch(()=>({}));return{status:s.status,json:a}}var vf=50*1024*1024,kf=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function Ef(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[i,s]of Object.entries(e.fields)){if(!kf.has(i)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(i))return null;n.append(i,s)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>vf)return null;n.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:`${e.id?`/market/mine/${e.id}/update`:"/market/submit"}${e.dryRun===!0?"?dryRun=1":""}`,body:n}}function Va(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=Ef(n);if(!r)return{status:400,json:{error:"invalid_request"}};let i=await t.getCloud();if(!i.token)return{status:401,error:"not_signed_in"};let s=Nt(i.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let a=await ir(i,s,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,error:String(a?.message||a)}}})}async function bs(t){if(!t.token)return"";try{let e=await Ze(t,"POST","/api/auth/handoff",{},5e3);if(e.status===200&&typeof e.json?.code=="string"&&e.json.code)return`code=${encodeURIComponent(e.json.code)}`;if((e.status===404||e.status===405)&&!t.fetch)return`token=${encodeURIComponent(t.token)}`}catch{}return""}var Ya=["membership","credits","storefront"],Ja=["monthly","quarterly","yearly","autorenew","autorenew-quarterly"],_f=t=>t==="autorenew-quarterly"?"autorenew&cycle=quarterly":t,Cf=/^[A-Za-z0-9_-]{1,64}$/,Af=["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","agent-tool","backpack","other"],Ka=t=>Af.includes(t)?t:void 0,ii=(t,e)=>{let n=Ka(e);return n?{...t,entry:n}:t};function Xa(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(i,s)=>{if(!t.isTrustedSender(i))return n;let a=await t.getCloud(),o=a.base;if(!o)return{ok:!1};let l=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",c=await bs(a),u=`${o}/account${c?`?${c}`:""}${l}`;return a.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(i,...s)=>{if(!t.isTrustedSender(i))return n;let a=s.length>=4,[o,l,c]=s.slice(0,3).map(b=>a&&b===null?void 0:b),u=Ka(s[3]);if(o!==void 0&&!Ya.includes(o))return{ok:!1,error:"invalid_tab"};if(l!==void 0&&(typeof l!="string"||!Cf.test(l)))return{ok:!1,error:"invalid_plan"};if(c!==void 0&&!Ja.includes(c))return{ok:!1,error:"invalid_period"};let f=(o??"membership")==="membership"&&l?`&plan=${encodeURIComponent(l)}${c?`&period=${_f(c)}`:""}`:"",g=await t.getCloud(),p=g.base;if(!p)return{ok:!1};let m=await bs(g),y=`${p}/pay?tab=${o??"membership"}${f}${u?`&from=${u}`:""}${m?`&${m}`:""}&redirect=${encodeURIComponent(`${p}/account`)}`;return g.signal?.throwIfAborted(),await t.openExternal(y),{ok:!0}}),t.handle("auth:resumeAutoRenew",async i=>{if(!t.isTrustedSender(i))return n;let s=await t.getCloud(),a=s.base;if(!a)return{ok:!1};let o=await bs(s);if(!o.startsWith("code="))return{ok:!1,error:"handoff_unavailable"};let l=`${a}/pay?tab=membership&action=resume_autorenew&${o}&redirect=${encodeURIComponent(`${a}/account`)}`;return s.signal?.throwIfAborted(),await t.openExternal(l),{ok:!0}}),t.handle("profile:publicOrigin",async i=>{if(!t.isTrustedSender(i))return n;let{base:s}=await t.getCloud();if(!s)return{ok:!1};try{let a=await fetch(`${s}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});a.body?.cancel().catch(()=>{});let o=a.status>=300&&a.status<400?a.headers.get("location"):null;return o&&/^https?:\/\//i.test(o)?{ok:!0,origin:new URL(o).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async i=>{if(!t.isTrustedSender(i))return e;let s=await r();if(!s.token)return{status:401,json:null};try{return await Ze(s,"GET","/api/token-quota/my",void 0,15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:useResetCard",async(i,...s)=>{if(!t.isTrustedSender(i))return e;let a=await r();if(!a.token)return{status:401,json:null};let o=s[0];if(o!==void 0&&o!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${String(o)}`}};let l=o??"both";try{return await Ze(a,"POST","/api/token-quota/reset-card/use",ii({type:l},s[1]),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(!Number.isInteger(s)||s<1||s>100)return{status:400,json:{error:"invalid_percent"}};try{return await Ze(o,"POST","/api/token-quota/background/convert",ii({percent:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:pointsAutoDeduct",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ze(o,"POST","/api/token-quota/auto-deduct",ii({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgAutoMain",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ze(o,"POST","/api/token-quota/background/auto-main",ii({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("feedback:submit",async(i,s)=>{if(!t.isTrustedSender(i))return n;let a=await t.getCloud();if(!a.base||!a.token)return{ok:!1,error:"not-logged-in"};if(s?.expectedAccountId!==void 0){let u=s.expectedAccountId;if(typeof u!="string"||!u||Ve(a.base,a.token)!==u)return{ok:!1,error:"account-changed"}}let o=(s?.description||"").trim();if(!o)return{ok:!1,error:"empty"};if(o.length>1e4)return{ok:!1,error:"description-too-long"};let l=[],c=!1;if(s?.sessionLogJson){let u=nr(s.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};l.push({filename:s.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:Ba(u)})}try{let u=await ir(a,`${a.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:o,attachments:l}),signal:AbortSignal.timeout(2e4)});if(!u.ok){let g=`HTTP ${u.status}`;try{g=(await u.json())?.detail||g}catch{}return{ok:!1,error:g}}return{ok:!0,id:(await u.json().catch(()=>({})))?.id??null,attachmentSkipped:c}}catch(u){return{ok:!1,error:u?.message||String(u)}}}),t.handle("cloud:fetch",async(i,s)=>{if(!t.isTrustedSender(i))return{status:0,error:"untrusted"};let a=s??{},o=typeof a.path=="string"?a.path:"",l=a.projectSource===void 0?null:a.projectSource;if(l!==null&&(typeof l!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(l)))return{status:0,error:"bad_project_source"};let c=Math.min(12e4,Math.max(1e3,Number(a.timeoutMs)||15e3)),u=typeof a.method=="string"?a.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(u))return{status:0,error:"bad_method"};if(!o.startsWith("/"))return{status:0,error:"bad_path"};let f=await t.getCloud();if(!String(f.base||""))return{status:0,error:"no_cloud_url"};let g=Nt(f.base,o);if(!g)return{status:0,error:"bad_path"};if(!f.token)return{status:401,error:"not_signed_in"};let p=a.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,y=setTimeout(()=>m.abort(),c);try{let b=await ir(f,g,{method:u,headers:{...p?{"Content-Type":"application/json"}:{},...l?{"X-Project-Source":l}:{}},body:p?JSON.stringify(a.body):void 0,signal:m.signal});return{status:b.status,json:await b.json().catch(()=>null)}}catch(b){return{status:0,error:String(b?.message||b)}}finally{clearTimeout(y)}}),Va(t)}import{createHash as vl}from"node:crypto";import{existsSync as Ep,promises as _p,readFileSync as Cp,renameSync as Ap,statSync as xp}from"node:fs";import Tp from"node:path";import{setTimeout as Ip}from"node:timers/promises";import{EventEmitter as tp}from"node:events";import{stat as np}from"node:fs";import{readdir as rp,stat as ip}from"node:fs/promises";import*as fe from"node:path";import{lstat as Za,readdir as xf,realpath as Tf,stat as If}from"node:fs/promises";import{join as Rf,resolve as Df,sep as Qa}from"node:path";import{Readable as Of}from"node:stream";var st={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},vn={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:st.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(vn);var rl="READDIRP_RECURSIVE_ERROR",Mf=new Set(["ENOENT","EPERM","EACCES","ELOOP",rl]),el=[st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE],Nf=new Set([st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE]),Pf=new Set([st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE]),$f=t=>Mf.has(t.code),jf=process.platform==="win32",tl=t=>!0,nl=t=>{if(t===void 0)return tl;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return tl},Ss=class extends Of{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??vn.highWaterMark});let n={...vn,...e},r=n.root??vn.root,i=n.type??vn.type;this._fileFilter=nl(n.fileFilter),this._directoryFilter=nl(n.directoryFilter);let s=n.lstat?Za:If;jf?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:vn.depth,this._wantsDir=Nf.has(i),this._wantsFile=Pf.has(i),this._wantsEverything=i===st.EVERYTHING_TYPE,this._root=Df(r),this._relStart=this._root.endsWith(Qa)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let a={path:this._root,depth:1};a.pending=this._exploreDir(this._root,1),this.parents=[a],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:i,depth:s}=n,a=r.splice(0,e).map(l=>this._formatEntry(l,i)),o=this._isDirent?a:await Promise.all(a);for(let l of o){if(!l)continue;if(this.destroyed)return;let c=this._getEntryType(l);typeof c!="string"&&(c=await c),c==="directory"&&this._directoryFilter(l)?(s<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:s+1}),this._wantsDir&&(this.push(l),e--)):(c==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}let s=i.pending??this._exploreDir(i.path,i.depth),a=this.parents[this.parents.length-1];if(a&&!a.pending&&(a.pending=this._exploreDir(a.path,a.depth)),this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await xf(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,i=Rf(n,r),s={path:i.slice(this._relStart),fullPath:i,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(i).then(a=>(s.stats=a,s),a=>{this._onError(a)})}_onError(e){$f(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await Tf(n),i=await Za(r);if(i.isFile())return"file";if(i.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===Qa){let a=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return a.code=rl,this._onError(a),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function il(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=st.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!el.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${el.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new Ss(r)}import{watch as Lf,unwatchFile as sl,watchFile as Ff}from"node:fs";import{realpath as vs,lstat as Uf,open as Hf,stat as al}from"node:fs/promises";import{type as zf}from"node:os";import*as _e from"node:path";var Bf="data",_s="end",ll="close",ci=()=>{};var ui=process.platform,Cs=ui==="win32",qf=ui==="darwin",Wf=ui==="linux",Gf=ui==="freebsd",cl=zf()==="OS400",Te={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},wt=Te,Vf="watch",Yf={lstat:Uf,stat:al},on="listeners",si="errHandlers",kn="rawEmitters",Jf=[on,si,kn],Kf=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Xf=t=>Kf.has(_e.extname(t).slice(1).toLowerCase()),Es=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},sr=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},Zf=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},or=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ul=t=>t instanceof Set?t.size===0:!t,oi=new Map;function ol(t,e,n,r,i){let s=(a,o)=>{n(t),i(a,o,{watchedPath:t}),o&&t!==o&&ai(_e.resolve(t,o),on,_e.join(t,o))};try{return Lf(t,{persistent:e.persistent},s)}catch(a){r(a);return}}var ai=(t,e,n,r,i)=>{let s=oi.get(t);s&&Es(s[e],a=>{a(n,r,i)})},Qf=(t,e,n,r)=>{let{listener:i,errHandler:s,rawEmitter:a}=r,o=oi.get(e),l;if(!n.persistent)return l=ol(t,n,i,s,a),l?l.close.bind(l):void 0;if(o)sr(o,on,i),sr(o,si,s),sr(o,kn,a);else{if(l=ol(t,n,ai.bind(null,e,on),s,ai.bind(null,e,kn)),!l)return;l.on(wt.ERROR,async c=>{let u=ai.bind(null,e,si);if(o&&(o.watcherUnusable=!0),Cs&&c.code==="EPERM")try{await(await Hf(t,"r")).close(),u(c)}catch{}else u(c)}),o={listeners:i,errHandlers:s,rawEmitters:a,watcher:l},oi.set(e,o)}return()=>{or(o,on,i),or(o,si,s),or(o,kn,a),ul(o.listeners)&&(o.watcher.close(),oi.delete(e),Jf.forEach(Zf(o)),o.watcher=void 0,Object.freeze(o))}},ks=new Map,ep=(t,e,n,r)=>{let{listener:i,rawEmitter:s}=r,a=ks.get(e),o=a&&a.options;return o&&(o.persistent<n.persistent||o.interval>n.interval)&&(sl(e),a=void 0),a?(sr(a,on,i),sr(a,kn,s)):(a={listeners:i,rawEmitters:s,options:n,watcher:Ff(e,n,(l,c)=>{Es(a.rawEmitters,f=>{f(wt.CHANGE,e,{curr:l,prev:c})});let u=l.mtimeMs;(l.size!==c.size||u>c.mtimeMs||u===0)&&Es(a.listeners,f=>f(t,l))})},ks.set(e,a)),()=>{or(a,on,i),or(a,kn,s),ul(a.listeners)&&(ks.delete(e),sl(e),a.options=a.watcher=void 0,Object.freeze(a))}},li=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,i=_e.dirname(e),s=_e.basename(e);this.fsw._getWatchedDir(i).add(s);let o=_e.resolve(e),l={persistent:r.persistent};n||(n=ci);let c;if(r.usePolling){let u=r.interval!==r.binaryInterval;l.interval=u&&Xf(s)?r.binaryInterval:r.interval,c=ep(e,o,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else c=Qf(e,o,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(e,n,r){if(this.fsw.closed)return;let i=_e.dirname(e),s=_e.basename(e),a=this.fsw._getWatchedDir(i),o=n;if(a.has(s))return;let l=async(u,f)=>{if(this.fsw._throttle(Vf,e,5)){if(!f||f.mtimeMs===0)try{let g=await al(e);if(this.fsw.closed)return;let p=g.atimeMs,m=g.mtimeMs;if((!p||p<=m||m!==o.mtimeMs)&&this.fsw._emit(wt.CHANGE,e,g),(qf||Wf||Gf)&&o.ino!==g.ino){this.fsw._closeFile(u),o=g;let y=this._watchWithNodeFs(e,l);y&&this.fsw._addPathCloser(u,y)}else o=g}catch{this.fsw._remove(i,s)}else if(a.has(s)){let g=f.atimeMs,p=f.mtimeMs;(!g||g<=p||p!==o.mtimeMs)&&this.fsw._emit(wt.CHANGE,e,f),o=f}}},c=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(wt.ADD,e,0))return;this.fsw._emit(wt.ADD,e,n)}return c}async _handleSymlink(e,n,r,i){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await vs(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(s)!==o&&(this.fsw._symlinkPaths.set(s,o),this.fsw._emit(wt.CHANGE,r,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(s,o),this.fsw._emit(wt.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,i,s,a,o){e=_e.join(e,"");let l=i?`${e}:${i}`:e;if(o=this.fsw._throttle("readdir",l,1e3),!o)return;let c=this.fsw._getWatchedDir(r.path),u=new Set,f=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(f)return f.on(Bf,async g=>{if(this.fsw.closed){f=void 0;return}let p=g.path,m=_e.join(e,p);if(u.add(p),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,m,p))){if(this.fsw.closed){f=void 0;return}(p===i||!i&&!c.has(p))&&(this.fsw._incrReadyCount(),m=_e.join(s,_e.relative(s,m)),this._addToNodeFs(m,n,r,a+1))}}).on(wt.ERROR,this._boundHandleError),new Promise((g,p)=>{if(!f)return p();f.once(_s,()=>{if(this.fsw.closed){f=void 0;return}let m=o?o.clear():!1;g(void 0),c.getChildren().filter(y=>y!==e&&!u.has(y)).forEach(y=>{this.fsw._remove(e,y)}),f=void 0,m&&this._handleRead(e,!1,r,i,s,a,o)})})}async _handleDir(e,n,r,i,s,a,o){let l=this.fsw._getWatchedDir(_e.dirname(e)),c=l.has(_e.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!c&&this.fsw._emit(wt.ADD_DIR,e,n),l.add(_e.basename(e)),this.fsw._getWatchedDir(e);let u,f,g=this.fsw.options.depth;if((g==null||i<=g)&&!this.fsw._symlinkPaths.has(o)){if(!s&&(await this._handleRead(e,r,a,s,e,i,u),this.fsw.closed))return;f=this._watchWithNodeFs(e,(p,m)=>{m&&m.mtimeMs===0||this._handleRead(p,!1,a,s,e,i,u)})}return f}async _addToNodeFs(e,n,r,i,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);r&&(o.filterPath=l=>r.filterPath(l),o.filterDir=l=>r.filterDir(l));try{let l=await Yf[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,l))return a(),!1;let c=this.fsw.options.followSymlinks,u;if(l.isDirectory()){let f=_e.resolve(e),g=c?await vs(e):e;if(this.fsw.closed||(u=await this._handleDir(o.watchPath,l,n,i,s,o,g),this.fsw.closed))return;f!==g&&g!==void 0&&this.fsw._symlinkPaths.set(f,g)}else if(l.isSymbolicLink()){let f=c?await vs(e):e;if(this.fsw.closed)return;let g=_e.dirname(o.watchPath);if(this.fsw._getWatchedDir(g).add(o.watchPath),this.fsw._emit(wt.ADD,o.watchPath,l),u=await this._handleDir(g,l,n,i,e,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(_e.resolve(e),f)}else u=this._handleFile(o.watchPath,l,n);return a(),u&&this.fsw._addPathCloser(e,u),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var As="/",sp="//",gl=".",op="..",ap="string",lp=/\\/g,ml=/\/\//g,cp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,up=/^\.[/\\]/;function di(t){return Array.isArray(t)?t:[t]}var xs=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function dp(t){return typeof t=="function"?t:typeof t=="string"?e=>t===e:t instanceof RegExp?e=>t.test(e):typeof t=="object"&&t!==null?e=>{if(t.path===e)return!0;if(t.recursive){let n=fe.relative(t.path,e);return n?!n.startsWith("..")&&!fe.isAbsolute(n):!1}return!1}:()=>!1}function fp(t){if(typeof t!="string")throw new Error("string expected");t=fe.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ml,"/"),e&&(t="/"+t),t}function dl(t,e,n){let r=fp(e);for(let i=0;i<t.length;i++){let s=t[i];if(s(r,n))return!0}return!1}function pp(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=di(t).map(i=>dp(i));return e==null?(i,s)=>dl(r,i,s):dl(r,e)}var fl=t=>{let e=di(t).flat();if(!e.every(n=>typeof n===ap))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(yl)},pl=t=>{let e=t.replace(lp,As),n=!1;return e.startsWith(sp)&&(n=!0),e=e.replace(ml,As),n&&(e=As+e),e},yl=t=>pl(fe.normalize(pl(t))),hl=(t="")=>e=>typeof e=="string"?yl(fe.isAbsolute(e)?e:fe.join(t,e)):e,hp=(t,e)=>fe.isAbsolute(t)?t:fe.join(e,t),gp=Object.freeze(new Set),Ts=class{path;_removeWatcher;items;constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==gl&&e!==op&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await rp(r)}catch{this._removeWatcher&&this._removeWatcher(fe.dirname(r),fe.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=ci,this.items=gp,Object.freeze(this)}},mp="stat",yp="lstat",Is=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let i=e;this.path=e=e.replace(up,""),this.watchPath=i,this.fullWatchPath=fe.resolve(i),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?mp:yp}entryPath(e){return fe.join(this.watchPath,fe.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},fi=class extends tp{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?di(e.ignored):di([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};cl&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let l=s.toLowerCase();l==="false"||l==="0"?i.usePolling=!1:l==="true"||l==="1"?i.usePolling=!0:i.usePolling=!!l}let a=process.env.CHOKIDAR_INTERVAL;a&&(i.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=ci,this._readyEmitted=!0,process.nextTick(()=>this.emit(Te.READY)))},this._emitRaw=(...l)=>this.emit(Te.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new li(this),Object.freeze(i)}_addIgnoredPath(e){if(xs(e)){for(let n of this._ignoredPaths)if(xs(n)&&n.path===e.path&&n.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let n of this._ignoredPaths)xs(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let s=fl(e);return i&&(s=s.map(a=>hp(a,i))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!r,void 0,0,n);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(fe.dirname(o),fe.basename(n||o))})}),this}unwatch(e){if(this.closed)return this;let n=fl(e),{cwd:r}=this.options;return n.forEach(i=>{!fe.isAbsolute(i)&&!this._closers.has(i)&&(r&&(i=fe.join(r,i)),i=fe.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let i=r();i instanceof Promise&&e.push(i)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let s=(this.options.cwd?fe.relative(this.options.cwd,r):r)||gl;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==Te.ERROR&&this.emit(Te.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let i=this.options;Cs&&(n=fe.normalize(n)),i.cwd&&(n=fe.relative(i.cwd,n));let s=[n];r!=null&&s.push(r);let a=i.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(n)))return o.lastChange=new Date,this;if(i.atomic){if(e===Te.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((l,c)=>{this.emit(...l),this.emit(Te.ALL,...l),this._pendingUnlinks.delete(c)})},typeof i.atomic=="number"?i.atomic:100),this;e===Te.ADD&&this._pendingUnlinks.has(n)&&(e=Te.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(e===Te.ADD||e===Te.CHANGE)&&this._readyEmitted){let l=(c,u)=>{c?(e=Te.ERROR,s[0]=c,this.emitWithAll(e,s)):u&&(s.length>1?s[1]=u:s.push(u),this.emitWithAll(e,s))};return this._awaitWriteFinish(n,a.stabilityThreshold,e,l),this}if(e===Te.CHANGE&&!this._throttle(Te.CHANGE,n,50))return this;if(i.alwaysStat&&r===void 0&&(e===Te.ADD||e===Te.ADD_DIR||e===Te.CHANGE)){let l=i.cwd?fe.join(i.cwd,n):n,c;try{c=await ip(l)}catch{}if(!c||this.closed)return;s.push(c)}return this.emitWithAll(e,s),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(Te.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let s=i.get(n);if(s)return s.count++,!1;let a,o=()=>{let c=i.get(n),u=c?c.count:0;return i.delete(n),clearTimeout(a),c&&clearTimeout(c.timeoutObject),u};a=setTimeout(o,r);let l={timeoutObject:a,clear:o,count:0};return i.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,i){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,o,l=e;this.options.cwd&&!fe.isAbsolute(e)&&(l=fe.join(this.options.cwd,e));let c=new Date,u=this._pendingWrites;function f(g){np(l,(p,m)=>{if(p||!u.has(e)){p&&p.code!=="ENOENT"&&i(p);return}let y=Number(new Date);g&&m.size!==g.size&&(u.get(e).lastChange=y);let b=u.get(e);y-b.lastChange>=n?(u.delete(e),i(void 0,m)):o=setTimeout(f,a,m)})}u.has(e)||(u.set(e,{lastChange:c,cancelWait:()=>(u.delete(e),clearTimeout(o),r)}),o=setTimeout(f,a))}_isIgnored(e,n){if(this.options.atomic&&cp.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(hl(r)),o=[...[...this._ignoredPaths].map(hl(r)),...s];this._userIgnored=pp(o,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Is(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=fe.resolve(e);return this._watched.has(n)||this._watched.set(n,new Ts(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let i=fe.join(e,n),s=fe.resolve(i);if(r=r??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(i).getChildren().forEach(g=>this._remove(i,g));let l=this._getWatchedDir(e),c=l.has(n);l.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=i;if(this.options.cwd&&(u=fe.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Te.ADD)return;this._watched.delete(i),this._watched.delete(s);let f=r?Te.UNLINK_DIR:Te.UNLINK;c&&!this._isIgnored(i)&&this._emit(f,i),this._closePath(i)}_closePath(e){this._closeFile(e);let n=fe.dirname(e);this._getWatchedDir(n).remove(fe.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:Te.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},i=il(e,r);return this._streams.add(i),i.once(ll,()=>{i=void 0}),i.once(_s,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function Rs(t,e={}){let n=new fi(e);return n.add(t),n}var wl={watch:Rs,FSWatcher:fi};import{execFile as wp}from"node:child_process";import{stat as bl}from"node:fs/promises";import{resolve as bp}from"node:path";import{promisify as Sp}from"node:util";function Vt(t){if(!t||typeof t!="object")return!1;let e=t;return Number.isInteger(e.dev)&&e.dev>=0&&Number.isInteger(e.ino)&&e.ino>0&&(e.birthtimeMs===void 0||Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0)&&(e.volumeId===void 0||typeof e.volumeId=="string"&&e.volumeId.length>0)}function an(t,e){return t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)&&(t.volumeId===void 0?t.dev===e.dev:t.volumeId===e.volumeId)}function bt(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Sl=Sp(wp);function vp(t){let e=t.match(/<key>VolumeUUID<\/key>\s*<string>([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})<\/string>/i)?.[1];return e?`darwin:${e.toLowerCase()}`:void 0}async function kp(t){if(process.platform!=="darwin")return;let{stdout:e}=await Sl("/bin/df",["-P",bp(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
|
|
2
|
-
`).slice(1).map(i=>i.trim().split(/\s+/)[0]).find(i=>/^\/dev\/disk\d+(?:s\d+)*$/.test(i));if(!
|
|
3
|
-
`,"utf8")}catch{}}var
|
|
1
|
+
var ic=null;function Qf(n){ic=n}function Me(){if(!ic)throw new Error("core host not set (call setCoreHost first)");return ic}var eg=new TextEncoder,hv=new TextDecoder("utf-8",{ignoreBOM:!0}),no=n=>eg.encode(n),Yt=n=>hv.decode(n),Ms=n=>typeof n=="string"?eg.encode(n).length:n.length;function tg(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function Ns(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),t=>t.charCodeAt(0))}async function ng(n){let e=new Blob([n]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function rt(n,e){try{let t=new URL(n);if(t.protocol!=="https:"&&t.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let i=r.replace(/-/g,"+").replace(/_/g,"/"),o=Uint8Array.from(atob(i),l=>l.charCodeAt(0)),a=JSON.parse(new TextDecoder().decode(o)),s=a.userId??a.sub;return typeof s!="string"&&typeof s!="number"||!String(s).trim()?null:`${t.origin}${t.pathname.replace(/\/+$/,"")}::${String(s)}`}catch{return null}}function oc(n){try{let e=n.split(".")[1];if(!e)return null;let t=JSON.parse(Yt(Ns(e)));return t&&typeof t=="object"?t:null}catch{return null}}function sc(n,e=Date.now()){let t=oc(n)?.iat;return typeof t=="number"?e-t*1e3:1/0}function rg(n,e=Date.now()){let t=oc(n)?.exp;return typeof t=="number"?t*1e3-e:1/0}var mv=36e5;function $s(n,e=Date.now()){return!!n&&sc(n,e)>=mv}async function Ls(n,e,t=8e3,r){if(!n||!e)return null;let i=n.replace(/\/+$/,"");try{let o=await fetch(`${i}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(t)});if(!o.ok)return null;let a=await o.json().catch(()=>null),s=typeof a?.token=="string"?a.token:"";return s&&s!==e?s:null}catch{return null}}var ro=(n,e)=>`${n.replace(/\/+$/,"")}\0${e}`,yv=(n,e)=>new Promise((t,r)=>{let i=()=>{clearTimeout(o),r(new Error("Sign-in cancelled."))},o=setTimeout(()=>{e.removeEventListener("abort",i),t()},n);e.aborted?i():e.addEventListener("abort",i,{once:!0})});function ig(n,e){let t=d=>e.write(JSON.stringify(d,null,2)),r=()=>{let d;try{d=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(d===null)return[];try{let g=JSON.parse(d);return Array.isArray(g.accounts)?g.accounts.filter(f=>f&&typeof f.token=="string"&&f.id===rt(f.cloudUrl,f.token)):null}catch{return null}},i=(d,g)=>{let f=rt(d.cloudUrl||"",d.token||"");if(!f||!d.token||!d.cloudUrl)return;let p=r();if(!p)return;let m=p.find(h=>h.id===f),y=oc(d.token),b={...m,id:f,cloudUrl:d.cloudUrl.replace(/\/+$/,""),token:d.token,username:g?.username||m?.username||y?.username,nickname:g?.nickname||m?.nickname};JSON.stringify(m)!==JSON.stringify(b)&&t({version:1,accounts:[...p.filter(h=>h.id!==f),b]})},o=()=>{let d=n.readCreds();i(d);let g=rt(d.cloudUrl,d.token);return(r()??[]).map(({token:f,...p})=>({...p,active:p.id===g}))},a=d=>{let g=r()?.find(f=>f.id===d);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},s=d=>{let g=rt(d.cloudUrl||"",d.token||""),f=r();g&&f&&t({version:1,accounts:f.filter(p=>p.id!==g)})},l=null;return{rememberForsionAccount:i,forsionAccounts:o,savedForsionAccount:a,forgetForsionAccount:s,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(d,g,f)=>{if(l)throw new Error("A sign-in is already in progress.");if(!d)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let p=new AbortController;l=p;let m=()=>{if(p.signal.aborted||l!==p)throw new Error("Sign-in cancelled.")};try{let y=d.replace(/\/+$/,""),b;try{b=await fetch(`${y}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([p.signal,AbortSignal.timeout(15e3)])}).then(S=>S.json())}catch(S){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${y}:${S?.message||S}`)}if(m(),!b?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let h=b.verification_uri_complete||`${b.verification_uri}?code=${b.user_code}`,E=new URL(`${y}/auth`);E.searchParams.set("logout","1"),E.searchParams.set("app","forsion-desktop"),E.searchParams.set("redirect",h);let v=E.toString();g?.({url:v,userCode:String(b.user_code||"")}),n.openExternal(v);let k=Date.now()+(b.expires_in||600)*1e3,C=(b.interval||2)*1e3;for(;Date.now()<k;){await yv(C,p.signal),m();let S=null;try{S=await fetch(`${y}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:b.device_code}),signal:AbortSignal.any([p.signal,AbortSignal.timeout(15e3)])})}catch{m();continue}if(m(),S.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let _=await S.json().catch(()=>({status:"pending"}));if(m(),_.status==="approved"&&_.token){let R={cloudUrl:y,token:_.token};return await f(R,m),m(),{token:_.token,cloudUrl:y}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===p&&(l=null)}},readAccounts:()=>r()??[]}}function Tt(n,e){if(typeof e!="string"||!e.startsWith("/"))return null;let t=String(n||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!t)return null;let r,i;try{r=new URL(t),i=new URL(t+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||i.origin!==r.origin||!i.pathname.startsWith("/api/")?null:i.toString()}function io(n,e,t){return n.fetch?n.fetch(e,t):fetch(e,{...t,headers:{Authorization:`Bearer ${n.token}`,...t.headers}})}async function Rt(n,e,t,r,i=6e4){let o=await(n.fetch??fetch)(n.base+t,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...n.token&&!n.fetch?{Authorization:`Bearer ${n.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(i)}),a=await o.json().catch(()=>({}));return{status:o.status,json:a}}var wv=50*1024*1024,bv=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function vv(n){if(!n||typeof n!="object")return null;let e=n;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let t=new FormData,r=0;for(let[i,o]of Object.entries(e.fields)){if(!bv.has(i)||typeof o!="string"||(r+=o.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(i))return null;t.append(i,o)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>wv)return null;t.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:`${e.id?`/market/mine/${e.id}/update`:"/market/submit"}${e.dryRun===!0?"?dryRun=1":""}`,body:t}}function og(n){n.handle("cloud:marketSubmit",async(e,t)=>{if(!n.isTrustedSender(e))return{status:0,error:"untrusted"};let r=vv(t);if(!r)return{status:400,json:{error:"invalid_request"}};let i=await n.getCloud();if(!i.token)return{status:401,error:"not_signed_in"};let o=Tt(i.base,r.path);if(!o)return{status:0,error:"no_cloud_url"};try{let a=await io(i,o,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,error:String(a?.message||a)}}})}async function ac(n){if(!n.token)return"";try{let e=await Rt(n,"POST","/api/auth/handoff",{},5e3);if(e.status===200&&typeof e.json?.code=="string"&&e.json.code)return`code=${encodeURIComponent(e.json.code)}`;if((e.status===404||e.status===405)&&!n.fetch)return`token=${encodeURIComponent(n.token)}`}catch{}return""}var sg=["membership","credits","storefront"],ag=["monthly","quarterly","yearly","autorenew","autorenew-quarterly","autorenew-yearly"],Sv=n=>n==="autorenew-quarterly"||n==="autorenew-yearly"?`autorenew&cycle=${n.slice(10)}`:n,kv=/^[A-Za-z0-9_-]{1,64}$/,Ev=["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","agent-tool","backpack","other"],lg=n=>Ev.includes(n)?n:void 0,Fs=(n,e)=>{let t=lg(e);return t?{...n,entry:t}:n};function cg(n){let e={status:0,error:"untrusted"},t={ok:!1,error:"untrusted"};n.handle("auth:openAccountCenter",async(o,a)=>{if(!n.isTrustedSender(o))return t;let s=await n.getCloud(),l=s.base;if(!l)return{ok:!1};let c=a&&/^[a-z0-9-]+$/i.test(a)?`#${a}`:"",u=await ac(s),d=`${l}/account${u?`?${u}`:""}${c}`;return s.signal?.throwIfAborted(),await n.openExternal(d),{ok:!0}}),n.handle("auth:openPayCenter",async(o,...a)=>{if(!n.isTrustedSender(o))return t;let s=a.length>=4,[l,c,u]=a.slice(0,3).map(b=>s&&b===null?void 0:b),d=lg(a[3]);if(l!==void 0&&!sg.includes(l))return{ok:!1,error:"invalid_tab"};if(c!==void 0&&(typeof c!="string"||!kv.test(c)))return{ok:!1,error:"invalid_plan"};if(u!==void 0&&!ag.includes(u))return{ok:!1,error:"invalid_period"};let g=(l??"membership")==="membership"&&c?`&plan=${encodeURIComponent(c)}${u?`&period=${Sv(u)}`:""}`:"",f=await n.getCloud(),p=f.base;if(!p)return{ok:!1};let m=await ac(f),y=`${p}/pay?tab=${l??"membership"}${g}${d?`&from=${d}`:""}${m?`&${m}`:""}&redirect=${encodeURIComponent(`${p}/account`)}`;return f.signal?.throwIfAborted(),await n.openExternal(y),{ok:!0}}),n.handle("auth:resumeAutoRenew",async o=>{if(!n.isTrustedSender(o))return t;let a=await n.getCloud(),s=a.base;if(!s)return{ok:!1};let l=await ac(a);if(!l.startsWith("code="))return{ok:!1,error:"handoff_unavailable"};let c=`${s}/pay?tab=membership&action=resume_autorenew&${l}&redirect=${encodeURIComponent(`${s}/account`)}`;return a.signal?.throwIfAborted(),await n.openExternal(c),{ok:!0}}),n.handle("profile:publicOrigin",async o=>{if(!n.isTrustedSender(o))return t;let{base:a}=await n.getCloud();if(!a)return{ok:!1};try{let s=await fetch(`${a}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});s.body?.cancel().catch(()=>{});let l=s.status>=300&&s.status<400?s.headers.get("location"):null;return l&&/^https?:\/\//i.test(l)?{ok:!0,origin:new URL(l).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>n.getCloud();n.handle("account:quota",async o=>{if(!n.isTrustedSender(o))return e;let a=await r();if(!a.token)return{status:401,json:null};try{return await Rt(a,"GET","/api/token-quota/my",void 0,15e3)}catch(s){return{status:0,json:{detail:String(s?.message||s)}}}}),n.handle("account:useResetCard",async(o,...a)=>{if(!n.isTrustedSender(o))return e;let s=await r();if(!s.token)return{status:401,json:null};let l=a[0];if(l!==void 0&&l!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${String(l)}`}};let c=l??"both";try{return await Rt(s,"POST","/api/token-quota/reset-card/use",Fs({type:c},a[1]),15e3)}catch(u){return{status:0,json:{detail:String(u?.message||u)}}}}),n.handle("account:bgConvert",async(o,a,s)=>{if(!n.isTrustedSender(o))return e;let l=await r();if(!l.token)return{status:401,json:null};if(!Number.isInteger(a)||a<1||a>100)return{status:400,json:{error:"invalid_percent"}};try{return await Rt(l,"POST","/api/token-quota/background/convert",Fs({percent:a},s),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),n.handle("account:pointsAutoDeduct",async(o,a,s)=>{if(!n.isTrustedSender(o))return e;let l=await r();if(!l.token)return{status:401,json:null};if(typeof a!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Rt(l,"POST","/api/token-quota/auto-deduct",Fs({enabled:a},s),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),n.handle("account:bgAutoMain",async(o,a,s)=>{if(!n.isTrustedSender(o))return e;let l=await r();if(!l.token)return{status:401,json:null};if(typeof a!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Rt(l,"POST","/api/token-quota/background/auto-main",Fs({enabled:a},s),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),n.handle("feedback:submit",async(o,a)=>{if(!n.isTrustedSender(o))return t;let s=await n.getCloud();if(!s.base||!s.token)return{ok:!1,error:"not-logged-in"};if(a?.expectedAccountId!==void 0){let d=a.expectedAccountId;if(typeof d!="string"||!d||rt(s.base,s.token)!==d)return{ok:!1,error:"account-changed"}}let l=(a?.description||"").trim();if(!l)return{ok:!1,error:"empty"};if(l.length>1e4)return{ok:!1,error:"description-too-long"};let c=[],u=!1;if(a?.sessionLogJson){let d=no(a.sessionLogJson);if(d.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};c.push({filename:a.sessionLogName||"tangu-session.json",mime_type:"application/json",size:d.length,data_base64:tg(d)})}try{let d=await io(s,`${s.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,attachments:c}),signal:AbortSignal.timeout(2e4)});if(!d.ok){let f=`HTTP ${d.status}`;try{f=(await d.json())?.detail||f}catch{}return{ok:!1,error:f}}return{ok:!0,id:(await d.json().catch(()=>({})))?.id??null,attachmentSkipped:u}}catch(d){return{ok:!1,error:d?.message||String(d)}}});let i=new Set(["vaults","vault-moves"]);n.handle("cloud:fetch",async(o,a)=>{if(!n.isTrustedSender(o))return{status:0,error:"untrusted"};let s=a??{},l=typeof s.path=="string"?s.path:"",c=s.projectSource===void 0?null:s.projectSource;if(c!==null&&(typeof c!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(c)))return{status:0,error:"bad_project_source"};let u=Object.prototype.hasOwnProperty.call(s,"contentCaps");if(u&&!i.has(s.contentCaps))return{status:0,error:"bad_content_caps"};let d=u?s.contentCaps:null,g=Math.min(12e4,Math.max(1e3,Number(s.timeoutMs)||15e3)),f=typeof s.method=="string"?s.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(f))return{status:0,error:"bad_method"};if(!l.startsWith("/"))return{status:0,error:"bad_path"};let p=await n.getCloud();if(!String(p.base||""))return{status:0,error:"no_cloud_url"};let m=Tt(p.base,l);if(!m)return{status:0,error:"bad_path"};if(!p.token)return{status:401,error:"not_signed_in"};let y=s.body!==void 0&&f!=="GET"&&f!=="DELETE",b=new AbortController,h=setTimeout(()=>b.abort(),g);try{let E=await io(p,m,{method:f,headers:{...y?{"Content-Type":"application/json"}:{},...c?{"X-Project-Source":c}:{},...d?{"X-Content-Caps":d}:{}},body:y?JSON.stringify(s.body):void 0,signal:b.signal});return{status:E.status,json:await E.json().catch(()=>null)}}catch(E){return{status:0,error:String(E?.message||E)}}finally{clearTimeout(h)}}),og(n)}import{createHash as Og}from"node:crypto";import{existsSync as vS,promises as SS,readFileSync as kS,renameSync as ES,statSync as _S}from"node:fs";import RS from"node:path";import{setTimeout as AS}from"node:timers/promises";import{EventEmitter as Zv}from"node:events";import{stat as Qv}from"node:fs";import{readdir as eS,stat as tS}from"node:fs/promises";import*as Se from"node:path";import{lstat as dg,readdir as _v,realpath as Rv,stat as Av}from"node:fs/promises";import{join as Cv,resolve as Iv,sep as ug}from"node:path";import{Readable as xv}from"node:stream";var Ft={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},ti={root:".",fileFilter:n=>!0,directoryFilter:n=>!0,type:Ft.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(ti);var hg="READDIRP_RECURSIVE_ERROR",Tv=new Set(["ENOENT","EPERM","EACCES","ELOOP",hg]),fg=[Ft.DIR_TYPE,Ft.EVERYTHING_TYPE,Ft.FILE_DIR_TYPE,Ft.FILE_TYPE],Dv=new Set([Ft.DIR_TYPE,Ft.EVERYTHING_TYPE,Ft.FILE_DIR_TYPE]),Pv=new Set([Ft.EVERYTHING_TYPE,Ft.FILE_DIR_TYPE,Ft.FILE_TYPE]),Ov=n=>Tv.has(n.code),Mv=process.platform==="win32",gg=n=>!0,pg=n=>{if(n===void 0)return gg;if(typeof n=="function")return n;if(typeof n=="string"){let e=n.trim();return t=>t.basename===e}if(Array.isArray(n)){let e=n.map(t=>t.trim());return t=>e.some(r=>t.basename===r)}return gg},lc=class extends xv{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??ti.highWaterMark});let t={...ti,...e},r=t.root??ti.root,i=t.type??ti.type;this._fileFilter=pg(t.fileFilter),this._directoryFilter=pg(t.directoryFilter);let o=t.lstat?dg:Av;Mv?this._stat=s=>o(s,{bigint:!0}):this._stat=o,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:ti.depth,this._wantsDir=Dv.has(i),this._wantsFile=Pv.has(i),this._wantsEverything=i===Ft.EVERYTHING_TYPE,this._root=Iv(r),this._relStart=this._root.endsWith(ug)?this._root.length:this._root.length+1,this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let a={path:this._root,depth:1};a.pending=this._exploreDir(this._root,1),this.parents=[a],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,r=t&&t.files;if(r&&r.length>0){let{path:i,depth:o}=t,a=r.splice(0,e).map(l=>this._formatEntry(l,i)),s=this._isDirent?a:await Promise.all(a);for(let l of s){if(!l)continue;if(this.destroyed)return;let c=this._getEntryType(l);typeof c!="string"&&(c=await c),c==="directory"&&this._directoryFilter(l)?(o<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:o+1}),this._wantsDir&&(this.push(l),e--)):(c==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}let o=i.pending??this._exploreDir(i.path,i.depth),a=this.parents[this.parents.length-1];if(a&&!a.pending&&(a.pending=this._exploreDir(a.path,a.depth)),this.parent=await o,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let r;try{r=await _v(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:t,path:e}}_formatEntry(e,t){let r=this._isDirent?e.name:e,i=Cv(t,r),o={path:i.slice(this._relStart),fullPath:i,basename:r};return this._isDirent?(o.dirent=e,o):this._stat(i).then(a=>(o.stats=a,o),a=>{this._onError(a)})}_onError(e){Ov(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let t=e[this._statsProp];return t.isFile()?"file":t.isDirectory()?"directory":t.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let t=e.fullPath;try{let r=await Rv(t),i=await dg(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(t.startsWith(r)&&t[o]===ug){let a=new Error(`Circular symlink detected: "${t}" points to "${r}"`);return a.code=hg,this._onError(a),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function mg(n,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Ft.FILE_DIR_TYPE),n){if(typeof n!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!fg.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${fg.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:n};return t&&(r.type=t),new lc(r)}import{watch as Nv,unwatchFile as yg,watchFile as $v}from"node:fs";import{realpath as cc,lstat as Lv,open as Fv,stat as bg}from"node:fs/promises";import{type as Bv}from"node:os";import*as qe from"node:path";var jv="data",fc="end",vg="close",zs=()=>{};var Hs=process.platform,gc=Hs==="win32",Uv=Hs==="darwin",Vv=Hs==="linux",zv=Hs==="freebsd",Sg=Bv()==="OS400",Je={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},pn=Je,Hv="watch",qv={lstat:Lv,stat:bg},Pr="listeners",Bs="errHandlers",ni="rawEmitters",Wv=[Pr,Bs,ni],Gv=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Jv=n=>Gv.has(qe.extname(n).slice(1).toLowerCase()),uc=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},oo=(n,e,t)=>{let r=n[e];r instanceof Set||(n[e]=r=new Set([r])),r.add(t)},Kv=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},so=(n,e,t)=>{let r=n[e];r instanceof Set?r.delete(t):r===t&&delete n[e]},kg=n=>n instanceof Set?n.size===0:!n,js=new Map;function wg(n,e,t,r,i){let o=(a,s)=>{t(n),i(a,s,{watchedPath:n}),s&&n!==s&&Us(qe.resolve(n,s),Pr,qe.join(n,s))};try{return Nv(n,{persistent:e.persistent},o)}catch(a){r(a);return}}var Us=(n,e,t,r,i)=>{let o=js.get(n);o&&uc(o[e],a=>{a(t,r,i)})},Yv=(n,e,t,r)=>{let{listener:i,errHandler:o,rawEmitter:a}=r,s=js.get(e),l;if(!t.persistent)return l=wg(n,t,i,o,a),l?l.close.bind(l):void 0;if(s)oo(s,Pr,i),oo(s,Bs,o),oo(s,ni,a);else{if(l=wg(n,t,Us.bind(null,e,Pr),o,Us.bind(null,e,ni)),!l)return;l.on(pn.ERROR,async c=>{let u=Us.bind(null,e,Bs);if(s&&(s.watcherUnusable=!0),gc&&c.code==="EPERM")try{await(await Fv(n,"r")).close(),u(c)}catch{}else u(c)}),s={listeners:i,errHandlers:o,rawEmitters:a,watcher:l},js.set(e,s)}return()=>{so(s,Pr,i),so(s,Bs,o),so(s,ni,a),kg(s.listeners)&&(s.watcher.close(),js.delete(e),Wv.forEach(Kv(s)),s.watcher=void 0,Object.freeze(s))}},dc=new Map,Xv=(n,e,t,r)=>{let{listener:i,rawEmitter:o}=r,a=dc.get(e),s=a&&a.options;return s&&(s.persistent<t.persistent||s.interval>t.interval)&&(yg(e),a=void 0),a?(oo(a,Pr,i),oo(a,ni,o)):(a={listeners:i,rawEmitters:o,options:t,watcher:$v(e,t,(l,c)=>{uc(a.rawEmitters,d=>{d(pn.CHANGE,e,{curr:l,prev:c})});let u=l.mtimeMs;(l.size!==c.size||u>c.mtimeMs||u===0)&&uc(a.listeners,d=>d(n,l))})},dc.set(e,a)),()=>{so(a,Pr,i),so(a,ni,o),kg(a.listeners)&&(dc.delete(e),yg(e),a.options=a.watcher=void 0,Object.freeze(a))}},Vs=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let r=this.fsw.options,i=qe.dirname(e),o=qe.basename(e);this.fsw._getWatchedDir(i).add(o);let s=qe.resolve(e),l={persistent:r.persistent};t||(t=zs);let c;if(r.usePolling){let u=r.interval!==r.binaryInterval;l.interval=u&&Jv(o)?r.binaryInterval:r.interval,c=Xv(e,s,l,{listener:t,rawEmitter:this.fsw._emitRaw})}else c=Yv(e,s,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(e,t,r){if(this.fsw.closed)return;let i=qe.dirname(e),o=qe.basename(e),a=this.fsw._getWatchedDir(i),s=t;if(a.has(o))return;let l=async(u,d)=>{if(this.fsw._throttle(Hv,e,5)){if(!d||d.mtimeMs===0)try{let g=await bg(e);if(this.fsw.closed)return;let f=g.atimeMs,p=g.mtimeMs;if((!f||f<=p||p!==s.mtimeMs)&&this.fsw._emit(pn.CHANGE,e,g),(Uv||Vv||zv)&&s.ino!==g.ino){this.fsw._closeFile(u),s=g;let m=this._watchWithNodeFs(e,l);m&&this.fsw._addPathCloser(u,m)}else s=g}catch{this.fsw._remove(i,o)}else if(a.has(o)){let g=d.atimeMs,f=d.mtimeMs;(!g||g<=f||f!==s.mtimeMs)&&this.fsw._emit(pn.CHANGE,e,d),s=d}}},c=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(pn.ADD,e,0))return;this.fsw._emit(pn.ADD,e,t)}return c}async _handleSymlink(e,t,r,i){if(this.fsw.closed)return;let o=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let s;try{s=await cc(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(o)!==s&&(this.fsw._symlinkPaths.set(o,s),this.fsw._emit(pn.CHANGE,r,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(o,s),this.fsw._emit(pn.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(o))return!0;this.fsw._symlinkPaths.set(o,!0)}_handleRead(e,t,r,i,o,a,s){e=qe.join(e,"");let l=i?`${e}:${i}`:e;if(s=this.fsw._throttle("readdir",l,1e3),!s)return;let c=this.fsw._getWatchedDir(r.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(d)return d.on(jv,async g=>{if(this.fsw.closed){d=void 0;return}let f=g.path,p=qe.join(e,f);if(u.add(f),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,p,f))){if(this.fsw.closed){d=void 0;return}(f===i||!i&&!c.has(f))&&(this.fsw._incrReadyCount(),p=qe.join(o,qe.relative(o,p)),this._addToNodeFs(p,t,r,a+1))}}).on(pn.ERROR,this._boundHandleError),new Promise((g,f)=>{if(!d)return f();d.once(fc,()=>{if(this.fsw.closed){d=void 0;return}let p=s?s.clear():!1;g(void 0),c.getChildren().filter(m=>m!==e&&!u.has(m)).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,p&&this._handleRead(e,!1,r,i,o,a,s)})})}async _handleDir(e,t,r,i,o,a,s){let l=this.fsw._getWatchedDir(qe.dirname(e)),c=l.has(qe.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!o&&!c&&this.fsw._emit(pn.ADD_DIR,e,t),l.add(qe.basename(e)),this.fsw._getWatchedDir(e);let u,d,g=this.fsw.options.depth;if((g==null||i<=g)&&!this.fsw._symlinkPaths.has(s)){if(!o&&(await this._handleRead(e,r,a,o,e,i,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(f,p)=>{p&&p.mtimeMs===0||this._handleRead(f,!1,a,o,e,i,u)})}return d}async _addToNodeFs(e,t,r,i,o){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let s=this.fsw._getWatchHelpers(e);r&&(s.filterPath=l=>r.filterPath(l),s.filterDir=l=>r.filterDir(l));try{let l=await qv[s.statMethod](s.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(s.watchPath,l))return a(),!1;let c=this.fsw.options.followSymlinks,u;if(l.isDirectory()){let d=qe.resolve(e),g=c?await cc(e):e;if(this.fsw.closed||(u=await this._handleDir(s.watchPath,l,t,i,o,s,g),this.fsw.closed))return;d!==g&&g!==void 0&&this.fsw._symlinkPaths.set(d,g)}else if(l.isSymbolicLink()){let d=c?await cc(e):e;if(this.fsw.closed)return;let g=qe.dirname(s.watchPath);if(this.fsw._getWatchedDir(g).add(s.watchPath),this.fsw._emit(pn.ADD,s.watchPath,l),u=await this._handleDir(g,l,t,i,e,s,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(qe.resolve(e),d)}else u=this._handleFile(s.watchPath,l,t);return a(),u&&this.fsw._addPathCloser(e,u),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var pc="/",nS="//",Cg=".",rS="..",iS="string",oS=/\\/g,Ig=/\/\//g,sS=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,aS=/^\.[/\\]/;function qs(n){return Array.isArray(n)?n:[n]}var hc=n=>typeof n=="object"&&n!==null&&!(n instanceof RegExp);function lS(n){return typeof n=="function"?n:typeof n=="string"?e=>n===e:n instanceof RegExp?e=>n.test(e):typeof n=="object"&&n!==null?e=>{if(n.path===e)return!0;if(n.recursive){let t=Se.relative(n.path,e);return t?!t.startsWith("..")&&!Se.isAbsolute(t):!1}return!1}:()=>!1}function cS(n){if(typeof n!="string")throw new Error("string expected");n=Se.normalize(n),n=n.replace(/\\/g,"/");let e=!1;return n.startsWith("//")&&(e=!0),n=n.replace(Ig,"/"),e&&(n="/"+n),n}function Eg(n,e,t){let r=cS(e);for(let i=0;i<n.length;i++){let o=n[i];if(o(r,t))return!0}return!1}function dS(n,e){if(n==null)throw new TypeError("anymatch: specify first argument");let r=qs(n).map(i=>lS(i));return e==null?(i,o)=>Eg(r,i,o):Eg(r,e)}var _g=n=>{let e=qs(n).flat();if(!e.every(t=>typeof t===iS))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(xg)},Rg=n=>{let e=n.replace(oS,pc),t=!1;return e.startsWith(nS)&&(t=!0),e=e.replace(Ig,pc),t&&(e=pc+e),e},xg=n=>Rg(Se.normalize(Rg(n))),Ag=(n="")=>e=>typeof e=="string"?xg(Se.isAbsolute(e)?e:Se.join(n,e)):e,uS=(n,e)=>Se.isAbsolute(n)?n:Se.join(e,n),fS=Object.freeze(new Set),mc=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Cg&&e!==rS&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let r=this.path;try{await eS(r)}catch{this._removeWatcher&&this._removeWatcher(Se.dirname(r),Se.basename(r))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=zs,this.items=fS,Object.freeze(this)}},gS="stat",pS="lstat",yc=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,r){this.fsw=r;let i=e;this.path=e=e.replace(aS,""),this.watchPath=i,this.fullWatchPath=Se.resolve(i),this.dirParts=[],this.dirParts.forEach(o=>{o.length>1&&o.pop()}),this.followSymlinks=t,this.statMethod=t?gS:pS}entryPath(e){return Se.join(this.watchPath,Se.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Ws=class extends Zv{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?qs(e.ignored):qs([]),awaitWriteFinish:t===!0?r:typeof t=="object"?{...r,...t}:!1};Sg&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let o=process.env.CHOKIDAR_USEPOLLING;if(o!==void 0){let l=o.toLowerCase();l==="false"||l==="0"?i.usePolling=!1:l==="true"||l==="1"?i.usePolling=!0:i.usePolling=!!l}let a=process.env.CHOKIDAR_INTERVAL;a&&(i.interval=Number.parseInt(a,10));let s=0;this._emitReady=()=>{s++,s>=this._readyCount&&(this._emitReady=zs,this._readyEmitted=!0,process.nextTick(()=>this.emit(Je.READY)))},this._emitRaw=(...l)=>this.emit(Je.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new Vs(this),Object.freeze(i)}_addIgnoredPath(e){if(hc(e)){for(let t of this._ignoredPaths)if(hc(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)hc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,r){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let o=_g(e);return i&&(o=o.map(a=>uS(a,i))),o.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let s=await this._nodeFsHandler._addToNodeFs(a,!r,void 0,0,t);return s&&this._emitReady(),s})).then(a=>{this.closed||a.forEach(s=>{s&&this.add(Se.dirname(s),Se.basename(t||s))})}),this}unwatch(e){if(this.closed)return this;let t=_g(e),{cwd:r}=this.options;return t.forEach(i=>{!Se.isAbsolute(i)&&!this._closers.has(i)&&(r&&(i=Se.join(r,i)),i=Se.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(r=>{let i=r();i instanceof Promise&&e.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,r)=>{let o=(this.options.cwd?Se.relative(this.options.cwd,r):r)||Cg;e[o]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Je.ERROR&&this.emit(Je.ALL,e,...t)}async _emit(e,t,r){if(this.closed)return;let i=this.options;gc&&(t=Se.normalize(t)),i.cwd&&(t=Se.relative(i.cwd,t));let o=[t];r!=null&&o.push(r);let a=i.awaitWriteFinish,s;if(a&&(s=this._pendingWrites.get(t)))return s.lastChange=new Date,this;if(i.atomic){if(e===Je.UNLINK)return this._pendingUnlinks.set(t,[e,...o]),setTimeout(()=>{this._pendingUnlinks.forEach((l,c)=>{this.emit(...l),this.emit(Je.ALL,...l),this._pendingUnlinks.delete(c)})},typeof i.atomic=="number"?i.atomic:100),this;e===Je.ADD&&this._pendingUnlinks.has(t)&&(e=Je.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Je.ADD||e===Je.CHANGE)&&this._readyEmitted){let l=(c,u)=>{c?(e=Je.ERROR,o[0]=c,this.emitWithAll(e,o)):u&&(o.length>1?o[1]=u:o.push(u),this.emitWithAll(e,o))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,l),this}if(e===Je.CHANGE&&!this._throttle(Je.CHANGE,t,50))return this;if(i.alwaysStat&&r===void 0&&(e===Je.ADD||e===Je.ADD_DIR||e===Je.CHANGE)){let l=i.cwd?Se.join(i.cwd,t):t,c;try{c=await tS(l)}catch{}if(!c||this.closed)return;o.push(c)}return this.emitWithAll(e,o),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Je.ERROR,e),e||this.closed}_throttle(e,t,r){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let o=i.get(t);if(o)return o.count++,!1;let a,s=()=>{let c=i.get(t),u=c?c.count:0;return i.delete(t),clearTimeout(a),c&&clearTimeout(c.timeoutObject),u};a=setTimeout(s,r);let l={timeoutObject:a,clear:s,count:0};return i.set(t,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,r,i){let o=this.options.awaitWriteFinish;if(typeof o!="object")return;let a=o.pollInterval,s,l=e;this.options.cwd&&!Se.isAbsolute(e)&&(l=Se.join(this.options.cwd,e));let c=new Date,u=this._pendingWrites;function d(g){Qv(l,(f,p)=>{if(f||!u.has(e)){f&&f.code!=="ENOENT"&&i(f);return}let m=Number(new Date);g&&p.size!==g.size&&(u.get(e).lastChange=m);let y=u.get(e);m-y.lastChange>=t?(u.delete(e),i(void 0,p)):s=setTimeout(d,a,p)})}u.has(e)||(u.set(e,{lastChange:c,cancelWait:()=>(u.delete(e),clearTimeout(s),r)}),s=setTimeout(d,a))}_isIgnored(e,t){if(this.options.atomic&&sS.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,o=(this.options.ignored||[]).map(Ag(r)),s=[...[...this._ignoredPaths].map(Ag(r)),...o];this._userIgnored=dS(s,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new yc(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Se.resolve(e);return this._watched.has(t)||this._watched.set(t,new mc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,r){let i=Se.join(e,t),o=Se.resolve(i);if(r=r??(this._watched.has(i)||this._watched.has(o)),!this._throttle("remove",i,100))return;!r&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(i).getChildren().forEach(g=>this._remove(i,g));let l=this._getWatchedDir(e),c=l.has(t);l.remove(t),this._symlinkPaths.has(o)&&this._symlinkPaths.delete(o);let u=i;if(this.options.cwd&&(u=Se.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Je.ADD)return;this._watched.delete(i),this._watched.delete(o);let d=r?Je.UNLINK_DIR:Je.UNLINK;c&&!this._isIgnored(i)&&this._emit(d,i),this._closePath(i)}_closePath(e){this._closeFile(e);let t=Se.dirname(e);this._getWatchedDir(t).remove(Se.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(t)}_readdirp(e,t){if(this.closed)return;let r={type:Je.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},i=mg(e,r);return this._streams.add(i),i.once(vg,()=>{i=void 0}),i.once(fc,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function wc(n,e={}){let t=new Ws(e);return t.add(n),t}var Tg={watch:wc,FSWatcher:Ws};import{execFile as hS}from"node:child_process";import{stat as Dg}from"node:fs/promises";import{resolve as mS}from"node:path";import{promisify as yS}from"node:util";function Bt(n){if(!n||typeof n!="object")return!1;let e=n;return Number.isInteger(e.dev)&&e.dev>=0&&Number.isInteger(e.ino)&&e.ino>0&&(e.birthtimeMs===void 0||Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0)&&(e.volumeId===void 0||typeof e.volumeId=="string"&&e.volumeId.length>0)}function Dt(n,e){return n.ino===e.ino&&(n.birthtimeMs===void 0||n.birthtimeMs===e.birthtimeMs)&&(n.volumeId===void 0?n.dev===e.dev:n.volumeId===e.volumeId)}function hn(n,e){return n.dev===e.dev&&n.ino===e.ino&&(n.birthtimeMs===void 0||n.birthtimeMs===e.birthtimeMs)}var Pg=yS(hS);function wS(n){let e=n.match(/<key>VolumeUUID<\/key>\s*<string>([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})<\/string>/i)?.[1];return e?`darwin:${e.toLowerCase()}`:void 0}async function bS(n){if(process.platform!=="darwin")return;let{stdout:e}=await Pg("/bin/df",["-P",mS(n)],{timeout:5e3,maxBuffer:256*1024}),t=e.split(`
|
|
2
|
+
`).slice(1).map(i=>i.trim().split(/\s+/)[0]).find(i=>/^\/dev\/disk\d+(?:s\d+)*$/.test(i));if(!t)return;let{stdout:r}=await Pg("/usr/sbin/diskutil",["info","-plist",t],{timeout:5e3,maxBuffer:256*1024});return wS(r)}async function dt(n,e=bS,t=process.platform){let r=await Dg(n);if(!r.isDirectory())throw Error("Sync root is not a directory");let i={dev:r.dev,ino:r.ino,...(t==="darwin"||t==="win32")&&r.birthtimeMs>0?{birthtimeMs:r.birthtimeMs}:{}},o=await e(n),a=await Dg(n);if(!a.isDirectory()||!hn(i,a))throw Error("Sync root changed while reading its identity");return{...i,...o?{volumeId:o}:{}}}var bc;function Mg(n){bc=n}var Ng={fs:SS,path:RS,directoryIdentity:dt,sha256Hex:n=>Og("sha256").update(n).digest("hex"),tmpTag:()=>process.pid,existsSync:vS,async compareAndReplace(n,e,t,r,i){if(!bc)throw new Error("This host needs the shared content write lock for safe cloud downloads");let o=!1,a=bc,s=()=>{if(!r())return;if(i){let c;try{c=_S(i.path)}catch(u){if(u.code==="ENOENT")return;throw u}if(!c.isDirectory()||!hn(i.identity,c))return}let l=null;try{l=Og("sha256").update(kS(e)).digest("hex")}catch(c){if(c.code!=="ENOENT")throw c}l===t&&(ES(n,e),o=!0)};for(let l=0;;l++)try{return await a(e,s),o}catch(c){let u=c.code;if(o||process.platform!=="win32"||l>=4||u!=="EPERM"&&u!=="EBUSY")throw c;await AS(20*2**l)}},watch(n,e,t){let r=Tg.watch(n,{ignoreInitial:!0,depth:e.depth,ignored:e.ignored});return r.on("change",t.change),r.on("add",t.add),r.on("unlink",t.unlink),r.on("unlinkDir",t.unlinkDir),r}};import{readdirSync as CS,lstatSync as kc,readFileSync as Ec,writeFileSync as IS,realpathSync as $g,opendirSync as xS,openSync as TS,fstatSync as DS,readSync as PS,closeSync as OS,constants as vc}from"node:fs";import{join as Gs,extname as Lg,sep as MS}from"node:path";var _c=300,Fg=5*1024*1024,Bg=20*1024*1024,NS=50*1024*1024,jg=new Set(["node_modules"]),$S=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Ug(n,e){let t=[],r=0,i=(o,a)=>{for(let s of CS(o)){if(s.startsWith("."))continue;let l=Gs(o,s),c;try{c=kc(l)}catch{continue}if(c.isSymbolicLink())continue;let u=a?`${a}/${s}`:s;if(c.isDirectory()){jg.has(s)||i(l,u);continue}if(!c.isFile()||s.endsWith(".d.ts"))continue;if(t.length>=_c)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${_c}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let d=Lg(s).toLowerCase(),g,f=e.mimeOf(d)??"application/octet-stream";if($S.has(d)){let p=e.transpile(Ec(l,"utf8"),d,u);g=Buffer.from(p??"","utf8"),f="text/javascript"}else g=Ec(l);if(g.length>Fg)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${u}`);if(r+=g.length,r>Bg)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");t.push({path:u,content_b64:g.toString("base64"),content_type:f,size:g.length})}};if(i(n,""),!t.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:t,totalBytes:r}}var Vg=".forsion-connect.json";function zg(n){try{return JSON.parse(Ec(Gs(n,Vg),"utf8"))}catch{return{}}}function Hg(n,e){try{IS(Gs(n,Vg),JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf8")}catch{}}var LS=new Set([".html",".htm",".js",".mjs",".cjs",".ts",".tsx",".jsx",".mts",".cts",".vue",".svelte"]),FS=400,BS=5e3,Sc=2*1024*1024,jS=12,US=/\bforsion\.ai\.(chat|generateImage|agent|status)\b/g;function qg(n){try{if(!kc(n).isDirectory())return null}catch{return null}let e=!1,t=new Set,r=0,i=0,o=null,a=l=>{let c;try{c=TS(l,vc.O_RDONLY|(vc.O_NOFOLLOW||0)|(vc.O_NONBLOCK||0))}catch{return null}try{if(!DS(c).isFile())return null;o??=Buffer.allocUnsafe(Sc+1);let u=0;for(;u<o.length;){let d=PS(c,o,u,o.length-u,null);if(d<=0)break;u+=d}return u>Sc?null:o.toString("utf8",0,u)}catch{return null}finally{try{OS(c)}catch{}}},s=(l,c)=>{let u;try{u=xS(l)}catch{return}try{for(;;){if(r>=FS||i>=BS)return;let d;try{d=u.readSync()}catch{return}if(!d)return;i++;let g=d.name;if(g.startsWith(".")||jg.has(g))continue;let f=Gs(l,g),p;try{p=kc(f)}catch{continue}if(p.isSymbolicLink())continue;if(p.isDirectory()){c<jS&&s(f,c+1);continue}if(!p.isFile()||p.size>Sc||!LS.has(Lg(g).toLowerCase()))continue;r++;let m=a(f);if(m!==null){!e&&m.includes("forsion-connect.js")&&(e=!0);for(let y of m.matchAll(US))t.add(`forsion.ai.${y[1]}`)}}}finally{try{u.closeSync()}catch{}}};return s(n,0),{usesSdk:e,sdkMethods:[...t].sort()}}function Wg(n){let e=zg(n),t=qg(n);return t?{...e,...t}:e}function Gg(n){let e={"/__forsion/chat":{method:"POST",path:"/api/chat/completions",auth:!0},"/__forsion/images":{method:"POST",path:"/api/images/generations",auth:!0},"/__forsion/user":{method:"GET",path:"/api/brain/users/me",auth:!0},"/__forsion/models":{method:"GET",path:"/api/models",auth:!1},"/__forsion/config":{method:"GET",path:"/api/connect/config",auth:!1},"/__forsion/agent":{method:"POST",path:"/api/agent/runs",auth:!0,agentRun:!0}};function t(r){if(e[r])return e[r];let i="/__forsion/agent-events/";if(r.startsWith(i)){let o=r.slice(i.length);if(/^[A-Za-z0-9-]{1,64}$/.test(o))return{method:"GET",path:`/api/agent/runs/${o}/events`,auth:!0,timeoutMs:9e5}}}return async(r,i)=>{let[o,a]=(r.url||"").split("?"),s=(p,m)=>{i.headersSent||(i.statusCode=p,i.setHeader("Content-Type","application/json")),i.end(JSON.stringify({detail:m}))},l=t(o);if(!l)return s(404,"unknown connect endpoint");if((r.method||"GET")!==l.method)return s(405,"method not allowed");let c="",u="";try{({base:c,token:u}=await n())}catch{}if(!c)return s(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(l.auth&&!u)return s(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let d;if(l.method==="POST"){let p=[],m=0;try{for await(let y of r){if(m+=y.length,m>NS)return r.destroy(),s(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");p.push(y)}}catch(y){return s(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${y?.message||String(y)}`)}d=Buffer.concat(p)}if(l.agentRun){let p;try{p=JSON.parse((d||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return s(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}d=Buffer.from(JSON.stringify({session_id:typeof p.session_id=="string"?p.session_id:"",message:typeof p.message=="string"?p.message:"",app_id:"connect",agent_config:{}}))}let g=new AbortController,f=setTimeout(()=>g.abort(new Error("proxy timeout")),l.timeoutMs??3e5);r.on("close",()=>g.abort());try{let p=await fetch(c+l.path+(a?`?${a}`:""),{method:l.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...u?{Authorization:`Bearer ${u}`}:{}},body:d&&d.length?new Uint8Array(d):void 0,signal:g.signal});if(i.statusCode=p.status,i.setHeader("Content-Type",p.headers.get("content-type")||"application/json"),i.setHeader("Cache-Control","no-store"),p.body)for await(let m of p.body)i.write(m);i.end()}catch(p){let m=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${p?.message||String(p)}`;if(i.headersSent){try{i.write(`data: ${JSON.stringify({error:m})}
|
|
4
4
|
|
|
5
|
-
`)}catch{}i.end()}else
|
|
5
|
+
`)}catch{}i.end()}else s(502,m)}finally{clearTimeout(f)}}}var Jg=`
|
|
6
6
|
(function () {
|
|
7
7
|
'use strict';
|
|
8
8
|
if (window.forsion) return;
|
|
@@ -196,69 +196,75 @@ var ms=null;function Ha(t){ms=t}function Ee(){if(!ms)throw new Error("core host
|
|
|
196
196
|
ai: { chat: chat, agent: agentRun, generateImage: generateImage, status: aiStatus }
|
|
197
197
|
};
|
|
198
198
|
})();
|
|
199
|
-
`,Wp=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function Gp(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function js(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Ls(t){t.setPreviewHooks({sdkJs:$l,proxy:Pl(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Nl(n):{}),t.handle("connect:list",async()=>{let e=await t.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:n,json:r}=await Ze(e,"GET","/api/connect/apps");return n===401||n===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:n!==200?{ok:!1,code:"error",detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,...r}}catch(n){return{ok:!1,code:"error",detail:n?.message||String(n)}}}),t.handle("connect:publish",async(e,n)=>{if(!n||typeof n.dir!="string"||!n.dir||!n.name||!n.slug||!n.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r;try{r=_l(n.dir);let s=null;try{s=_l(t.projectsRoot())}catch{}if(!(!!s&&(r===s||r.startsWith(s+jp)))&&!Gp(t,r))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let i=await t.getCloud();if(!i.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:s,totalBytes:a}=Il(r,Wp(t));if(!s.some(u=>u.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:o,json:l}=await Ze(i,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:s},3e5);if(o===401)return{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"};if(o!==200)return{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${o}`,used:l?.used,limit:l?.limit};Ol(r,{slug:String(l.slug)});let c=typeof l.publicUrl=="string"&&/^https?:\/\//i.test(l.publicUrl)?l.publicUrl:`${i.base}${l.url}`;return{ok:!0,slug:l.slug,handle:l.handle,url:c,totalBytes:a}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:unpublish",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return i===401||i===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingApply",async(e,n)=>{if(!n||typeof n.slug!="string"||!n.slug||typeof n.summary!="string"||!n.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200?{ok:!1,code:s?.code||"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0,status:s.status}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await Ze(e,"GET","/api/connect/store");return n!==200?{ok:!1,detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,items:Array.isArray(r.items)?r.items:[]}}catch(n){return{ok:!1,detail:n?.message||String(n)}}}),t.log("[forsion-extend] connect handlers registered")}import{createHash as Vp}from"node:crypto";import{hostname as Yp}from"node:os";async function lr(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let r=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let i=await r.json();if(!i)return{status:"offline"};let s=i.avatar||i.avatarUrl||i.avatar_url||void 0;return s&&/^\/(?!\/)/.test(s)&&(s=n+s),{status:"ok",user:{username:i.username||i.nickname||void 0,nickname:i.nickname||void 0,avatar:s,membershipTier:i.membershipTier||i.membership_tier||void 0}}}catch{return{status:"offline"}}}var jl=t=>`${t.seq}:${t.hash}`,hi=(t=Yp())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},Jp=t=>Vp("sha256").update(t).digest("hex");function Fs(t){if(t===null)return{baseSeq:0,baseHash:null};if(typeof t!="string")return;let e=t.indexOf(":"),n=Number(e===-1?t:t.slice(0,e));if(!Number.isInteger(n)||n<=0)return;let r=e===-1?"":t.slice(e+1);return{baseSeq:n,baseHash:/^[0-9a-f]{64}$/.test(r)?r:null}}function gi(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=hi(),i=async(s,a)=>{let o=t.getToken();if(!o)throw new Error("penzor-not-logged-in");let l=await fetch(s,{...a,headers:{...a.headers,Authorization:`Bearer ${o}`}});if(l.status===409){let c=await l.json().catch(()=>({}));throw new Error(`cas-conflict ${String(c.code??"")}: seq=${String(c.seq??"?")}`)}if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`penzor ${a.method??"GET"} ${l.status}: ${c.slice(0,200)}`)}return l};return{kind:"penzor",async walk(s){let a=await i(n("/manifest"),{method:"GET",signal:s}),{files:o}=await a.json();return o.map(l=>({key:l.path,size:l.size,mtimeMs:l.mtimeMs,id:jl(l),hash:l.hash}))},async readFile(s,a){let l=await(await i(n(`/file?path=${encodeURIComponent(s)}`),{method:"GET",signal:a})).json(),c=await fetch(l.url,{signal:a});if(!c.ok)throw new Error(`penzor blob GET ${c.status}: ${s}`);let u=Buffer.from(await c.arrayBuffer());if(Jp(u)!==l.hash)throw new Error(`penzor hash mismatch: ${s}`);return u},async writeFile(s,a,o,l,c){let u=Fs(c),f=new URLSearchParams({path:s,mtimeMs:String(Math.floor(o)||0)});u&&(f.set("baseSeq",String(u.baseSeq)),u.baseHash&&f.set("baseHash",u.baseHash));let p=await(await i(n(`/file?${f.toString()}`),{method:"PUT",body:new Uint8Array(a),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:l})).json();return{key:s,size:p.size,mtimeMs:p.mtimeMs,id:jl(p)}},async rm(s,a,o){let l=Fs(o),c=new URLSearchParams({path:s});l&&l.baseSeq>0&&(c.set("baseSeq",String(l.baseSeq)),l.baseHash&&c.set("baseHash",l.baseHash)),await i(n(`/file?${c.toString()}`),{method:"DELETE",signal:a})},async check(){try{return await i(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var mi="forsion-diagnostics",Fl=50*1024*1024,Ll=new Map;async function Kp(t,e){let n=Ll.get(e);if(n)return{id:n};let r=await lr(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let i=r.user?.username?.trim();return i?(Ll.set(e,i),{id:i}):{error:"penzor-auth-unverified"}}var Us=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function Hs(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,i=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(i)||i===mi)return{error:"penzor-bad-vault"};let s=await Kp(n.cloudUrl,n.token);if("error"in s)return s;let a=n.token;return{remote:gi({baseUrl:n.cloudUrl,vault:i,getToken:()=>a}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${s.id}|${i}`,maxFileBytes:Fl}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as Zp}from"node:fs";import{access as Qp,link as eh,lstat as th,mkdir as nh,open as rh,readdir as ih,rename as sh,stat as Gl,unlink as qs}from"node:fs/promises";import{request as oh}from"node:http";import{request as ah}from"node:https";import{homedir as lh}from"node:os";import{basename as Vl,extname as ch,isAbsolute as uh,join as ur}from"node:path";import{randomUUID as wi}from"node:crypto";var cr=52428800;var Ul=["bytes","signed","text"],Hl=/^[A-Za-z0-9_-]{1,64}$/,zl=/^[a-z0-9][a-z0-9-]{0,63}$/;function yi(t){if(typeof t!="string")return null;let n=(t.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f<>:"|?*]/g,"").trim().slice(0,200);return n&&n!=="."&&n!==".."?n:null}var Xp={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".svg":"image/svg+xml",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Bl(t){let e=t.lastIndexOf(".");return Xp[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function ql(t,e,n,r){let i=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",s=encodeURIComponent(n).replace(/['()*]/g,o=>`%${o.charCodeAt(0).toString(16).toUpperCase()}`),a="";for(let[o,l]of Object.entries(e))a+=`--${t}\r
|
|
200
|
-
|
|
199
|
+
`,VS=n=>({transpile:(e,t,r)=>n.transpileForServe(e,t,r),mimeOf:e=>n.mimeOf(e)});function zS(n,e){let t=n.isAdoptedCreation;if(typeof t!="function")return!1;try{return t.call(n,e)===!0}catch{return!1}}function Rc(n){let e=n;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Ac(n){n.setPreviewHooks({sdkJs:Jg,proxy:Gg(()=>n.getCloud())}),n.handle("connect:meta",(e,t)=>typeof t=="string"&&t?Wg(t):{}),n.handle("connect:list",async()=>{let e=await n.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:t,json:r}=await Rt(e,"GET","/api/connect/apps");return t===401||t===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:t!==200?{ok:!1,code:"error",detail:r?.detail||`HTTP ${t}`}:{ok:!0,base:e.base,...r}}catch(t){return{ok:!1,code:"error",detail:t?.message||String(t)}}}),n.handle("connect:publish",async(e,t)=>{if(!t||typeof t.dir!="string"||!t.dir||!t.name||!t.slug||!t.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r;try{r=$g(t.dir);let o=null;try{o=$g(n.projectsRoot())}catch{}if(!(!!o&&(r===o||r.startsWith(o+MS)))&&!zS(n,r))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let i=await n.getCloud();if(!i.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:o,totalBytes:a}=Ug(r,VS(n));if(!o.some(u=>u.path===t.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${t.entry}`};let{status:s,json:l}=await Rt(i,"POST","/api/connect/apps",{slug:t.slug,name:t.name,entry:t.entry,files:o},3e5);if(s===401)return{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"};if(s!==200)return{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${s}`,used:l?.used,limit:l?.limit};Hg(r,{slug:String(l.slug)});let c=typeof l.publicUrl=="string"&&/^https?:\/\//i.test(l.publicUrl)?l.publicUrl:`${i.base}${l.url}`;return{ok:!0,slug:l.slug,handle:l.handle,url:c,totalBytes:a}}catch(o){return{ok:!1,code:"error",detail:o?.message||String(o)}}}),n.handle("connect:unpublish",async(e,t)=>{if(!t||typeof t!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await n.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:o}=await Rt(r,"DELETE",`/api/connect/apps/${encodeURIComponent(t)}`);return i===401||i===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),n.handle("connect:listingApply",async(e,t)=>{if(!t||typeof t.slug!="string"||!t.slug||typeof t.summary!="string"||!t.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await n.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:o}=await Rt(r,"PUT",`/api/connect/apps/${encodeURIComponent(t.slug)}/listing`,{summary:t.summary});return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200?{ok:!1,code:o?.code||"error",detail:o?.detail||`HTTP ${i}`}:{ok:!0,status:o.status}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),n.handle("connect:listingWithdraw",async(e,t)=>{if(!t||typeof t!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await n.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:o}=await Rt(r,"DELETE",`/api/connect/apps/${encodeURIComponent(t)}/listing`);return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),n.handle("connect:store",async()=>{let e=await n.getCloud();try{let{status:t,json:r}=await Rt(e,"GET","/api/connect/store");return t!==200?{ok:!1,detail:r?.detail||`HTTP ${t}`}:{ok:!0,base:e.base,items:Array.isArray(r.items)?r.items:[]}}catch(t){return{ok:!1,detail:t?.message||String(t)}}}),n.log("[forsion-extend] connect handlers registered")}import{createHash as IA}from"node:crypto";import{realpath as AE}from"node:fs/promises";import{basename as CE}from"node:path";import{readFile as vp,rename as Ep,mkdir as vk,unlink as Sk,open as Sp,readdir as kk}from"node:fs/promises";import{join as Nr,dirname as Mc,relative as Ek,isAbsolute as _p,sep as _k,basename as $c}from"node:path";import{createHash as Rk,randomUUID as Rp}from"node:crypto";import{readFile as HS}from"node:fs/promises";import{isAbsolute as Yg,join as qS}from"node:path";var WS=/^[A-Za-z0-9_-]{1,64}$/,Xg=/^[A-Za-z0-9_-]{1,64}$/,Kg=n=>WS.test(n)&&n!=="__proto__",Zg=()=>({version:3,marks:Object.create(null),retired:Object.create(null)}),ao=n=>typeof n=="number"&&Number.isFinite(n),GS=/^[0-9a-f]{64}$/;function JS(n){let e=n;return!!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.vaultId=="string"&&Xg.test(e.vaultId)&&typeof e.prefix=="string"&&e.prefix.endsWith("/")&&e.prefix.length>1&&e.prefix.length<=1024&&ao(e.at)&&(e.purgeAt===null||typeof e.purgeAt=="string")&&typeof e.purging=="boolean"&&typeof e.purged=="boolean"&&typeof e.reverted=="boolean"&&Number.isSafeInteger(e.generation)&&typeof e.wasPaused=="boolean"&&typeof e.root=="string"&&Yg(e.root)}function KS(n){let e=n;return!e||typeof e!="object"||Array.isArray(e)||!(e.to==="device"||typeof e.to=="string"&&GS.test(e.to))||!Number.isSafeInteger(e.generation)||!ao(e.at)||typeof e.wasEnabled!="boolean"||!Ic(e.target)||!Ks(e.scope)||e.onDiffer!=="newer"&&e.onDiffer!=="hold"?!1:e.to==="device"==(e.target.kind==="remote")}function Cc(n){let e=JSON.parse(n);if(!e||typeof e!="object"||e.version!==3||!e.marks||typeof e.marks!="object"||Array.isArray(e.marks)||!e.retired||typeof e.retired!="object"||Array.isArray(e.retired))throw Error("bad shape");let t=Zg(),r=i=>typeof i=="string"&&Yg(i);for(let[i,o]of Object.entries(e.marks)){if(!Kg(i)||!o||typeof o!="object"||Array.isArray(o))throw Error("bad mark");let a=o.unbinding;if(a!==void 0&&!(a&&typeof a=="object"&&ao(a.at)&&Number.isSafeInteger(a.generation)&&r(a.root)&&Bt(a.rootIdentity)))throw Error("bad unbinding mark");let s=o.retarget;if(s!==void 0&&!(s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.toVaultId=="string"&&Xg.test(s.toVaultId)&&typeof s.fromVaultId=="string"&&s.fromVaultId.length>0&&(s.fromNs==="default"||typeof s.fromNs=="string"&&/^vault-[A-Za-z0-9_-]{1,64}$/.test(s.fromNs))&&typeof s.fromPrefix=="string"&&s.fromPrefix.endsWith("/")&&ao(s.at)&&(s.movedAt===null||typeof s.movedAt=="string")&&Number.isSafeInteger(s.generation)&&typeof s.wasPaused=="boolean"&&(s.root===void 0||r(s.root))))throw Error("bad retarget mark");let l=o.kindMove;if(l!==void 0&&!KS(l))throw Error("bad kind move mark");let c=o.cloudDeleted;if(c!==void 0&&!JS(c))throw Error("bad cloud deleted mark");t.marks[i]={...a?{unbinding:{at:a.at,generation:a.generation,root:a.root,rootIdentity:a.rootIdentity}}:{},...s?{retarget:{toVaultId:s.toVaultId,fromVaultId:s.fromVaultId,fromNs:s.fromNs,fromPrefix:s.fromPrefix,at:s.at,movedAt:s.movedAt,generation:s.generation,wasPaused:s.wasPaused,...s.root!==void 0?{root:s.root}:{}}}:{},...l?{kindMove:{to:l.to,generation:l.generation,at:l.at,wasEnabled:l.wasEnabled,target:YS(l.target),scope:XS(l.scope),onDiffer:l.onDiffer}}:{},...c?{cloudDeleted:{vaultId:c.vaultId,prefix:c.prefix,at:c.at,purgeAt:c.purgeAt,purging:c.purging,purged:c.purged,reverted:c.reverted,generation:c.generation,wasPaused:c.wasPaused,root:c.root}}:{}}}for(let[i,o]of Object.entries(e.retired)){if(!Kg(i)||!o||typeof o!="object"||Array.isArray(o)||!r(o.root)||!Bt(o.rootIdentity)||!ao(o.at))throw Error("bad retired entry");t.retired[i]={root:o.root,rootIdentity:o.rootIdentity,at:o.at}}return t}function YS(n){return n.kind==="penzor"?{kind:"penzor",vaultId:n.vaultId,ns:n.ns,prefix:n.prefix,placement:n.placement}:{kind:"remote",targetId:n.targetId,dir:n.dir,direction:n.direction,ignore:n.ignore.map(String),maxFileBytes:n.maxFileBytes}}function XS(n){return n.mode==="all"?{mode:"all"}:{mode:"some",items:n.items.map(e=>({path:e.path,kind:e.kind})),...n.exclude?{exclude:[...n.exclude]}:{}}}var Js=class{dir;constructor(e){this.dir=e}file(e){return qS(this.dir(),e,"bindings.v3.json")}async read(e){let t=this.file(e),r;try{r=await HS(t,"utf8")}catch(i){if(i.code==="ENOENT")return Zg();throw new Xe(t,i)}try{return Cc(r)}catch(i){throw new Xe(t,i)}}update(e,t){let r=this.file(e);return mn(r,async()=>{let i=await this.read(e),o=t(Cc(JSON.stringify(i)));if(!o)return i;let a=Cc(JSON.stringify(o));return await je(r,a),a})}};import{isAbsolute as dk}from"node:path";function ZS(n,e){let t=Object.create(null);for(let o=0;o<e.length;o++){let a=e[o];t[a]?t[a].push(o):t[a]=[o]}let i=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let o=0;o<n.length;o++){let a=n[o],s=t[a]||[],l=0,c=i[0];for(let u of s){let d;for(d=l;d<i.length&&!(i[d].buffer2index<u&&(d===i.length-1||i[d+1].buffer2index>u));d++);if(d<i.length){let g={buffer1index:o,buffer2index:u,chain:i[d]};if(l===i.length?i.push(c):i[l]=c,l=d+1,c=g,l===i.length)break}}i[l]=c}return i[i.length-1]}function Qg(n,e){let t=ZS(n,e),r=[],i=n.length,o=e.length;for(let a=t;a!==null;a=a.chain){let s=i-a.buffer1index-1,l=o-a.buffer2index-1;i=a.buffer1index,o=a.buffer2index,(s||l)&&r.push({buffer1:[i+1,s],buffer1Content:n.slice(i+1,i+1+s),buffer2:[o+1,l],buffer2Content:e.slice(o+1,o+1+l)})}return r.reverse(),r}function QS(n,e,t){let r=[];function i(l,c){r.push({ab:c,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}Qg(e,n).forEach(l=>i(l,"a")),Qg(e,t).forEach(l=>i(l,"b")),r.sort((l,c)=>l.oStart-c.oStart);let o=[],a=0;function s(l){l>a&&(o.push({stable:!0,buffer:"o",bufferStart:a,bufferLength:l-a,bufferContent:e.slice(a,l)}),a=l)}for(;r.length;){let l=r.shift(),c=l.oStart,u=l.oStart+l.oLength,d=[l];for(s(c);r.length;){let g=r[0],f=g.oStart;if(f>u)break;u=Math.max(u,f+g.oLength),d.push(r.shift())}if(d.length===1){if(l.abLength>0){let g=l.ab==="a"?n:t;o.push({stable:!0,buffer:l.ab,bufferStart:l.abStart,bufferLength:l.abLength,bufferContent:g.slice(l.abStart,l.abStart+l.abLength)})}}else{let g={a:[n.length,-1,e.length,-1],b:[t.length,-1,e.length,-1]};for(;d.length;){l=d.shift();let h=l.oStart,E=h+l.oLength,v=l.abStart,k=v+l.abLength,C=g[l.ab];C[0]=Math.min(v,C[0]),C[1]=Math.max(k,C[1]),C[2]=Math.min(h,C[2]),C[3]=Math.max(E,C[3])}let f=g.a[0]+(c-g.a[2]),p=g.a[1]+(u-g.a[3]),m=g.b[0]+(c-g.b[2]),y=g.b[1]+(u-g.b[3]),b={stable:!1,aStart:f,aLength:p-f,aContent:n.slice(f,p),oStart:c,oLength:u-c,oContent:e.slice(c,u),bStart:m,bLength:y-m,bContent:t.slice(m,y)};o.push(b)}a=u}return s(e.length),o}function ep(n,e,t,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof n=="string"&&(n=n.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof t=="string"&&(t=t.split(r.stringSeparator));let o=[],a=QS(n,e,t),s=[];function l(){s.length&&o.push({ok:s}),s=[]}function c(u,d){if(u.length!==d.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==d[g])return!1;return!0}return a.forEach(u=>{u.stable?s.push(...u.bufferContent):r.excludeFalseConflicts&&c(u.aContent,u.bContent)?s.push(...u.aContent):(l(),o.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),l(),o}function Ys(n,e){let t=n.lastIndexOf("/"),r=t<0?"":n.slice(0,t+1),i=t<0?n:n.slice(t+1),o=i.lastIndexOf("."),a=o>0?i.slice(0,o):i,s=o>0?i.slice(o):"",l=u=>String(u).padStart(2,"0"),c=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${r}${a} (conflict ${c})${s}`}function ek(n,e){if(e<2)return n;let t=n.lastIndexOf("."),r=t>n.lastIndexOf("/")&&t>n.lastIndexOf(")"),i=r?n.slice(0,t):n,o=r?n.slice(t):"";return`${i}-${e}${o}`}function tk(n){let e=3735928559,t=1103547991;for(let i=0;i<n.length;i++){let o=n.charCodeAt(i);e=Math.imul(e^o,2654435761),t=Math.imul(t^o,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let r=4294967296*(2097151&t)+(e>>>0);return`${n.length.toString(36)}-${r.toString(36)}`}var ri=(n,e)=>e.seq===n.seq&&e.hash!==null&&e.hash!==n.hash,tp=(n,e)=>e.seq!==n.seq||ri(n,e);function Xs(n,e,t){if(n===null&&e===null&&t===null)return{kind:"none"};if(t===null)return n===null?e?{kind:"dropShadow"}:{kind:"none"}:e?n===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(n===null)return e?tp(e,t)?{kind:"pull"}:{kind:"pushDelete"}:{kind:"pull"};if(!e)return n===t.hash?{kind:"adopt"}:{kind:"hold"};if(ri(e,t))return n===t.hash?{kind:"adopt"}:n===e.hash?{kind:"pull"}:{kind:"hold"};let r=n!==e.hash,i=tp(e,t);return!r&&!i?{kind:"none"}:r?i?n===t.hash?{kind:"adopt"}:t.hash===e.hash?{kind:"push",baseSeq:t.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function np(n,e,t){let r=ep(n.split(`
|
|
200
|
+
`),e.split(`
|
|
201
|
+
`),t.split(`
|
|
202
|
+
`),{excludeFalseConflicts:!0}),i=[];for(let o of r){if(o.conflict)return null;o.ok&&i.push(...o.ok)}return i.join(`
|
|
203
|
+
`)}function lo(n,e,t=200){return n>=t||e>=5&&n>=Math.max(5,Math.ceil(e/2))}var op=["merge","cloud","local"],sp={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Xt(n,e=!1){if(typeof n!="string"||!n&&!e||n.length>512||n.startsWith("/")||/[\\\u0000-\u001f\u007f]/.test(n)||n&&n.split("/").some(t=>!t||t==="."||t===".."||t.endsWith(".")||t.endsWith(" ")||t.startsWith(".forsion-sync")))throw Error("Invalid content path");return n}function nk(n){if(n==="default"||n==="off"||typeof n=="string"&&/^device-[A-Za-z0-9_-]{1,64}$/.test(n))return n;throw Error("Invalid content target")}function Zt(n,e){let t=n;if(!t||t.version!==1||typeof t.enabled!="boolean"||!Array.isArray(t.rules)||t.rules.length>512)throw Error("Invalid content sync configuration");let r=new Set,i=new Set,o=t.rules.map(a=>{let s=Xt(a.source,!0),l=nk(a.target);if(typeof a.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(a.id)||i.has(a.id)||r.has(s))throw Error("Duplicate or invalid sync rule");return i.add(a.id),r.add(s),{id:a.id,source:s,target:l,...a.sourceId&&/^[a-f0-9-]{36}$/i.test(a.sourceId)?{sourceId:a.sourceId}:{}}});return{version:1,revision:e,enabled:t.enabled,rules:o}}function Hn(n,e){let t=null;for(let r of e)(!r.source||n===r.source||n.startsWith(r.source+"/"))&&(!t||r.source.length>t.source.length)&&(t=r);return t}var ut={status:"penzor:sync:status",get:"penzor:sync:get",preview:"penzor:sync:preview",apply:"penzor:sync:apply",run:"penzor:sync:run",pause:"penzor:sync:pause",retry:"penzor:sync:retry",rename:"penzor:sync:rename",setup:"penzor:sync:setup",archiveSeen:"penzor:sync:archiveSeen",confirmDeletes:"penzor:sync:confirmDeletes",abandonDeletes:"penzor:sync:abandonDeletes"},rp=200,Qs=6e4,rk=50;function xc(n,e,t,r){return n.deleted?"forget":n.busy||r?"skip":n.version?e&&e.version===n.version&&co(e.file,n.file)?"delete":"download":t?"cancel":"skip"}var co=(n,e)=>n===void 0||e===void 0||n===e,ik=(n,e)=>{let t=e.indexOf("/");return n+":"+(t<0?"":e.slice(0,t))};function ea(n,e,t){if(!n.length)return!1;if(t.latched||n.length>=rp||t.recent+n.length>rk)return!0;let r=a=>{let s=new Map;for(let l of a){let c=ik(l.ns,l.path);s.set(c,(s.get(c)??0)+1)}return s},i=r(n),o=r(e);for(let[a,s]of i)if(lo(s,o.get(a)??0,rp))return!0;return!1}var Mr=n=>n.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||n,ip=n=>String(n??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Tc=(n,e,t)=>{let r=ip(n);return r?/[\[\]]/.test(n)||n.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(i=>i.id!==t&&ip(i.name)===r)?"taken":null:null},ap=["Amadeus","agents","human","Plugins"],Or=1024*1024,Zs=50*Or,ok=[{prefix:"Amadeus/",ext:[".md",".db"],maxBytes:5*Or},{prefix:"Amadeus/",maxBytes:5*Or},{prefix:"agents/",maxBytes:5*Or},{prefix:"human/",maxBytes:5*Or},{prefix:"",maxBytes:50*Or}],sk=[{prefix:"",maxBytes:50*Or}];function Qt(n,e,t){let r=Array.isArray(t)&&t.length?t:e==="default"?ok:sk,i=n.toLowerCase();for(let o of r)if(!(!o||typeof o.prefix!="string"||!Number.isSafeInteger(o.maxBytes)||o.maxBytes<=0)&&n.startsWith(o.prefix)&&!(Array.isArray(o.ext)&&o.ext.length&&!o.ext.some(a=>typeof a=="string"&&i.endsWith(a.toLowerCase()))))return Math.min(o.maxBytes,Zs);return Zs}var ak=6e4,lk=10*6e4,lp=n=>n<=1?0:Math.min(ak*2**(n-2),lk),mr="delete-guard";var Le=n=>n.normalize("NFC").trim().toLowerCase(),ck=["my vault","\u4E91\u7AEF\u7B14\u8BB0","cloud notes"],yr="My Vault";function qn(n){if(typeof n!="string")return"empty";let e=n.normalize("NFC").trim();return e?e==="."||e===".."?"dot":/[/\\]/.test(e)?"separator":/[\u0000-\u001f\u007f]/.test(e)?"control":new TextEncoder().encode(e).length>255?"too_long":null:"empty"}var uo=n=>ck.includes(Le(n));var pt=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Pt=n=>typeof n=="string",Wn=n=>Pt(n)&&n.length>0,xn=n=>typeof n=="boolean",Tn=n=>typeof n=="number"&&Number.isFinite(n),wr=n=>Tn(n)&&Number.isSafeInteger(n)&&n>=0,cp=n=>Tn(n)&&Number.isInteger(n)&&n>=0,up=n=>wr(n)&&n>0,br=n=>Pt(n)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(n),ii=n=>Pt(n)&&/^[a-f0-9]{64}$/.test(n),na=n=>Pt(n)&&/^(default|device-[A-Za-z0-9_-]{1,64}|vault-[A-Za-z0-9_-]{1,64})$/.test(n),oi=(n,e)=>Pt(n)&&e.includes(n),ke=(n,e)=>n===void 0||e(n),fp=(n,e,t)=>e.every(r=>ke(n[r],t)),gp=n=>Pt(n)&&!n.includes("\0")&&dk(n);function en(n,e=!1){try{return Xt(n,e),!0}catch{return!1}}var pp=n=>en(n)&&!n.includes("/")&&Buffer.byteLength(n)<=255,hp=n=>n===""||br(n);function ta(n,e){let t=n.indexOf(":");return t>0&&br(e)&&n.slice(t+1)===e&&na(n.slice(0,t))}function uk(n,e){return pt(e)&&ta(n,e.id)&&en(e.path)&&Wn(e.version)&&ii(e.hash)&&fp(e,["base","inode","stat"],Pt)&&ke(e.statAt,Tn)&&ke(e.memoryDeleted,xn)&&ke(e.file,Wn)&&ke(e.outsideScope,t=>t===!0)}function fk(n,e){return pt(e)&&ta(n,e.localId)&&br(e.id)&&en(e.path)&&up(e.revision)&&hp(e.parentId)&&pp(e.name)&&ke(e.outsideScope,t=>t===!0)}function gk(n){return pt(n)&&br(n.id)&&en(n.path)&&na(n.target)&&oi(n.direction,["upload","download","merge","rename","delete"])&&oi(n.state,["queued","active","done","failed","paused","conflict"])&&wr(n.done)&&(n.size===null||wr(n.size))&&Tn(n.at)&&ke(n.error,Pt)&&ke(n.finishedAt,Tn)}function pk(n){return pt(n)&&en(n.path)&&ii(n.hash)&&Pt(n.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(n.stage)&&ke(n.parentId,br)&&ke(n.stageRoot,gp)&&ke(n.stageIdentity,Bt)&&(n.stageDev===void 0&&n.stageIno===void 0||n.stageRoot!==void 0&&cp(n.stageDev)&&cp(n.stageIno))}function hk(n){return pt(n)&&en(n.prefix,!0)&&gp(n.root)&&(n.dev===void 0&&n.ino===void 0&&n.volumeId===void 0&&n.birthtimeMs===void 0||Bt(n))}function mk(n){return pt(n)&&oi(n.state,["running","done"])&&xn(n.seen)&&fp(n,["name","folderId","shelfId","shelfName"],Pt)&&ke(n.files,wr)&&ke(n.at,Tn)&&ke(n.rewritten,xn)}function dp(n){return pt(n)&&Wn(n.key)&&na(n.ns)&&br(n.id)&&en(n.path)&&oi(n.side,["cloud","local"])}function yk(n){return pt(n)&&xn(n.latched)&&In(n.pending,dp)&&ke(n.confirmed,e=>In(e,Wn))&&ke(n.restore,e=>In(e,dp))}function wk(n,e){return pt(e)&&en(n)&&e.path===n&&na(e.ns)&&br(e.id)&&Pt(e.version)&&(e.remoteHash===null||ii(e.remoteHash))&&ke(e.file,Wn)&&wr(e.revision)&&ii(e.localHash)&&Tn(e.localMtime)&&(e.remoteMtime===null||Tn(e.remoteMtime))&&wr(e.size)&&Tn(e.at)&&ke(e.cloudGone,t=>t===!0)&&ke(e.inode,t=>e.cloudGone===!0&&typeof t=="string"&&t.length>0)}var fo=(n,e)=>pt(n)&&Object.entries(n).every(([t,r])=>e(t,r)),In=(n,e)=>Array.isArray(n)&&n.every(e);function Dc(n){if(typeof n!="string")return!1;let e=/^Amadeus\/([^/]+)\/$/.exec(n);return!!e&&qn(e[1])===null&&!/[\u0000-\u001f\u007f\\]/.test(e[1])}function si(n){let e=n.moved;return Array.isArray(e)?e.flatMap(t=>{if(!pt(t)||!Dc(t.prefix))return[];let r=Pt(t.vaultId)&&/^[A-Za-z0-9_-]{1,64}$/.test(t.vaultId)&&(t.at==null||Pt(t.at));return[{prefix:t.prefix,vaultId:r?t.vaultId:null,at:Pt(t.at)?t.at:null}]}):[]}function Gn(n){if(!pt(n)||!pt(n.config)||!wr(n.config.revision)||!xn(n.owned)||!xn(n.paused)||!fo(n.files,uk)||!fo(n.folders,fk)||!In(n.jobs,gk)||!ke(n.accountReview,xn)||!ke(n.releasing,xn)||!ke(n.scopeExclusions,e=>In(e,t=>en(t)))||!ke(n.scopeFirstRound,e=>In(e,t=>en(t)))||!ke(n.deleteGuard,yk)||!ke(n.deleteDecisions,e=>In(e,t=>pt(t)&&oi(t.kind,["confirm","restore"])&&In(t.keys,Wn)))||!ke(n.held,e=>fo(e,wk))||!ke(n.agentArchive,mk)||!ke(n.roots,e=>In(e,hk))||!ke(n.trash,e=>In(e,pk))||!ke(n.unconfirmed,e=>fo(e,(t,r)=>ta(t,t.slice(-36))&&ii(r)))||!ke(n.pendingUploads,e=>fo(e,(t,r)=>pt(r)&&ta(t,r.id)&&en(r.path))))throw Error("Invalid content sync state; original data was retained");Zt(n.config,n.config.revision)}function mp(n){return pt(n)&&br(n.id)&&hp(n.parentId)&&pp(n.name)&&en(n.path)&&oi(n.kind,["file","folder"])&&up(n.revision)&&xn(n.deleted)&&ke(n.busy,xn)&&ke(n.version,Wn)&&ke(n.hash,ii)&&ke(n.size,wr)&&ke(n.mtime,Tn)&&ke(n.file,Wn)&&n.version===void 0==(n.hash===void 0)}function yp(n){return mp(n)&&n.deleted===!0}function vr(n,e){let t=()=>Error("Incomplete or invalid cloud content manifest");if(!pt(n)||n.schemaVersion!==1||n.namespace!==e||!Wn(n.folder)||!Array.isArray(n.nodes))throw t();let r=new Map,i=new Set;for(let o of n.nodes){if(!mp(o)||r.has(o.id)||!o.deleted&&i.has(o.path))throw t();r.set(o.id,o),o.deleted||i.add(o.path)}for(let o of r.values()){let a=o.parentId?r.get(o.parentId):void 0;if(o.parentId&&(!a||a.kind!=="folder"||a.deleted&&!o.deleted)||o.path!==(a?a.path+"/"+o.name:o.name))throw t()}}var bk=null;function bp(n,e){let t=n.replace(/\/+$/,""),r=e.replace(/\/+$/,"");return t===r||r.startsWith(t+"/")||t.startsWith(r+"/")}var wp=(n,e)=>`${n}\0${e}`,yn=class n{ask;memo=new Map;done=new Map;constructor(e){this.ask=e}static of(e){let t=e.syncTargets;return typeof t?.identity=="function"?new n((r,i)=>t.identity(r,i)):null}fetch(e,t){let r=wp(e,t),i=this.memo.get(r);return i||(i=this.resolve(e,t).then(o=>(this.done.set(r,o),o)),this.memo.set(r,i)),i}async prefetch(e){await Promise.all([...e].map(([t,r])=>this.fetch(t,r)))}peek(e,t){return this.done.get(wp(e,t))}async resolve(e,t){let r,i=new Promise(a=>{r=setTimeout(()=>a({ok:!1,code:"unavailable"}),bk??12e3)}),o=Promise.resolve().then(()=>this.ask(e,t)).then(a=>typeof a=="string"&&a.replace(/\/+$/,"")?{ok:!0,id:a}:{ok:!1,code:"unavailable"},a=>({ok:!1,code:a?.message==="target-not-found"?"not_found":"unavailable"}));try{return await Promise.race([o,i])}finally{clearTimeout(r)}}},ra=class extends Error{code="target_identity_unavailable";constructor(){super("target_identity_unavailable"),this.name="TargetIdentityUnavailableError"}};var Lc={kind:"interval",minutes:5},ae=n=>Rk("sha256").update(n).digest("hex"),Xe=class extends Error{file;constructor(e,t){super(`Invalid vault sync state; original data was retained (${t?.message??String(t)})`),this.file=e,this.name="VaultSyncStateError"}},Ak=new Set(["folder","file","page"]),Ck=new Set(["active","takeover","needs-card","needs-rename-answer","needs-choice"]),Kn=n=>typeof n=="string"&&n.length>0&&n.length<=1024&&!n.startsWith("/")&&!n.includes("\\")&&!n.split("/").some(e=>!e||e==="."||e==="..");function Ap(n,e=!1){let t=n;return!t||typeof t!="object"||typeof t.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(t.id)||typeof t.root!="string"||!_p(t.root)||!Bt(t.rootIdentity)||typeof t.nameKey!="string"||typeof t.enabled!="boolean"||typeof t.paused!="boolean"||!Ck.has(t.state)||t.role!=="primary"&&t.role!=="backup"||!Number.isSafeInteger(t.generation)||!Number.isFinite(t.createdAt)||!Ks(t.scope)?!1:e?Ik(t.target)&&t.role==="primary"&&t.state!=="takeover"&&(t.firstRound===void 0||t.firstRound==="pair"||t.firstRound==="scope")&&(t.firstRoundOnDiffer===void 0||t.firstRoundOnDiffer==="newer"||t.firstRoundOnDiffer==="hold")&&(t.firstRoundPrevScope===void 0||Ks(t.firstRoundPrevScope))&&(t.firstRoundExclusions===void 0||Array.isArray(t.firstRoundExclusions)&&t.firstRoundExclusions.every(r=>Kn(r)&&r.startsWith(di))):Ic(t.target)}var ai=n=>n.kind==="penzor"&&n.placement==="default";function Ik(n){let e=n;return e?.kind==="penzor"&&e.placement==="default"&&e.ns==="default"&&e.prefix==="Amadeus/"&&typeof e.vaultId=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e.vaultId)}function Ic(n){let e=n;return e?.kind==="penzor"?typeof e.vaultId=="string"&&(e.ns==="default"||/^vault-[A-Za-z0-9_-]{1,64}$/.test(e.ns))&&typeof e.prefix=="string"&&e.prefix.endsWith("/")&&["own","legacy-entry","legacy-root"].includes(e.placement):e?.kind==="remote"?typeof e.targetId=="string"&&typeof e.dir=="string"&&["both","push","pull"].includes(e.direction)&&Array.isArray(e.ignore)&&(e.maxFileBytes===null||Number.isSafeInteger(e.maxFileBytes)):!1}function Ks(n){let e=n;return e?.mode==="some"?Array.isArray(e.items)&&e.items.every(t=>Kn(t?.path)&&Ak.has(t.kind))&&(e.exclude===void 0||Array.isArray(e.exclude)&&e.exclude.every(Kn)):e?.mode==="all"}function xk(n,e,t){let r=JSON.parse(e);if(!r||r.version!==2||!Array.isArray(r.bindings)||!r.bindings.every(i=>Ap(i)))throw Error("bad shape");if(t){let i=r.cadence;if(!i||!(i.kind==="manual"||i.kind==="interval"&&[5,10,30].includes(i.minutes)))throw Error("bad cadence")}if(new Set(r.bindings.map(i=>i.id)).size!==r.bindings.length)throw Error("duplicate binding id");return r}var ia=new Map,mn=(n,e)=>{let t=(ia.get(n)??Promise.resolve()).then(e,e),r=t.catch(()=>{});return ia.set(n,r),r.then(()=>{ia.get(n)===r&&ia.delete(n)}),t};async function je(n,e,t){await vk(Mc(n),{recursive:!0,mode:448});let r=`${n}.tmp-${Rp()}`;try{let i=await Sp(r,"wx",384);try{await i.writeFile(JSON.stringify(e)),await i.sync()}finally{await i.close()}t?.(),await Ep(r,n)}finally{await Sk(r).catch(()=>{})}try{let i=await Sp(Mc(n),"r");try{await i.sync()}finally{await i.close()}}catch(i){if(!["EISDIR","EPERM","EINVAL"].includes(i.code??""))throw i}}var Ae=n=>mn("\0vault-sync-admission",n),jt=(n,e)=>{let t=e.replace(/[\\/]+$/,"");for(let r of n){let i=r.replace(/[\\/]+$/,"");if(i===t||Jn(i,t)||Jn(t,i))return!0}return!1},oa=class{home;v3=new Js(()=>this.dir());constructor(e){this.home=e}dir(){return Nr(this.home(),"vault-sync")}accountFile(e){return Nr(this.dir(),`${ae(e)}.json`)}defaultFile(e){return Nr(this.dir(),ae(e),"bindings.default.json")}deviceFile(){return Nr(this.dir(),"device.json")}stateFile(e,t){return Nr(this.dir(),e,`${t}.json`)}scopeOf(e,t){return e.target.kind==="remote"?"device":ae(t??"")}async read(e,t,r){let i;try{i=await vp(e,"utf8")}catch(o){if(o.code==="ENOENT")return r();throw new Xe(e,o)}try{return xk(e,i,t)}catch(o){throw new Xe(e,o)}}readMainAccount(e){return this.read(this.accountFile(e),!1,()=>({version:2,bindings:[]}))}checkDefaultBindings(e,t){let r=t;if(r?.version!==1||!Array.isArray(r.bindings)||!r.bindings.every(i=>Ap(i,!0)&&i.id!=="__proto__")||new Set(r.bindings.map(i=>i.id)).size!==r.bindings.length)throw new Xe(e,Error("bad default bindings"));return r.bindings}async readDefaultBindings(e){let t=this.defaultFile(e);try{return this.checkDefaultBindings(t,JSON.parse(await vp(t,"utf8")))}catch(r){if(r.code==="ENOENT")return[];throw r instanceof Xe?r:new Xe(t,r)}}async readAccountParts(e){let t=await this.readMainAccount(e),r=await this.readDefaultBindings(e),i=new Set(t.bindings.map(o=>o.id));if(r.some(o=>i.has(o.id)))throw new Xe(this.defaultFile(e),Error("duplicate binding id"));return{main:t,side:r}}async readAccount(e){let{main:t,side:r}=await this.readAccountParts(e);return{...t,bindings:[...t.bindings,...r]}}readDevice(){return this.read(this.deviceFile(),!0,()=>({version:2,cadence:Lc,bindings:[]}))}updateAccount(e,t){let r=this.accountFile(e);return mn(r,async()=>{let{main:i,side:o}=await this.readAccountParts(e),a={...i,bindings:[...i.bindings,...o]},s=t(structuredClone(a));if(!s)return a;let l=s.bindings.filter(g=>ai(g.target)),c=s.bindings.filter(g=>!ai(g.target)),u=JSON.stringify(i.bindings)!==JSON.stringify(c),d=JSON.stringify(o)!==JSON.stringify(l);if(u&&d)throw Error("default_retarget_unsupported");if(u&&await je(r,{...s,bindings:c}),d){let g=this.defaultFile(e),f=this.checkDefaultBindings(g,{version:1,bindings:l});await je(g,{version:1,bindings:f})}return s})}updateDevice(e){let t=this.deviceFile();return mn(t,async()=>{let r=await this.readDevice(),i=e(structuredClone(r));return i?(await je(t,i),i):r})}};function li(){return Rp()}var ci=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n),di="Amadeus/",la="default_scope_unavailable";async function ca(n,e,t){try{let r=await n.libraries?.(t);if(!r?.some(a=>a.kind==="default"&&a.id===e&&a.vaultId===e&&a.prefix===di&&!a.deleted))throw Error("default_missing");let i=new Set,o=a=>{if(!Dc(a))throw Error("bad_legacy_prefix");i.add(a)};for(let a of r){if(a.kind==="legacy"){if(a.vaultId!==e)throw Error("bad_legacy_vault");o(a.prefix)}a.splitFrom?.vaultId===e&&o(a.splitFrom.prefix)}return[...i].sort()}catch{throw Error(la)}}function tn(n,e,t){if(n.kind!=="penzor"||!n.vaultId)return null;let r=n.vaultId.toLowerCase();return e.find(i=>i.id!==t&&i.target.kind==="penzor"&&i.target.vaultId.toLowerCase()===r&&i.target.prefix===n.prefix)??null}function Cp(n,e){if(e.mode!=="some"||n.mode!=="some"||!Array.isArray(e.items))return null;let t=[];for(let i of e.items){let o=n.items.find(a=>a.path===i?.path&&a.kind===i?.kind);if(!o)return null;t.push(o)}let r=e.exclude??[];if(!Array.isArray(r)||!r.every(Kn))throw Error("invalid_scope");return(n.exclude??[]).every(i=>r.includes(i))?{mode:"some",items:t,...r.length?{exclude:[...r]}:{}}:null}function Jn(n,e,t=process.platform==="darwin"||process.platform==="win32"){let r=s=>(t?s.toLowerCase():s).replace(/[\\/]+$/,""),i=r(n),o=r(e),a=(s,l)=>{let c=Ek(l,s);return c===""||!c.startsWith("..")&&!_p(c)&&c.split(_k)[0]!==".."};return a(i,o)||a(o,i)}function Fc(n){if(!n||n.config?.backend==="off"||n.config?.backend==="penzor")return null;let e=n.currentTargetId!==void 0?n.currentTargetId:n.targetId;return typeof e!="string"||!e||Ip(n)?null:{targetId:e,name:typeof n.root=="string"&&n.root?$c(n.root):""}}var Ip=n=>n.hold==="v2"&&n.handshake!=="released";function xp(n){if(!n||n.config?.backend==="off"||Ip(n)||typeof n.root!="string"||!n.root)return null;let e=t=>Array.isArray(t)?t.filter(r=>typeof r=="string"):[];return{root:n.root,name:$c(n.root.replace(/[\\/]+$/,"")),ignore:[...e(n.config?.ignore),...e(n.entryIgnores)]}}function Tk(n){if(typeof n!="string")return null;let e=n.trim();if(!e||e.startsWith("#")||e.startsWith("/"))return null;let t=r=>Kn(r)&&!/[*?]/.test(r)?{kind:"dir",path:r}:null;return e.endsWith("/**")?t(e.slice(0,-3)):e.endsWith("/")?t(e.slice(0,-1)):/[*?]/.test(e)||!Kn(e)?null:e.includes("/")?{kind:"file",path:e}:{kind:"name",name:e}}function Dk(n,e,t){return n.kind==="dir"?e===n.path?t:e.startsWith(n.path+"/"):n.kind==="name"?e.split("/").includes(n.name):!t&&e===n.path}function Pk(n,e){if(n.mode!=="some")return"all";let t=e.map(Tk).filter(i=>i!==null),r=(i,o)=>t.some(a=>Dk(a,i,o));return n.items.filter(i=>i.kind==="folder"?!r(i.path,!0):i.kind==="file"?!r(i.path,!1):!r(i.path,!1)||!r(`${i.path.replace(/\.md$/i,"")}.fd`,!0)).map(i=>i.path)}var Ok=(n,e,t=process.platform==="darwin"||process.platform==="win32")=>{let r=i=>(t?i.toLowerCase():i).replace(/[\\/]+$/,"");return r(n)===r(e)};function Bc(n,e,t){if(!t)return null;if(t==="unknown"){let i=e.mode==="some"?e.items.map(o=>o.path):"all";return i==="all"||i.length?{holder:sa(""),uncovered:i}:null}if(!Ok(n,t.root))return null;let r=Pk(e,t.ignore);return r==="all"||r.length?{holder:sa(t.name),uncovered:r}:null}var $r=class extends Error{code="legacy_remote_same_root";inUseBy;uncovered;constructor(e){super("legacy_remote_same_root"),this.name="LegacyRemoteSameRootError",this.inUseBy={...e.holder},this.uncovered=Array.isArray(e.uncovered)?[...e.uncovered]:e.uncovered}get failure(){return{ok:!1,error:"legacy_remote_same_root",inUseBy:{...this.inUseBy},uncovered:Array.isArray(this.uncovered)?[...this.uncovered]:this.uncovered}}};function nn(n,e,t){let r=Bc(n,e,t);if(r)throw new $r(r)}function po(n,e,t){return n.target.kind==="remote"&&n.target.direction==="push"&&!(t.kind==="remote"&&t.direction==="push")?!0:!Mk(n.scope,e)}var Pc=(n,e)=>n===e||n.startsWith(e+"/"),Tp=n=>`${n.replace(/\.md$/i,"")}.fd`,Oc=n=>n.kind==="folder"?[[n.path,!0]]:n.kind==="file"?[[n.path,!1]]:[[n.path,!1],[Tp(n.path),!0]];function Mk(n,e){if(e.mode==="all")return n.mode==="all";if(n.mode==="all")return!0;if(!Array.isArray(e.items)||!e.items.every(a=>Kn(a?.path)&&["folder","file","page"].includes(a.kind)))return!1;let t=n.exclude??[],r=Array.isArray(e.exclude)?e.exclude:[],i=(a,[s,l])=>Oc(a).some(([c,u])=>u?Pc(s,c):!l&&s===c),o=(a,s)=>Oc(a).some(([l])=>[s,Tp(s)].some(c=>Pc(l,c)||Pc(c,l)));return e.items.every(a=>{if(!Oc(a).every(l=>n.items.some(c=>i(c,l))))return!1;let s=n.items.some(l=>l.path===a.path&&l.kind===a.kind);return t.every(l=>!o(a,l)||s&&r.includes(l))})}var sa=n=>({bindingId:null,name:n,source:"remotesync"}),kp=n=>n.replace(/^\/+|\/+$/g,"").toLowerCase(),Dp=(n,e)=>n.replace(/[\\/]+$/,"")===e.replace(/[\\/]+$/,""),Nk=(n,e)=>{let t=kp(n),r=kp(e);return!t||!r||t===r||t.startsWith(r+"/")||r.startsWith(t+"/")},jc=(n,e)=>!!e?.has(n.id)&&!n.enabled&&n.state==="takeover",Pp=(n,e,t)=>n.id!==e.id&&n.target.kind==="remote"&&!jc(n,t)&&!(Dp(n.root,e.root)&&!n.enabled&&n.state!=="takeover");function $k(n,e,t={}){if(n.target.kind!=="remote")return[];let r=[[n.target.targetId,n.target.dir]];for(let i of e)Pp(i,n,t.released)&&i.target.kind==="remote"&&r.push([i.target.targetId,i.target.dir]);return t.legacy&&t.legacy!=="unknown"&&r.push([t.legacy.targetId,""]),r}async function Yn(n,e,t){t.identities&&await t.identities.prefetch($k(n,e,t))}function ho(n,e,t={}){if(n.target.kind!=="remote")return null;let{targetId:r,dir:i}=n.target,o=t.identities??null,a=!1,s=null;if(o){let d=o.peek(r,i);d?.ok?s=d.id:a=!0}let l=(d,g)=>{if(!o||s===null)return!1;let f=o.peek(d,g);return f?.ok?bp(s,f.id):((!f||f.code==="unavailable")&&(a=!0),!1)},c=null;for(let d of e)if(!(!Pp(d,n,t.released)||d.target.kind!=="remote"||!(d.target.targetId===r&&Nk(i,d.target.dir)||l(d.target.targetId,d.target.dir)))){if(Dp(d.root,n.root))return{code:"remote_dir_nested",holder:aa(d)};c??=d}if(c)return{code:"remote_dir_in_use",holder:aa(c)};let u=t.legacy;if(u==="unknown")return{code:"remote_dir_in_use",holder:sa("")};if(u&&(u.targetId===r||l(u.targetId,"")))return{code:"remote_dir_in_use",holder:sa(u.name)};if(a)throw new ra;return null}var aa=n=>({bindingId:n.id,name:$c(n.root)}),go=class extends Error{code="remote_dir_in_use";inUseBy;constructor(e){super("remote_dir_in_use"),this.name="RemoteDirInUseError",this.inUseBy={...e}}get failure(){return{ok:!1,error:"remote_dir_in_use",inUseBy:{...this.inUseBy}}}},Nc=class extends Error{code="remote_dir_nested";inUseBy;constructor(e){super("remote_dir_nested"),this.name="RemoteDirNestedError",this.inUseBy={...e}}},Uc=n=>n.code==="remote_dir_in_use"?new go(n.holder):new Nc(n.holder);function Xn(n,e,t={}){let r=ho(n,e,t);if(r)throw Uc(r)}async function mo(n,e,t,r){let i=new Set(["bindings.json","bindings.v3.json","bindings.default.json","last-sync.json"]),o=new Set([`${t}.json`,`${t}.remote.json`]),a=`${t}.bases`,s=Mc(n.stateFile(e,t)),l=await kk(s).catch(c=>{if(c.code==="ENOENT")return[];throw c});for(let c of l){let[u,d,g]=c.split(".tmp-");i.has(u)||c!==a&&(!o.has(u)||d!==void 0&&(g!==void 0||!ci(d)))||await Ep(Nr(s,c),Nr(s,`${c}.retired-${r}`)).catch(f=>{if(f.code!=="ENOENT")throw f})}}function Ke(n,e,t={}){if((t.mirrorDirs??[]).some(i=>Jn(n.root,i)))return"mirror_root";for(let i of e)if(!(i.id===n.id||!i.enabled&&i.state!=="takeover")){if(i.root.replace(/[\\/]+$/,"")===n.root.replace(/[\\/]+$/,"")){if(n.role==="primary"&&i.role==="primary")return"primary_exists";continue}if(Jn(i.root,n.root))return"root_nested"}let r=[n.root,...e.map(i=>i.root)];if(n.folderDir&&r.some(i=>Jn(i,n.folderDir)))return"folder_target_nested";for(let i of t.folderDirs??[])if(Jn(n.root,i))return"folder_target_nested";return null}import{readFile as cd,rename as ch,mkdir as sd,cp as gE,lstat as pE,open as hE,realpath as mE}from"node:fs/promises";import{join as Mn,basename as Ea}from"node:path";import{randomUUID as yE}from"node:crypto";import{constants as Mp,lstatSync as Lr,readdirSync as Fk,readFileSync as Bk,renameSync as da,unlinkSync as jk,linkSync as Uk,mkdirSync as fa,realpathSync as Hc,rmdirSync as Vk}from"node:fs";import{open as ga,lstat as ua,readdir as Np,realpath as Fp,readFile as qc,writeFile as zk,mkdir as Bp,unlink as Hk}from"node:fs/promises";import{join as Zn,dirname as Fr,relative as Wc,resolve as zc,sep as pa}from"node:path";import{randomUUID as jp,createHash as qk}from"node:crypto";var Lk=/[\u0000-\u001f\u007f]/;function Dn(n){let e=n.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||Lk.test(e))return null;let t=e.split("/");for(let r of t)if(!r||r==="."||r==="..")return null;return t.join("/")}function yo(n,e){let t=n.replace(/\\/g,"/").normalize("NFC");return e===""?Dn(t):t.startsWith(`${e}/`)?Dn(t.slice(e.length+1)):null}function Op(n,e){return e===""?n:`${e}/${n}`}var Vc=".forsion-sync-id.json";function rn(n){return!!(n===".DS_Store"||n==="Icon\r"||n===Vc||n===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(n)||/^\..+\.lock$/.test(n))}function We(n){return/\.md$/i.test(n)?"page":/\.db$/i.test(n)?"db":"binary"}var it=n=>n==="page"||n==="db";var ui=n=>`${n.size}:${n.mtime}:${n.ctime}:${n.inode}`,Qn=n=>({size:n.size,mtime:n.mtimeMs,ctime:n.ctimeMs,inode:`${n.dev}:${n.ino}:${n.birthtimeMs}`}),Up=Vc,Wk=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),$p=n=>!Wk.has(n)&&!n.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(n)&&(!n.startsWith(".")||n===".memory-tombstones.json"),Ue=n=>qk("sha256").update(n).digest("hex");function Vp(n){if(process.platform==="win32"&&n.split("/").some(e=>/[:*?"<>|]/.test(e)||/^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\..*)?$/i.test(e)))throw Error("This name is not a safe Windows file destination")}async function wt(n,e,t=!1){if(t){if(e.split("/").some(s=>s===".."||s==="."||!s)||e.startsWith("/")||e.includes("\\"))throw Error("Invalid internal content path")}else Xt(e,!0);Vp(e);let r=await Fp(n),i=Zn(r,...e.split("/").filter(Boolean)),o=Wc(r,i);if(o===".."||o.startsWith(".."+pa))throw Error("Content path escapes root");let a=r;for(let s of o.split(pa).filter(Boolean)){a=Zn(a,s);try{if((await ua(a)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(l){if(l.code!=="ENOENT")throw l}}return i}function wn(n,e,t=!1){if(t||Xt(e,!0),Vp(e),e.split("/").some(o=>o===".."||o===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let i=Hc(n);for(let o of e.split("/").filter(Boolean)){i=Zn(i,o);try{if(Lr(i).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(a){if(a.code!=="ENOENT")throw a}}return i}var Lp=n=>n?.code!=="ENOENT";async function bn(n,e={}){let t=new Map,r=[],i=[],o=new Set,a=n.filter(d=>d.prefix).map(d=>d.prefix),s=[];for(let d of n)try{s.push({...d,root:await Fp(d.root)})}catch(g){if(g.code!=="ENOENT")throw g}if(new Set(s.map(d=>d.root)).size!==s.length)throw Error("Managed roots refer to the same directory; choose a separate vault folder");let l=d=>{try{return Xt(d),!0}catch{return!1}},c=async d=>{let g;try{g=await Np(d,{withFileTypes:!0})}catch{return}for(let f of g){if(!$p(f.name)||!f.isDirectory()&&!f.isFile())continue;let p=Zn(d,f.name);try{let m=await ua(p);if(m.isSymbolicLink())continue;o.add(Qn(m).inode),m.isDirectory()&&await c(p)}catch{}}};for(let d of s){let g=d.root;if(!(await ua(g)).isDirectory())throw Error(`Sync root is not a directory: ${d.prefix||"Forsion"}`);let f=async(p,m)=>{let y;try{y=await ua(p)}catch(E){if(!m||p===g)throw E;Lp(E)&&(r.push({path:m,reason:"unreadable"}),i.push(m));return}if(y.isSymbolicLink()||p!==g&&s.some(E=>E!==d&&E.root===p)||m&&d.prefix===""&&a.some(E=>m===E||m.startsWith(E+"/")))return;if(m&&!l(m)){r.push({path:m,reason:"invalid-name"}),o.add(Qn(y).inode),y.isDirectory()&&await c(p);return}let b,h=null;if(y.isDirectory())try{if(e.markers!==!1)try{let E=JSON.parse(await qc(Zn(p,Up),"utf8"));/^[a-f0-9-]{36}$/i.test(E.id)&&(b=E.id)}catch(E){if(E.code!=="ENOENT"&&!(E instanceof SyntaxError))throw E}h=await Np(p,{withFileTypes:!0})}catch(E){if(!m||p===g)throw E;if(!Lp(E))return;r.push({path:m,reason:"unreadable"}),i.push(m);return}if(m&&t.set(m,{path:m,physical:p,root:g,kind:y.isDirectory()?"folder":"file",localId:b,...Qn(y),size:y.isFile()?y.size:0}),!!h)for(let E of h)!$p(E.name)||!E.isDirectory()&&!E.isFile()||await f(Zn(p,E.name),m?`${m}/${E.name}`:E.name)};await f(g,d.prefix)}let u=[...t.values()].sort((d,g)=>d.path.split("/").length-g.path.split("/").length||d.path.localeCompare(g.path));return Gk(u,{skipped:r,unscanned:i,skippedInodes:o})}function Gk(n,e){for(let[t,r]of Object.entries(e))Object.defineProperty(n,t,{value:r,enumerable:!1,configurable:!0});return n}var Br=(n,e)=>n.some(t=>e===t||e.startsWith(t+"/"));async function Gc(n){if(n.kind!=="folder")throw Error("Folder identity required");if(n.localId)return n.localId;let e=await wt(n.root,Wc(n.root,Zn(n.physical,Up)).split(pa).join("/"),!0),t=jp();try{let r=await ga(e,"wx",384);try{await r.writeFile(JSON.stringify({version:1,id:t})+`
|
|
204
|
+
`)}finally{await r.close()}return n.localId=t,t}catch(r){if(r.code!=="EEXIST")throw r;let i=JSON.parse(await qc(e,"utf8"));if(!/^[a-f0-9-]{36}$/i.test(i.id))throw Error("Invalid folder sync identity");return n.localId=i.id,i.id}}async function er(n){let e=await wt(n.root,Wc(n.root,n.physical).split(pa).join("/")),t=await ga(e,Mp.O_RDONLY|(Mp.O_NOFOLLOW||0));try{if((await t.stat()).size>50*1024*1024)throw Error("File exceeds 50 MB content limit");return await t.readFile()}finally{await t.close()}}function Ze(n,e){Xt(e);let t=[...n].sort((r,i)=>i.prefix.length-r.prefix.length).find(r=>!r.prefix||e===r.prefix||e.startsWith(r.prefix+"/"));if(!t)throw Error("Content root unavailable");return{root:t.root,relative:t.prefix?e.slice(t.prefix.length).replace(/^\//,""):e}}async function Jc(n,e,t,r,i=async(o,a)=>a()){let o=Ze(n,e);await Bp(o.root,{recursive:!0});let a=await wt(o.root,o.relative),s=await qc(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});if((s?Ue(s):null)!==r)throw Error("Local file changed during download");let l=Zn(o.root,`.forsion-sync-${jp()}.tmp`);try{await zk(l,t,{flag:"wx",mode:384}),await wt(o.root,o.relative),await i(a,()=>{wn(o.root,o.relative),fa(Fr(a),{recursive:!0}),wn(o.root,o.relative);let c=null;try{c=Bk(a)}catch(u){if(u.code!=="ENOENT")throw u}if((c?Ue(c):null)!==r)throw Error("Local file changed during download");da(l,a)})}finally{await Hk(l).catch(()=>{})}}async function zp(n,e){let t=Ze(n,e),r=await wt(t.root,t.relative),i=await ga(r,"r+");try{await i.sync()}finally{await i.close()}let o=zc(t.root);for(let a=Fr(r);;a=Fr(a)){try{let s=await ga(a,"r");try{await s.sync()}finally{await s.close()}}catch(s){if(!["EISDIR","EPERM","EINVAL"].includes(s?.code))throw s}if(zc(a)===o||Fr(a)===a||!zc(a).startsWith(o))return}}async function Hp(n,e,t=async(r,i)=>i()){let r=Ze(n,e);await Bp(r.root,{recursive:!0});let i=await wt(r.root,r.relative);await t([i],()=>{wn(r.root,r.relative),fa(i,{recursive:!0})})}async function Kc(n,e,t,r=async(i,o)=>o()){let i=Ze(n,e),o=Ze(n,t);if(i.root!==o.root)throw Error("Folder move crosses a managed source");let a=await wt(i.root,i.relative),s=await wt(o.root,o.relative);await r([a,s],()=>{if(wn(i.root,i.relative),wn(o.root,o.relative),Jk(s)){let c=Lr(a),u=Lr(s),d=Hc(Fr(a));if((c.dev===u.dev&&c.ino===u.ino&&d===Hc(Fr(s))?Fk(d).filter(p=>{let m=Lr(Zn(d,p));return m.dev===c.dev&&m.ino===c.ino}):[]).length!==1)throw Error("Local rename destination exists");da(a,s);return}fa(Fr(s),{recursive:!0});let l=Lr(a);if(l.isDirectory()){if(process.platform==="win32"){da(a,s);return}fa(s,{mode:448});try{da(a,s)}catch(c){try{Vk(s)}catch{}throw c}}else{Uk(a,s);let c=Lr(a);if(c.ino!==l.ino||c.dev!==l.dev)throw Error("Source changed during rename");jk(a)}})}function Jk(n){try{return Lr(n),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Yc=".forsion-vault.md",qp=n=>`${n}/${Yc}`;function ha(n){let e=/^devices:\s*(\[.*\])\s*$/m.exec(n??"");if(!e)return null;try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(r=>!!r&&typeof r.id=="string"&&typeof r.name=="string").map(r=>({id:r.id,name:r.name,...typeof r.since=="string"?{since:r.since}:{}})):null}catch{return null}}var Wp=n=>`---
|
|
205
|
+
devices: ${JSON.stringify(n.map(e=>({id:e.id,name:e.name,...e.since?{since:e.since}:{}})))}
|
|
206
|
+
---
|
|
207
|
+
`;var Ut=n=>n.replace(/\\/g,"/").normalize("NFC");function Xc(n){let e=Ut(n.path);return e?n.kind==="folder"?`${e}/`:n.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function fi(n,e,t){let r=Ut(t);if(!r)return!1;if(n.some(i=>Ut(i.path)===r))return!0;for(let i of e??[]){let o=Ut(i);if(!o)continue;let a=`${o.replace(/\.md$/i,"")}.fd`;if(r===o||r.startsWith(`${o}/`)||r===a||r.startsWith(`${a}/`))return!1}return n.some(i=>{let o=Xc(i);return!!o&&r.startsWith(o)})}function Zc(n,e,t){let r=Ut(n),i=Ut(e);return r===i?Ut(t):r.startsWith(`${i}/`)?Ut(t)+r.slice(i.length):null}function wo(n,e,t){let r=!1,i=n.map(o=>{let a=Zc(o,e,t);return a===null?o:(r=!0,a)});return{changed:r,next:i}}var Qc=null;function Gp(n){Qc=n}var Jp=null;function Kp(n){Jp=n}var Yp=()=>Jp;function Ve(){if(!Qc)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return Qc}var Ye=()=>Ve().accountId();function Sr(n=Ye()){return n?Me().sha256Hex(n):"signed-out"}var ot=(n=Ye())=>Ve().readConfig(n),kr=(n,e=Ye())=>Ve().writeConfig(n,e),gi=(n,e=Ye())=>Ve().updateConfig(n,e),ht=(n=Ye())=>Ve().cloudVaultDir(n),pi=n=>Ve().isManagedCloudVault(n);function bo(n){let e=n.replace(/\.md$/i,""),t=n.lastIndexOf("/"),r=t<0?"":n.slice(0,t);return{root:n,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function vo(n){return/\.md$/i.test(n)?bo(n):{root:n,fdPrefix:"\0",assetPrefix:"\0"}}function ma(n,e,t){return!!(e===n.root||e.startsWith(n.fdPrefix)||`${e}/`===n.fdPrefix||t==="binary"&&e.startsWith(n.assetPrefix)||t==="folder"&&(`${e}/`===n.assetPrefix||e.startsWith(n.assetPrefix)))}var Kk=n=>Me().sha256Hex(n).slice(0,8),Yk=n=>n.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",vn="\u4E0E\u6211\u5171\u4EAB";function Xp(n,e){let t=Kk(`${n.vaultId}:${n.path}`),r=n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"";return{key:t,vaultId:n.vaultId,rootPath:n.path,title:n.title,localRelDir:`${vn}/${Yk(n.title)}-${t}`,serverDir:r,scopes:e,inScope:(i,o)=>e.some(a=>ma(a,i,o)),scopeKey:e.map(i=>i.root).join("\0")}}function Zp(n){return Xp(n,[bo(n.path),...(n.items??[]).map(vo)])}function Qp(n){let e=n.map(Zp),t=n.flatMap((i,o)=>{let a=e[o].serverDir?`${e[o].serverDir}/`:"";return(i.items??[]).filter(s=>!s.startsWith(a)).map(s=>Xp({vaultId:i.vaultId,path:s,title:(s.split("/").pop()??s).replace(/\.md$/i,"")},[vo(s)]))}),r=new Map;for(let i of[...e,...t])r.has(i.key)||r.set(i.key,i);return[...r.values()]}var Xk=n=>{let e=[];for(let t of n.split("/"))!t||t==="."||(t===".."&&e.length&&e[e.length-1]!==".."?e.pop():e.push(t));return e.join("/")};function eh(n,e){let t=l=>l.normalize("NFC"),r=t(e.replace(/\\/g,"/")),i=n.find(l=>r.startsWith(`${t(l.localRelDir)}/`));if(!i)return null;let o=r.slice(t(i.localRelDir).length+1),a=Xk(i.serverDir?`${i.serverDir}/${o}`:o);if(!a||a===".."||a.startsWith("../"))return null;let s=[i,...n].find(l=>l.vaultId===i.vaultId&&(!l.serverDir||a.startsWith(`${l.serverDir}/`))&&l.inScope(a,We(a)));return s?`${s.localRelDir}/${s.serverDir?a.slice(s.serverDir.length+1):a}`:null}function ed(){let n=Ve().readCreds(),e=rt(n.cloudUrl??"",n.token??""),t=new AbortController,r=()=>{let d=Ve().readCreds();if(t.signal.aborted||!e||rt(d.cloudUrl??"",d.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return d},i=()=>{let d=r();if(!d.cloudUrl||!d.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return d.cloudUrl.replace(/\/+$/,"")},o=async(d,g,f)=>{let p=r();if(!p.cloudUrl||!p.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let m=await fetch(`${p.cloudUrl.replace(/\/+$/,"")}/api/amadeus${g}`,{method:d,headers:{Authorization:`Bearer ${p.token}`,...f!==void 0?{"Content-Type":"application/json"}:{}},body:f!==void 0?JSON.stringify(f):void 0,signal:AbortSignal.any([t.signal,AbortSignal.timeout(2e4)])});if(!m.ok){let b=null;try{b=await m.json()}catch{}throw Object.assign(new Error(b?.detail||`http ${m.status}`),{status:m.status,code:b?.code})}let y=await m.json();return r(),y},a=null,s=async()=>(r(),a||(a=(await o("GET","/vaults")).vaults[0]?.id??"default",a)),l=()=>{try{let d=(r().token??"").split(".")[1],g=JSON.parse(Yt(Ns(d)));return typeof g.userId=="string"?g.userId:null}catch{return null}},c=async()=>(await o("GET","/shared-with-me")).items.map(g=>{let f=Zp(g),p=g.path.split("/").pop()??g.path;return{...g,localPath:`${f.localRelDir}/${p}`}}),u=null;return{stop:()=>t.abort(),call:o,ensureOwnVault:s,myUserId:l,sharedWithMe:c,linkBase:async()=>{if(r(),u)return u;try{u=((await o("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||i()}catch{u=i()}return u},async heartbeat(d,g){let f=(d??"").replace(/\\/g,"/"),p,m=null,y=g.find(b=>f.startsWith(`${b.localRelDir}/`));y?(p=y.vaultId,m=y.serverDir?`${y.serverDir}/${f.slice(y.localRelDir.length+1)}`:f.slice(y.localRelDir.length+1)):(p=await s(),m=f||null),await o("POST",`/vaults/${encodeURIComponent(p)}/presence`,{page:m})}}}var hi=n=>Me().sha256Hex(n).slice(0,8);function th(n){return n.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Pn(n,e=[]){let t=[],r=[];for(let i of n){let o=Ut(i.path);if(!o)continue;r.push(o);let a=Xc(i);a&&t.push(a)}return{entries:n,exclude:e,prefixes:t,paths:r}}function ya(n,e){let t=th(Ut(e));if(!t)return!1;if(fi(n.entries,n.exclude,t))return!0;let r=`${t}/`;for(let i of n.paths)if(i.startsWith(r))return!0;for(let i of n.prefixes)if(i.startsWith(r))return!0;return!1}function So(n,e,t){let r=!1,i=n.map(o=>{let a=Zc(o.path,e,t);return a===null?o:(r=!0,{...o,path:a})});return{changed:r,next:i}}function nh(n,e,t,r){if(e==="delete"||e==="delete-folder"){let i=Ut(t),o=n.filter(a=>{let s=Ut(a.path);return!(s===i||e==="delete-folder"&&s.startsWith(`${i}/`))});return{changed:o.length!==n.length,next:o}}return r?So(n,t,r):{changed:!1,next:n}}function td(n,e){let t=Dn(n);return!t||t!==n.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":t.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":t===vn?`\u300C${vn}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(t)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}var Zk=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],Qk=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],ko=".memory-tombstones.json",ih=n=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(n),rh=n=>n==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(n),eE=n=>/^\d{4}-\d{2}-\d{2}$/.test(n)&&Number.isFinite(Date.parse(`${n}T00:00:00Z`))&&new Date(`${n}T00:00:00Z`).toISOString().slice(0,10)===n,tE=n=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(n)&&!n.startsWith("__");function nE(n){if(!n||n.length>1024||/[\\\x00-\x1f:]/.test(n))return!1;if(n===ko)return!0;let e=n.split("/");return e.some(t=>!t||t.startsWith(".")||t.endsWith(".")||t.endsWith(" "))?!1:Zk.includes(n)||ih(n)?!0:n.startsWith("LOG/")?e.length===2&&n.endsWith(".md")&&eE(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var rE=n=>n==="muse"||/^historian-[a-z0-9]{1,12}$/.test(n),iE=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,oE=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function Ot(n){let e=n.slice(n.lastIndexOf("/")+1);return iE.test(e)||oE.test(e)}function oh(n,e,t=1){let r=n.lastIndexOf("/"),i=r<0?"":n.slice(0,r+1),o=r<0?n:n.slice(r+1),a=o.lastIndexOf("."),s=a>0?o.slice(0,a):o,l=a>0?o.slice(a):"",c=d=>String(d).padStart(2,"0"),u=`${e.getFullYear()}-${c(e.getMonth()+1)}-${c(e.getDate())} ${c(e.getHours())}${c(e.getMinutes())}${t>1?` ${t}`:""}`;return`${i}${s} (conflict ${u})${l}`}function nd(n,e="file"){if(n==="agents"||n==="human")return e==="folder";let t=n.startsWith("human/"),r=n.startsWith("agents/");if(!t&&!r)return null;if(Ot(n))return!1;if(t){let c=n.slice(6);return e==="folder"?rh(c):Qk.includes(c)||ih(c)}let i=n.slice(7),o=i.indexOf("/"),a=o<0?i:i.slice(0,o),s=o<0?"":i.slice(o+1);if(!tE(a)||rE(a))return!1;if(e==="file")return nE(s);if(s===""||s==="LOG"||rh(s))return!0;let l=s.split("/");return l[0]==="Library"&&l.every(c=>c&&!c.startsWith(".")&&!c.endsWith(".")&&!c.endsWith(" "))}var sE=n=>Math.max(3,Math.ceil(n*.1)),aE=(n,e)=>n===429&&e!=="MASS_DELETE_BLOCKED";function lE(n,e=Date.now()){if(!n)return null;let t=n.trim();if(/^\d+$/.test(t))return Number(t)*1e3;let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-e)}function cE(n){let e=n.get("ratelimit"),t,r,i;if(e){let o=a=>Number(new RegExp(`(?:^|[;,\\s])${a}=(\\d+)`).exec(e)?.[1]??NaN);t=o("limit"),r=o("remaining"),i=o("reset")}else t=Number(n.get("ratelimit-limit")??NaN),r=Number(n.get("ratelimit-remaining")??NaN),i=Number(n.get("ratelimit-reset")??NaN);return![t,r,i].every(o=>Number.isFinite(o)&&o>=0)||t<=0?null:{limit:t,remaining:r,resetMs:i*1e3}}function dE(n={}){let e=n.now??Date.now,t=0,r=null,i=new Set,o=()=>{for(let s of[...i])try{s()}catch{}},a=s=>{let l=e()+Math.min(Math.max(s,0),6e5);l<=t||(t=l,r&&clearTimeout(r),r=setTimeout(()=>{r=null,o()},t-e()),r.unref?.(),o())};return{until:()=>t>e()?t:null,async ready(s){for(;t>e();)s?.throwIfAborted(),await new Promise((l,c)=>{let u=setTimeout(d,t-e());function d(){s?.removeEventListener("abort",g),l()}function g(){clearTimeout(u),c(s.reason??new DOMException("Aborted","AbortError"))}s?.addEventListener("abort",g,{once:!0})});s?.throwIfAborted()},observe(s,l,c,u){let d=cE(l);if(aE(s,c)){let g=lE(l.get("retry-after"),e())??(typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null)??(d&&d.remaining===0&&d.resetMs>0?d.resetMs:null);return a(Math.max(g??3e4,1e3)),!0}return d&&d.remaining<=sE(d.limit)&&d.resetMs>0&&a(d.resetMs),!1},subscribe(s){return i.add(s),()=>{i.delete(s)}}}}var sh=new Map;function On(n){let e;try{e=new URL(n).origin}catch{e=n.replace(/\/+$/,"")}let t=sh.get(e);return t||(t=dE(),sh.set(e,t)),t}var wa=["vaults","vault-moves"],tr=[mr,...wa].join(","),ah=n=>n?[mr,...wa]:[mr,"vaults"];var rd=tr,lh=6e4;function id(n,e){let t=n;if(!Array.isArray(t?.libraries))throw Error("bad_library_list");let r=s=>typeof s=="string",i=s=>Number.isSafeInteger(s)&&s>=0,o=r(t.generatedAt)?t.generatedAt:e;if(!o)throw Error("bad_library_list");let a=t.libraries.map(s=>{if(!s||!r(s.id)||!r(s.vaultId)||!r(s.prefix)||!r(s.name)||!(s.kind==="default"||s.kind==="own"||s.kind==="legacy")||!(s.nameKey===null||r(s.nameKey))||!i(s.files)||!i(s.bytes)||!Array.isArray(s.devices))throw Error("bad_library_list");let l=s.devices.map(f=>{if(!f||!r(f.deviceId)||!r(f.name))throw Error("bad_library_list");return{deviceId:f.deviceId,name:f.name,scope:f.scope==="some"?"some":"all",lastSyncAt:r(f.lastSyncAt)?f.lastSyncAt:null,caps:Array.isArray(f.caps)?f.caps.filter(r):[],clientVersion:r(f.clientVersion)?f.clientVersion:null}}),c=s.markerDevices,u=c===null?null:Array.isArray(c)?c.filter(f=>!!f&&r(f.id)&&r(f.name)).map(f=>({id:f.id,name:f.name,...r(f.since)?{since:f.since}:{},...typeof f.superseded=="boolean"?{superseded:f.superseded}:{}})):void 0,d=uE(s.splitFrom),g=s.deleted;return{id:s.id,kind:s.kind,vaultId:s.vaultId,prefix:s.prefix,name:s.name,nameKey:s.nameKey,files:s.files,bytes:s.bytes,updatedAt:r(s.updatedAt)?s.updatedAt:null,devices:l,...u!==void 0?{markerDevices:u}:{},...typeof s.protectedRoot=="boolean"?{protectedRoot:s.protectedRoot}:{},...g&&typeof g=="object"&&r(g.at)&&r(g.purgeAt)?{deleted:{at:g.at,purgeAt:g.purgeAt,...g.purging===!0?{purging:!0}:{}}}:{},...d?{splitFrom:d}:{}}});return{generatedAt:o,libraries:a}}function uE(n){let e=n,t=i=>typeof i=="string";if(!e||typeof e!="object"||Array.isArray(e)||!t(e.splitId)||!t(e.vaultId)||!t(e.prefix)||!t(e.at))return;let r=Array.isArray(e.deleteBlocked)?e.deleteBlocked.filter(i=>!!i&&typeof i=="object"&&t(i.code)&&t(i.detail)).map(i=>({code:i.code,detail:i.detail,...Array.isArray(i.items)?{items:i.items}:{}})):[];return{splitId:e.splitId,vaultId:e.vaultId,prefix:e.prefix,at:e.at,...r.length?{deleteBlocked:r}:{}}}var ze=class extends Error{status;code;constructor(e,t,r){super(r),this.status=e,this.code=t,this.name="PenzorHttpError"}};function ba(n){let e=n.filter(r=>r.isDefault===!0);if(e.length)return e[0];let t=n.filter(r=>r.name===yr);return t.length?[...t].sort((r,i)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")))[0]:null}var Eo=n=>n.kind!=="file"||typeof n.file=="string"&&n.file.length>0;function _o(n,e){let t=()=>{let a=n.readCreds();return{account:rt(a.cloudUrl||"",a.token||""),api:_o({readCreds:()=>a},e)}},r=()=>t().api,i=async(a,s={})=>{let l=n.readCreds();if(!l.token)throw new ze(401,"not_signed_in","not_signed_in");await On(l.cloudUrl).ready(s.signal??new AbortController().signal);let u=AbortSignal.timeout(lh),d=s.signal?AbortSignal.any([s.signal,u]):u,g=await fetch(l.cloudUrl.replace(/\/+$/,"")+a,{...s,signal:d,headers:{Authorization:`Bearer ${l.token}`,"X-Content-Device":e(),"X-Content-Caps":rd,...s.body?{"Content-Type":"application/json"}:{},...s.headers??{}}});if(!g.ok){let f=await g.json().catch(()=>null)??{};throw new ze(g.status,typeof f.code=="string"?f.code:void 0,typeof f.detail=="string"?f.detail:typeof f.error=="string"?f.error:`http_${g.status}`)}return g},o=async a=>id(await(await i("/api/amadeus/libraries",{signal:a})).json(),new Date().toISOString());return{pinned:r,snapshot:t,async vaults(a){let s=await(await i("/api/amadeus/vaults",{signal:a})).json();if(!Array.isArray(s?.vaults))throw Error("bad_vault_list");return s.vaults.filter(l=>l&&typeof l.id=="string"&&typeof l.name=="string")},async resolve(a,s){let l=await(await i("/api/amadeus/vaults/resolve",{method:"POST",body:JSON.stringify({name:a}),signal:s})).json();if(!Array.isArray(l?.candidates))throw Error("bad_resolve");return l.candidates.filter(c=>c&&(c.kind==="own"||c.kind==="legacy")&&typeof c.vaultId=="string")},async createVault(a,s){let l=await(await i("/api/amadeus/vaults",{method:"POST",body:JSON.stringify({name:a}),signal:s})).json();if(!l?.vault||typeof l.vault.id!="string")throw Error("bad_vault");return l.vault},async renameVault(a,s,l){let c=await(await i(`/api/amadeus/vaults/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({name:s}),signal:l})).json();if(!c?.vault||typeof c.vault.id!="string")throw Error("bad_vault");return c.vault},async manifest(a,s){let l=await(await i(`/api/remotesync/content/${encodeURIComponent(a)}`,{signal:s})).json();if(!l||!Array.isArray(l.nodes))throw Error("bad_manifest");return l},async putDevice(a,s){await i(`/api/remotesync/content/devices/${encodeURIComponent(e())}`,{method:"PUT",body:JSON.stringify(a),signal:s})},async libraries(a){return(await o(a)).libraries},libraryList:o,async sharedWithMe(){let a=AbortSignal.timeout(lh),s=await(await i("/api/amadeus/shared-with-me",{method:"GET",signal:a})).json();if(!Array.isArray(s?.items)||s.items.some(l=>typeof l?.vaultId!="string"||!l.vaultId))throw Error("bad_shared_list");return s.items},async devices(a){let s=await(await i("/api/remotesync/content/devices",{signal:a})).json();if(!Array.isArray(s?.devices))throw Error("bad_device_list");let l=c=>typeof c=="string";return s.devices.filter(c=>!!c&&l(c.id)&&l(c.name)).map(c=>({id:c.id,name:c.name,...l(c.lastSeen)?{lastSeen:c.lastSeen}:{},...Array.isArray(c.vaults)?{vaults:c.vaults.filter(u=>!!u&&l(u.vaultId)&&l(u.prefix)).map(u=>({vaultId:u.vaultId,prefix:u.prefix,...l(u.scope)?{scope:u.scope}:{},...u.lastSyncAt===null||l(u.lastSyncAt)?{lastSyncAt:u.lastSyncAt}:{}}))}:{}}))}}}var va=new Map,od=new Set(["done","reverted","refused"]),jr=new Set(["remote_dir_in_use","remote_dir_nested","primary_exists","target_identity_unavailable","root_nested"]);function Ao(n){return n.kind==="remote"?`remote|${n.targetId}|${n.dir}`:`penzor|${n.vaultId}|${n.ns}|${n.prefix}|${n.placement}`}var dh=null;function uh(n){dh=n}function fd(){return dh}var ld=null,fE=15e3;function gd(n){ld=n}async function fh(n,e){return ld?ld(n,e):new Set}var ad=3,Sa=new Set(["sealed","round-running","done"]),Ro=new Set(["reverted","refused"]);function wE(n,e=[]){return{mode:"some",items:n.map(t=>({path:t.path,kind:t.kind==="asset"?"file":t.kind})),...e.length?{exclude:e}:{}}}function Vt(n){if(n.mode==="all")return t=>!!t&&!Ot(t);let e=Pn(n.items.map(t=>({path:t.path,kind:t.kind==="file"?"asset":t.kind})),n.exclude??[]);return t=>!!t&&!Ot(t)&&ya(e,t)}var bE=n=>{let e=n;return e?.name==="AbortError"||e?.name==="TimeoutError"||e?.name==="TypeError"&&/fetch/i.test(String(n.message))||["ECONNREFUSED","ECONNRESET","ENOTFOUND","ETIMEDOUT","EAI_AGAIN"].includes(e?.code??e?.cause?.code??"")||(e?.status??0)>=500},bt=n=>String(n?.message??n).slice(0,300),ka=async n=>{try{return await pE(n),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}},dd=n=>n.replace(/[\\/]+$/,"");async function pe(n){try{return dd(await mE(n))}catch{return dd(n)}}var ud=class{home;constructor(e){this.home=e}file(){return Mn(this.home(),"vault-sync","takeover.json")}async read(){let e;try{e=await cd(this.file(),"utf8")}catch(t){if(t.code==="ENOENT")return{version:1,entries:[]};throw new Xe(this.file(),t)}try{let t=JSON.parse(e);if(t?.version!==1||!Array.isArray(t.entries)||!t.entries.every(r=>r&&typeof r.source=="string"&&typeof r.root=="string"&&typeof r.phase=="string"&&typeof r.archiveDir=="string"&&Number.isSafeInteger(r.attempts)))throw Error("bad shape");return t}catch(t){throw new Xe(this.file(),t)}}update(e){let t=this.file();return mn(t,async()=>{let r=await this.read(),i=e(structuredClone(r));return i?(await je(t,i),i):r})}},vE=(n,e)=>n.source===e.source&&n.root===e.root&&n.account===e.account,vt=class n{dir;constructor(e){this.dir=e}static fresh(e,t=Date.now()){return new n(Mn(e,"sync-takeover",`${new Date(t).toISOString().replace(/[:.]/g,"-")}-${yE().slice(0,8)}`))}async ensure(){await sd(this.dir,{recursive:!0,mode:448})}async log(e){await this.ensure();let t=await hE(Mn(this.dir,"log.jsonl"),"a",384);try{await t.write(JSON.stringify({at:Date.now(),...e})+`
|
|
208
|
+
`),await t.datasync()}finally{await t.close()}}async copy(e,t){if(!await ka(e))return!1;let r=Mn(this.dir,"copied",t,Ea(e));return await sd(Mn(this.dir,"copied",t),{recursive:!0,mode:448}),await gE(e,r,{recursive:!0,force:!0,preserveTimestamps:!0}),await this.log({event:"copied",from:e,to:r}),!0}async writeJson(e,t){await this.ensure(),await je(Mn(this.dir,e),t)}async move(e,t){if(!await ka(e))return null;let r=Mn(this.dir,"moved",t);await sd(r,{recursive:!0,mode:448});let i=Mn(r,Ea(e));for(let o=2;await ka(i);o++)i=Mn(r,`${Ea(e)}~${o}`);return await ch(e,i),await this.log({event:"moved",from:e,to:i}).catch(()=>{}),{from:e,to:i}}async moveBack(e){for(let t of[...e].reverse())await ka(t.from)||(await ch(t.to,t.from),await this.log({event:"moved-back",from:t.to,to:t.from}).catch(()=>{}))}},_a=class{ledger;accounts=new Map;legacyMemo=new Map;hooks=null;revertingNow=new Set;deviceArchive=null;deps;constructor(e){this.deps=e,this.ledger=new ud(e.home)}attach(e){this.hooks=e}now(){return this.deps.now?.()??Date.now()}say(e){this.deps.log?.(`[vault-sync] ${e}`)}stateOf(e){let t=this.accounts.get(e);return t||(t={live:new Set,inflight:null,attempted:new Set},this.accounts.set(e,t)),t}ownership(){let e=this.deps.host.contentSync?.ownership;if(!e)throw Error("ownership_unavailable");return e}legacyContentFile(e){return Mn(this.deps.home(),"content-sync",`${ae(e)}.json`)}legacyContentState(e){let t=ae(e),r=this.legacyMemo.get(t);return r||(r=(async()=>{let i;try{i=JSON.parse(await cd(this.legacyContentFile(e),"utf8"))}catch(a){return a.code==="ENOENT"?"absent":"unreadable"}try{Gn(i)}catch{return"unreadable"}let o=i;return o.accountReview||o.releasing?"review":o.config?.enabled&&o.owned?"active":"off"})(),this.legacyMemo.set(t,r)),r}liveRoots(e){return new Set(this.stateOf(ae(e)).live)}async mayRun(e,t){if(e.state!=="takeover")return!0;let r=t===null?null:ae(t),i=(await this.ledger.read()).entries.find(o=>o.bindingId===e.id&&o.account===r);return!!i&&i.pendingFinish===void 0&&Sa.has(i.phase)}async releasedBindings(){let e;try{e=(await this.ledger.read()).entries}catch{return new Set}return new Set(e.filter(t=>Ro.has(t.phase)&&typeof t.bindingId=="string"&&t.bindingId).map(t=>t.bindingId))}async roundStarting(e){await this.ledger.update(t=>{let r=t.entries.find(i=>i.bindingId===e&&i.phase==="sealed"&&i.pendingFinish===void 0);if(r)return r.phase="round-running",r.updatedAt=this.now(),t}),await this.deps.crashPoint?.("round-running")}async roundFinished(e,t,r,i,o,a){let l=(await this.ledger.read()).entries.find(p=>p.bindingId===e);if(!l||l.pendingFinish!==void 0||Ro.has(l.phase))return;let c=async p=>{let m=y=>{let b=y.bindings.find(h=>h.id===e);if(!(!b||!b.enabled||b.state!=="takeover"||a!==void 0&&b.generation!==a))return b.state="active",delete b.firstRound,delete b.reason,(l.source==="entry"||l.source==="remotesync")&&(b.takeoverCard=p),y};l.account&&t?await this.deps.store.updateAccount(t,m):await this.deps.store.updateDevice(m)};if(l.phase==="done"){let p=l.stats;await c({adopted:p?.adopted??0,filled:p?.filled??0,held:o,revived:p?.revived??0});return}let u=(l.stats?.revived??0)+i.revived,d={adopted:(l.stats?.adopted??0)+i.adopted,filled:(l.stats?.filled??0)+i.filled,revived:Math.max(u,l.revivedHint?.length??0),held:o};if(!r){await this.ledger.update(p=>{let m=p.entries.find(y=>y.bindingId===e);if(!(!m||m.pendingFinish!==void 0))return m.stats={...d,revived:u},m.updatedAt=this.now(),p});return}let g={adopted:d.adopted,filled:d.filled,held:d.held,revived:d.revived},f=!1;await this.ledger.update(p=>{let m=p.entries.find(y=>y.bindingId===e);if(!(!m||m.pendingFinish!==void 0||m.phase!=="round-running"&&m.phase!=="sealed"))return m.phase="done",m.stats=d,m.updatedAt=this.now(),f=!0,p}),f&&(await c(g),await new vt(l.archiveDir).log({event:"done",source:l.source,root:l.root,stats:d}).catch(()=>{}))}async gate(e,t){let r=ae(e),i=this.stateOf(r);if(i.inflight)return this.answer(i,t);let o=new AbortController,a=this.runGate(e,t,i,o.signal).catch(c=>{this.say(`takeover gate: ${bt(c)}`)});i.inflight=a,a.finally(()=>{i.inflight===a&&(i.inflight=null)});let s,l=await Promise.race([a.then(()=>!1),new Promise(c=>{s=setTimeout(()=>c(!0),this.deps.gateMs??fE)})]);return clearTimeout(s),l&&(o.abort(new Error("takeover_gate_timeout")),this.say("takeover gate timed out; entry engines start as before")),this.answer(i,t)}async answer(e,t){let r=new Set(e.live);for(let i of t.entrySync)(r.has(dd(i.vaultRoot))||r.has(await pe(i.vaultRoot)))&&r.add(i.vaultRoot);return r}async runGate(e,t,r,i){let o=ae(e),a=await this.ledger.read(),s=await this.legacyContentState(e),l=await this.ownership().get(e),c=new Set(await Promise.all(l.entryRoots.map(pe))),u=a.entries.filter(b=>b.account===o&&b.source==="entry"&&b.phase==="reverted"&&c.has(b.root)&&!this.revertingNow.has(b.root));if(u.length)try{let b=new Set(u.flatMap(E=>[E.root,...E.formerRoots??[]])),h=[];for(let E of l.entryRoots)b.has(await pe(E))||h.push(E);for(let E of b)r.live.delete(E),c.delete(E);await this.ownership().set({...l,entryRoots:h},e);for(let E of u)E.bindingId&&await this.dropBinding(e,E.bindingId).catch(v=>this.say(`revert binding ${E.root}: ${bt(v)}`)),await new vt(E.archiveDir).log({event:"reverted",root:E.root,by:"resume"}).catch(()=>{})}catch(b){this.say(`resume revert: ${bt(b)}`)}let d=new Map;for(let b of t.entrySync)b.entries.length&&d.set(await pe(b.vaultRoot),b);for(let b of a.entries){if(b.account!==o||b.source!=="entry"||!Sa.has(b.phase))continue;if(c.has(b.root)){r.live.add(b.root);continue}let h=d.get(b.root);if(!(!h||r.attempted.has(b.root))){if(i.aborted)return;r.attempted.add(b.root),await this.reseal(e,b,t,r,h.vaultRoot,i).catch(E=>this.say(`reseal ${b.root}: ${bt(E)}`))}}if(s==="unreadable"||s==="review"||s==="active")return;let g=null,f=b=>b?.archiveDir?new vt(b.archiveDir):g??=vt.fresh(this.deps.home(),this.now()),p=null,m=a.entries.some(b=>b.source==="content-off"&&b.account===o&&b.phase!=="done"&&b.phase!=="refused"),y=()=>p??=s==="off"||m?this.sealContentOff(e,a,f,i).catch(b=>(this.say(`content-off seal: ${bt(b)}`),!1)):Promise.resolve(!0);for(let b of a.entries){if(b.account!==o||b.source!=="entry"||b.phase!=="archived"||!c.has(b.root)||d.has(b.root)||r.attempted.has(b.root))continue;if(i.aborted)return;r.attempted.add(b.root);let h=await y();if(i.aborted)return;h&&await this.seal(e,b,t,r,b.rawRoot??b.root,i).catch(E=>this.say(`resume seal ${b.root}: ${bt(E)}`))}for(let[b,h]of d){if(i.aborted)return;if(r.attempted.has(b))continue;let E=a.entries.find(v=>v.source==="entry"&&v.root===b&&v.account===o);if(!(E&&(Ro.has(E.phase)||Sa.has(E.phase)))){if(E&&E.attempts>=ad){await this.refuse(E,"takeover_failed");continue}r.attempted.add(b);try{let v=E;if((!v||v.phase==="detected")&&(v=await this.detect(e,b,h,t,v,f(v),i),!v||v.phase!=="archived"))continue;if(i.aborted)return;let k=await y();if(i.aborted)return;if(!k){await this.fail(v,"content_sync_leftover_not_archived",!1);continue}await this.seal(e,v,t,r,h.vaultRoot,i)}catch(v){if(this.say(`takeover ${b}: ${bt(v)}`),v instanceof Xe)throw v}}}}async detect(e,t,r,i,o,a,s){let l=ae(e),c=`Amadeus/${r.cloudName}`,u=D=>`${D}|default|${c}/`,d=o??{source:"entry",root:t,account:l,phase:"detected",originalOwnership:await this.ownership().get(e),targetFingerprint:"",archiveDir:a.dir,attempts:0,updatedAt:this.now()};d.rawRoot=r.vaultRoot,o||(d=await this.put(d));let g=this.deps.api(),f,p;try{await dt(t),f=await g.vaults(s),p=await g.manifest("default",s)}catch(D){await this.fail(d,bt(D),!bE(D));return}let m=p.moved;if(Array.isArray(m)&&m.some(D=>D?.prefix===`${c}/`)){await this.fail(d,"vault_moved",!1);return}let y=ba(f),b=i.cloudSync?.vaultId||f[0]?.id;if(!y||b!==y.id){await this.refuse(d,"non_default_vault");return}d.targetFingerprint=u(y.id);let E=p.nodes.filter(D=>!D.deleted).filter(D=>D.kind==="file");if(E.length&&!E.some(D=>typeof D.file=="string"&&D.file)){await this.fail({...d,reason:"no_backing_identity"},"manifest_without_backing",!1);return}let v=wE(r.entries,r.exclude??[]),k=Vt(v),C=D=>D.startsWith(c+"/")?D.slice(c.length+1):null,S=[];for(let D of E){let M=C(D.path);if(!(M===null||!k(M))){if(!Eo(D)){S.push({path:D.path,id:D.id,size:D.size});continue}if((D.size??0)>Qt(D.path,"default",p.limits)){await this.refuse(d,"too_large_for_new_sync");return}}}let _;try{_=await bn([{prefix:c,root:t}],{markers:!1})}catch(D){await this.fail(d,bt(D),!0);return}if(_.unscanned.some(D=>{let M=C(D);return M===null||k(M)})){await this.fail(d,"scope_unreadable",!0);return}for(let D of _){if(D.kind!=="file")continue;let M=C(D.path);if(M!==null&&k(M)&&D.size>Qt(D.path,"default",p.limits)){await this.refuse(d,"too_large_for_new_sync");return}}let R=[];try{let D=JSON.parse(await cd(i.shadowFiles(r.vaultRoot)[0],"utf8")),M=new Set(E.map($=>$.path)),x=new Set(_.filter($=>$.kind==="file").map($=>$.path));for(let $ of Object.keys(D?.files??{})){let O=`Amadeus/${$}`,q=C(O);q!==null&&k(q)&&!M.has(O)&&x.has(O)&&R.push(q)}}catch(D){if(D.code!=="ENOENT"){await this.fail(d,bt(D),!0);return}}if(d.revivedHint=R.sort(),s.aborted)return;let N=null;try{let D=new vt(d.archiveDir);await D.log({event:"detected",source:"entry",root:t,cloudName:r.cloudName,vaultId:y.id});for(let $ of i.shadowFiles(r.vaultRoot))await D.copy($,"userData");await D.writeJson(`entry-config-${ae(t).slice(0,8)}.json`,{entrySync:r,cloudSync:i.cloudSync??null,ownership:d.originalOwnership}),await D.writeJson(`other-backed-${ae(t).slice(0,8)}.json`,S),await D.writeJson(`revived-${ae(t).slice(0,8)}.json`,d.revivedHint);let M=await dt(t),x=await Ae(async()=>{let $=(await this.deps.store.readDevice()).bindings;return this.deps.store.updateAccount(e,O=>{let q=O.bindings.find(ce=>ce.root===t&&ce.target.kind==="penzor"&&ce.target.placement==="legacy-entry"&&ce.state==="takeover");if(q){N=null,d.bindingId=q.id;return}let ie=Ke({root:t,role:"primary"},[...O.bindings,...$]);if(ie)throw Object.assign(Error(ie),{refuse:!0});let Y={kind:"penzor",vaultId:y.id,ns:"default",prefix:`${c}/`,placement:"legacy-entry"};if(tn(Y,O.bindings))throw Object.assign(Error("already_local"),{refuse:"already_local"});let ne=li();return N=ne,d.bindingId=ne,O.bindings.push({id:ne,root:t,rootIdentity:M,nameKey:Le(Ea(t)),target:Y,scope:v,enabled:!0,paused:!1,state:"takeover",role:"primary",generation:1,firstRound:"takeover",createdAt:this.now()}),O})});return d=await this.put({...d,phase:"archived",lastError:void 0,reason:void 0,updatedAt:this.now()}),await D.log({event:"archived",root:t,bindingId:d.bindingId}),await this.deps.crashPoint?.("archived"),d}catch(D){N&&await this.deps.store.updateAccount(e,x=>(x.bindings=x.bindings.filter($=>$.id!==N),x)).catch(()=>{});let M=D.refuse;if(M){await this.refuse(d,M===!0?"double_engine":M);return}if(await this.fail({...d,bindingId:void 0},bt(D),!0),D instanceof Xe)throw D;return}}async seal(e,t,r,i,o,a){let s=new vt(t.archiveDir);if(t.resetBaseline){let g=(await this.deps.store.readAccount(e)).bindings.find(f=>f.id===t.resetBaseline);if(g){await this.hooks?.stopBinding(g.id);let f=this.deps.store.stateFile(this.deps.store.scopeOf(g,e),g.id);for(let p of[f,f.replace(/\.json$/,".bases")]){let m=await s.move(p,"vault-sync-reseal");m&&await s.log({event:"moved",...m}).catch(()=>{})}}t=await this.put({...t,resetBaseline:void 0,updatedAt:this.now()})}let l=this.ownership(),c=await l.get(e);if(a.aborted)return;i.live.add(t.root);let u=[],d=!1;try{await s.log({event:"seal-begin",root:t.root}),(await Promise.all(c.entryRoots.map(pe))).includes(t.root)||(await l.set({entryRoots:[...c.entryRoots,t.root],mirror:"keep",human:c.human},e),d=!0),await this.deps.crashPoint?.("ownership-set");for(let g of r.shadowFiles(o)){let f=await s.move(g,"userData");f&&u.push(f)}await this.deps.crashPoint?.("moved"),await this.put({...t,phase:"sealed",lastError:void 0,updatedAt:this.now()}),await s.log({event:"sealed",root:t.root,moved:u.length}),await this.deps.crashPoint?.("sealed")}catch(g){i.live.delete(t.root),await s.moveBack(u).catch(f=>this.say(`move back ${t.root}: ${bt(f)}`)),d&&await l.set(c,e).catch(f=>this.say(`ownership restore ${t.root}: ${bt(f)}`)),await s.log({event:"seal-failed",root:t.root,error:bt(g)}).catch(()=>{}),await this.fail(t,bt(g),!0)}}async reseal(e,t,r,i,o,a){if(a.aborted)return;t.bindingId&&await this.deps.store.updateAccount(e,l=>{let c=l.bindings.find(u=>u.id===t.bindingId);if(c)return c.state="takeover",c.firstRound="takeover",l});let s=await this.put({...t,phase:"archived",stats:void 0,revivedHint:void 0,lastError:void 0,...t.bindingId?{resetBaseline:t.bindingId}:{},updatedAt:this.now()});await new vt(t.archiveDir).log({event:"reseal-begin",root:t.root}).catch(()=>{}),await this.seal(e,s,r,i,o,a)}async sealContentOff(e,t,r,i){let o=ae(e),a=t.entries.find(d=>d.source==="content-off"&&d.account===o);if(a&&(a.phase==="done"||Sa.has(a.phase)))return!0;if(a&&a.phase==="refused")return!1;let s=this.legacyContentFile(e),l=s.replace(/\.json$/,".bases"),c=r(a);a||(a=await this.put({source:"content-off",root:"",account:o,phase:"detected",originalOwnership:null,targetFingerprint:"",archiveDir:c.dir,attempts:0,updatedAt:this.now()}));let u=[];try{if((a.phase==="detected"||a.phase==="reverted")&&(await c.copy(s,"content-sync"),await c.copy(l,"content-sync"),a=await this.put({...a,phase:"archived",updatedAt:this.now()})),i.aborted)return!1;for(let d of[s,l]){let g=await c.move(d,"content-sync");g&&u.push(g)}return await this.put({...a,phase:"done",lastError:void 0,updatedAt:this.now()}),await c.log({event:"content-off-archived",moved:u.length}),!0}catch(d){return await c.moveBack(u).catch(()=>{}),await this.fail(a,bt(d),!0),!1}}async put(e){return await this.ledger.update(t=>{let r=t.entries.findIndex(i=>vE(i,e));return r>=0?t.entries[r]=e:t.entries.push(e),t}),e}async fail(e,t,r){let i=e.attempts+(r?1:0);await this.put({...e,phase:i>=ad?"refused":"detected",attempts:i,lastError:t,reason:i>=ad?"takeover_failed":e.reason,updatedAt:this.now()}).catch(()=>{})}async refuse(e,t){await this.put({...e,phase:"refused",reason:t,updatedAt:this.now()}),await new vt(e.archiveDir).log({event:"refused",source:e.source,root:e.root,reason:t}).catch(()=>{})}async revert(e,t){let r=await pe(t),o=(await this.ledger.read()).entries.find(a=>a.root===r&&a.source!=="content-off"&&(a.account===(e?ae(e):null)||a.source==="remotesync"));if(!o||Ro.has(o.phase))throw Error("nothing_to_revert");if(o.source==="remotesync"){let a=fd();if(!a?.revert)throw Error("revert_unavailable");await a.revert(this.remoteContext(),r);return}if(!e)throw Error("not_signed_in");if(this.revertingNow.has(r))throw Error("revert_in_progress");this.revertingNow.add(r);try{await this.revertEntry(e,r,o)}finally{this.revertingNow.delete(r)}}async revertEntry(e,t,r){await Ae(async()=>{r.bindingId&&await this.disableBinding(e,r.bindingId),await this.put({...r,phase:"reverted",updatedAt:this.now()})}),this.stateOf(ae(e)).live.delete(t),r.bindingId&&await this.hooks?.stopBinding(r.bindingId);let o=this.ownership(),a=await o.get(e),s=[],l=new Set([t,...r.formerRoots??[]]);for(let c of a.entryRoots)l.has(await pe(c))||s.push(c);s.length!==a.entryRoots.length&&await o.set({...a,entryRoots:s},e),r.bindingId&&await this.dropBinding(e,r.bindingId),await new vt(r.archiveDir).log({event:"reverted",root:t,by:"user"}).catch(()=>{})}async disableBinding(e,t){let r=i=>{let o=i.bindings.find(a=>a.id===t);if(!(!o||!o.enabled))return o.enabled=!1,i};await this.deps.store.updateAccount(e,r),await this.deps.store.updateDevice(r)}async dropBinding(e,t){let r=i=>{let o=i.bindings.filter(a=>a.id!==t);if(o.length!==i.bindings.length)return i.bindings=o,i};await this.deps.store.updateAccount(e,r),await this.deps.store.updateDevice(r)}async relocateRoot(e,t,r,i){let o=f=>f.replace(/[\\/]+$/,""),a=o(r),s=await pe(i),l=ae(e),c=this.ownership(),u=await c.get(e),d=u.entryRoots.map(o);d.includes(a)&&!d.includes(s)&&await c.set({...u,entryRoots:[...u.entryRoots,s]},e),await this.ledger.update(f=>{let p=!1;for(let m of f.entries)m.source==="entry"&&m.account===l&&m.bindingId===t&&m.root===a&&(m.formerRoots=[...new Set([...m.formerRoots??[],a])],m.root=s,m.rawRoot=s,m.updatedAt=this.now(),p=!0);return p?f:void 0});let g=this.accounts.get(l);g?.live.has(a)&&g.live.add(s)}async view(e){let t=e?ae(e):null,r=i=>!od.has(i.phase)||!jr.has(i.reason??"");return(await this.ledger.read()).entries.filter(i=>i.account===t||i.account===null).map(i=>({root:i.root,source:i.source,phase:i.phase,lastError:od.has(i.phase)&&jr.has(i.lastError??"")?void 0:i.lastError,reason:r(i)?i.reason:void 0,...i.inUseBy&&!od.has(i.phase)?{inUseBy:{bindingId:i.inUseBy.bindingId,name:i.inUseBy.name}}:{}}))}remoteContext(){let e=this.deps.host;if(!e.syncTargets)throw Error("sync_targets_unavailable");let t=()=>this.deviceArchive??=vt.fresh(this.deps.home(),this.now()),r=this,i=async o=>(await r.deps.store.readDevice()).bindings.find(a=>a.id===o);return{host:e,syncTargets:e.syncTargets,async entry(o){let a=await pe(o);return(await r.ledger.read()).entries.find(l=>l.source==="remotesync"&&l.root===a)??r.put({source:"remotesync",root:a,account:null,phase:"detected",originalOwnership:null,targetFingerprint:"",archiveDir:t().dir,attempts:0,updatedAt:r.now()})},async advance(o,a,s={}){return r.put({...o,...s,phase:a,updatedAt:r.now()})},async cleanupEntries(){return(await r.ledger.read()).entries.filter(o=>o.source==="remotesync"&&(o.pendingFinish!==void 0||Ro.has(o.phase)&&o.bindingId!==void 0))},async archiveDir(){return await t().ensure(),t().dir},async archiveCopy(o){await t().copy(o,"remotesync")},async archiveMove(o){await t().move(o,"remotesync")},async log(o){await t().log({source:"remotesync",...o})},async addDeviceBinding(o){let a=o.target.kind==="remote"?yn.of(e):null;if(a){let s=await pe(o.root),l=e.accountId?.()??null,c=(await r.deps.store.readDevice()).bindings,u=l?(await r.deps.store.readAccount(l)).bindings:[];await Yn({root:s,target:o.target},[...c,...u],{released:await r.releasedBindings(),identities:a})}return Ae(async()=>{let s=await pe(o.root),l=Ao(o.target),c=(await r.deps.store.readDevice()).bindings,u=new Map;for(let y of c)u.set(y.id,await pe(y.root));let d=c.find(y=>u.get(y.id)===s&&Ao(y.target)===l);if(d)return d;let g=e.accountId?.()??null,f=g?(await r.deps.store.readAccount(g)).bindings:[],p=await r.releasedBindings(),m;return await r.deps.store.updateDevice(y=>{if(y.bindings.some(h=>!u.has(h.id)))throw Error("device_bindings_changed");let b=Ke({root:s,role:o.role},[...y.bindings,...f]);if(b&&!(b==="primary_exists"&&o.state==="needs-choice")){let h=b==="primary_exists"?[...y.bindings,...f].find(E=>E.role==="primary"&&(E.enabled||E.state==="takeover")&&(u.get(E.id)??E.root)===s):void 0;throw h?Object.assign(new Error(b),{code:b,inUseBy:aa(h)}):Error(b)}return Xn({root:s,target:o.target},[...y.bindings,...f],{released:p,identities:a}),m={...o,root:s,id:li(),generation:1,createdAt:r.now()},y.bindings.push(m),y}),m})},async stopBinding(o){await r.hooks?.stopBinding(o)},readDeviceBinding:i,async updateDeviceBinding(o,a){let s,l=u=>{let d=u.bindings.findIndex(g=>g.id===o);if(!(d<0))return u.bindings[d]=s={...u.bindings[d],...a,id:o},u};await r.deps.store.updateDevice(l);let c=s?null:e.accountId?.()??null;if(c&&await r.deps.store.updateAccount(c,l),!s)throw Error("binding_not_found");return s},async removeDeviceBinding(o){if(!ci(o))throw e.log?.("[vault-sync] skip remote takeover removal: invalid binding id"),Error("not_takeover_binding");let a=`${r.deps.home()}\0${o}`,l=(va.get(a)??Promise.resolve()).catch(()=>{}).then(async()=>{let c=async()=>(await r.ledger.read()).entries.some(g=>g.source==="remotesync"&&g.bindingId===o),u=await i(o);if(!u)return await c()&&await mo(r.deps.store,"device",o,r.now()),{removed:!1};if(u.state!=="takeover"||!await c())throw Error("not_takeover_binding");await r.hooks?.stopBinding(o);let d=!1;return await Ae(async()=>{if(!await c())throw Error("not_takeover_binding");await r.deps.store.updateDevice(g=>{let f=g.bindings.findIndex(p=>p.id===o);if(!(f<0)){if(g.bindings[f].state!=="takeover")throw Error("not_takeover_binding");return g.bindings.splice(f,1),d=!0,g}})}),await r.hooks?.stopBinding(o),await mo(r.deps.store,"device",o,r.now()),{removed:d}});va.set(a,l);try{return await l}finally{va.get(a)===l&&va.delete(a)}},entryRoots(){let o=[];for(let a of r.accounts.values())o.push(...a.live);return o},async runTakeoverRound(o,a){if(!r.hooks)throw Error("runtime_not_ready");return r.hooks.runTakeoverRound(o,a)}}}};var Co="VERSION_CHANGED",Nn=class extends Error{code=Co;path;constructor(e){super(`version_changed: ${e}`),this.path=e,this.name="VersionChangedError"}},gh=n=>{let e=n;return e?.code==="TARGET_DIR_MISSING"||e?.code==="target-dir-missing"||e?.message==="target-dir-missing"},ph=null;function hh(n){ph=n}function Io(){return ph}import{createHash as SE}from"node:crypto";var kE=[".DS_Store","desktop.ini","Thumbs.db",".git/",".trash/",".forsion-sync-id.json"];function pd(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];r==="*"?n[t+1]==="*"?(e+=".*",t++):e+="[^/]*":r==="?"?e+="[^/]":e+=r.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${e}$`)}function EE(n=[]){let e=[],t=[];for(let r of[...kE,...n]){let i=String(r).trim().normalize("NFC");!i||i.startsWith("#")||(i.endsWith("/")?t.push(pd(`${i}**`)):i.includes("/")?t.push(pd(i.replace(/^\//,""))):e.push(pd(i)))}return r=>{let i=r.normalize("NFC");return t.some(o=>o.test(i))?!0:e.length===0?!1:i.split("/").some(o=>e.some(a=>a.test(o)))}}var mh=n=>SE("sha256").update(n).digest("hex"),yh=n=>/^cas-conflict\b/.test(String(n?.message??"")),xo=(n,e)=>Object.assign(new Error(`${n}: ${e}`),{code:n}),_E=n=>Buffer.isBuffer(n)?n:Buffer.from(n.buffer,n.byteOffset,n.byteLength);function RE(n,e){let t=EE(e.ignore),r=e.maxFileBytes!==null&&Number.isSafeInteger(e.maxFileBytes)&&e.maxFileBytes>0?e.maxFileBytes:null,i={createExclusive:n.caps.createExclusive===!0,casWrite:n.caps.casWrite===!0,casDelete:n.caps.casDelete===!0,realMove:!1},o=new Map,a=c=>o.get(c)??c,s=()=>r!==null?[{prefix:"",maxBytes:r}]:[],l=c=>{if(e.direction==="pull")throw xo("remote-direction-pull",c);if(t(c))throw xo("remote-ignored-path",c)};return{kind:"remote",caps:i,async list(c){let u=await n.walk(c),d=new Map,g=new Map;for(let f of u){let p=f.key.normalize("NFC"),m=d.get(p);if(m!==void 0&&m!==f.key)throw Object.assign(new Error(`remote-nfc-collision: ${p}`),{code:"remote-nfc-collision"});d.set(p,f.key);let y=t(p)||r!==null&&f.size>r;g.set(p,{kind:"file",version:f.id,...f.hash?{hash:f.hash}:{},size:f.size,mtime:f.mtimeMs,backing:y?"other":"vault"})}return o=d,{entries:g,limits:s()}},async read(c,u,d){let g=a(c),f=await n.stat(g,d);if(!f||u!==null&&f.id!==u)throw new Nn(c);let p=await n.readFile(g,d),m=await n.stat(g,d);if(!m||m.id!==f.id)throw new Nn(c);let y=mh(p);if(f.hash&&f.hash!==y)throw new Nn(c);return{bytes:new Uint8Array(p.buffer,p.byteOffset,p.byteLength),version:m.id,hash:y}},async write(c,u,d,g,f){if(l(c),r!==null&&u.byteLength>r)throw Object.assign(new Error("too_large"),{status:413,code:"TOO_LARGE",maxBytes:r});if(d!==null&&typeof d!="string")throw new TypeError("expected must be null or a version");let p=a(c),m=typeof f?.mtimeMs=="number"&&Number.isFinite(f.mtimeMs)&&f.mtimeMs>0?Math.floor(f.mtimeMs):0,y;try{y=await n.writeFile(p,_E(u),m,g,d)}catch(b){throw yh(b)?new Nn(c):b}return o.set(c,p),{version:y.id,hash:mh(u)}},async remove(c,u,d){if(e.direction==="pull")throw xo("remote-direction-pull",c);if(e.direction==="push")throw xo("remote-direction-push",c);if(t(c))throw xo("remote-ignored-path",c);if(typeof u!="string")throw new TypeError("remove needs the version it saw");try{await n.rm(a(c),d,u)}catch(g){throw yh(g)?new Nn(c):g}o.delete(c)},limits:s,inScope:c=>!!c&&!t(c),...typeof n.mkdir=="function"?{async mkdir(c,u){if(c!=="")throw new TypeError("mkdir only creates the binding's own directory");await n.mkdir(u)}}:{}}}function wh(n){return async e=>{let t=n.syncTargets;if(!t)throw Object.assign(new Error("sync_targets_unavailable"),{code:"sync_targets_unavailable"});return RE(await t.open(e.target.targetId,e.target.dir),e.target)}}var IE=3,Rh=!1;function xE(n=!0){Rh=n}var To=new Set(["done","reverted","refused"]),TE=new Set(["archived","sealed","round-running"]),DE=n=>n.normalize("NFC").trim().toLowerCase(),bh=n=>n.replace(/[\\/]+$/,"");async function Ur(n){try{return bh(await AE(n))}catch{return bh(n)}}function Mt(n){let e=n;return typeof e?.code=="string"&&/^[A-Za-z0-9_.-]{1,64}$/.test(e.code)?e.code:typeof e?.message=="string"&&/^[a-z][a-z0-9_-]{2,63}$/.test(e.message)?e.message:typeof e?.name=="string"&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"error"}var Qe=n=>Object.assign(new Error(n),{code:n});function PE(n){let e=n;return e?.name==="AbortError"||e?.name==="TimeoutError"||e?.message==="runtime_not_ready"||e?.code==="legacy_config_changed"||e?.name==="TypeError"&&/fetch/i.test(String(e.message))?!0:["ECONNREFUSED","ECONNRESET","ENOTFOUND","ETIMEDOUT","EAI_AGAIN","ENETUNREACH"].includes(e?.code??e?.cause?.code??"")||(e?.status??0)>=500}var Vr=n=>JSON.stringify([n.root,n.config.backend,n.config.dir,n.config.direction,n.config.ignore,n.config.maxFileMB,n.entryIgnores??[],n.legacyKey??null]),OE=n=>typeof n.legacyKey=="string"?{expectKey:n.legacyKey}:void 0,vh={kind:"penzor",vaultId:"",ns:"default",prefix:"Amadeus/",placement:"own"};async function Sh(n,e,t){let r=Array.isArray(e.entryIgnores)?e.entryIgnores.filter(d=>typeof d=="string"&&d.length>0):[],i=await Promise.all(n.entryRoots().map(Ur)),o=r.length>0||i.includes(t);if(e.config.backend==="penzor")return{target:vh,state:"needs-card",fingerprint:Ao(vh)};let{targetId:a}=await n.syncTargets.importLegacyRemoteSync(),s=await n.syncTargets.legacyRemoteSync();if(!s||Vr(s)!==Vr(e))throw Qe("legacy_config_changed");let l=e.config.maxFileMB,c={kind:"remote",targetId:a,dir:"",direction:e.config.direction,ignore:[...new Set([...e.config.ignore,...r])],maxFileBytes:typeof l=="number"&&Number.isFinite(l)&&l>0?Math.floor(l*1024*1024):null},u=Ao(c);return o?{target:c,state:"needs-choice",reason:"remote_same_root",fingerprint:u}:{target:c,state:"takeover",fingerprint:u}}async function ME(n,e,t,r){return n.addDeviceBinding({root:e,rootIdentity:r,nameKey:DE(CE(e)),target:t.target,scope:{mode:"all"},enabled:!0,paused:t.state!=="takeover",state:t.state,role:"primary",...t.reason?{reason:t.reason}:{},...t.state==="takeover"?{firstRound:"takeover"}:{}})}var NE=new Set(["folder_target_nested","mirror_root","device_bindings_changed",...jr]),Do=n=>jr.has(n.reason??"");function kh(n){let e=n?.inUseBy;return e&&typeof e=="object"&&typeof e.bindingId=="string"&&typeof e.name=="string"?{bindingId:e.bindingId,name:e.name}:void 0}var Eh=(n,e)=>n.syncTargets.unsealLegacyRemoteSync(typeof e.legacyKey=="string"?{expectKey:e.legacyKey}:void 0),hd=(n,e)=>n.syncTargets.unsealLegacyRemoteSync({restoreAutoSync:!0,...typeof e?.legacyKey=="string"?{expectKey:e.legacyKey}:{}}),Ah=n=>ae(n?Vr(n):"null"),md=n=>n?.state==="takeover"&&!n.enabled&&n.paused;async function yd(n,e){let t=e.pendingFinish;if(!t||!ci(t.bindingId)||t.bindingId!==e.bindingId||t.phase!=="reverted"&&!(t.phase==="refused"&&Number.isSafeInteger(t.attempts)&&typeof t.lastError=="string"))throw Qe("invalid_takeover_cleanup");if(t.step==="handback"){if(!md(await n.readDeviceBinding(t.bindingId)))throw Qe("binding_not_found");let i=await n.syncTargets.legacyRemoteSync();if(i?.hold!=="none"){if(Ah(i)!==t.legacySnapshot)throw Qe("legacy_config_changed");await hd(n,i)}let{legacySnapshot:o,...a}=t;t={...a,step:"remove"},e=await n.advance(e,e.phase,{pendingFinish:t})}if(t.step!=="remove")throw Qe("invalid_takeover_cleanup");try{await n.removeDeviceBinding(t.bindingId)}catch(i){throw Qe(Mt(i))}let r=t.phase==="refused"?{attempts:t.attempts,lastError:t.lastError,reason:"takeover_failed"}:{};await n.advance(e,t.phase,{...r,pendingFinish:void 0}),await n.log({event:t.phase,root:e.root,...r}).catch(()=>{})}async function _h(n,e,t,r,i){if(!ci(t))throw Qe("invalid_takeover_binding_id");if(e.bindingId!==t)throw Qe("binding_not_found");let o=i===void 0?{...r,bindingId:t,step:"remove"}:{...r,bindingId:t,step:"handback",legacySnapshot:Ah(i)};await yd(n,await n.advance(e,e.phase,{pendingFinish:o}))}var $E=(n,e)=>n.config.backend!=="penzor"&&e.reason!=="remote_same_root";function LE(){let n=Promise.resolve(),e=i=>{let o=n.then(i,i);return n=o.catch(()=>{}),o},t=null;async function r(i,o,a,s,l,c){let u=await i.entry(o);if(To.has(u.phase)||u.pendingFinish!==void 0)return;let d=Mt(a),g=async(b=!1)=>{try{return b?await hd(i):await i.syncTargets.unsealLegacyRemoteSync(),!0}catch(h){return c(`unseal failed: ${Mt(h)}`),!1}};if(jr.has(d)){let b=kh(a);c(`takeover held (${d}), legacy sync stays sealed`),await i.advance(u,u.phase,{lastError:d,reason:d,inUseBy:b}).catch(()=>{}),await i.log({event:"held",root:o,reason:d,...b?{inUseBy:b.bindingId}:{}}).catch(()=>{});return}if(l.aborted){!s&&!Do(u)&&(await g()?u.lastError==="unseal_failed"&&await i.advance(u,u.phase,{lastError:void 0}).catch(()=>{}):await i.advance(u,u.phase,{lastError:"unseal_failed"}).catch(()=>{}));return}if(Do(u)){c(`failed while held (${u.reason}): ${d}, legacy sync stays sealed`),await i.advance(u,u.phase,{lastError:d}).catch(()=>{});return}let f=PE(a);c(`${f?"will retry":"failed"} at ${u.phase}: ${d}`);let p=s?!0:await g(),m=u.attempts+(f?0:1);if(m<IE){await i.advance(u,u.phase,{attempts:m,lastError:p?d:"unseal_failed"}).catch(()=>{});return}if(!p){await i.advance(u,u.phase,{attempts:m,lastError:"unseal_failed"}).catch(()=>{});return}let y;if(u.bindingId)try{y=await i.updateDeviceBinding(u.bindingId,{enabled:!1,paused:!0,reason:"takeover_failed"}),await i.stopBinding(u.bindingId)}catch(b){c(`stop binding failed: ${Mt(b)}, staying sealed`),await i.advance(u,u.phase,{lastError:d}).catch(()=>{});return}if(s&&!u.bindingId){await i.advance(u,u.phase,{attempts:m,lastError:d}).catch(()=>{});return}if(y?.state==="takeover")try{let b=await i.readDeviceBinding(y.id);if(b||y.target.kind==="remote"){if(!md(b))throw Qe("binding_not_found");let h=await i.entry(o);if(To.has(h.phase))return;let E=await i.syncTargets.legacyRemoteSync();if(E?.hold==="v2"&&(!E.root||await Ur(E.root)!==o))throw Qe("legacy_config_changed");await _h(i,h,y.id,{phase:"refused",attempts:m,lastError:d},E);return}}catch(b){c(`finish refused failed: ${Mt(b)}`);return}if(s&&!await g(!0)){await i.advance(u,u.phase,{lastError:d}).catch(()=>{});return}await i.advance(u,"refused",{attempts:m,lastError:d,reason:"takeover_failed"}).catch(()=>{}),await i.log({event:"refused",root:o,attempts:m}).catch(()=>{})}return{async run(i,o){let a=d=>i.host.log(`[vault-sync] remotesync takeover: ${d}`);if(!Rh){a("not enabled yet (remote bindings cannot run in this build), remotesync left as is");return}let s="",l=!1,c=await e(async()=>{let d;try{d=await i.syncTargets.legacyRemoteSync()}catch(m){return a(`legacy config unreadable, left as is (${Mt(m)})`),null}if(o.aborted)return null;let g;try{g=await i.cleanupEntries()}catch(m){return a(`takeover ledger unreadable: ${Mt(m)}`),null}for(let m of g){if(o.aborted)return null;try{m.pendingFinish!==void 0?await yd(i,m):await i.removeDeviceBinding(m.bindingId)}catch(y){Mt(y)!=="not_takeover_binding"&&a(`resume binding removal failed: ${Mt(y)}`)}}if(g.some(m=>m.pendingFinish?.step==="handback"))try{d=await i.syncTargets.legacyRemoteSync()}catch(m){return a(`legacy config unreadable, left as is (${Mt(m)})`),null}if(!d)return null;if(d.config.backend==="off"){if(d.hold==="v2"&&!d.archived&&d.root){let m=await i.entry(await Ur(d.root));if(Do(m)&&!To.has(m.phase)&&m.pendingFinish===void 0)try{await Eh(i,d),await i.advance(m,m.phase,{reason:void 0,inUseBy:void 0,lastError:void 0})}catch(y){a(`unseal failed: ${Mt(y)}, staying sealed`)}}return null}if(d.config.backend==="gdrive")return a("google drive backend is unsupported, left as is"),null;if(!d.root)return a(`no usable root (${Mt({message:d.rootError??"unknown"})}), nothing to take over`),null;s=await Ur(d.root);let f=await i.entry(s);if(To.has(f.phase)||f.pendingFinish!==void 0||o.aborted)return null;if(f.bindingId&&d.hold==="none"){let m=await i.readDeviceBinding(f.bindingId);if(!m?.enabled||m.paused)return null}let p=async(m,y=!1)=>{if(a(m),!Do(f))return null;if(!y||f.reason==="primary_exists")return a(`held (${f.reason}), legacy sync stays sealed`),f.lastError!==f.reason&&await i.advance(f,f.phase,{lastError:f.reason}).catch(()=>{}),null;try{await Eh(i,d),await i.advance(f,f.phase,{reason:void 0,inUseBy:void 0,lastError:void 0})}catch(b){a(`unseal failed: ${Mt(b)}, staying sealed`)}return null};if(l=!!f.bindingId||!!f.targetFingerprint,!l){if(d.archived)return a("legacy sync was already handed over for another root, left as is"),null;if(d.config.backend==="penzor")return p("penzor backend needs a vault choice first, left as is",!0);if((Array.isArray(d.entryIgnores)?d.entryIgnores.filter(y=>typeof y=="string"&&y.length>0):[]).length>0||(await Promise.all(i.entryRoots().map(Ur))).includes(s))return p("this root also has entry sync, left as is")}try{await i.syncTargets.sealLegacyRemoteSync();let m=await i.syncTargets.legacyRemoteSync();if(!m||Vr(m)!==Vr(d))throw Qe(l?"legacy_config_changed_bound":"legacy_config_changed");if(f.bindingId){if(f.phase==="detected"&&(await Sh(i,m,s)).fingerprint!==f.targetFingerprint)throw Qe("legacy_config_changed_bound")}else{let y=await Sh(i,m,s);if(o.aborted)throw Object.assign(new Error("aborted"),{name:"AbortError"});if(f.targetFingerprint&&f.targetFingerprint!==y.fingerprint)throw Qe("legacy_config_changed_bound");let b=await dt(s);f.targetFingerprint||(f=await i.advance(f,"detected",{targetFingerprint:y.fingerprint})),l=!0;let h;try{h=await ME(i,s,y,b)}catch(E){let v=Mt(E);throw NE.has(v)&&(f=await i.advance(f,f.phase,{targetFingerprint:"",...jr.has(v)?{reason:v,lastError:v,inUseBy:kh(E)}:{}}),l=!1),E}f=await i.advance(f,"detected",{bindingId:h.id,targetFingerprint:y.fingerprint,reason:h.state==="needs-choice"?h.reason??y.reason:y.reason,inUseBy:void 0,lastError:void 0}),await i.log({event:"bound",root:s,bindingId:h.id,state:h.state,backend:m.config.backend,direction:m.config.direction})}if(f.phase==="detected"){let y=await i.syncTargets.archiveLegacyRemoteSync(await i.archiveDir(),OE(m));await i.log({event:"archived",root:s,copied:y.copied.length,moved:y.moved.length}),f=await i.advance(f,"archived")}return f.phase==="archived"&&(f=await i.advance(f,"sealed")),$E(d,f)?f.bindingId:null}catch(m){return await r(i,s,m,l,o,a),null}});if(!c)return;let u=i.runTakeoverRound(c,o);t={p:u,root:s};try{await u}catch(d){await e(()=>r(i,s,d,!0,o,a))}finally{t?.p===u&&(t=null)}},async revert(i,o){await e(async()=>{let a=await Ur(o);if(t)throw Qe("takeover_round_running");let s;try{s=await i.syncTargets.legacyRemoteSync()}catch{throw Qe("legacy_config_unreadable")}if(s&&s.config.backend!=="off"&&!s.root)throw Qe("legacy_root_unavailable");let l=s&&s.config.backend!=="off"?await Ur(s.root):null,c=s?Vr(s):null,u=await i.entry(a);if(u.pendingFinish!==void 0){await yd(i,u);return}if(To.has(u.phase))throw new Error("nothing_to_revert");if(Do(u))throw Qe(u.reason);if(!u.bindingId&&u.targetFingerprint)throw new Error("binding_unknown");let d=(!!u.bindingId||u.lastError==="unseal_failed")&&(l===null||l===a)&&(!s?.archived||TE.has(u.phase)),g;if(u.bindingId){let p=await i.updateDeviceBinding(u.bindingId,{enabled:!1,paused:!0});if(p.state!=="takeover"&&(await i.entry(a)).phase==="done")throw await i.stopBinding(u.bindingId),Qe("takeover_finished");if(await i.stopBinding(u.bindingId),p.state==="takeover"){let m=await i.readDeviceBinding(u.bindingId);if(m||p.target.kind==="remote"){if(!md(m))throw Qe("binding_not_found");g=u.bindingId}}}if(d){let p;try{p=await i.syncTargets.legacyRemoteSync()}catch{throw Qe("legacy_config_unreadable")}if((p?Vr(p):null)!==c)throw Qe("legacy_config_changed")}let f=await i.entry(a);if(g){await _h(i,f,g,{phase:"reverted"},d?s:void 0);return}d&&await hd(i,s),await i.advance(f,"reverted"),await i.log({event:"reverted",root:a})})}}}function Ch(n){hh(wh(n)),uh(LE()),xE()}import{readFile as vA}from"node:fs/promises";import{basename as Tl}from"node:path";import{hostname as Rw}from"node:os";import{createHash as A$}from"node:crypto";import{readFileSync as Ci,lstatSync as hy,statSync as E0,renameSync as _0,linkSync as R0,unlinkSync as Qd,readdirSync as A0,rmdirSync as C0,writeFileSync as I0,mkdirSync as x0,copyFileSync as T0,constants as D0}from"node:fs";import{readFile as Jo,writeFile as Xa,mkdir as ay,rename as Ko,readdir as Yo,lstat as un,stat as eu,unlink as Xo}from"node:fs/promises";import{join as st,dirname as Ii,relative as Zo,sep as xi}from"node:path";import{hostname as tu}from"node:os";import{createHash as fu,randomUUID as kn}from"node:crypto";import{isUtf8 as nu}from"node:buffer";import{Readable as P0}from"node:stream";import{performance as ru}from"node:perf_hooks";import{setImmediate as O0}from"node:timers/promises";var on=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var mi=new Set(["agents","plugins"]),wd=n=>mi.has(n),sn=n=>on.some(e=>mi.has(e.id)&&Aa(n.toLowerCase(),e.path.toLowerCase()));var Oo=/^[a-z0-9][a-z0-9-]{0,63}$/,Ra=new Set(["muse"]),Mo=n=>{let e=/^agents\/([^/]+)$/.exec(n);return e&&Oo.test(e[1])?e[1]:null},FE=n=>[...Ra].some(e=>Aa(n,`agents/${e}`));function Ih(n){let e=n.split(/^\s*\[/m)[0]??"",t=o=>{let a=new RegExp(`^[ \\t]*${o}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(a?.[1]!=null?a[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):a?.[2])?.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,80)||void 0},r=t("name"),i=t("name_en");return{...r?{name:r}:{},...i?{nameEn:i}:{}}}var Er=(n,e)=>Hn(e,n)?.target??"off",Aa=(n,e)=>n===e||n.startsWith(e+"/"),BE=n=>on.some(e=>Aa(n,e.path)),bd=n=>n.some(e=>e.id==="default")?No():"default",xh=(n,e)=>n.enabled?Er(n.rules,e):"off";function Th(n,e,t){t==="off"&&(n=n.filter(o=>e?!o.source.startsWith(e+"/"):!o.source||BE(o.source)));let r=n.find(o=>o.source===e),i=n.filter(o=>o!==r);return e&&Er(i,e)===t?i:r?n.map(o=>o===r?{...o,target:t}:o):[...n,{id:e?No():bd(n),source:e,target:t}]}function yi(n,e,t,r=!1){if(FE(e)||sn(e))return n;let i=n.rules;if(!n.enabled){let o=i.find(s=>!s.source),a=e?i.filter(s=>s.source&&Aa(s.source,e)):[];i=[{id:o?.id??bd(a),source:"",target:"off"},...a],e!=="agents"&&(i=Po(i,"agents","off"))}if(!e)for(let o of on)i.some(a=>a.source===o.path)||(i=[...i,{id:No(),source:o.path,target:Er(i,o.path)}]);return Dh({...n,rules:Th(i,e,t)},r)}function Dh(n,e=!1){let t=r=>Er(n.rules,r)!=="off";return{...n,enabled:on.some(r=>!mi.has(r.id)&&t(r.path))||n.rules.some(r=>r.source&&!sn(r.source)&&r.target!=="off")||e&&t("")}}function Ph(n,e){let t=!n.enabled&&n.revision===0,r=t?[]:n.rules.filter(a=>a.source&&sn(a.source)),i=new Set(r.map(a=>a.id)),o=[...e.rules.filter(a=>!a.source||!sn(a.source)).map(a=>i.has(a.id)?{...a,id:No()}:a),...r];for(let a of on){if(!mi.has(a.id))continue;let s=t?"off":Er(n.rules,a.path);Er(o,a.path)!==s&&(o=Po(o,a.path,s))}return{...e,rules:o}}function Oh(n){let e=n.rules.some(t=>t.source==="")?n.rules:[{id:bd(n.rules),source:"",target:"default"},...n.rules];for(let t of on)t.id!=="agents"&&!mi.has(t.id)&&Er(e,t.path)==="off"&&(e=Th(e,t.path,"default"));e=Po(e,"agents","off");for(let t of on)mi.has(t.id)&&(e=Po(e,t.path,"off"));return{...n,enabled:!0,rules:e}}function Po(n,e,t){let r=n.find(i=>i.source===e);return r?n.map(i=>i===r?{...i,target:t}:i):[...n,{id:No(),source:e,target:t}]}function Mh(n,e){let t=n;for(let r of new Set(e))Oo.test(r)&&!Ra.has(r)&&(t=yi(t,`agents/${r}`,"default"));return t}function Nh(n){let e=Er(n.rules,"agents")!=="off"||n.rules.some(i=>i.source.startsWith("agents/")&&i.target!=="off"),t=n.rules.some(i=>i.source.startsWith("agents/"));if(!e&&!t)return null;let r=Po(n.rules.filter(i=>!i.source.startsWith("agents/")),"agents","off");return n.enabled?Dh({...n,rules:r},!0):{...n,rules:r}}var jE=0,No=()=>`rule-${Date.now().toString(36)}-${(jE++).toString(36)}`;var $h=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function Lh(n){return n==="TOO_LARGE"?"skippedTooLarge":n==="ASSET_404"?"skippedNotFound":n==="EXISTS"?"skippedExists":/^http \d+$/.test(n)?"errHttp":n==="timeout"?"errTimeout":"skippedOther"}function vd(n){let e=n??"";if(/^(?:ENOENT|EACCES|EPERM|EBUSY|EISDIR|ENOTDIR|EEXIST|EMFILE|ENFILE|ENOSPC|EROFS|EIO|ENAMETOOLONG)\b/.test(e))return"errOther";let t=/^(?:cloud|sse) http (\d{3})\b/i.exec(e);return t?t[1]==="401"||t[1]==="403"?"errAuth":"errHttp":/timeout|timed out|etimedout/i.test(e)?"errTimeout":!e||/fetch failed|econn|enotfound|eai_again|enetunreach|ehostunreach|enetdown|network|socket|terminated|other side closed|und_err|^cloud http 0\b/i.test(e)?"errOffline":"errOther"}function Fh(n){if(!(n instanceof Error))return;let e=n.cause,t=e&&typeof e=="object"?[e.code,e.message].filter(r=>typeof r=="string"&&r).join(" "):"";return t?`${n.message} (${t})`:n.message}function Bh(n,e){if(n==="offline")return vd(e);if(n==="auth-required")return e==="not-logged-in"?null:"errAuth";if(n!=="error")return null;let t=e??"";return t.startsWith("vault-missing")?"errVaultMissing":t.startsWith("scan-failed")?"errScan":t.startsWith("mirror-missing")?"errMirrorMissing":"errOther"}function Ca(n,e=0){if(/^(account_changed|content_sync_closed|paused)$/.test(n)||/^File exceeds \d+ MB/.test(n))return null;if(n==="not_signed_in"||e===401||e===403)return"errAuth";let t=/^content_http_(\d{3})$/.exec(n);return t?t[1]==="401"||t[1]==="403"?"errAuth":"errHttp":/timeout|timed out|aborted due to timeout/i.test(n)?"errTimeout":/fetch failed|econn|enotfound|eai_again|network|socket/i.test(n)?"errOffline":/^Sync root (unavailable|changed|is not a directory)|^content_roots_changed/.test(n)?"errVaultMissing":e?"errHttp":"errOther"}function Ia(n){let e=null;return{error(t){t!==e&&(e=t,n?.(t))},ok(){e=null}}}var UE=/^\d{4}-\d{2}-\d{2}$/,jh=["vault","content"],Uh=new Set($h),VE=40,wi=n=>new Date(n).toISOString().slice(0,10),bi=n=>typeof n=="string"&&UE.test(n),Vh=!1,an=Object.create(null),vi=!1,Sd=()=>Date.now(),$o=new Set,xa="";function Nt(n,e,t=1,r){try{if(!Vh||!Uh.has(e)||!(typeof t=="number"&&Number.isFinite(t)&&t>0))return;let i=wi(Sd());if(r!==void 0){i!==xa&&($o.clear(),xa=i);let s=`${n}\0${e}\0${r}`;if($o.has(s))return;$o.add(s)}let o=an[i]??={},a=o[n]??={};a[e]=(a[e]??0)+Math.round(t),vi=!0}catch{}}function kd(n){Vh=n}function zh(n){if(an=Object.create(null),$o.clear(),xa="",vi=!1,!(!n||typeof n!="object"||Array.isArray(n))){for(let[e,t]of Object.entries(n))if(!(!bi(e)||!t||typeof t!="object"))for(let r of jh){let i=t[r];if(!i||typeof i!="object")continue;let o={};for(let[a,s]of Object.entries(i))Uh.has(a)&&typeof s=="number"&&Number.isFinite(s)&&s>0&&(o[a]=Math.round(s));Object.keys(o).length&&((an[e]??={})[r]=o)}}}function Hh(){let n=wi(Sd()-VE*864e5),e={};for(let t of Object.keys(an).sort()){if(t<n){delete an[t];continue}e[t]=JSON.parse(JSON.stringify(an[t]))}return e}var qh=()=>vi,Wh=()=>{vi=!1};function Gh(n,e){let t=[];for(let r of Object.keys(an).sort())if(!(r<=n||r>e))for(let i of jh){let o=an[r][i];o&&Object.keys(o).length&&t.push({day:r,system:i,counts:{...o}})}return t}function Ed(n){for(let e of Object.keys(an))e<=n&&(delete an[e],vi=!0)}function Jh(){Object.keys(an).length&&(vi=!0),an=Object.create(null),$o.clear(),xa=""}function Kh(n){Sd=n}var Yh=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var zE=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function Xh(n,e=[]){let t=n;for(let r of[...e].filter(i=>i&&i.length>=2).sort((i,o)=>o.length-i.length))t=t.split(r).join("[path]");return t.replace(/^(Duplicate folder sync identity|Concurrent (?:folder|file) rename): [\s\S]*$/,"$1: [path]")}var Lo=class{since;cur=null;last=null;runs=[];totals={runs:0,completedRuns:0,idleRuns:0};errors=[];clock;constructor(e=Date.now){this.clock=e,this.since=e()}reset(){this.since=this.clock(),this.cur=null,this.last=null,this.runs=[],this.errors=[],this.totals={runs:0,completedRuns:0,idleRuns:0}}begin(e=this.clock()){this.cur={at:e,counts:{}}}count(e,t=1){t>0&&(this.cur&&(this.cur.counts[e]=(this.cur.counts[e]??0)+t),this.totals[e]=(this.totals[e]??0)+t)}fault(e,t=[],r=this.clock()){if(!e||zE.test(e))return;this.count("errors"),/^File exceeds \d+ MB/.test(e)&&this.count("tooLarge");let i=this.errors[this.errors.length-1];if(i&&i.text===e){i.n++,i.at=r,this.addPaths(t);return}this.errors.push({first:r,at:r,n:1,text:e}),this.addPaths(t),this.errors.length>20&&this.errors.shift()}addPaths(e){let t=this.errors[this.errors.length-1],r=e.filter(i=>typeof i=="string"&&i);!t||!r.length||(t.paths=[...new Set([...t.paths??[],...r])].slice(0,8))}end(e,t=this.clock()){let r=this.cur;if(!r)return;this.cur=null;let i={at:r.at,ms:Math.max(0,t-r.at),completed:e,counts:r.counts};this.last=i,this.totals.runs++,e&&this.totals.completedRuns++,!e||Object.keys(r.counts).length?(this.runs.push(i),this.runs.length>20&&this.runs.shift()):this.totals.idleRuns++}snapshot(){let e=t=>({...t,counts:{...t.counts}});return{since:this.since,lastRun:this.last&&e(this.last),runs:this.runs.map(e),totals:{...this.totals},errors:this.errors.map(t=>({...t,...t.paths?{paths:[...t.paths]}:{}}))}}},Zh=null;function Qh(n){Zh=n}function em(){try{return Zh?.()??null}catch{return null}}import{lstat as HE,readdir as qE}from"node:fs/promises";import{join as WE}from"node:path";var Rd="Amadeus",GE=/ (?:\(import-[0-9a-f]{16}\)(?:\.[a-zA-Z0-9]{1,12})?|\(restored [0-9a-f]{8}\))$/i,JE=/^\.forsion-vault(?: \(import-[0-9a-f]{16}\))?\.md(?: \(restored [0-9a-f]{8}\))?$/i;function _d(n){return n.startsWith(Rd+"/")&&n.split("/")[1]||void 0}async function Ta(n,e,t,r=[]){let i=new Set;for(let f of[...e,...si(t).map(p=>p.prefix)]){let p=_d(f);p&&i.add(p)}for(let f of t.nodes){let p=f.path.split("/");!f.deleted&&f.kind==="file"&&p.length===3&&p[0]===Rd&&JE.test(p[2])&&i.add(p[1])}let o=new Set(await qE(n)),a=new Set([...i,...o]);for(let f of r){let p=_d(f);p&&a.add(p)}for(let f of t.nodes){let p=_d(f.path);p&&a.add(p)}let s=f=>f.normalize("NFC").trim().replace(/[. ]+$/g,"").toLowerCase(),l=new Map;for(let f of i){let p=s(f);l.set(p,[...l.get(p)??[],f])}let c=async f=>{if(/[<>:"|?*]/.test(f)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(f))return null;let p=await HE(WE(n,f)).catch(()=>null);return p?.isDirectory()?`${p.dev}:${p.ino}`:null},u=new Map(await Promise.all([...i].map(async f=>[f,await c(f)]))),d=new Set([...u.values()].filter(f=>f!==null)),g=[];for(let f of a){let p;try{p=Xt(`${Rd}/${f}`)}catch{continue}if(!i.has(f)&&!GE.test(f)){let m=l.get(s(f));if(!m&&!d.size)continue;let y=await c(f);if(y&&d.has(y)){g.push(p);continue}if(!m||y&&o.has(f)&&m.every(b=>o.has(b)&&u.get(b)))continue}g.push(p)}return g.sort()}import{randomUUID as KE}from"node:crypto";import{mkdir as YE,readFile as XE,writeFile as ZE}from"node:fs/promises";import{join as QE}from"node:path";var Fo=n=>QE(n,"content-sync-device.json"),Si=(n,e)=>mn(Fo(n),e);async function zr(n,e){let t=JSON.parse(await XE(Fo(n),"utf8"));if(typeof t?.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(t.id)||e!==void 0&&t.id!==e)throw Error("Invalid device sync ID");if(t.name!==void 0&&typeof t.name!="string")throw Error("Invalid device name");return t}function Da(n){return Si(n,async()=>{try{return await zr(n)}catch(t){if(t.code!=="ENOENT")throw t}let e={id:KE()};await YE(n,{recursive:!0});try{await ZE(Fo(n),JSON.stringify(e),{flag:"wx",mode:384})}catch(t){if(t.code!=="EEXIST")throw t;return zr(n)}return e})}import{mkdirSync as e_,readFileSync as t_,renameSync as n_,unlinkSync as r_,writeFileSync as i_}from"node:fs";import{dirname as o_,join as s_}from"node:path";import{randomUUID as tm}from"node:crypto";var xd=n=>s_(n,"content-sync","active-account.json"),Ad=()=>Error("Invalid content sync account binding; original data was retained");function Bo(n){try{let e=JSON.parse(t_(n,"utf8"));if(e?.version!==1||!(e.account===null&&e.pending===!0||typeof e.account=="string"&&/^[a-f0-9]{64}$/.test(e.account))||e.epoch!==void 0&&(typeof e.epoch!="string"||!/^[a-f0-9-]{36}$/i.test(e.epoch))||e.pending!==void 0&&typeof e.pending!="boolean"||e.pending&&!e.epoch)throw Ad();return e}catch(e){if(e?.code==="ENOENT")return null;throw Ad()}}function Td(n,e){e_(o_(n),{recursive:!0,mode:448});let t=n+".tmp-"+tm();try{i_(t,JSON.stringify(e),{flag:"wx",mode:384}),n_(t,n)}finally{try{r_(t)}catch{}}}var Cd=new WeakMap,Id=new WeakSet;function nm(n,e){let t=Cd.get(n);return t||Cd.set(n,t=new Set),t.add(e),()=>{t.delete(e)}}function Pa(n){if(Id.has(n))throw Ad()}function ki(n,e,t){if(!n.contentSync||e===t)return;let r=xd(n.homeDir());try{let i=Bo(r);Td(r,{version:1,account:i?.account??null,epoch:tm(),pending:!0}),Id.delete(n)}catch(i){throw Id.add(n),i}finally{for(let i of Cd.get(n)??[])i()}}import{promises as Ri}from"node:fs";import Kr from"node:path";import{execFile as e0}from"node:child_process";import t0 from"node:os";var a_=1024,De=class extends Error{status;body;constructor(e,t,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=t}},rm=n=>12e4+Math.ceil(n/256);function l_(n,e){let t=AbortSignal.timeout(n);if(!e)return t;let r=new AbortController;for(let i of[t,e])i.addEventListener("abort",()=>r.abort(i.reason),{once:!0});return r.signal}function im(n,e){if(!n||!e)return n??e;let t=new AbortController;for(let r of[n,e]){if(r.aborted){t.abort(r.reason);break}r.addEventListener("abort",()=>t.abort(r.reason),{once:!0})}return t.signal}function om(n){let e=`${n.baseUrl.replace(/\/+$/,"")}/api/amadeus`,t=n.gate??On(n.baseUrl),r=()=>n.getToken?.()??n.token,i=async(s,l)=>{let c=r();for(let u=0;;u++){let d={...l.headers,Authorization:`Bearer ${c}`},g=await fetch(s,{...l,headers:d});if(r(),g.status!==401||g.redirected)return g;let f=await g.text(),p=r();if(p===c||u>0)return new Response(f,{status:g.status,statusText:g.statusText,headers:g.headers});c=p}},o=async(s,l,c)=>{let u={Authorization:`Bearer ${n.token}`,...c?.headers};s!=="GET"&&(u["X-Amadeus-Client"]=n.clientId);let d;for(c?.json!==void 0?(u["Content-Type"]="application/json",d=JSON.stringify(c.json),d.length>=a_&&(u["Content-Encoding"]="gzip",d=await ng(d))):c?.form&&(d=c.form);;){t.until()!==null&&await t.ready(im(c?.signal,n.signal));let g=await i(l,{method:s,headers:u,body:d,signal:l_(c?.timeoutMs??3e4,c?.signal)});if(!g.ok){let p=null;try{p=await g.json()}catch{}if(r(),t.observe(g.status,g.headers,p?.code,p?.retryAfterMs))continue;throw new De(g.status,p,l)}t.observe(g.status,g.headers);let f=await g.json();return r(),f}},a=s=>new URLSearchParams(s).toString();return{clientId:n.clientId,async listVaults(){return((await o("GET",`${e}/vaults`)).vaults??[]).map(l=>({id:String(l.id),name:String(l.name),lastChangeSeq:Number(l.lastChangeSeq??0)}))},async tree(s){let l=await o("GET",`${e}/vaults/${s}/tree`);if(!Array.isArray(l.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:l.folders??[],seq:Number(l.seq??0),maxFileBytes:Number.isInteger(l.maxFileBytes)&&l.maxFileBytes>0?l.maxFileBytes:void 0,entries:l.entries.map(c=>({path:String(c.path),kind:c.kind,seq:Number(c.seq??0),hash:c.hash??null,size:Number(c.size??0),updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}))}},async getFile(s,l){let c=await o("GET",`${e}/vaults/${s}/file?${a({path:l})}`);return{content:String(c.content??""),seq:Number(c.seq??0),hash:c.hash??null,updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}},putFile(s,l,c,u,d=!1,g){return o("PUT",`${e}/vaults/${s}/file`,{json:{path:l,content:c,baseSeq:u,...d?{force:!0}:{},...g?{expectedHash:g}:{}}})},async deleteFile(s,l,c,u){let d={path:l};c!==void 0&&(d.baseSeq=String(c)),u?.expectedHash&&(d.expectedHash=u.expectedHash),await o("DELETE",`${e}/vaults/${s}/file?${a(d)}`,u?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(s,l,c){return o("POST",`${e}/vaults/${s}/move`,{json:{from:l,to:c}})},renameFolder(s,l,c){return o("POST",`${e}/vaults/${s}/folders/rename`,{json:{path:l,newName:c}})},moveFolder(s,l,c){return o("POST",`${e}/vaults/${s}/folders/move`,{json:{path:l,dest:c}})},async deleteFolder(s,l){await o("DELETE",`${e}/vaults/${s}/folders?${a({path:l})}`)},putBinary(s,l,c,u){let d=new FormData;return d.set("path",l),u?.ifAbsent&&d.set("ifAbsent","true"),u?.baseSeq!==void 0&&d.set("baseSeq",String(u.baseSeq)),u?.expectedHash&&d.set("expectedHash",u.expectedHash),d.set("file",new Blob([new Uint8Array(c)]),l.split("/").pop()||"file"),o("POST",`${e}/vaults/${s}/binary`,{form:d,timeoutMs:rm(c.length),signal:u?.signal})},async listVersions(s,l){return((await o("GET",`${e}/vaults/${s}/file/versions?${a({path:l})}`)).versions??[]).map(u=>({id:String(u.id),seq:Number(u.seq??0)}))},async getVersion(s,l){let c=await o("GET",`${e}/vaults/${s}/file/versions/${l}`);return String(c.content??"")},async getAsset(s,l,c){let u=new AbortController;c?.addEventListener("abort",()=>u.abort(c.reason),{once:!0});let d=()=>u.abort(new DOMException("Asset download timed out","TimeoutError")),g;try{let f;for(;;){if(clearTimeout(g),t.until()!==null&&await t.ready(im(c,n.signal)),g=setTimeout(d,12e4),f=await i(`${e}/vaults/${s}/asset?${a({ref:l})}`,{headers:{Authorization:`Bearer ${n.token}`},signal:u.signal}),f.status!==429){t.observe(f.status,f.headers);break}let m=await f.json().catch(()=>null);if(!t.observe(f.status,f.headers,m?.code,m?.retryAfterMs))break}if(!f.ok)throw new De(f.redirected&&(f.status===401||f.status===403)?502:f.status,null,"asset:"+l);clearTimeout(g),g=setTimeout(d,rm(Number(f.headers.get("content-length"))||0));let p=new Uint8Array(await f.arrayBuffer());return r(),p}finally{clearTimeout(g)}},async changes(s,l){let c=await o("GET",`${e}/vaults/${s}/changes?${a({since:String(l)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function Oa(n,e){let t=!1,r=0,i=null,o=null,a=()=>{let c=e.getSince(),u=[...c!==null&&Number.isSafeInteger(c)&&c>=0?[`since=${c}`]:[],...n.caps?[`caps=${encodeURIComponent(n.caps)}`]:[]];return`${n.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${n.vaultId}/events${u.length?`?${u.join("&")}`:""}`},s=(c,u=!1)=>{if(t)return;i?.abort(),e.onDown(c,u);let d=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,o=setTimeout(()=>void l(),d)},l=async()=>{if(t)return;i=new AbortController;try{await n.gate?.ready(i.signal)}catch{return}if(t)return;let c;try{if(c=await fetch(a(),{headers:{Authorization:`Bearer ${n.getToken?.()??n.token}`,Accept:"text/event-stream",...n.caps?{"X-Content-Caps":n.caps}:{}},signal:i.signal}),t){await c.body?.cancel();return}n.getToken?.()}catch(b){s(b);return}if(c.status===429&&n.gate&&(c.body?.cancel().catch(()=>{}),n.gate.observe(c.status,c.headers))){if(t)return;o=setTimeout(()=>void l(),Math.max(0,(n.gate.until()??Date.now())-Date.now()));return}if(!c.ok||!c.body){s(new Error(`sse http ${c.status}`));return}n.gate?.observe(c.status,c.headers),r=0;let u=Date.now();e.onOpen();let d=c.body.getReader(),g=new TextDecoder,f="",p="",m=[],y=()=>{if(n.getToken?.(),!m.length&&!p)return;let b=m.join(`
|
|
209
|
+
`),h=p||"message";p="",m=[];let E=null;try{E=b?JSON.parse(b):null}catch{return}h==="hello"?e.onHello(Number(E?.seq??0)):h==="change"?e.onChange(E):h==="reset"?e.onReset():h==="presence"?e.onPresence?.(E):h==="presence-roster"?e.onPresenceRoster?.(E):e.onOther?.(h,E)};try{for(;;){let{done:b,value:h}=await d.read();if(b)break;for(f+=g.decode(h,{stream:!0});;){let E=f.indexOf(`
|
|
210
|
+
`);if(E<0)break;let v=f.slice(0,E).replace(/\r$/,"");if(f=f.slice(E+1),v==="")y();else{if(v.startsWith(":"))continue;v.startsWith("event:")?p=v.slice(6).trim():v.startsWith("data:")&&m.push(v.slice(5).replace(/^ /,""))}}}}catch(b){t||s(b,Date.now()-u>=1e4);return}s(new Error("sse stream ended"),Date.now()-u>=1e4)};return l(),{stop:()=>{t=!0,o&&clearTimeout(o),i?.abort()}}}var zt=n=>Me().path.join(Ve().userDataDir(),Ve().isDevMode()?`${n}.dev.json`:`${n}.json`),Dd=zt,Sn=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),qr=n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0,Hr=n=>typeof n=="string"&&Dn(n)===n,jo=n=>typeof n=="string"&&n.length>0,sm=n=>Sn(n)&&qr(n.seq)&&jo(n.hash)&&qr(n.size)&&typeof n.mtimeMs=="number"&&Number.isFinite(n.mtimeMs),am=n=>typeof n=="number"&&Number.isFinite(n),c_=n=>Sn(n)&&jo(n.localHash)&&qr(n.localSize)&&am(n.localMtimeMs)&&qr(n.remoteSeq)&&(n.remoteHash===null||jo(n.remoteHash))&&(n.remoteUpdatedAt===null||typeof n.remoteUpdatedAt=="string")&&am(n.since),d_=n=>Sn(n)&&Hr(n.from)&&Hr(n.to)&&(n.kind==="file"||n.kind==="folder")&&(n.hashes===void 0||Sn(n.hashes)&&Object.values(n.hashes).every(jo));async function Pd(n){return Od(Dd(n))}var Ma=(n,e,t)=>n!==null&&n.vaultRoot===e&&n.vaultId===t&&n.folder==="";async function Od(n){let e;try{e=await Me().fs.readFile(n,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let t;try{t=JSON.parse(e)}catch{throw Error("Invalid cloud vault sync state; original data was retained")}if(!Sn(t)||typeof t.vaultRoot!="string"||!t.vaultRoot||typeof t.vaultId!="string"||!t.vaultId||typeof t.folder!="string"||t.rootIdentity!==void 0&&!Bt(t.rootIdentity)||t.mirrorMissing!==void 0&&t.mirrorMissing!==!0||t.mirrorRestore!==void 0&&t.mirrorRestore!=="list"&&(!Sn(t.mirrorRestore)||!Object.entries(t.mirrorRestore).every(([r,i])=>Hr(r)&&Sn(i)&&qr(i.seq)&&(i.hash===null||jo(i.hash))))||!Sn(t.files)||!Object.entries(t.files).every(([r,i])=>Hr(r)&&sm(i))||t.cursor!==void 0&&!qr(t.cursor)||t.lastSyncAt!=null&&!qr(t.lastSyncAt)||t.pending!==void 0&&(!Sn(t.pending)||!Object.entries(t.pending).every(([r,i])=>Hr(r)&&(i==="local"||i==="remote")))||t.moves!==void 0&&(!Array.isArray(t.moves)||!t.moves.every(d_))||t.held!==void 0&&(!Sn(t.held)||!Object.entries(t.held).every(([r,i])=>Hr(r)&&c_(i)))||t.dormant!==void 0&&(!Sn(t.dormant)||!Object.entries(t.dormant).every(([r,i])=>Hr(r)&&sm(i)))||t.dormantRoot!==void 0&&!Bt(t.dormantRoot))throw Error("Invalid cloud vault sync state; original data was retained");return{...t,cursor:t.cursor??0,lastSyncAt:t.lastSyncAt??null}}function lm(n){let e=null,t=null,r=Promise.resolve(),i=null,o=()=>{if(!e)return r;let a=e,s=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let l=Dd(n),c=`${l}.tmp-${Me().tmpTag()}-${Date.now()}-0`;await Me().fs.writeFile(c,s,"utf8"),await Me().fs.rename(c,l),i=null}catch(l){e??=a,i=l}}),r};return{save(a){e=a,!t&&(t=setTimeout(()=>{t=null,o()},500))},async flush(a=!1){if(t&&(clearTimeout(t),t=null),await o(),a&&i)throw i}}}async function cm(n){try{await Me().fs.unlink(Dd(n))}catch{}}var Uo=/^[0-9a-f]{64}$/;function dm(n){let e=Me(),t=()=>zt(n).replace(/\.json$/,".bases"),r=s=>e.path.join(t(),s),i=s=>e.fs.access(r(s)).then(()=>!0,()=>!1),o=new Map,a=(s,l)=>{let c=(o.get(s)??Promise.resolve()).then(l,l);return o.set(s,c),c.finally(()=>{o.get(s)===c&&o.delete(s)}),c};return{put(s,l){return Uo.test(s)?a(s,async()=>{try{if(await i(s))return;await e.fs.mkdir(t(),{recursive:!0});let c=`${r(s)}.tmp-${e.tmpTag()}-${Date.now()}`;await e.fs.writeFile(c,l,"utf8"),await e.fs.rename(c,r(s))}catch{}}):Promise.resolve()},async get(s){if(!Uo.test(s))return null;try{let l=await e.fs.readFile(r(s),"utf8");return e.sha256Hex(l)===s?l:null}catch{return null}},drop(s,l){return Uo.test(s)?a(s,async()=>{if(!(l&&!l()))try{await e.fs.rm(r(s),{force:!0})}catch{}}):Promise.resolve()},async has(s){return Uo.test(s)&&i(s)},async prune(s){let l;try{l=(await e.fs.readdir(t(),{withFileTypes:!0})).filter(c=>c.isFile()).map(c=>c.name)}catch{return}for(let c of l)if(!s.has(c)&&!(!Uo.test(c)&&!/^[0-9a-f]{64}\.tmp-/.test(c)))try{await e.fs.rm(e.path.join(t(),c),{force:!0})}catch{}}}}var $a=720*60*60*1e3,u_=/^[0-9a-f]{64}$/,fm="device",f_=/^(?:[0-9a-f]{64}|device|signed-out)$/,Na=new Map,um=(n,e)=>{let t=(Na.get(n)??Promise.resolve()).then(e,e),r=t.catch(()=>{});return Na.set(n,r),r.then(()=>{Na.get(n)===r&&Na.delete(n)}),t},Wr=class extends Error{constructor(e){super(`sync recovery save failed: ${e?.message??String(e)}`),this.name="RecoveryError"}};function Vo(n,e){let t=Me(),r=()=>t.path.join(e?e():Ve().homeDir(),"sync-recovery",n),i=l=>t.fs.access(l).then(()=>!0,()=>!1),o=async(l,c)=>{let u=`${l}.tmp-${t.tmpTag()}-${Date.now()}`;try{await t.fs.writeFile(u,c),await t.fs.rename(u,l)}catch(d){throw await t.fs.rm(u,{force:!0}).catch(()=>{}),d}},a={async save(l,c){let u=r(),d=await um(u,async()=>{try{let g=t.path.join(u,t.sha256Hex(l));await t.fs.mkdir(u,{recursive:!0}),await i(g)||await o(g,l);let f=`${g}.json`,p=[];try{let m=JSON.parse(await t.fs.readFile(f,"utf8"));Array.isArray(m)&&(p=m)}catch{}return p.push({...c,savedAt:Date.now()}),await o(f,JSON.stringify(p)),g}catch(g){throw new Wr(g)}});return a.prune(),d},prune(l=Date.now()){let c=r();return um(c,()=>s(c,l))}},s=async(l,c)=>{let u;try{u=(await t.fs.readdir(l,{withFileTypes:!0})).filter(d=>d.isFile()).map(d=>d.name)}catch{return}for(let d of u){if(!u_.test(d))continue;let g=t.path.join(l,d),f=0;try{let p=JSON.parse(await t.fs.readFile(`${g}.json`,"utf8"));f=Math.max(0,...p.map(m=>Number(m?.savedAt)||0))}catch{try{f=(await t.fs.stat(g)).mtimeMs}catch{continue}}if(!(c-f<=$a))try{await t.fs.rm(g,{force:!0}),await t.fs.rm(`${g}.json`,{force:!0})}catch{}}};return a}async function gm(n,e=Date.now()){let t=Me(),r;try{r=(await t.fs.readdir(t.path.join(n,"sync-recovery"),{withFileTypes:!0})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return}for(let i of r)f_.test(i)&&await Vo(i,()=>n).prune(e).catch(()=>{})}var g_=()=>({uploaded:0,downloaded:0,merged:0,renamed:0,deletedCloud:0,deletedLocal:0,held:0}),$t=(n,e)=>{try{return n()}catch{return e}},p_=n=>n.failedCount>0||Object.values(n.counts).some(e=>e>0),Ei=class{live=null;lastSummary=null;clock;queued;constructor(e={}){this.clock=e.clock??Date.now,this.queued=e.queued??(()=>0)}get active(){return this.live!==null}begin(e="checking"){$t(()=>{this.live||(this.live={startedAt:this.clock(),stage:e,done:0,planned:0,plannedDone:0,bytesTotal:0,bytesDone:0,current:null,counts:g_(),failed:[],failedCount:0})},void 0)}stage(e){$t(()=>{this.live&&(this.live.stage=e)},void 0)}plan(e,t){$t(()=>{let r=this.live;!r||!(e>0)||(r.planned+=e,r.bytesTotal=r.bytesTotal===null||t===null?null:r.bytesTotal+t)},void 0)}drop(){$t(()=>{let e=this.live;e&&e.planned>e.plannedDone&&e.planned--},void 0)}at(e,t,r=null){$t(()=>{this.live&&(this.live.current={path:e,op:t,bytesDone:null,bytesTotal:r})},void 0)}bytes(e){$t(()=>{let t=this.live?.current;t&&(t.bytesDone=e)},void 0)}stepDone(e,t=0){$t(()=>{let r=this.live;r&&(r.done++,e&&r.plannedDone++,t>0&&(r.bytesDone+=t),r.current=null)},void 0)}addBytes(e){$t(()=>{this.live&&e>0&&(this.live.bytesDone+=e)},void 0)}count(e,t=1){$t(()=>{this.live&&t>0&&(this.live.counts[e]+=t)},void 0)}fail(e){$t(()=>{let t=this.live;if(!t)return;let r=t.failed.findIndex(i=>i.path===e.path);if(r>=0){t.failed[r]=e;return}t.failedCount++,t.failed.length<20&&t.failed.push(e)},void 0)}end(e){return $t(()=>{let t=this.live;if(!t)return null;this.live=null;let r={startedAt:t.startedAt,finishedAt:this.clock(),completed:e,counts:t.counts,failed:t.failed,failedCount:t.failedCount};return this.lastSummary=r,r},null)}last(){return this.lastSummary}progress(){return $t(()=>{let e=this.live;if(!e)return null;let t=Math.max(0,$t(this.queued,0)),r=Math.max(0,e.planned-e.plannedDone),i=e.done+r+t,a=e.planned>0&&e.done===e.plannedDone&&t===0&&e.bytesTotal!==null&&e.bytesTotal>0?e.bytesTotal:null;return{startedAt:e.startedAt,stage:e.stage,files:{done:e.done,total:e.stage==="checking"&&i===0?null:i},bytes:a===null&&e.bytesDone===0?null:{done:e.bytesDone,total:a},current:e.current?{...e.current}:null}},null)}reset(){this.live=null,this.lastSummary=null}},_i=class{open=new Map;seq=0;mergeWithinMs;constructor(e={}){this.mergeWithinMs=e.mergeWithinMs??6e4}take(e,t,r={}){return $t(()=>{let i=p_(t);if(!i&&!r.keepIdle)return null;let o=this.open.get(e.feed),a=o&&t.startedAt-o.record.finishedAt<=this.mergeWithinMs,s=o&&(i&&o.changed&&a||!i&&!o.changed);if(o&&s){let c=o.record,u=[...c.failed.filter(g=>!t.failed.some(f=>f.path===g.path)),...t.failed].slice(-20),d={...c,...i?{}:{startedAt:t.startedAt},finishedAt:t.finishedAt,completed:t.completed,uploaded:c.uploaded+t.counts.uploaded,downloaded:c.downloaded+t.counts.downloaded,merged:c.merged+t.counts.merged,renamed:c.renamed+t.counts.renamed,deletedCloud:c.deletedCloud+t.counts.deletedCloud,deletedLocal:c.deletedLocal+t.counts.deletedLocal,held:c.held+t.counts.held,failed:u,failedCount:Math.max(u.length,c.failedCount,t.failedCount)};return this.open.set(e.feed,{record:d,changed:i}),d}let l={...e,id:`${e.feed}#${t.startedAt.toString(36)}-${(this.seq++).toString(36)}`,startedAt:t.startedAt,finishedAt:t.finishedAt,completed:t.completed,...t.counts,failed:t.failed.slice(0,20),failedCount:t.failedCount};return this.open.set(e.feed,{record:l,changed:i}),l},null)}reset(){this.open.clear()}};var pm=5*1024*1024,hm=5*1024*1024,h_=3e4,m_=5e3,y_=5*6e4,w_=2500,b_=3e3,v_=5,S_=256*1024,k_=5,La=1024*1024,mm=200,E_=6e4,__=50,R_=".sync-trash",St=n=>Me().sha256Hex(n),Md=n=>{let{mirror:e,...t}=n??{};return t};function zo(n,e){let t=e??{localRoot:ht(),shadowName:`amadeus-sync-${Sr()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]},r=w=>{let A=yo(w,"");if(!A||A.split("/").some(rn))return null;for(let T of t.excludePrefixes??[])if(A===T.replace(/\/$/,"")||A.startsWith(T))return null;if(t.ignoreNames?.length&&A.split("/").some(T=>t.ignoreNames.includes(T)))return null;let I=t.serverDir?`${t.serverDir}/${A}`:A;return t.inScope&&!t.inScope(I,We(I))?null:I},i=w=>{let A;if(t.serverDir){if(!w.startsWith(`${t.serverDir}/`))return null;A=w.slice(t.serverDir.length+1)}else{for(let I of t.excludePrefixes??[])if(w.startsWith(I))return null;A=w}return A.split("/").some(I=>rn(I)||!!t.ignoreNames?.includes(I))?null:A},o=(w,A)=>!t.inScope||t.inScope(w,A),a=t.accountId??Ye(),{fs:s,path:l,directoryIdentity:c}=Me(),u=w=>s.access(w).then(()=>!0,()=>!1),d=!1,g=!1,f=0,p=Promise.resolve(),m=new Set,y="disabled",b=null,h=null,E=null,v=null,k=null,C=null,S=null,_=null,R=null,N=()=>{let w=n.loadCreds();if(!C||a!==Ye()||!w.token||w.cloudUrl?.replace(/\/+$/,"")!==C.cloudUrl.replace(/\/+$/,""))throw new De(401,{code:"ACCOUNT_CHANGED"},"sync-session");return w.token},D=null,M=0,x=new Map,$=null,O=lm(t.shadowName),q=dm(t.shadowName),ie=Vo(Sr(a)),Y=!1,ne=new Map,ce=!1,Re=!1,Ee=[],me=new Ei({queued:()=>Z.reduce((w,A)=>w+(Lt(A.key)?1:0),0)}),Ce=(w,A,I)=>{try{n.onHealth?.(w,A,I)}catch{}w==="uploads"&&me.count("uploaded",A??1)},Be=Ia(Ce),_e=0,ft=()=>{Re||Ce("massDeleteGuard"),Re=!0},at=()=>{h&&(h.pending=ne.size?Object.fromEntries(ne):void 0,O.save(h))},Ir=()=>{Re=!1,Ee.length=0},te=()=>{if(Re)return!0;let w=Date.now();for(;Ee.length&&w-Ee[0]>E_;)Ee.shift();return Ee.length>=__?(ft(),!0):!1},Z=[],P=new Set,F=(w,A)=>{if(A==="syncing"&&w!=="syncing"){me.begin("transferring");return}if(w!=="syncing"||A==="syncing")return;let I=me.end(A==="idle");if(I)try{n.onRound?.(I)}catch{}},L=!1,j=null,z=null,W=null,ee=null,K=()=>{!d||ee||(ee=setTimeout(()=>{ee=null,n.onStatus(Rn())},200))},H=(w,A,I)=>{let T=y;y=w,A!==void 0&&(b=A),se(T,w,I),F(T,w),K()},oe=!1,se=(w,A,I)=>{if(A==="syncing"&&w!=="syncing"&&(_e=Date.now()),A==="idle"&&w==="syncing"&&(Ce("cycles"),Ce("cycleMsTotal",Math.max(0,Date.now()-_e))),A==="idle"||A==="disabled"){oe=!1,Be.ok();return}if(I===null)return;let T=I??Bh(A,b);T&&Be.error(T)},ue=(w,A)=>{x.set(w,A),Ce(Lh(A),1,w),me.fail(If(w,A))},X=(w,A=!1)=>{if(!(!d||!g)){if(w.key){if(P.has(w.key))return;P.add(w.key)}A?Z.unshift(w):Z.push(w),tv()}},ye=new Map,Ne=w=>{if(!d)return;let A=(h?.files[w]?.size??0)>S_,I=(t.pushQuietMs??b_)*(A?k_:1),T=Date.now(),B=ye.get(w);B&&clearTimeout(B.timer);let V=B?.since??T,J=Math.max(0,Math.min(I,V+I*v_-T)),U=setTimeout(()=>{ye.delete(w),X({key:w,run:()=>Ge(w,!0)})},J);ye.set(w,{timer:U,since:V}),K()},Pe=()=>{for(let{timer:w}of ye.values())clearTimeout(w);ye.clear()},Ht=new Set(["EACCES","EPERM","EISDIR","ENOTDIR","ENAMETOOLONG","EILSEQ","EINVAL","ELOOP","EBUSY","EFBIG","EIO"]),gr=w=>!(w instanceof De)&&typeof w?.code=="string"&&Ht.has(w.code),pr=w=>!(w instanceof De)||w.status>=500||w.status===0,Lt=w=>!!w&&!w.startsWith("\0"),Qb=w=>w instanceof De?w.body?.code||`http ${w.status}`:w?.code??"error",Yi=w=>w instanceof De&&(w.status===401||w.status===403),ev=w=>w==="pull"||w==="push"||w==="pushCreate"||w==="pushDelete"||w==="deleteLocal"||w==="conflict",If=(w,A)=>{let I=i(w)??w;if(A==="TOO_LARGE"){let T=it(We(w))?pm:$??hm;return{path:I,reason:"too-large",code:A,maxBytes:T,...h?.files[w]?.size?{size:h.files[w].size}:{}}}return Ht.has(A)?{path:I,reason:"unreadable",code:A}:/^http 5\d\d$/.test(A)||A==="timeout"?{path:I,reason:"failed",code:A}:{path:I,reason:"rejected",code:A}},Ss=(w,A)=>{ue(w,Qb(A)),K()},tv=async()=>{if(!L){L=!0;try{for(;Z.length;){(y==="idle"||y==="starting")&&H("syncing");let w=Z.shift();w.key&&P.delete(w.key);let A=Lt(w.key);A&&me.at(i(w.key)??w.key,"check");try{await w.run(),A&&me.stepDone(!1)}catch(I){if(!d)return;if(Yi(I)){Z.length=0,P.clear(),eo(),H("auth-required","login-expired");return}if(pr(I)&&!(gr(I)&&Lt(w.key))){X(w,!0),eo(),H("offline",I?.message||"network error"),Xi();return}Ss(w.key??"(op)",I),A&&me.stepDone(!1)}}d&&y==="syncing"&&(h&&(h.lastSyncAt=Date.now(),O.save(h)),H("idle",null))}finally{L=!1;for(let w of m)w();m.clear()}}},Xi=()=>{!d||j||(j=setTimeout(()=>{j=null,to()},h_))},Te=new Map,xr=0,nt=null,ks=()=>!!z||!!nt||!d,Jl=w=>w instanceof De&&w.status>=500||w?.name==="TimeoutError",xf=t.pushRetryMs??m_,Tf=w=>{Te.get(w)&&(Te.delete(w),x.delete(w))},Zi=(w,A)=>{(A||!Te.has(w))&&Te.set(w,A)},Df=(w,A,I)=>{ue(w,A instanceof De?`http ${A.status}`:"timeout"),Zi(w,I),xr=Math.min(xr*2||xf,y_),z=setTimeout(Es,xr),K()},Pf=(w,A,I)=>{let T=new AbortController,B=A(T.signal).then(J=>()=>J,J=>()=>{throw J}),V={path:w,abort:T,after:[],settle:async()=>{let J=await B;if(nt===V){nt=null;try{await I(J)}catch(U){if(Yi(U)||pr(U))throw U;Ss(w,U)}finally{for(let U of V.after)X(U);Of(w)}}}};nt=V,B.then(()=>X({run:V.settle}))},ei=(w,A)=>{for(let[I,T]of[...Te])!T||!yt(I,w)||(Te.delete(I),x.delete(I),A!==null&&Te.set(A+I.slice(w.length),T));K()},Es=()=>{z=null;let[w]=Te;if(w===void 0)return;let[A]=w;P.delete(A),X({key:A,run:async()=>{if(nt?.path===A)return;let I=Te.get(A),T=!I&&Te.delete(A);(I||T)&&x.delete(A);try{I?await Et(A,I.seq):T&&await Ge(A,!0)}finally{T&>(A)&&Zi(A),Of(A)}}})},Of=w=>{if(!ks())if(Te.has(w)){let A=Te.get(w);Te.delete(w),Te.set(w,A),z=setTimeout(Es,xr||xf)}else Es()},lt=w=>{if(!D||!h)throw new Error("engine not bound");let A=i(w);if(A===null)throw new Error("path outside binding: "+w);let I=l.resolve(D,Op(A,h.folder)),T=l.relative(D,I);if(T.startsWith("..")||l.isAbsolute(T))throw new Error("path escapes vault: "+w);return I},_s=w=>({size:w,mtimeMs:-1}),Mf=async w=>{try{let A=await s.stat(w);return A.isFile()?{size:A.size,mtimeMs:Math.floor(A.mtimeMs)}:null}catch{return null}},Nf=async w=>{if(!s.lstat||!D)return Mf(w);let A=l.relative(D,w).split(l.sep),I=D;for(let[T,B]of A.entries()){I=l.join(I,B);let V=await s.lstat(I).catch(J=>{if(J?.code==="ENOENT")return null;throw J});if(!V)return null;if(V.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(T===A.length-1&&V.isFile())return{size:V.size,mtimeMs:Math.floor(V.mtimeMs)};if(T===A.length-1||!V.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},nv=0,Kl=async(w,A,I,T)=>{if(!await It())throw Error("Cloud vault sync root is unavailable or changed");let B=D&&E?{path:D,identity:E}:void 0;await s.mkdir(l.dirname(w),{recursive:!0});let V=`${w}.tmp-${Me().tmpTag()}-${Date.now()}-${nv++}`;await s.writeFile(V,A);let J=await Mf(V)??_s(Ms(A));try{if(!T())return null;let U=Me().compareAndReplace;if(!U)throw new Error("Host does not support safe cloud download commits");let G=await U(V,w,I,T,B);if(!G&&!await It())throw Error("Cloud vault sync root is unavailable or changed");return G?J:null}finally{await It()&&await s.rm(V,{force:!0})}},$f=async w=>{let A;try{A=await s.readdir(w,{withFileTypes:!0})}catch{return}for(let I of A)I.isDirectory()&&await $f(l.join(w,I.name));try{await s.rmdir(w)}catch{}},qt=async w=>{let A=lt(w),I=await Nf(A);if(!await It())throw Error("Cloud vault sync root is unavailable or changed");if(s.lstat&&!I)return null;let T;try{T=await s.readFile(A)}catch(V){if(V?.code!=="ENOENT")throw V;if(!await It())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:it(We(w))?St(Yt(T)):St(T),size:I?.size??T.length,mtimeMs:I?.mtimeMs??-1,buf:T}},Ct=async(w,A,I,T,B)=>{if(!h)return;let V=h.files[w]?.hash;h.files[w]={seq:A,hash:I,size:T.size,mtimeMs:T.mtimeMs},h.mirrorRestore&&h.mirrorRestore!=="list"&&delete h.mirrorRestore[w],O.save(h),B!==void 0&&await Lf(w,I,B),V&&V!==I&&await Yl(V)},Lf=async(w,A,I)=>{if(!it(We(w))||Ms(I)>La)return;let T=typeof I=="string"?I:Yt(I);St(T)===A&&await q.put(A,T)},Yl=async w=>{let A=()=>!!h&&!Object.values(h.files).some(I=>I.hash===w)&&!Object.values(h.dormant??{}).some(I=>I.hash===w);A()&&await q.drop(w,A)},Wt=w=>{if(h&&w in h.files){let A=h.files[w].hash;delete h.files[w],O.save(h),Yl(A)}},Gt=(w,A,I)=>{if(!h)return;let T=h.held?.[w];Wt(w),h.held={...h.held,[w]:{localHash:A.hash,localSize:A.size,localMtimeMs:A.mtimeMs,remoteSeq:I.seq,remoteHash:I.hash,remoteUpdatedAt:I.updatedAt!==void 0?I.updatedAt:T&&T.remoteSeq===I.seq?T.remoteUpdatedAt:null,since:T?.since??Date.now()}},O.save(h),K()},$e=w=>{if(!h?.held||!Object.hasOwn(h.held,w))return;let{[w]:A,...I}=h.held;h.held=Object.keys(I).length?I:void 0,O.save(h),K()},_n=w=>h?.held&&Object.hasOwn(h.held,w)?h.held[w]:void 0,fn=w=>i(w)!==null&&o(w,We(w)),Xl=w=>{!h||!Object.hasOwn(h.files,w)||(h.dormant={...h.dormant,[w]:h.files[w]},E&&(h.dormantRoot??=E),delete h.files[w],O.save(h))},Rs=w=>{if(!h?.dormant||!Object.hasOwn(h.dormant,w))return;let A=h.dormant[w].hash,{[w]:I,...T}=h.dormant;h.dormant=Object.keys(T).length?T:void 0,h.dormant||delete h.dormantRoot,O.save(h),Yl(A)},Ff=w=>!!h?.dormant&&Object.hasOwn(h.dormant,w)&&!Object.hasOwn(h.files,w)&&fn(w),Bf=()=>X({key:"\0full",run:Tr}),jf=()=>{if(h){for(let w of Object.keys(h.files))!fn(w)&&!gt(w)&&Xl(w);for(let w of Object.keys(h.held??{}))!fn(w)&&!gt(w)&&$e(w)}},Et=async(w,A)=>{if(!v||!h||gt(w))return;if(Ff(w)){Bf();return}me.at(i(w)??w,"download");let I=He,T=We(w),B=_n(w);if(B&&!it(T)){Tf(w),A!==null&&A!==B.remoteSeq&&Gt(w,{hash:B.localHash,size:B.localSize,mtimeMs:B.localMtimeMs},{seq:A,hash:null,updatedAt:null});return}if(it(T)){let G;try{G=await v.getFile(h.vaultId,w),Ce("downloads")}catch(re){if(re instanceof De&&re.status===404){await Zl(w);return}throw re}await Uf(w,T,G.content,G.seq,G.hash??St(G.content),I);return}if(ks()){Zi(w,{seq:A}),K();return}let{vaultId:V}=h,J=v,U={seq:A};Te.set(w,U),Pf(w,G=>J.getAsset(V,w,G),async G=>{let re=Te.get(w)===U,Q;try{Q=G(),xr=0,Ce("downloads")}catch(fe){if(!re)return;if(Te.delete(w),fe instanceof De&&fe.status===404){ue(w,"ASSET_404"),K();return}if(Jl(fe)){Df(w,fe,{seq:A});return}throw fe}re&&await Uf(w,T,Q,A??0,St(Q),I)}),K()},Uf=async(w,A,I,T,B,V)=>{if(!h)return;let J=async de=>{await Ct(w,T,B,de,I),Te.get(w)&&(Te.delete(w),x.delete(w))},U=await qt(w);if(V!==He||gt(w))return;let G=h.mirrorRestore,re=G&&G!=="list"&&Object.hasOwn(G,w)?G[w]:void 0;if(re&&(re.hash!==B||re.seq!==T)){let de={...re};Object.assign(re,{hash:B,seq:T}),O.save(h);try{await O.flush(!0)}catch(ge){throw Object.assign(re,de),O.save(h),ge}if(!d||V!==He||gt(w))return}if(U&&U.hash===B){await J(U),$e(w);return}let Q=h.files[w];if(U&&(!Q||_n(w)||ri(Q,{seq:T,hash:B})&&U.hash!==Q.hash)){Tf(w),Gt(w,U,{seq:T,hash:B});return}if($e(w),U&&Q&&B===Q.hash&&U.hash!==Q.hash){await J(_s(Q.size)),X({key:w,run:()=>Ge(w)});return}let fe=U?St(U.buf):null;if(U&&(!Q||U.hash!==Q.hash)){if(Q&&it(A)&&typeof I=="string"&&await rv(w,Q,U,I,T,B,()=>V===He&&!gt(w))){me.count("merged");return}if(V!==He||gt(w)||!await Vf(w,()=>V===He&&!gt(w)))return;fe=null}let ct=await Kl(lt(w),I,fe,()=>d&&V===He&&!gt(w));if(!ct){X({key:w,run:()=>Ge(w)});return}await J(ct),me.count("downloaded")},rv=async(w,A,I,T,B,V,J)=>{try{if(!v||!h||I.buf.length>La||T.length>La)return!1;let U=await q.get(A.hash);if(U===null){let fe=(await v.listVersions(h.vaultId,w)).find(de=>de.seq===A.seq);if(!fe)return!1;let ct=await v.getVersion(h.vaultId,fe.id);if(St(ct)!==A.hash)return!1;U=ct}let G=Yt(I.buf),re;if(We(w)==="db"){let Q=Yp(),fe=Q?Q(w,G,U,T):null;re=fe&&!fe.conflict?fe.content:null}else re=np(G,U,T);return re===null?!1:await Kl(lt(w),re,St(I.buf),()=>d&&J())?(await Ct(w,B,V,_s(Ms(re)),T),X({key:w,run:()=>Ge(w)}),!0):(X({key:w,run:()=>Ge(w)}),!0)}catch{return!1}},Vf=async(w,A)=>{let I=Dn(Ys(w,new Date));if(!I)return!0;let T=I.lastIndexOf("."),B=T>I.lastIndexOf("/"),V=B?I.slice(0,T):I,J=B?I.slice(T):"",U=I,G=Me().existsSync;if(G)for(let re=2;G(lt(U));re++)U=`${V}-${re}${J}`;else for(let re=2;await u(lt(U));re++)U=`${V}-${re}${J}`;if(!A())return!1;try{await s.rename(lt(w),lt(U))}catch(re){if(re?.code==="ENOENT")return!0;throw re}return M++,Ce("conflicts"),X({key:U,run:()=>Ge(U)}),K(),!0},zf=async w=>{if(!D)return;let A=lt(w),I=i(w)??w;me.at(I,"delete");let T=l.join(D,R_,new Date().toISOString().slice(0,10),...I.split("/")),B=await u(T)?`${T}.${Date.now()}`:T;try{await s.mkdir(l.dirname(B),{recursive:!0}),await s.rename(A,B)}catch(V){if(V?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${A}: ${V?.message??String(V)}`)}me.count("deletedLocal")},Zl=async w=>{if(!h||i(w)===null)return;ei(w,null),$e(w),Rs(w);let A=await qt(w);if(gt(w))return;let I=h.files[w]??null,T=Xs(A?.hash??null,I,null);if(T.kind==="deleteLocal"){if(!ce&&te()){ne.set(w,"local"),at(),K();return}Ee.push(Date.now()),await zf(w),Wt(w)}else T.kind==="pushCreate"?(Wt(w),X({key:w,run:()=>Ge(w)})):Wt(w)},Hf=(w,A)=>{if(h){ei(w,A);for(let I of Object.keys(h.files))if(I===w||I.startsWith(`${w}/`)){let T=A+I.slice(w.length);h.files[T]=h.files[I],delete h.files[I]}for(let I of[h.held,h.dormant])if(I)for(let T of Object.keys(I))(T===w||T.startsWith(`${w}/`))&&(I[A+T.slice(w.length)]=I[T],delete I[T]);O.save(h),K()}},qf=async w=>{if(!v||!h||w.seq<=h.cursor||!await It())return;if(w.origin.client&&v.clientId===w.origin.client){h.cursor=w.seq,O.save(h);return}let A=w.type==="structure"?"folder":w.type,I=B=>i(B)!==null&&o(B,A);if(!I(w.path)&&!(w.newPath&&I(w.newPath))){h.cursor=w.seq,O.save(h);return}let T=w.path;if(w.op!=="write"&&w.op!=="mkdir"){for(;nt&&(yt(nt.path,T)||w.newPath&&yt(nt.path,w.newPath));)await nt.settle();if(!d)return}switch(w.op){case"write":await Et(T,w.fileSeq);break;case"delete":await Zl(T);break;case"move":{let B=w.newPath;if(!B)break;let V=h.files[T],J=await qt(T),U=!!Te.get(T);ei(T,B),Rs(T),_n(T)&&($e(T),X({key:T,run:()=>Ge(T)})),U&&Zi(B,{seq:w.fileSeq});let G=B!==T&&await Nf(lt(B)).then(re=>re!==null,()=>!0);if(J&&V&&G)await Et(B,w.fileSeq);else if(J&&V)try{await s.mkdir(l.dirname(lt(B)),{recursive:!0}),await s.rename(lt(T),lt(B)),h.files[B]={...V,seq:U?V.seq:w.fileSeq??V.seq},delete h.files[T],O.save(h)}catch{await Et(B,w.fileSeq)}else Wt(T),await Et(B,w.fileSeq);break}case"mkdir":await s.mkdir(lt(T),{recursive:!0});break;case"rename-folder":case"move-folder":{let B=w.newPath;if(!B)break;try{await s.mkdir(l.dirname(lt(B)),{recursive:!0}),await s.rename(lt(T),lt(B))}catch{}Hf(T,B);break}case"delete-folder":{let B=`${T}/`;for(let V of[...Object.keys(h.files),...Object.keys(h.held??{}),...Object.keys(h.dormant??{})])(V===T||V.startsWith(B))&&await Zl(V);ei(T,null),await $f(lt(T));break}}if(h.cursor=w.seq,O.save(h),w.op==="move"||w.op==="rename-folder"||w.op==="move-folder"||w.op==="delete"||w.op==="delete-folder")try{await n.onRemoteApplied?.(w)}catch{}},iv=async(w,A,I)=>{let T=Number(A?.seq??0),B=A?.content??null,V;if(A?.seq===void 0&&v&&h)try{let G=await v.getFile(h.vaultId,w);T=G.seq,B=G.content,V=G.updatedAt}catch(G){if(!(G instanceof De)||G.status!==404)throw G;T=0,B=null}if(B!==null&&St(B)===I.hash){await Ct(w,T,I.hash,I,B),$e(w);return}if(B===null&&T===0){if(!h?.files[w]){ue(w,A?.code||"EXISTS"),K();return}Wt(w),X({key:w,run:()=>Ge(w)});return}let J=h?.files[w],U=B===null?null:St(B);if(!J||ri(J,{seq:T,hash:U})){Gt(w,I,{seq:T,hash:U,updatedAt:V});return}await Et(w,T)},As=async(w,A)=>{if(!v||!h)return;let I=await qt(w);if(!I){X({key:w,run:()=>Ge(w)});return}if(I.size>pm){ue(w,"TOO_LARGE"),K();return}me.at(i(w)??w,"upload",I.size);let T=Yt(I.buf),B=A>0?h.files[w]?.hash:void 0;try{let V=await v.putFile(h.vaultId,w,T,A,!1,B);Ce("uploads"),x.delete(w),await Ct(w,V.seq,V.hash??I.hash,I,I.buf),$e(w)}catch(V){if(V instanceof De&&V.status===409){await iv(w,V.body,I);return}throw V}},Cs=async(w,A)=>{if(!v||!h)return;let I=await qt(w);if(!I){X({key:w,run:()=>Ge(w)});return}if(I.size>($??hm)){ue(w,"TOO_LARGE"),K();return}if(me.at(i(w)??w,"upload",I.size),Zi(w),K(),ks())return;let{vaultId:T}=h,B=v,V=A>0?h.files[w]?.hash:void 0;Pf(w,J=>B.putBinary(T,w,I.buf,{baseSeq:A,signal:J,expectedHash:V}),async J=>{if(h){Te.get(w)||Te.delete(w);try{let U=J();xr=0,Ce("uploads"),x.delete(w),await Ct(w,U.seq,I.hash,I),$e(w)}catch(U){if(Jl(U)){Df(w,U);return}if(!(U instanceof De)||U.status!==409)throw U;let G=Number(U.body?.seq??0),re=U.body?.hash??null;if(re!==null&&re===I.hash){await Ct(w,G,I.hash,I),$e(w);return}if(G===0){if(!h.files[w]){ue(w,U.body?.code||"EXISTS"),K();return}Wt(w),X({key:w,run:()=>Ge(w)});return}let Q=h.files[w];if(!Q||ri(Q,{seq:G,hash:re})){Gt(w,I,{seq:G,hash:re});return}await Et(w,G)}}})},Wf=async w=>{if(!v||!h||gt(w)||i(w)===null)return;me.at(i(w)??w,"delete");let A=He,I=h.files[w];if(I){if(it(We(w)))try{let T=await v.getFile(h.vaultId,w);if(T.seq!==I.seq||T.hash!==null&&T.hash!==I.hash){await Et(w,T.seq);return}}catch(T){if(T instanceof De&&T.status===404){Wt(w);return}throw T}if(!(!await It()||A!==He||gt(w))){try{await v.deleteFile(h.vaultId,w,I.seq,{confirmed:ce,expectedHash:I.hash})}catch(T){if(T instanceof De&&T.status===409){await Et(w,Number(T.body?.seq??0)||null);return}if(T instanceof De&&T.status===429&&T.body?.code==="MASS_DELETE_BLOCKED"){ne.set(w,"remote"),ft(),at(),K();return}throw T}Wt(w),me.count("deletedCloud")}}},Is=w=>s.stat(w).catch(A=>{if(A?.code==="ENOENT")return null;throw A}),Ql=async w=>{let A=Ve();if(e||!a||a!==Ye()||w!==ht(a)||!A.isManagedCloudVault(w)||!s.lstat)return!1;let I=A.homeDir(),T=l.relative(I,w);if(!T||T.startsWith("..")||l.isAbsolute(T))return!1;let B=I;for(let V of T.split(l.sep)){B=l.join(B,V);let J=await s.lstat(B).catch(U=>{if(U.code==="ENOENT")return null;throw U});if(J&&(!J.isDirectory()||J.isSymbolicLink()))return!1}return!0},hr=w=>(g=!1,ce=!1,Z.length=0,P.clear(),nc(),eo(),H("error",`${w}: ${D}`),Xi(),!1),ec=w=>{let A=E??h?.rootIdentity,I=w!==null&&w.isDirectory();return I&&(!A||hn(A,w))?!0:hr(I?"vault-changed":"vault-missing")},It=async()=>!!D&&ec(await Is(D)),He=0,xs=new Set,Ts=new Map,xt=w=>JSON.stringify([w.from,w.to]),yt=(w,A)=>w===A||w.startsWith(`${A}/`),gt=w=>[...h?.moves??[],...xs].some(A=>yt(w,A.from)||yt(w,A.to)),gn=()=>!!(h?.moves?.length||xs.size),Ds=async w=>{if(!v||!h)return;let{from:A,to:I,kind:T}=w;if(i(A)===null||i(I)===null)throw new Error("Invalid queued cloud move");if(nt&&(yt(nt.path,A)||yt(nt.path,I))){nt.after.push({key:`move:${xt(w)}`,run:()=>Ds(w)});return}if(w.hashes??=Object.fromEntries([...Object.entries(h.held??{}).filter(([U,G])=>yt(U,A)&&G.remoteHash!==null).map(([U,G])=>[U.slice(A.length),G.remoteHash]),...Object.entries(h.files).filter(([U])=>yt(U,A)).map(([U,G])=>[U.slice(A.length),G.hash])]),O.save(h),await O.flush(!0),!await It())return;let B,V=!1;try{if(T==="folder"){let U=l.posix.dirname(A)==="."?"":l.posix.dirname(A),G=l.posix.dirname(I)==="."?"":l.posix.dirname(I);U===G?await v.renameFolder(h.vaultId,A,l.posix.basename(I)):await v.moveFolder(h.vaultId,A,G)}else{let U=await v.move(h.vaultId,A,I);B=Number(U.seq)}}catch(U){if(!(U instanceof De)||U.status!==404)throw U;let G=await v.tree(h.vaultId);if(G.entries.some(fe=>yt(fe.path,A))||G.folders.some(fe=>yt(fe,A)))throw U;let Q=G.entries.find(fe=>fe.path===I);if(B=Q?.seq,V=!Q&&!G.entries.some(fe=>yt(fe.path,I))&&!G.folders.some(fe=>yt(fe,I)),!V){let fe=Object.entries(w.hashes);if(!(fe.length>0&&fe.every(([de,ge])=>G.entries.some(Oe=>Oe.path===I+de&&Oe.hash===ge))))throw new De(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(V){for(let U of Object.keys(h.files))yt(U,A)&&delete h.files[U];for(let U of Object.keys(h.held??{}))yt(U,A)&&$e(U);for(let U of Object.keys(h.dormant??{}))yt(U,A)&&Rs(U);ei(A,null)}else Hf(A,I),B!==void 0&&h.files[I]&&!Te.get(I)&&(h.files[I].seq=B);h.moves=(h.moves??[]).filter(U=>xt(U)!==xt(w)),O.save(h);try{await O.flush(!0)}catch(U){throw h.moves.unshift(w),O.save(h),U}let J=Ts.get(xt(w));Ts.delete(xt(w)),J?.(),gt(I)||(T==="folder"?await tc():await Ge(I))},Ge=async(w,A=!1)=>{if(!h||gt(w))return;if(nt?.path===w){nt.after.push({key:w,run:()=>Ge(w,A)});return}if(!fn(w)){Xl(w),$e(w);return}if(!await It())return;let I=await qt(w);if(gt(w))return;let T=h.files[w]??null;if(!T&&Ff(w)){Bf();return}let B=_n(w);if(B){I&&I.hash===B.remoteHash&&it(We(w))?await Et(w,null):I&&I.hash===B.remoteHash?(await Ct(w,B.remoteSeq,I.hash,I),$e(w)):I&&I.hash!==B.localHash&&Gt(w,I,{seq:B.remoteSeq,hash:B.remoteHash});return}let V=Xs(I?.hash??null,T,T?{seq:T.seq,hash:T.hash}:null);switch(V.kind){case"push":it(We(w))?await As(w,V.baseSeq):await Cs(w,V.baseSeq);break;case"pushCreate":it(We(w))?await As(w,0):await Cs(w,0);break;case"pushDelete":if(A){Os();break}if(!ce&&(ne.has(w)||te())){ne.set(w,"remote"),at(),K();break}Ee.push(Date.now()),await Wf(w);break;case"dropShadow":Wt(w);break;default:I&&T&&I.hash===T.hash&&I.mtimeMs>=0&&(T.size!==I.size||T.mtimeMs!==I.mtimeMs)&&await Ct(w,T.seq,T.hash,I,I.buf);break}},ov=async(w,A)=>{if(!v||!h)return;let I=await v.tree(h.vaultId);if(!h)return;let T=new Map(I.entries.map(B=>[B.path,B]));for(let B of w){if(!d||!h||!_n(B)||gt(B)||nt?.path===B)continue;if(!fn(B)){$e(B);continue}let V=await qt(B),J=T.get(B)??null;if(!V||!J){$e(B),V?X({key:B,run:()=>Ge(B)}):await Et(B,J?.seq??null);continue}if(V.hash===J.hash){await Ct(B,J.seq,V.hash,V,it(We(B))?V.buf:void 0),$e(B);continue}let U;if(A==="newer"){let Q=J.updatedAt?Date.parse(J.updatedAt):NaN;if(!Number.isFinite(Q)||V.mtimeMs<0)continue;U=V.mtimeMs>Q?"local":"cloud"}else U=A;let G=He,re=()=>d&&G===He&&!gt(B)&&fn(B);try{if(U==="both"){if(!await Vf(B,re))continue;$e(B),await Et(B,J.seq);continue}let Q=it(We(B));if(!Q&&ks())continue;U==="local"?await sv(B,V,J,Q):await av(B,V,J,Q,re)}catch(Q){let fe=Q?.name==="RecoveryError";if(Yi(Q)||(Q instanceof De?Q.status===0:!fe&&!Jl(Q)&&pr(Q)))throw Q;ue(B,Q instanceof De?Q.body?.code||`http ${Q.status}`:Q?.name==="TimeoutError"?"timeout":fe?"RECOVERY_FAILED":"RESOLVE_FAILED"),K()}}},sv=async(w,A,I,T)=>{if(!v||!h)return;let{vaultId:B}=h;if(T){let U=await v.getFile(B,w),G=St(U.content);if(U.seq!==I.seq||U.hash!==null&&U.hash!==G||I.hash!==null&&G!==I.hash){Gt(w,A,{seq:U.seq,hash:U.hash??G,updatedAt:U.updatedAt});return}if(await ie.save(U.content,{binding:t.shadowName,path:w,side:"cloud"}),!fn(w)){$e(w);return}try{let re=await v.putFile(B,w,Yt(A.buf),U.seq,!1,G);Ce("uploads"),x.delete(w),await Ct(w,re.seq,re.hash??A.hash,A,A.buf),$e(w)}catch(re){if(!(re instanceof De)||re.status!==409)throw re;await Gf(w,A)}return}let V=await v.getAsset(B,w),J=St(V);if(I.hash!==null&&J!==I.hash){Gt(w,A,{seq:I.seq,hash:null,updatedAt:I.updatedAt??null});return}if(await ie.save(V,{binding:t.shadowName,path:w,side:"cloud"}),!fn(w)){$e(w);return}try{let U=await v.putBinary(B,w,A.buf,{baseSeq:I.seq,expectedHash:J});Ce("uploads"),x.delete(w),await Ct(w,U.seq,A.hash,A),$e(w)}catch(U){if(!(U instanceof De)||U.status!==409)throw U;Gt(w,A,{seq:Number(U.body?.seq??I.seq),hash:U.body?.hash??null,updatedAt:null})}},av=async(w,A,I,T,B)=>{if(!v||!h)return;let{vaultId:V}=h,J,U,G;if(T){let Q=await v.getFile(V,w);J=Q.content,U=Q.seq,G=St(Q.content)}else if(J=await v.getAsset(V,w),U=I.seq,G=St(J),I.hash!==null&&G!==I.hash){Gt(w,A,{seq:I.seq,hash:null,updatedAt:I.updatedAt??null});return}await ie.save(A.buf,{binding:t.shadowName,path:w,side:"local"});let re=await Kl(lt(w),J,St(A.buf),B);if(!re){if(!fn(w)){$e(w);return}await Gf(w,null);return}Ce("downloads"),me.count("downloaded"),x.delete(w),await Ct(w,U,G,re,J),$e(w)},Gf=async(w,A)=>{if(!v||!h)return;let I=A??await qt(w);if(!I){$e(w),await Et(w,null);return}if(!it(We(w))){let V=_n(w);Gt(w,I,{seq:V?.remoteSeq??0,hash:null});return}let T;try{T=await v.getFile(h.vaultId,w)}catch(V){if(!(V instanceof De)||V.status!==404)throw V;$e(w),X({key:w,run:()=>Ge(w)});return}let B=St(T.content);if(B===I.hash){await Ct(w,T.seq,I.hash,I,T.content),$e(w);return}Gt(w,I,{seq:T.seq,hash:B,updatedAt:T.updatedAt})},Jf=async()=>{let w=new Map;if(!D||!h)return w;let A=D,I=null,T=async B=>{if(I)return;let V;try{V=await s.readdir(B,{withFileTypes:!0})}catch(J){I=`${B}: ${J?.message??String(J)}`;return}for(let J of V){if(rn(J.name)||J.isDirectory()&&t.ignoreNames?.includes(J.name))continue;let U=l.join(B,J.name);if(J.isDirectory())await T(U);else if(J.isFile()){let G=l.relative(A,U).split(l.sep).join("/"),re=r(G);if(!re)continue;try{let Q=await s.stat(U);if(!Q.isFile())continue;w.set(re,{size:Q.size,mtimeMs:Math.floor(Q.mtimeMs)})}catch(Q){if(Q?.code==="ENOENT")continue;I=`${U}: ${Q?.message??String(Q)}`;return}}}};return await T(A),I?(H("error",`scan-failed: ${I}`),Xi(),null):w},tc=async()=>{let w=He;if(gn()||w!==He||!h||!await It())return;let A=await Jf();if(!A||gn()||w!==He||!await It())return;let I=!1;for(let[V,J]of[...ne])(J==="remote"&&A.has(V)||J==="local"&&!A.has(V))&&(ne.delete(V),I=!0);ne.size||Ir();for(let[V,J]of A){let U=h.files[V];if(U&&U.size===J.size&&U.mtimeMs===J.mtimeMs)continue;let G=_n(V);G&&G.localSize===J.size&&G.localMtimeMs===J.mtimeMs||X({key:V,run:()=>Ge(V)})}for(let V of Object.keys(h.files))fn(V)||Xl(V);let T=Object.keys(h.files),B=T.filter(V=>!A.has(V));if(B.length&&!ce&&(Re||lo(B.length,T.length,mm))){ft();for(let V of B)ne.set(V,"remote");at(),K();return}I&&(at(),K());for(let V of B)ne.has(V)||X({key:V,run:()=>Ge(V)})},lv=async w=>{if(!h)return;let A=new Set;for(let[I,T]of Object.entries(h.files)){if(!it(We(I))||T.size>La)continue;A.add(T.hash);let B=w.get(I);if(!(!B||B.size!==T.size||B.mtimeMs!==T.mtimeMs||await q.has(T.hash)))try{let V=await qt(I);V&&V.hash===T.hash&&await Lf(I,T.hash,V.buf)}catch{}}for(let I of Object.values(h.dormant??{}))A.add(I.hash);await q.prune(A)},Tr=async()=>{if(nt){nt.after.push({run:Tr});return}let w=He;if(gn()||w!==He||!v||!h||!D||(me.stage("checking"),!await It()))return;let A=await v.tree(h.vaultId);if(A.maxFileBytes!==void 0&&A.maxFileBytes!==$&&($=A.maxFileBytes,K()),gn()||w!==He)return;let I=new Map;for(let de of A.entries)i(de.path)===null||!o(de.path,de.kind)||I.set(de.path,de);for(let[de,ge]of[...Te])ge&&!I.has(de)&&ei(de,null);let T=await Jf();if(!T||gn()||w!==He||!await It())return;if(h.mirrorRestore==="list"){for(let ge of Object.keys(h.files))!T.has(ge)&&!ne.has(ge)&&delete h.files[ge];let de=Object.create(null);for(let[ge,{seq:Oe,hash:_t}]of I)Object.hasOwn(h.files,ge)||(de[ge]={seq:Oe,hash:_t});h.mirrorRestore=de,O.save(h);try{await O.flush(!0)}catch(ge){throw h.mirrorRestore="list",O.save(h),ge}}let B=h.mirrorRestore;if(jf(),h.dormant){let de=!h.dormantRoot||!E||Dt(h.dormantRoot,E);for(let[ge,Oe]of Object.entries(h.dormant))fn(ge)&&(de&&T.has(ge)&&I.has(ge)&&!Object.hasOwn(h.files,ge)?(h.files[ge]=Oe,delete h.dormant[ge]):Rs(ge));h.dormant&&!Object.keys(h.dormant).length&&(delete h.dormant,delete h.dormantRoot),O.save(h)}Y||(Y=!0,await lv(T));let V=new Set([...I.keys(),...T.keys(),...Object.keys(h.files),...Object.keys(B??{}),...Object.keys(h.held??{})]),J=Object.keys(h.files).length,U=[];for(let de of V){if(gn()||w!==He)return;let ge=h.files[de]??null,Oe=I.get(de)??null,_t=T.get(de)??null,Jt=null,An=_s(_t?.size??0);if(_t)if(ge&&ge.size===_t.size&&ge.mtimeMs===_t.mtimeMs)Jt=ge.hash,An=_t;else{let Kt;try{Kt=await qt(de)}catch(Dr){if(!gr(Dr))throw Dr;Ss(de,Dr);continue}Kt&&(Jt=Kt.hash,An=Kt)}if(B&&Object.hasOwn(B,de)){let Kt=B[de];!ge&&Jt!==null&&Kt.hash===Jt&&(ge=h.files[de]={seq:Kt.seq,hash:Jt,size:An.size,mtimeMs:An.mtimeMs}),(ge||!Oe)&&delete B[de]}U.push({sp:de,d:Xs(Jt,ge,Oe?{seq:Oe.seq,hash:Oe.hash}:null),rSeq:Oe?.seq??null,rHash:Oe?.hash??null,rUpdatedAt:Oe?.updatedAt??null,localHash:Jt,localStat:An})}if(gn()||w!==He)return;let G=U.filter(de=>de.d.kind==="deleteLocal"||de.d.kind==="pushDelete").length,re=!ce&&(Re||lo(G,J,mm));re&&G&&ft(),ne.clear();let Q=U.filter(de=>ev(de.d.kind)&&!(re&&(de.d.kind==="deleteLocal"||de.d.kind==="pushDelete"))),fe=de=>de.d.kind==="push"||de.d.kind==="pushCreate"?de.localStat.size:de.d.kind==="pull"||de.d.kind==="conflict"?I.get(de.sp)?.size??0:0;me.stage("transferring"),me.plan(Q.length,Q.reduce((de,ge)=>de+fe(ge),0));let ct=new Set(Q);for(let de of U){let{sp:ge,d:Oe,rSeq:_t,rHash:Jt,rUpdatedAt:An,localHash:Kt,localStat:Dr}=de;if(gn()||w!==He)return;if(Oe.kind!=="hold"&&_n(ge)&&$e(ge),re&&(Oe.kind==="deleteLocal"||Oe.kind==="pushDelete")){ne.set(ge,Oe.kind==="deleteLocal"?"local":"remote");continue}try{if((Oe.kind==="deleteLocal"||Oe.kind==="pushDelete")&&((await qt(ge))?.hash??null)!==Kt){X({key:ge,run:()=>Ge(ge)}),ct.delete(de)&&me.drop();continue}if(gn()||w!==He)return;switch(Oe.kind){case"adopt":{let Cn=it(We(ge))?await qt(ge):null;await Ct(ge,_t,Kt,Dr,Cn&&Cn.hash===Kt?Cn.buf:void 0);break}case"pull":await Et(ge,_t);break;case"push":it(We(ge))?await As(ge,Oe.baseSeq):await Cs(ge,Oe.baseSeq);break;case"pushCreate":it(We(ge))?await As(ge,0):await Cs(ge,0);break;case"pushDelete":await Wf(ge);break;case"deleteLocal":await zf(ge),Wt(ge);break;case"conflict":await Et(ge,_t);break;case"hold":_n(ge)||me.count("held"),Gt(ge,{hash:Kt,size:Dr.size,mtimeMs:Dr.mtimeMs},{seq:_t,hash:Jt,updatedAt:An});break;case"dropShadow":Wt(ge);break;case"none":break}ct.has(de)&&me.stepDone(!0,fe(de))}catch(Cn){if(!d||Yi(Cn)||pr(Cn)&&!gr(Cn))throw Cn;Ss(ge,Cn),ct.has(de)&&me.stepDone(!0)}}ce&&(ce=!1,Ee.length=0),ne.size||Ir(),at(),re&&K();for(let de of A.folders)if(!(i(de)===null||!o(de,"folder")))try{await s.mkdir(lt(de),{recursive:!0})}catch{}h.cursor=A.seq,h.lastSyncAt=Date.now(),B&&!Object.keys(B).length&&delete h.mirrorRestore,O.save(h)},cv=async()=>{if(!v||!h)return;let w=h.cursor,A=await v.changes(h.vaultId,w);if(A.changes.length===0&&A.seq>w||A.changes.length>0&&A.changes[0].seq!==w+1){await Tr();return}for(let T of A.changes)await qf(T)},Qi=null,Kf=[],nc=()=>{Qi&&Kf.push(Qi.close()),Qi=null},dv=()=>{if(!d||Qi||!D)return;let w=Me();if(!w.watch)return;let A=I=>{if(!D)return;let T=l.relative(D,I);if(!T||T.startsWith(".."))return;let B=r(T);B&&Ne(B)};Qi=w.watch(D,{depth:12,ignored:I=>{let T=l.basename(I);return rn(T)||!!t.ignoreNames?.includes(T)}},{change:A,add:A,unlink:()=>Os(),unlinkDir:()=>Os()})},eo=()=>{k?.stop(),k=null},uv=()=>{if(!d||!v||!h||k)return;let w=C;w&&(k=Oa({baseUrl:w.cloudUrl,vaultId:h.vaultId,token:w.token,getToken:N,gate:S??void 0},{getSince:()=>h?.cursor??0,onHello:A=>{h&&A>h.cursor&&X({run:cv})},onChange:A=>{X({run:()=>qf(A)})},onReset:()=>{X({run:Tr})},onOpen:()=>{(y==="offline"||y==="starting")&&H("idle",null),X({run:tc})},onDown:(A,I)=>{let T=vd(Fh(A));y==="idle"||y==="syncing"?(H("offline",void 0,I?null:T),oe=!!I):y==="offline"&&oe&&!I&&(oe=!1,Be.error(T))},onPresence:A=>n.onPresence?.(h?.vaultId??"",A),onPresenceRoster:A=>n.onPresenceRoster?.(h?.vaultId??"",A)}))},fv=async()=>{let w=await ot(a);if(w.cloudSync?.deviceId)return w.cloudSync.deviceId;let A=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await kr({cloudSync:{...Md(w.cloudSync),deviceId:A}},a),A},gv=async w=>{eo(),nc(),E=null,Z.length=0,P.clear(),ne.clear(),ce=!1,Re=!1,Ee.length=0;let A=await ot(a);if(w!==f)return;let I=A.cloudSync;if(I?.enabled===!1||!e&&I?.mirror===!1){D=null,v=null,H("disabled",null);return}if(!a||a!==Ye()){H("auth-required","not-logged-in");return}if(D=t.localRoot,t.requireRootExists){let J=await s.stat(D).then(U=>U.isDirectory()).catch(()=>!1);if(w!==f)return;if(!J){H("error",`vault-missing: ${D}`),Xi();return}}if(w!==f)return;let T=n.loadCreds();if(!T.cloudUrl||!T.token){v=null,H("auth-required","not-logged-in");return}H("starting",null);let B=I?.deviceId??await fv();if(w!==f)return;let V=t.clientIdSuffix?`${B}#${t.clientIdSuffix}`:B;C={cloudUrl:T.cloudUrl,token:T.token},S=On(T.cloudUrl),_=new AbortController,R?.(),R=S.subscribe(K),v=om({baseUrl:T.cloudUrl,token:T.token,clientId:V,gate:S,signal:_.signal,getToken:()=>{if(w!==f)throw new De(401,{code:"ACCOUNT_CHANGED"},"sync-session");return N()}});try{let J=t.vaultId==="first"?I?.vaultId:t.vaultId;if(!J){let Q=await v.listVaults();if(w!==f)return;if(!Q.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");J=Q[0].id,await kr({cloudSync:{...Md(I),vaultId:J}},a)}if(w!==f)return;let U=await Pd(t.shadowName);if(w!==f||(h=Ma(U,D,J)?U:{vaultRoot:D,folder:"",vaultId:J,cursor:0,lastSyncAt:null,files:{}},w!==f))return;h.moves?.some(Q=>[Q.from,Q.to].some(fe=>fe.split("/").some(rn)))&&(h.moves=h.moves.filter(Q=>![Q.from,Q.to].some(fe=>fe.split("/").some(rn))),O.save(h));for(let[Q,fe]of Object.entries(h.pending??{}))ne.set(Q,fe);ne.size&&(Re=!0);let G=await Is(D);if(w!==f)return;let re=()=>gn()||!!Object.keys(h?.pending??{}).length;if(!G&&!t.requireRootExists){if(h.rootIdentity||Object.keys(h.files).length||h.mirrorMissing||re()){let Q=await Ql(D);if(w!==f)return;if(!Q||re()){hr("vault-missing");return}if(h.mirrorMissing=!0,O.save(h),await O.flush(!0),w!==f)return;let fe=await Ql(D);if(w!==f)return;if(!fe||re()){hr("vault-missing");return}}if(await s.mkdir(D,{recursive:!0}),G=await Is(D),w!==f)return}if(!G?.isDirectory()){ec(G);return}if(typeof G.dev=="number"&&Number.isInteger(G.dev)&&G.dev>=0&&typeof G.ino=="number"&&Number.isInteger(G.ino)&&G.ino>0){let Q=c?await c(D):{dev:G.dev,ino:G.ino,...G.birthtimeMs&&G.birthtimeMs>0?{birthtimeMs:G.birthtimeMs}:{}};if(w!==f)return;if(!Bt(Q))throw Error("Invalid sync root identity; original state retained");let fe=h.rootIdentity,ct=fe&&!Dt(fe,Q);if(!hn(Q,G)){hr("vault-changed");return}let de=!fe&&!e&&Ve().isManagedCloudVault(D)&&(Object.keys(h.files).length>0||re());if(ct||h.mirrorMissing||de){let Oe=(!fe||(fe.volumeId?fe.volumeId===Q.volumeId:fe.dev===Q.dev))&&await Ql(D),_t=Oe&&(await s.readdir(D,{withFileTypes:!0})).every(An=>An.isDirectory()&&t.excludePrefixes?.includes(An.name+"/")),Jt=_t&&await Is(D);if(w!==f)return;if(_t){if(!Jt||!hn(Q,Jt)||re()){hr("vault-changed");return}h.files={},h.cursor=0,h.lastSyncAt=null,h.mirrorRestore="list"}else if(ct||h.mirrorMissing&&!fe){hr("vault-changed");return}else if(de){if(!Oe||re()){hr("vault-changed");return}h.mirrorRestore="list"}}if(E=Q,(h.mirrorMissing||JSON.stringify(fe)!==JSON.stringify(Q))&&(delete h.mirrorMissing,h.rootIdentity=Q,O.save(h),await O.flush(!0)),w!==f||!await It())return}else{if(h.mirrorMissing){hr("vault-changed");return}if(!ec(G))return}if(w!==f)return;g=!0,dv();for(let Q of h.moves??[])X({key:`move:${xt(Q)}`,run:()=>Ds(Q)});X({run:Tr}),X({run:async()=>{uv()}})}catch(J){if(w!==f)return;Yi(J)?H("auth-required","login-expired"):(H("offline",J?.message||String(J)),Xi())}},Yf=()=>{d=!1,g=!1,eo(),nc(),Z.length=0,P.clear(),Pe();for(let w of[j,z,W,ee])w&&clearTimeout(w);j=z=W=ee=null,nt?.abort.abort(),nt=null,_?.abort(new DOMException("sync engine stopped","AbortError")),R?.(),R=null},Xf=async()=>{L&&await new Promise(w=>m.add(w)),await Promise.all(Kf.splice(0)),await O.flush(),h=null,E=null,v=null,C=null,S=null,_=null,D=null,M=0,x.clear(),Te.clear(),xr=0,$=null,ne.clear(),ce=!1,Re=!1,Ee.length=0,y="disabled",b=null,me.end(!1)},pv=()=>{Zf()},Ps=null,to=()=>{Y=!1,Ps?.(),Ps=Ve().onBeforeQuit(pv);let w=++f;Yf();let A=p.catch(()=>{}).then(async()=>{await Xf(),w===f&&(d=!0,await gv(w))});return p=A,A},Zf=()=>{Ps?.(),Ps=null,++f,Yf();let w=p.catch(()=>{}).then(Xf);return p=w,w},Rn=()=>{let w=Object.entries(h?.held??{}).map(([A,I])=>({...I,path:A,local:i(A)??A}));return{enabled:y!=="disabled",state:y==="idle"&&(ye.size||Te.size)?"syncing":y,lastSyncAt:h?.lastSyncAt??null,pending:Z.length+ye.size+Te.size,conflicts:M,skipped:[...[...x].map(([A,I])=>({path:A,reason:I})),...w.map(A=>({path:A.path,reason:"HELD"}))],error:b,pendingDeletions:ne.size,maxFileBytes:$,held:w,heldCount:w.length,rateLimitedUntil:y!=="disabled"?S?.until()??null:null,round:me.progress(),lastRound:me.last(),failures:[...x].map(([A,I])=>If(A,I))}},rc=()=>g&&y==="idle"&&!L&&!Z.length&&!ye.size&&!Te.size&&!W&&!gn();return{retirementIdle:rc,async flushForRetirement(){return rc()?(await O.flush(!0),rc()):!1},getStatus:Rn,start(){to()},notifyLocal(w,A,I){if(!h||y==="disabled"||y==="auth-required")return;let T=r(w),B=I?r(I):null;if(A==="write"&&T){rn(T.split("/").pop()||"")||Ne(T);return}if(A==="remove"){if(!T)return;let V=`${T}/`,J=!1;for(let U of Object.keys(h.files))(U===T||U.startsWith(V))&&(J=!0,X({key:U,run:()=>Ge(U)}));!J&&T&&X({key:T,run:()=>Ge(T)})}},holdLocalMove(w,A){let I=B=>t.serverDir?`${t.serverDir}/${B.replace(/\\/g,"/").normalize("NFC")}`:B.replace(/\\/g,"/").normalize("NFC"),T={from:I(w),to:I(A)};return++He,xs.add(T),()=>{xs.delete(T)}},async notifyLocalMove(w,A,I,T){let B=r(w),V=r(A),J=h??await Pd(t.shadowName),U=yo(w,""),G=U&&(t.serverDir?`${t.serverDir}/${U}`:U);if(!B&&V&&G&&!G.split("/").some(rn)&&J&&Object.keys(J.files).some(re=>re===G||re.startsWith(`${G}/`))&&(B=G),!B&&!V){I?.();return}if(B&&V){let re=h??J;if(!re){I?.();return}let Q=T??(Object.keys(re.files).some(ct=>ct.startsWith(`${B}/`))?"folder":"file"),fe={from:B,to:V,kind:Q};re.moves??=[],re.moves.some(ct=>xt(ct)===xt(fe))||(re.moves.push(fe),++He),I&&Ts.set(xt(fe),I),O.save(re);try{await O.flush(!0)}catch(ct){throw re.moves=re.moves.filter(de=>xt(de)!==xt(fe)),Ts.delete(xt(fe)),O.save(re),ct}h===re&&d&&y!=="disabled"&&y!=="auth-required"&&X({key:`move:${xt(fe)}`,run:()=>Ds(fe)});return}B&&this.notifyLocal(w,"remove"),V&&(X({key:V,run:()=>Ge(V)}),Os()),I?.()},async setEnabled(w){let A=await ot(a);return await kr({cloudSync:{...Md(A.cloudSync),enabled:w}},a),await to(),Rn()},async restart(){return await to(),Rn()},async syncNow(){if(x.clear(),!g){let w=f;if(await p,w!==f)return Rn()}if(y==="disabled"||y==="auth-required"||y==="error"||y==="offline"||!g||!v)await to();else{z&&(clearTimeout(z),Es());for(let w of h?.moves??[])X({key:`move:${xt(w)}`,run:()=>Ds(w)});X({run:Tr})}return Rn()},resolveHeld(w,A){if(!g||!h?.held||!["local","cloud","both","newer"].includes(A))return Rn();let I=[...new Set(w)].filter(T=>typeof T=="string"&&!!_n(T));return I.length&&X({run:()=>ov(I,A)}),Rn()},rescope(){d&&X({key:"\0rescope",run:async()=>jf()})},confirmMassDeletions(){return!g||!ne.size||(ce=!0,X({run:Tr})),Rn()},stop:Zf};function Os(){d&&(W&&clearTimeout(W),W=setTimeout(()=>{W=null,X({run:tc})},w_))}}import{promises as ym}from"node:fs";import A_ from"node:path";async function wm(n){let e=await ym.readdir(n,{withFileTypes:!0}).catch(()=>[]),t=[],r=Object.create(null);for(let i of e){if(!i.isDirectory()||i.name.startsWith("."))continue;let o=await ym.readFile(A_.join(n,i.name,Yc),"utf8").catch(()=>null);if(o===null)continue;t.push(i.name);let a=ha(o);a?.length&&(r[i.name]=a)}return{names:t.sort(),devices:r}}var et={get:"amadeus:sync:get",getAll:"amadeus:sync:get-all",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",resolveHeld:"amadeus:sync:resolve-held",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryMark:"amadeus:entry-sync:mark",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};import{lstat as Wo,mkdir as H_,readFile as Lm,readdir as Fm,realpath as q_,rename as W_}from"node:fs/promises";import{basename as qo,dirname as Vd,isAbsolute as Bm,join as dn,resolve as rr,sep as Ud}from"node:path";var he={get:"vaultsync:get",status:"vaultsync:status",resolveName:"vaultsync:resolveName",preview:"vaultsync:preview",apply:"vaultsync:apply",setEnabled:"vaultsync:setEnabled",setScope:"vaultsync:setScope",setTarget:"vaultsync:setTarget",run:"vaultsync:run",resolve:"vaultsync:resolve",deletesConfirm:"vaultsync:deletes:confirm",deletesAbandon:"vaultsync:deletes:abandon",renameAnswer:"vaultsync:rename:answer",choose:"vaultsync:choose",setCadence:"vaultsync:setCadence",recoveryList:"vaultsync:recovery:list",recoveryRestore:"vaultsync:recovery:restore",takeoverRevert:"vaultsync:takeover:revert",quitCheck:"vaultsync:quitCheck",resolveAll:"vaultsync:resolveAll",dismissCard:"vaultsync:dismissCard",downloadCheck:"vaultsync:downloadCheck",download:"vaultsync:download",create:"vaultsync:create",unbind:"vaultsync:unbind",libraries:"vaultsync:libraries",openOnline:"vaultsync:openOnline"};var _r={fetch:"cloudvault:fetch",eventsOpen:"cloudvault:events:open",eventsClose:"cloudvault:events:close",event:"cloudvault:event",upload:"cloudvault:upload",assetUrl:"cloudvault:asset-url"},oO=he.openOnline,Nd=(n,e)=>typeof n=="string"&&n.length>0&&n.length<=e&&!/[\u0000-\u001f]/.test(n),C_=n=>n!==""&&n!=="."&&n!==".."&&!/[\\\u0000-\u001f]/.test(n);function I_(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;if(e.kind!=="online"||typeof e.account!="string"||!/^[0-9a-f]{64}$/.test(e.account)||!Nd(e.libraryId,4096)||!Nd(e.vaultId,1024)||!Nd(e.name,1024)||!e.name.trim())return null;let t=e.prefix;return typeof t!="string"||t.length>1024||!t.startsWith("Amadeus/")||!t.endsWith("/")||!t.slice(0,-1).split("/").every(C_)?null:{kind:"online",account:e.account,libraryId:e.libraryId,vaultId:e.vaultId,prefix:t,name:e.name}}function Fa(n,e){return I_({kind:"online",account:e,libraryId:n.id,vaultId:n.vaultId,prefix:n.prefix,name:n.name})}import{randomUUID as M_}from"node:crypto";var bm=/^[A-Za-z0-9\-._~!$&'()*+,;=:@%/]+$/,x_=/%(2e|2f|5c)/i,T_=/[\\/%\u0000-\u001f\u007f]/;function vm(n){if(!n||x_.test(n))return null;let e;try{e=decodeURIComponent(n)}catch{return null}return!e||e==="."||e===".."||T_.test(e)?null:e}function D_(n){if(typeof n!="string"||n.length>2048||!n.startsWith("/")||n.startsWith("//")||!bm.test(n))return null;let e=[];for(let t of n.slice(1).split("/")){let r=vm(t);if(r===null)return null;e.push(r)}return e}function Ba(n){return typeof n!="string"||n.length>256||!bm.test(n)||n.includes("/")?null:vm(n)}var P_=(n,e)=>n[0]!=="amadeus"?!1:n[1]==="link-meta"?n.length===2&&e==="GET":n[1]==="vaults"?!(n.length===4&&n[3].toLowerCase()==="events"):n[1]==="libraries"?n.length===2:n[1]==="shared-with-me",O_=n=>n.length===4&&n[0]==="amadeus"&&n[1]==="vaults"&&(n[3]==="binary"||n[3]==="import");function $d(n,e,t="GET"){let r=D_(n);return!r||!(e==="fetch"?P_(r,t):O_(r))?null:"/"+r.map(encodeURIComponent).join("/")}var Em=n=>{let e=n.cloudUrl||"",t=n.token||"";return{account:t?rt(e,t):null,cloudUrl:e,token:t}},ja=class{boot=M_().slice(0,8);n=0;last=void 0;observe(e){return e!==this.last&&(this.last=e,this.n++),`${this.boot}.${this.n}`}},N_=new Set(["GET","POST","PUT","PATCH","DELETE"]),$_=new Set(["content-type","content-range","content-disposition","accept-ranges","etag","last-modified","retry-after","ratelimit","ratelimit-policy","ratelimit-limit","ratelimit-remaining","ratelimit-reset"]),Sm=100*1024*1024,_m=1024*1024*1024,Rm=/^[A-Za-z0-9!#$&^_.+-]{1,64}\/[A-Za-z0-9!#$&^_.+-]{1,64}(\s*;\s*[A-Za-z0-9_.-]{1,32}=[A-Za-z0-9_.\-"]{1,64}){0,3}$/,Am=/[\u0000-\u001f\u007f]/,Ho=n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},Cm=n=>ArrayBuffer.isView(n)&&!(n instanceof DataView)&&n.BYTES_PER_ELEMENT===1;function L_(n){if(n===void 0)return"";if(!n||typeof n!="object"||Array.isArray(n))return null;let e=new URLSearchParams,t=Object.entries(n);if(t.length>32)return null;for(let[i,o]of t){if(!/^[A-Za-z0-9_.-]{1,64}$/.test(i)||["token","at","caps"].includes(i.toLowerCase())||typeof o!="string"||o.length>8192)return null;e.append(i,o)}let r=e.toString();return r?`?${r}`:""}function Im(n){if(n!==void 0)return typeof n!="string"||!/^[A-Za-z0-9._:-]{1,64}$/.test(n)||/^desk-/i.test(n)||n.toLowerCase()==="agent"?null:n}var F_=n=>{let e={};return n.forEach((t,r)=>{$_.has(r.toLowerCase())&&(e[r.toLowerCase()]=t)}),e};async function Ld(n,e,t,r,i,o){let a=AbortSignal.timeout(o),s,l;try{s=await(n.fetch??fetch)(r,{...i,signal:a,redirect:"manual"});let f=Number(s.headers.get("content-length"));if(Number.isFinite(f)&&f>Sm)return await s.body?.cancel().catch(()=>{}),{status:0,json:null,headers:{},error:"response_too_large",accountGeneration:t};l=new Uint8Array(await s.arrayBuffer())}catch{return{status:0,json:null,headers:{},error:a.aborted?"timeout":"network",accountGeneration:t}}let c=n.snap(),u=n.gens.observe(c.account);if(c.account!==e.account||u!==t)return{status:409,json:{code:"ACCOUNT_CHANGED"},headers:{},error:"account_changed",accountGeneration:u};if(l.length>Sm)return{status:0,json:null,headers:{},error:"response_too_large",accountGeneration:u};let d=s.headers.get("content-type")??"",g={status:s.status,json:null,headers:F_(s.headers),accountGeneration:u};if(!d||/json/i.test(d)||/^text\//i.test(d)){let f=new TextDecoder().decode(l);try{g.json=f?JSON.parse(f):null}catch{g.json=f}}else g.bytes=l;return g}function xm(n){let e=n.snap(),t=n.gens.observe(e.account);return{s:e,gen:t,fail:(r,i,o=null)=>({status:r,json:o,headers:{},error:i,accountGeneration:t})}}function Tm(n){return async(e,t,r,i)=>{if(!n.trusted(e))return{status:0,json:null,headers:{},error:"untrusted"};let o=Ho(i),{s:a,gen:s,fail:l}=xm(n),c=typeof t=="string"?t.toUpperCase():"";if(!N_.has(c))return l(0,"bad_method");let u=$d(r,"fetch",c);if(!u)return l(403,"path_not_allowed",{code:"PATH_NOT_ALLOWED"});if(c!=="GET"&&o.accountGeneration===void 0)return l(0,"generation_required");if(o.accountGeneration!==void 0&&o.accountGeneration!==s)return l(409,"account_changed",{code:"ACCOUNT_CHANGED"});if(!a.account)return l(0,"not_signed_in");let d=L_(o.query);if(d===null)return l(0,"bad_query");let g=Im(o.client);if(g===null)return l(0,"bad_client");let f={Authorization:`Bearer ${a.token}`,"X-Content-Caps":tr};c!=="GET"&&g&&(f["X-Amadeus-Client"]=g);let p;if(o.json!==void 0&&o.bytes!==void 0)return l(0,"bad_body");if(o.json!==void 0){if(c==="GET")return l(0,"bad_body");try{p=JSON.stringify(o.json)}catch{return l(0,"bad_body")}f["Content-Type"]="application/json"}else if(o.bytes!==void 0){if(c==="GET"||!Cm(o.bytes)||o.bytes.byteLength>_m||typeof o.contentType!="string"||!Rm.test(o.contentType))return l(0,"bad_body");p=new Uint8Array(o.bytes.buffer,o.bytes.byteOffset,o.bytes.byteLength).slice(),f["Content-Type"]=o.contentType}let m=Tt(a.cloudUrl,u);if(!m||!new URL(m).pathname.endsWith(`/api${u}`))return l(403,"path_not_allowed",{code:"PATH_NOT_ALLOWED"});let y=Math.min(12e4,Math.max(1e3,Number(o.timeoutMs)||3e4));return Ld(n,a,s,m+d,{method:c,headers:f,body:p},y)}}function B_(n){if(!Array.isArray(n)||n.length>32)return null;let e=0,t=[];for(let r of n){let i=Ho(r);if(typeof i.name!="string"||!/^[A-Za-z0-9_.-]{1,64}$/.test(i.name)||!Cm(i.bytes)||i.filename!==void 0&&(typeof i.filename!="string"||!i.filename||i.filename.length>255||Am.test(i.filename)||/\\/.test(i.filename))||i.type!==void 0&&(typeof i.type!="string"||!Rm.test(i.type)))return null;e+=i.bytes.byteLength,t.push({name:i.name,...i.filename!==void 0?{filename:i.filename}:{},...i.type!==void 0?{type:i.type}:{},bytes:i.bytes})}return e<=_m?t:null}function Dm(n){return async(e,t,r,i)=>{if(!n.trusted(e))return{status:0,json:null,headers:{},error:"untrusted"};let o=Ho(i),{s:a,gen:s,fail:l}=xm(n),c=$d(t,"upload");if(!c)return l(403,"path_not_allowed",{code:"PATH_NOT_ALLOWED"});if(o.accountGeneration===void 0)return l(0,"generation_required");if(o.accountGeneration!==s)return l(409,"account_changed",{code:"ACCOUNT_CHANGED"});if(!a.account)return l(0,"not_signed_in");let u=B_(r);if(!u)return l(0,"bad_parts");let d=Im(o.client);if(d===null)return l(0,"bad_client");let g=new FormData,f=0;for(let y of u){f+=y.bytes.byteLength;let b=new Uint8Array(y.bytes.byteLength);b.set(y.bytes),y.filename===void 0?g.append(y.name,new TextDecoder().decode(b)):g.append(y.name,new Blob([b],y.type?{type:y.type}:{}),y.filename)}let p={Authorization:`Bearer ${a.token}`,"X-Content-Caps":tr,...d?{"X-Amadeus-Client":d}:{}},m=Tt(a.cloudUrl,c);return!m||!new URL(m).pathname.endsWith(`/api${c}`)?l(403,"path_not_allowed",{code:"PATH_NOT_ALLOWED"}):Ld(n,a,s,m,{method:"POST",headers:p,body:g},Math.min(36e5,12e4+Math.ceil(f/256)))}}var km=(n,e)=>typeof n=="string"&&n.length>0&&n.length<=e&&!Am.test(n);function Pm(n){let e=new Map,t=()=>n.now?.()??Date.now();return async(r,i,o,a)=>{if(!n.trusted(r))return{ok:!1,error:"untrusted"};let s=Ho(a),l=Ba(i);if(!l||!km(o,4096)||s.page!==void 0&&!km(s.page,4096))return{ok:!1,error:"invalid_args"};let c=n.snap(),u=n.gens.observe(c.account);if(s.accountGeneration!==void 0&&s.accountGeneration!==u)return{ok:!1,error:"account_changed",accountGeneration:u};if(!c.account)return{ok:!1,error:"not_signed_in",accountGeneration:u};let d=`/amadeus/vaults/${encodeURIComponent(l)}`,g=Tt(c.cloudUrl,`${d}/asset-token`),f=Tt(c.cloudUrl,`${d}/asset`);if(!g||!f)return{ok:!1,error:"invalid_args",accountGeneration:u};for(let[v,k]of e)k.until<=t()&&e.delete(v);let p=`${u}\0${l}`,m=e.get(p);if(!m){let v=Ld(n,c,u,g,{method:"POST",headers:{Authorization:`Bearer ${c.token}`,"X-Content-Caps":tr}},3e4).then(k=>{let C=Ho(k.json);return k.status!==200||typeof C.token!="string"||!/^[\x21-\x7e]{1,4096}$/.test(C.token)?{error:k.status===409&&k.error==="account_changed"?"account_changed":k.status?"asset_token_failed":k.error??"network",status:k.status}:{token:C.token,ttlSec:Math.min(3600,Math.max(30,Number(C.ttlSec)||600))}});m={until:t()+3e4,token:v},e.set(p,m),v.then(k=>{"error"in k?e.delete(p):m.until=t()+k.ttlSec*500})}let y=await m.token,b=n.snap(),h=n.gens.observe(b.account);if(b.account!==c.account)return{ok:!1,error:"account_changed",accountGeneration:h};if("error"in y)return{ok:!1,error:y.error,...y.status?{status:y.status}:{},accountGeneration:h};let E=new URL(f);return E.searchParams.set("ref",o),s.page!==void 0&&E.searchParams.set("page",s.page),E.searchParams.set("caps",tr),E.searchParams.set("at",y.token),{ok:!0,url:E.toString(),expiresAt:m.until,accountGeneration:h}}}import{randomUUID as j_}from"node:crypto";var U_=64,Ua=class{streams=new Map;subs=new Map;bySender=new Map;watched=new WeakSet;timer=null;deps;constructor(e){this.deps=e}open(e,t,r){let i=Ba(t);if(!i||!e||typeof e.send!="function")return{ok:!1,error:"invalid_args"};let o=this.deps.snap(),a=this.deps.gens.observe(o.account),s=r&&typeof r=="object"?r:{};if(s.accountGeneration!==void 0&&s.accountGeneration!==a)return{ok:!1,error:"account_changed",accountGeneration:a};if(!o.account)return{ok:!1,error:"not_signed_in",accountGeneration:a};this.checkAccounts(o);let l=this.bySender.get(e);if((l?.size??0)>=U_)return{ok:!1,error:"too_many",accountGeneration:a};let c=`${o.account}\0${i}`,u=this.streams.get(c);u||(u=this.start(c,o,i));let d={id:j_(),sender:e,stream:u};return u.subs.add(d),this.subs.set(d.id,d),this.watch(e),l?l.add(d):this.bySender.set(e,new Set([d])),u.open&&setTimeout(()=>{this.subs.get(d.id)===d&&(this.push(d,"open"),this.push(d,"reset"))},0),{ok:!0,subscriptionId:d.id,accountGeneration:a,state:u.open?"open":"connecting"}}close(e,t){if(typeof t!="string")return{ok:!1,error:"invalid_args"};let r=this.subs.get(t);return r?r.sender!==e?{ok:!1,error:"not_found"}:(this.drop(r),{ok:!0}):{ok:!0}}dispose(){for(let e of[...this.streams.values()])this.teardown(e,!0)}start(e,t,r){let i={key:e,account:t.account,vaultId:r,handle:null,open:!1,opened:!1,closed:!1,subs:new Set};this.streams.set(e,i);let o=()=>!i.closed;return i.handle=Oa({baseUrl:t.cloudUrl,vaultId:encodeURIComponent(r),token:t.token,caps:tr,getToken:()=>{let a=this.deps.snap();if(this.deps.gens.observe(a.account),a.account!==i.account||!a.token)throw this.teardown(i,!0),Error("account_changed");return a.token}},{getSince:()=>null,onOpen:()=>{if(!o())return;let a=i.opened;i.open=!0,i.opened=!0,this.all(i,"open"),a&&this.all(i,"reset")},onDown:()=>{i.open=!1},onHello:a=>{o()&&this.emit(i,"hello",{seq:a})},onChange:a=>{o()&&this.emit(i,"change",a)},onReset:()=>{o()&&this.all(i,"reset")},onPresence:a=>{o()&&this.emit(i,"presence",a)},onPresenceRoster:a=>{o()&&this.emit(i,"presence-roster",a)},onOther:(a,s)=>{o()&&(this.emit(i,a,s),a==="vault-deleted"&&this.teardown(i,!0))}}),i.closed&&i.handle.stop(),this.ensureTimer(),i}emit(e,t,r){for(let i of e.subs)this.send(i,{subscriptionId:i.id,event:{type:t,data:r}})}all(e,t){for(let r of e.subs)this.push(r,t)}push(e,t){this.send(e,{subscriptionId:e.id,state:t})}send(e,t){try{e.sender.isDestroyed?.()||e.sender.send(_r.event,t)}catch(r){this.deps.log?.(`[cloud-vault] push: ${String(r?.message??r)}`)}}teardown(e,t){if(!e.closed){e.closed=!0,e.handle?.stop(),this.streams.get(e.key)===e&&this.streams.delete(e.key);for(let r of[...e.subs])t&&this.push(r,"closed"),this.forget(r);this.stopTimerIfIdle()}}drop(e){let t=e.stream;this.forget(e),t.subs.size||this.teardown(t,!1)}forget(e){e.stream.subs.delete(e),this.subs.get(e.id)===e&&this.subs.delete(e.id);let t=this.bySender.get(e.sender);t?.delete(e),t&&!t.size&&this.bySender.delete(e.sender)}dropSender(e){for(let t of[...this.bySender.get(e)??[]])this.drop(t)}watch(e){if(this.watched.has(e))return;this.watched.add(e);let t=()=>this.dropSender(e);try{e.once?.("destroyed",t),e.on?.("render-process-gone",t),e.on?.("did-navigate",t)}catch(r){this.deps.log?.(`[cloud-vault] watch sender: ${String(r?.message??r)}`)}}checkAccounts(e=this.deps.snap()){this.deps.gens.observe(e.account);for(let t of[...this.streams.values()])t.account!==e.account&&this.teardown(t,!0)}ensureTimer(){this.timer||(this.timer=setInterval(()=>{try{this.checkAccounts()}catch(e){this.deps.log?.(`[cloud-vault] account check: ${String(e?.message??e)}`)}},this.deps.pollMs),this.timer.unref?.())}stopTimerIfIdle(){!this.streams.size&&this.timer&&(clearInterval(this.timer),this.timer=null)}};var Om=!1;function Fd(){return Om}function Bd(n){try{return n.canOpenOnline?.()===!0}catch{return!1}}function Gr(n){return typeof n.openLibrary=="function"&&Fd()&&Bd(n)}function V_(){Om=!0}function z_(n){return typeof n.readCreds=="function"&&typeof n.handle=="function"&&typeof n.isTrustedSender=="function"}function Mm(n,e={}){if(!z_(n)){n.log?.("[cloud-vault] host has no readCreds; online vault relay not registered");return}let t=new ja,r=s=>{if(!s||typeof s!="object")return!1;let l=s;if(l.senderFrame==null||!l.sender||l.senderFrame!==l.sender.mainFrame)return!1;try{return n.isTrustedSender(l)===!0}catch{return!1}},i={snap:()=>Em(n.readCreds()),gens:t,trusted:r,...e.fetch?{fetch:e.fetch}:{}},o=new Ua({snap:i.snap,gens:t,pollMs:e.accountPollMs??3e3,log:s=>n.log?.(s)}),a=[[_r.fetch,Tm(i)],[_r.upload,Dm(i)],[_r.assetUrl,Pm(i)],[_r.eventsOpen,(s,l,c)=>r(s)?o.open(s.sender,l,c):{ok:!1,error:"untrusted"}],[_r.eventsClose,(s,l)=>r(s)?o.close(s.sender,l):{ok:!1,error:"untrusted"}]];try{for(let[s,l]of a)n.handle(s,l)}catch(s){n.log?.(`[cloud-vault] register: ${String(s?.message??s)}`),o.dispose();return}return V_(),{close:async()=>{o.dispose()}}}var ln=null;function jm(n){ln=n}var Um=null;function zd(n){Um=n}function Wa(){return Um}var Ga=n=>n?.cloudSync?.mirror===!1,G_=new Set(["detected","clean","sealed","archived","done","blocked"]),J_=new Set(["unpushed","mirror_in_use","shadow_unreadable","scan_failed","mirror_busy","share_unknown","ledger_unreadable","seal_unconfirmed","unseal_unconfirmed","archive_conflict","shadow_cross_device","prerequisite_lost","config_unreadable","shadow_identity"]),Va=n=>Number.isSafeInteger(n)&&n>=0,nr=n=>typeof n=="string"&&n.length>0,Vm=n=>!!n&&typeof n=="object"&&!Array.isArray(n),zm=n=>typeof n=="string"&&Dn(n)===n,K_=n=>!Vm(n)||!zm(n.root)?!1:[bo(n.root),vo(n.root)].some(e=>e.fdPrefix===n.fdPrefix&&e.assetPrefix===n.assetPrefix),Hd=n=>n==="sealed"||n==="archived"||n==="done",Nm=(n,e)=>Bm(e)&&e===rr(e)&&Vd(e)===rr(n,"sync-takeover");function Y_(n,e){if(!Vm(n)||!nr(n.source)||!/^(mirror|share:[0-9a-f]{8})$/.test(n.source)||!nr(n.account)||!/^[0-9a-f]{64}$/.test(n.account)||!nr(n.phase)||!G_.has(n.phase)||!Va(n.updatedAt)||n.reason!==void 0&&(!nr(n.reason)||!J_.has(n.reason))||n.pending!==void 0&&!Va(n.pending))return!1;let t=Hd(n.phase);return(n.phase==="clean"||t)&&(!nr(n.vaultId)||typeof n.hasShadow!="boolean")?!1:n.source!=="mirror"?n.archiveDir!==void 0||n.archiving!==void 0||n.restoring!==void 0||n.dirRetiredInPlace!==void 0||n.previousArchives!==void 0||n.unconfirmedFiles!==void 0||n.unconfirmedBytes!==void 0?!1:nr(n.vaultId)&&nr(n.localRoot)&&Bm(n.localRoot)&&n.localRoot===rr(n.localRoot)&&(n.serverDir===""||zm(n.serverDir))&&Array.isArray(n.scopes)&&n.scopes.length>0&&n.scopes.every(K_):(n.phase==="clean"||t)&&n.hasShadow!==!0||n.previousArchives!==void 0&&(!Array.isArray(n.previousArchives)||!n.previousArchives.every(r=>nr(r)&&Nm(e,r)))||(t?!nr(n.archiveDir)||!Nm(e,n.archiveDir):n.archiveDir!==void 0)||n.archiving!==void 0&&(n.archiving!==!0||!t)||(n.phase==="archived"||n.phase==="done")&&n.archiving!==!0||n.restoring!==void 0&&(!t||n.phase==="done"||n.restoring!=="moving"&&n.restoring!=="unseal")||n.dirRetiredInPlace!==void 0&&(n.dirRetiredInPlace!==!0||n.phase!=="archived"&&n.phase!=="done")?!1:n.phase==="done"?Va(n.unconfirmedBytes)&&Va(n.unconfirmedFiles):n.unconfirmedBytes===void 0&&n.unconfirmedFiles===void 0}var za=class{home;constructor(e){this.home=e}file(){return dn(this.home(),"vault-sync","mirror-retire.json")}validate(e){if(e?.version!==1||!Array.isArray(e.entries)||!e.entries.every(r=>Y_(r,this.home())))throw Error("bad shape");if(new Set(e.entries.map(r=>`${r.account}\0${r.source}`)).size!==e.entries.length)throw Error("duplicate entry");let t=new Map(e.entries.filter(r=>r.source==="mirror").map(r=>[r.account,r]));for(let r of e.entries)if(t.get(r.account)?.phase!==r.phase)throw Error("missing or conflicting mirror phase")}async read(){let e;try{e=await Lm(this.file(),"utf8")}catch(t){if(Ha(t))return{version:1,entries:[]};throw new Xe(this.file(),t)}try{let t=JSON.parse(e);return this.validate(t),t}catch(t){throw new Xe(this.file(),t)}}put(e,t){let r=this.file();return mn(r,async()=>{let i=await this.read(),o={version:1,entries:[...i.entries.filter(s=>s.account!==e),...t]};this.validate(o);let a=s=>JSON.stringify(s.map(({updatedAt:l,...c})=>c));a(i.entries.filter(s=>s.account===e))!==a(t)&&await je(r,o)})}};async function qd(n,e){let t=ae(e);return(await new za(()=>n).read()).entries.find(r=>r.account===t&&r.source==="mirror")?.phase}var Ja=n=>n!==void 0&&Hd(n),Hm=n=>{let e=yo(n,"");return e&&!e.split("/").some(rn)?e:null},qm=n=>{let e=Hm(n);return e===vn||e?.startsWith(`${vn}/`)?null:e},X_=(n,e)=>t=>{let r=Hm(t);if(!r)return null;let i=n?`${n}/${r}`:r;return e.some(o=>ma(o,i,We(i)))?i:null},le=class extends Error{reason;constructor(e){super(e),this.reason=e}},Ha=n=>n?.code==="ENOENT",cn=async n=>{try{return await Wo(n)}catch(e){if(Ha(e))return null;throw new le("scan_failed")}},jd=(n,e)=>n===e||n.startsWith(e.endsWith(Ud)?e:e+Ud),Jr=async n=>{let e=await cn(n);if(e&&!e.isDirectory())throw new le("archive_conflict");return!!e};function Z_(n,e){return!!n.localRoot&&Vd(n.localRoot)===dn(e,vn)&&n.serverDir!==void 0&&!!n.scopes&&!!n.vaultId}async function $m(n,e,t,r=""){let i=t?.files??{},o=r?`${r}/`:"",a=new Set(Object.keys(i).filter(d=>d.startsWith(o)&&e(d.slice(o.length))===d)),s=t?.pending??{},l=t?.held??{},c={files:0,bytes:0,deletions:0,intents:new Set([...Object.keys(l),...Object.keys(s)]).size+(t?.moves?.length??0)},u=async d=>{let g=await Wo(d);if(!g.isDirectory())throw new le("scan_failed");for(let p of await Fm(d,{withFileTypes:!0})){if(rn(p.name))continue;let m=dn(d,p.name),y=m.slice(n.length+1).split(Ud).join("/");if(y===vn&&e===qm)continue;if(p.isDirectory()){await u(m);continue}if(!p.isFile())continue;let b=e(y);if(!b)continue;let h=await Wo(m);if(!h.isFile())throw new le("scan_failed");let E=await Lm(m),v=await Wo(m);if(h.dev!==v.dev||h.ino!==v.ino||h.size!==v.size||h.mtimeMs!==v.mtimeMs||h.ctimeMs!==v.ctimeMs)throw new le("scan_failed");a.delete(b);let k=Me().sha256Hex(it(We(b))?Yt(E):E);Object.hasOwn(i,b)&&i[b].hash===k||(c.files++,c.bytes+=E.byteLength)}let f=await Wo(d);if(g.dev!==f.dev||g.ino!==f.ino||g.mtimeMs!==f.mtimeMs||g.ctimeMs!==f.ctimeMs)throw new le("scan_failed")};try{await Jr(n)&&await u(n)}catch{throw new le("scan_failed")}return c.deletions=[...a].filter(d=>!Object.hasOwn(s,d)&&!Object.hasOwn(l,d)).length,c}var qa=class{store;chain=Promise.resolve();queued=null;manualAccount=null;closed=!1;transient=new Map;deps;constructor(e,t){this.deps=e,this.store=new za(t)}home(){return this.deps.host.homeDir()}kick(e={}){let t=this.deps.host.accountId();if(this.closed||!t)return Promise.resolve();if(e.manual&&(this.manualAccount=t),this.queued)return this.queued;let r=this.chain.then(async()=>{this.queued=null;let i=this.deps.host.accountId(),o=i!==null&&i===this.manualAccount;this.manualAccount=null,!this.closed&&i&&await this.attempt(i,o).catch(a=>{a instanceof le?this.transient.set(ae(i),a.reason):this.deps.host.log?.(`[vault-sync] mirror retire: ${String(a?.message??a).slice(0,240)}`)})});return this.queued=r,this.chain=r.catch(()=>{}),r}async idle(){for(;;){let e=this.chain;if(await e,e===this.chain)return}}close(){this.closed=!0}async view(e){let t=this.deps.host.contentSync;if(!e||this.deps.host.accountId()!==e||t?.mirrorRetire?.version!==1||!t.ownership)return;let r=ae(e),i;try{i=(await this.store.read()).entries.filter(l=>l.account===r)}catch{return{phase:"blocked",reason:"ledger_unreadable"}}let o=i.find(l=>l.source==="mirror");if(!o)return;if(o.phase==="done")try{let l=await t.ownership.get(e);if(l.mirrorRetired!==!0||l.mirror!=="keep")return;let c=await ot(e);if(!Ga(c)||c.cloudSync?.vaultId!==o.vaultId)return{phase:"blocked",reason:"config_unreadable"}}catch{return{phase:"blocked",reason:"config_unreadable"}}if(this.deps.host.accountId()!==e)return;let a=o.phase==="done"?void 0:this.transient.get(r)??o.reason,s=i.reduce((l,c)=>l+(c.pending??0),0);return{phase:o.phase,...a?{reason:a}:{},...s?{pending:s}:{},...o.phase==="done"?{unconfirmedBytes:o.unconfirmedBytes}:{},...o.dirRetiredInPlace?{dirRetiredInPlace:!0}:{}}}canProceed(e){let t=this.deps.host;return!this.closed&&this.deps.allowed()&&t.accountId()===e&&t.contentSync?.mirrorRetire?.version===1&&typeof t.contentSync.ownership?.patchMirrorRetired=="function"&&!!ln&&Gr(t)}async context(e){if(!this.canProceed(e))throw new le("prerequisite_lost");let t=this.deps.host.contentSync.ownership,r,i;try{r=await ot(e),i=await t.get(e)}catch{throw new le("config_unreadable")}if(!this.canProceed(e))throw new le("prerequisite_lost");let o=r.cloudSync;if(r.cloudAccountId!==void 0&&r.cloudAccountId!==e||i.mirror!=="keep"||!o?.vaultId||(i.mirrorRetired===!0?o.mirror!==!1:o.enabled===!1||o.mirror===!1))throw new le("config_unreadable");return{account:e,acct:ae(e),cfg:r,own:i,ownership:t,vaultId:o.vaultId,mirrorDir:ht(e)}}async recheck(e,t){let r=await this.context(e.account);if(e.vaultId!==r.vaultId||e.mirrorDir!==r.mirrorDir||r.own.mirrorRetired===!0!==t)throw new le("shadow_identity");if(await this.inUse(r))throw new le("mirror_in_use");if(!this.canProceed(e.account))throw new le("prerequisite_lost")}async attempt(e,t){let r=ae(e);this.transient.delete(r);for(let i=0;i<8&&!this.closed;i++){let o=await this.context(e),s=(await this.store.read().catch(()=>{throw new le("ledger_unreadable")})).entries.filter(c=>c.account===r),l=s.find(c=>c.source==="mirror");if(t&&i===0&&l?.phase==="blocked"&&l.reason==="unpushed"&&o.own.mirrorRetired!==!0){if(!this.canProceed(e))throw new le("prerequisite_lost");let c=this.livePlans(o,l),u=s.filter(d=>d.pending&&c.some(g=>g.source===d.source&&g.vaultId===d.vaultId&&g.localRoot===d.localRoot&&JSON.stringify(g.scopes)===JSON.stringify(d.scopes)));u.length&&ln.kick(u.map(d=>d.source==="mirror"?null:d.source.slice(6)))}if(l&&Hd(l.phase)){if(l.restoring){await this.restore(o,s,l);return}if(o.own.mirrorRetired!==!0){if(l.phase==="sealed"&&l.archiving)throw new le("seal_unconfirmed");await this.restartCycle(o,l);continue}if(l.vaultId!==o.vaultId)throw new le("shadow_identity");if(l.phase==="done")return;if(l.phase==="archived"){await this.finish(o,s,l);return}if(!await this.archive(o,s,l))return}else if(!await this.cleanAndSeal(o,s,l))return}}async put(e,t){if(this.deps.host.accountId()!==e.account)throw new le("prerequisite_lost");await this.store.put(e.acct,t.map(r=>({...r,updatedAt:this.deps.now()}))).catch(()=>{throw new le("ledger_unreadable")})}phaseAll(e,t,r={}){return e.map(({reason:i,pending:o,...a})=>({...a,phase:t,...a.source==="mirror"?r:{}}))}async inUse(e){let t=async i=>{try{return await q_(i)}catch(o){if(Ha(o))return rr(i);throw new le("scan_failed")}},r=await t(e.mirrorDir);for(let i of[e.cfg.lastVault,e.cfg.localVault,Ve().vaultRoot()])if(i&&(jd(rr(i),rr(e.mirrorDir))||jd(await t(i),r)))return!0;return!1}shadowName(e,t){return`amadeus-sync-${e.acct}${t==="mirror"?"":`-share-${t.slice(6)}`}`}archivePaths(e,t){let r=t.archiveDir,i=dn(r,"mirror");return{archiveDir:r,mirror:i,userData:dn(i,"userData"),cloud:dn(i,qo(e.mirrorDir))}}async shareKeys(e,t){let r=Ve().isDevMode()?"\\.dev":"",i=new RegExp(`^amadeus-sync-${e.acct}-share-([0-9a-f]{8})${r}\\.(json|bases)$`),o;try{o=await Fm(t)}catch(a){if(Ha(a))return new Set;throw new le("shadow_unreadable")}return new Set(o.flatMap(a=>{let s=i.exec(a);return s?[s[1]]:[]}))}async shadowFor(e,t,r){let i=zt(this.shadowName(e,t.source)),o=r&&dn(r,qo(i)),[a,s]=await Promise.all([cn(i),o?cn(o):null]);if(a&&s)throw new le("archive_conflict");if(a&&!a.isFile()||s&&!s.isFile())throw new le("shadow_unreadable");if(!a&&!s){let c=u=>u.replace(/\.json$/,".bases");if(t.source==="mirror"||t.hasShadow||await cn(c(i))||o&&await cn(c(o)))throw new le("shadow_unreadable");return null}let l=await Od(a?i:o).catch(()=>{throw new le("shadow_unreadable")});if(!l)throw new le("shadow_unreadable");if(!Ma(l,t.localRoot??e.mirrorDir,t.vaultId))throw new le("shadow_identity");if(l.mirrorMissing||l.mirrorRestore)throw new le("mirror_busy");return l}livePlans(e,t){let r=ln?.sharePlans();if(!r)throw new le("share_unknown");return[{...t,vaultId:e.vaultId,hasShadow:!0},...r.map(i=>({source:`share:${i.key}`,account:e.acct,phase:t.phase,updatedAt:0,vaultId:i.vaultId,localRoot:rr(e.mirrorDir,i.localRelDir),serverDir:i.serverDir,scopes:i.scopes}))]}async check(e,t,r,i){let o=new Set(t.filter(l=>l.source!=="mirror").map(l=>l.source.slice(6))),a=await this.shareKeys(e,Ve().userDataDir());if(i)for(let l of await this.shareKeys(e,i))a.add(l);for(let l of a)if(!o.has(l))throw new le("share_unknown");let s={total:0,bytes:0,needsRestore:!1,entries:[]};for(let l of t){let c=await this.shadowFor(e,l,i),u;if(l.source==="mirror")u=await $m(r,qm,c);else{if(!Z_(l,e.mirrorDir))throw new le("ledger_unreadable");if(!await Jr(dn(r,vn))&&c)throw new le("scan_failed");u=await $m(dn(r,vn,qo(l.localRoot)),X_(l.serverDir,l.scopes),c,l.serverDir)}let d=u.files+u.deletions+u.intents;s.entries.push({...l,hasShadow:!!c,pending:d}),s.total+=d,s.bytes+=u.bytes,s.needsRestore||=u.deletions>0||u.intents>0||l.source!=="mirror"&&u.files>0}return s}async cleanAndSeal(e,t,r){let i=r??{source:"mirror",account:e.acct,phase:"detected",updatedAt:0};if(e.own.mirrorRetired===!0){if(i.phase!=="clean"||i.vaultId!==e.vaultId)throw new le("ledger_unreadable");return await this.put(e,this.phaseAll(t,"sealed",{archiveDir:vt.fresh(this.home(),this.deps.now()).dir})),!0}if(await this.inUse(e))return await this.put(e,this.blocked(t.length?t:[i],"mirror_in_use")),!1;r||(await this.put(e,[i]),await this.deps.crash("detected"));let o=this.livePlans(e,i);if(!await ln.flush().catch(()=>!1))throw new le("mirror_busy");if(!await Jr(e.mirrorDir))throw new le("scan_failed");let a;try{a=await this.check(e,o,e.mirrorDir)}catch(s){if(!(s instanceof le))throw s;return await this.put(e,this.blocked(t.length?t:[i],s.reason)),!1}if(a.total)return await this.put(e,this.blocked(a.entries,"unpushed")),!1;if(await this.put(e,this.phaseAll(a.entries,"clean")),await this.deps.crash("clean"),JSON.stringify(this.livePlans(e,i))!==JSON.stringify(o))throw new le("share_unknown");return await this.patch(e,!1,!0)?(await this.put(e,this.phaseAll(a.entries,"sealed",{archiveDir:vt.fresh(this.home(),this.deps.now()).dir})),await this.deps.crash("sealed"),!0):!1}blocked(e,t){return e.map(({reason:r,archiveDir:i,archiving:o,restoring:a,dirRetiredInPlace:s,pending:l,...c})=>({...c,phase:"blocked",...c.source==="mirror"?{reason:t}:{},...t==="unpushed"&&l?{pending:l}:{}}))}async patch(e,t,r){await this.recheck(e,t);let i=()=>{let s=Ve().vaultRoot();return this.canProceed(e.account)&&!(s&&jd(rr(s),rr(e.mirrorDir)))&&(r?ln.idle():ln.quiet())};if(!i())throw new le("mirror_busy");let o=await e.ownership.patchMirrorRetired(e.account,{vaultId:e.vaultId,from:t,to:r},i).catch(()=>{throw new le(r?"seal_unconfirmed":"unseal_unconfirmed")});r&&o&&await this.deps.crash("ownership-set");let a=await e.ownership.get(e.account).catch(()=>null);if(!this.canProceed(e.account))throw new le("prerequisite_lost");if(!o||!a||a.mirrorRetired===!0!==r)throw new le(r?"seal_unconfirmed":"unseal_unconfirmed");return!0}async verifyArchive(e,t){let{archiveDir:r,mirror:i,userData:o,cloud:a}=this.archivePaths(e,t);for(let c of[Vd(r),r,i,o])await Jr(c);let s=await Jr(e.mirrorDir),l=await Jr(a);if(s&&l)throw new le("archive_conflict");if(!s&&!l)throw new le("scan_failed");if(!t.archiving&&l||t.phase==="archived"&&!t.restoring&&(t.dirRetiredInPlace?!s:!l))throw new le("archive_conflict");return{root:s?e.mirrorDir:a,userData:o}}shadowMoves(e,t,r){return t.flatMap(i=>{let o=zt(this.shadowName(e,i.source)),a=o.replace(/\.json$/,".bases");return[{from:o,to:dn(r,qo(o)),required:i.hasShadow===!0},{from:a,to:dn(r,qo(a)),required:!1,directory:!0}]})}async requireArchived(e){for(let t of e){if(await cn(t.from))throw new le("archive_conflict");if(t.required&&!await cn(t.to))throw new le("shadow_unreadable")}}async archive(e,t,r){if(!ln?.quiet())throw new le("mirror_busy");if(await this.inUse(e))throw new le("mirror_in_use");let{root:i,userData:o}=await this.verifyArchive(e,r),a=await this.check(e,t,i,r.archiving?o:void 0);if(a.total)return await this.beginRestore(e,a.entries,r),!1;let{archiveDir:s,cloud:l}=this.archivePaths(e,r),c=new vt(s),u,d=await Ae(async()=>{await this.recheck(e,!0);let g=this.phaseAll(a.entries,"sealed",{archiving:!0});await this.put(e,g),await this.deps.crash("archive-begin"),await this.recheck(e,!0),await H_(o,{recursive:!0,mode:448}).catch(()=>{throw new le("archive_conflict")}),await c.log({event:"mirror-retire-archive",account:e.acct,mirrorDir:e.mirrorDir}).catch(()=>{throw new le("archive_conflict")});let f=this.shadowMoves(e,g,o);for(let y of f){let b=await this.moveFixed(e,y);if(b==="cross-device")throw new le("shadow_cross_device");b==="moved"&&await c.log({event:"moved",from:y.from,to:y.to}).catch(()=>{})}await this.deps.crash("shadows-moved"),await this.recheck(e,!0);let p=await this.check(e,g,i,o);if(p.total)return u=p,!1;await this.requireArchived(f);let m=await this.moveFixed(e,{from:e.mirrorDir,to:l,required:!0,directory:!0});return m==="cross-device"&&await c.log({event:"dir-retired-in-place",dir:e.mirrorDir}).catch(()=>{}),m==="moved"&&await c.log({event:"moved",from:e.mirrorDir,to:l}).catch(()=>{}),await this.deps.crash("dir-moved"),await this.recheck(e,!0),await this.put(e,this.phaseAll(g,"archived",{...m==="cross-device"?{dirRetiredInPlace:!0}:{}})),await this.deps.crash("archived"),!0});return u&&await this.beginRestore(e,u.entries,{...r,archiving:!0}),d}async moveFixed(e,t){let[r,i]=await Promise.all([cn(t.from),cn(t.to)]),o=a=>t.directory?a.isDirectory():a.isFile();if(r&&!o(r)||i&&!o(i)||r&&i)throw new le("archive_conflict");if(!r){if(!i&&t.required)throw new le("archive_conflict");return"absent"}if(await this.recheck(e,!0),!ln?.quiet())throw new le("mirror_busy");if(await cn(t.to))throw new le("archive_conflict");if(!this.canProceed(e.account))throw new le("prerequisite_lost");try{await W_(t.from,t.to)}catch(a){if(a.code==="EXDEV")return"cross-device";throw new le("archive_conflict")}return"moved"}async beginRestore(e,t,r){await this.recheck(e,!0);let i={...r,restoring:"moving"},o=t.map(a=>a.source==="mirror"?{...i,pending:a.pending}:a);await this.put(e,o),await this.restore(e,o,i)}async restore(e,t,r){if(e.vaultId!==r.vaultId)throw new le("shadow_identity");let{cloud:i,userData:o}=this.archivePaths(e,r);if(r.restoring==="moving"){if(e.own.mirrorRetired!==!0)throw new le("seal_unconfirmed");let s=await this.verifyArchive(e,r);await this.check(e,t,s.root,r.archiving?o:void 0),await Ae(async()=>{if(await this.recheck(e,!0),await this.moveFixed(e,{from:i,to:e.mirrorDir,required:!0,directory:!0})==="cross-device")throw new le("archive_conflict");for(let c of this.shadowMoves(e,t,o))if(await this.moveFixed(e,{...c,from:c.to,to:c.from})==="cross-device")throw new le("shadow_cross_device")}),await this.put(e,t.map(l=>l.source==="mirror"?{...l,restoring:"unseal"}:l))}if(e.own.mirrorRetired===!0){if(!await Jr(e.mirrorDir)||await cn(i))throw new le("archive_conflict");if((await this.shareKeys(e,o)).size)throw new le("archive_conflict");for(let s of this.shadowMoves(e,t,o))if(await cn(s.to))throw new le("archive_conflict");await this.check(e,t,e.mirrorDir),await this.patch(e,!0,!1)}await this.put(e,this.blocked(t,"unpushed")),this.canProceed(e.account)&&await ln.refreshShares();let a=t.filter(s=>s.source!=="mirror"&&s.pending).map(s=>s.source.slice(6));a.length&&this.canProceed(e.account)&&ln.kick(a)}async finish(e,t,r){let{root:i,userData:o}=await this.verifyArchive(e,r);await this.requireArchived(this.shadowMoves(e,t,o));let a=await this.check(e,t,i,o);if(a.needsRestore){await this.beginRestore(e,a.entries,r);return}await this.recheck(e,!0);let{mirror:s}=this.archivePaths(e,r),l=a.total,c=a.bytes;await je(dn(s,"retire.json"),{version:1,account:e.acct,keep:!0,unconfirmedBytes:c,unconfirmedFiles:l,dirRetiredInPlace:!!r.dirRetiredInPlace,at:this.deps.now()}).catch(()=>{throw new le("archive_conflict")}),await this.recheck(e,!0),await this.put(e,this.phaseAll(t,"done",{unconfirmedBytes:c,unconfirmedFiles:l})),await this.deps.crash("done")}async restartCycle(e,t){await this.put(e,[{source:"mirror",account:e.acct,phase:"detected",previousArchives:[...t.previousArchives??[],t.archiveDir],updatedAt:0}]),this.canProceed(e.account)&&await ln.refreshShares()}};import{constants as Q_,promises as Wm}from"node:fs";async function Gm(n,e){try{await Wm.copyFile(zt(n),zt(e),Q_.COPYFILE_EXCL)}catch(t){let r=t?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw t}return await Wm.unlink(zt(n)).catch(()=>{}),!0}var Jm=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],Wd=n=>Jm.every(e=>typeof n[e]=="function"),n0=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,held:[],heldCount:0,rateLimitedUntil:null,side:"local"});function Gd(n){let e=null,t=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};n.handle(et.get,()=>e?e.get():n0()),n.handle(et.getAll,()=>e?e.getAll():{engines:[],pendingDeletionsTotal:0}),n.handle(et.setEnabled,(r,i)=>t().setEnabled(i)),n.handle(et.syncNow,()=>t().syncNow()),n.handle(et.confirmDeletions,()=>t().confirmDeletions()),n.handle(et.resolveHeld,(r,i)=>t().resolveHeld(i)),n.handle(et.entryGet,()=>t().entryGet()),n.handle(et.otherSideDbs,()=>t().otherSideDbs()),n.handle(et.entryEnable,(r,i)=>t().entryEnable(i)),n.handle(et.entryDisable,(r,i)=>t().entryDisable(i)),n.handle(et.entryMark,(r,i,o)=>t().entryMark(i,o)),n.handle(et.entryClosure,(r,i,o)=>t().entryClosure(i,o)),n.handle(et.collabCall,(r,i,o)=>t().collabCall(i,o)),n.handle(et.switchSide,(r,i)=>t().switchSide(r.sender.id,i)),n.setAmadeusSyncFactory(r=>{Gp(r),Kp(r0(n));let i=Km(r,n.syncRecords);return e=i.handlers,i.instance}),n.log("[forsion-extend] amadeus cloud sync registered")}function r0(n){let e=n.contentSync?.merge;return e?(t,r,i,o)=>{if(!/\.db$/i.test(t)||/^(agents|human)(\/|$)/.test(t))return null;let a;try{a=e(t,r,i,o)}catch{return null}return a&&!a.conflict&&!Jd(i,r,a.content)?null:a}:null}function Jd(n,e,t){let r,i,o;try{[r,i,o]=[JSON.parse(n),JSON.parse(e),JSON.parse(t)]}catch{return!1}let a=c=>Array.isArray(c)&&c.every(u=>u&&typeof u=="object"&&typeof u.id=="string")?c.map(u=>u.id):null,s=(c,u)=>c.filter(d=>u.includes(d)),l=(c,u)=>c.length===u.length&&c.every((d,g)=>d===u[g]);for(let c of Object.keys(i)){let u=a(i[c]),d=a(r?.[c]);if(!u||!d||l(s(d,u),s(u,d)))continue;let g=a(o?.[c]);if(!g||!l(s(u,g),s(g,u)))return!1}return!0}function Km(n,e){let t=n.notifyAll,r=()=>n.vaultRoot(),i=new _i,o=(P,F,L)=>{if(e)try{let j=i.take({feed:P,engine:"legacy",vault:F,target:"penzor"},L);j&&e.append(j,Ye())}catch{}},a=0,s=!1,l=ed(),c=new Map,u=()=>{let P=Date.now();for(let[F,L]of c)P-L.at>7e4&&c.delete(F);t(et.presence,[...c.values()])},g={loadCreds:()=>n.readCreds(),onHealth:(P,F,L)=>Nt("vault",P,F,L),onStatus:P=>t(et.status,{...P,ownPendingDeletions:P.pendingDeletions,pendingDeletions:Be(),side:k()?"cloud":"local"}),onRound:P=>o("legacy:mirror",null,P),onPresence:(P,F)=>{let L=F;L?.userId&&(c.set(L.userId,{userId:L.userId,username:String(L.username??"user"),page:L.page??null,at:Number(L.at)||Date.now()}),u())},onPresenceRoster:(P,F)=>{if(Array.isArray(F)){for(let L of F){let j=L;j?.userId&&c.set(j.userId,{userId:j.userId,username:String(j.username??"user"),page:j.page??null,at:Number(j.at)||Date.now()})}u()}}},f=()=>{let P=a;return{...g,onStatus:F=>{P===a&&g.onStatus(F)},onRound:F=>{P===a&&g.onRound(F)},onPresence:(F,L)=>{P===a&&g.onPresence(F,L)},onPresenceRoster:(F,L)=>{P===a&&g.onPresenceRoster(F,L)}}},p=zo(f()),m=new Map,y=[],b=!1,h=0,E=0,v=async(P,F)=>{let L=Ye();if(!s||!L)return;let j=a,z=++h,W=l;b=!1;let ee=()=>j===a&&z===h&&s&&Ye()===L,K=async()=>{let X=await Promise.all([ot(L),qd(n.homeDir(),L)]).catch(()=>null);if(!ee())return!1;if(!X)return b=!1,!1;if(!Ja(X[1])&&!Ga(X[0]))return X[0].cloudSync?.enabled!==!1?!0:(b=!1,!1);y=[],b=!1;let ye=[...m.values()];m.clear(),E++;try{await Promise.all(ye.map(({engine:Ne})=>Ne.stop()))}finally{E--}return!1};if(!await K())return;let H=W.sharedWithMe().catch(()=>null);F?.();let oe=await H;if(!oe){ee()&&(b=!1);return}if(!await K())return;let se=Qp(oe);y=se;let ue=new Map(se.map(X=>[X.key,X.scopeKey]));for(let[X,ye]of m)if(ue.get(X)!==ye.plan.scopeKey){if(await ye.engine.stop(),!ee())return;m.delete(X)}for(let X of se){if(m.has(X.key)||P&&!P.has(X.key))continue;if(!await K())return;let ye=f(),Ne=zo({...ye,onStatus:Pe=>ye.onStatus({...Pe,shareKey:X.key}),onRound:Pe=>{j===a&&o(`legacy:share:${X.key}`,null,Pe)}},{localRoot:Kr.join(ht(),...X.localRelDir.split("/")),shadowName:`amadeus-sync-${Sr()}-share-${X.key}`,vaultId:X.vaultId,serverDir:X.serverDir,inScope:X.inScope});m.set(X.key,{engine:Ne,plan:X}),Ne.start()}ee()&&(b=!0)},k=()=>r()===ht(),C=(P,F=P.base)=>{P.base=F;let L=[F,...P.pendingMoves];P.scope.current=Pn(L.flatMap(j=>j.entries),L.flatMap(j=>j.exclude)),P.engine.rescope()},S=new Map,_=new Set,R=new Set,N=null,D=()=>N??=new Promise(P=>{let F=()=>t0.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return P(F());e0("scutil",["--get","ComputerName"],{timeout:1500},(L,j)=>P(!L&&String(j).trim()||F()))}),M=async()=>{let P=(await ot()).cloudSync?.deviceId;return P?{id:P,name:await D()}:null},x=new Map,$=(P,F,L)=>{let j=a,z=(x.get(P)??Promise.resolve()).catch(()=>{}).then(async()=>{j!==a||L&&!await L()||j!==a||await O(P,F,j)});return x.set(P,z),z.finally(()=>{x.get(P)===z&&x.delete(P)}).catch(()=>{}),z},O=async(P,F,L)=>{let j=l,z=encodeURIComponent(await j.ensureOwnVault()),W=qp(P);for(let ee=0;ee<3;ee++){let K=null;try{K=await j.call("GET",`/vaults/${z}/file?path=${encodeURIComponent(W)}`)}catch(oe){if(oe?.status!==404)throw oe}let H=F(!!K,K?ha(K.content):null);if(H===void 0||L!==a)return;try{if(H===null){K&&await j.call("DELETE",`/vaults/${z}/file?path=${encodeURIComponent(W)}&baseSeq=${K.seq}`);return}await j.call("PUT",`/vaults/${z}/file`,{path:W,content:Wp(H),baseSeq:K?.seq??0});return}catch(oe){if(oe?.status!==409)throw oe}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},q=async P=>!!(await ot()).entrySync?.some(F=>F.cloudName===P&&F.entries.length>0),ie=(P,F)=>$(P,(L,j)=>{let z=j?.find(ee=>ee.id===F.id);if(z&&z.name===F.name)return;let W=z?.since??new Date().toISOString().slice(0,10);return[...(j??[]).filter(ee=>ee.id!==F.id),{...F,since:W}]},()=>q(P)),Y=(P,F)=>$(P,(L,j)=>{if(!L||!j?.some(W=>W.id===F))return;let z=j.filter(W=>W.id!==F);return z.length?z:null},async()=>!await q(P)),ne=()=>{t(et.entryChange)},ce=async(P,F)=>{let L=S.get(P);if(!L)return;let j=ee=>ee&&ee.startsWith(`${L.cloudName}/`)?ee.slice(L.cloudName.length+1):null,z=j(F.path);if(!z)return;let W=!1;await gi(ee=>{if(S.get(P)!==L)return!1;let K=(ee.entrySync??[]).find(X=>X.vaultRoot===P);if(!K)return!1;let H=F.op,oe=j(F.newPath),se=nh(K.entries,H,z,oe),ue=oe?wo(K.exclude??[],z,oe):{changed:!1,next:K.exclude??[]};if(!se.changed&&!ue.changed)return!1;W=!0,K.entries=se.next,ue.changed&&(K.exclude=ue.next),C(L,Pn(K.entries,K.exclude??[]))}),W&&S.get(P)===L&&ne()},Re=P=>{let F=a;return{...f(),onStatus:L=>{F===a&&t(et.status,{...L,ownPendingDeletions:L.pendingDeletions,pendingDeletions:Be(),side:"local",binding:P})},onRound:L=>{F===a&&o(`legacy:entry:${P}`,P,L)},onRemoteApplied:async L=>{F===a&&await ce(P,L)}}},Ee=async()=>{let P=Ye();if(!s||!P)return;let F=a,L=l,j=Sr(P);await n.adoptLegacyCloudState(P,Gm);let z=await ot(P),W=z.entrySync??[];if(F!==a||!s||P!==Ye())return;let ee=await fh(P,{entrySync:W.filter(H=>!S.has(H.vaultRoot)&&H.entries.length>0),cloudSync:z.cloudSync,shadowFiles:H=>{let oe=zt(`amadeus-sync-${j}-entry-${hi(H)}`),se=zt(`amadeus-sync-entry-${hi(H)}`);return[oe,oe.replace(/\.json$/,".bases"),se,se.replace(/\.json$/,".bases")]}});if(F!==a||!s||P!==Ye())return;ee.size&&(W=W.filter(H=>!ee.has(H.vaultRoot)));let K=new Map(W.map(H=>[H.vaultRoot,H]));for(let[H,oe]of S){let se=K.get(H);if(!(se&&se.cloudName===oe.cloudName)&&(await oe.engine.stop(),F!==a||(S.delete(H),se&&await cm(`amadeus-sync-${j}-entry-${hi(H)}`),F!==a)))return}for(let H of W){let oe=S.get(H.vaultRoot);if(oe){C(oe,Pn(H.entries,H.exclude??[]));continue}let se={current:Pn(H.entries,H.exclude??[])},ue=H.cloudName,X=zo(Re(H.vaultRoot),{accountId:P,localRoot:H.vaultRoot,shadowName:`amadeus-sync-${j}-entry-${hi(H.vaultRoot)}`,vaultId:"first",serverDir:ue,clientIdSuffix:`entry-${hi(H.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:ye=>ye===ue?!0:ye.startsWith(`${ue}/`)?ya(se.current,ye.slice(ue.length+1)):!1});S.set(H.vaultRoot,{engine:X,scope:se,cloudName:ue,base:se.current,pendingMoves:new Set}),X.start()}if(z.cloudSync?.enabled!==!1)for(let H of W){let oe=H.entries.length>0,se=oe?_:R;se.has(H.cloudName)||((oe?R:_).delete(H.cloudName),(async()=>{try{let ue=await M();if(!ue||F!==a||(await(oe?ie(H.cloudName,ue):Y(H.cloudName,ue.id)),F!==a))return;se.add(H.cloudName),(oe?R:_).delete(H.cloudName)}catch{}})())}},me=async(P,F,L,j,z)=>{let W=F.replace(/\\/g,"/").normalize("NFC"),ee=L.replace(/\\/g,"/").normalize("NFC"),K=!1,H,oe,se,ue=z??"file";try{await gi(async X=>{if(S.get(P)!==j)return!1;let ye=(X.entrySync??[]).find(Lt=>Lt.vaultRoot===P);if(!ye)return!1;let Ne=So(ye.entries,W,ee),Pe=wo(ye.exclude??[],W,ee),Ht=fi(ye.entries,ye.exclude,W);!z&&await Ri.stat(Kr.join(P,...ee.split("/"))).then(Lt=>Lt.isDirectory(),()=>!1)&&(ue="folder");let gr=ue==="folder"?"folder":/\.md$/i.test(ee)?"page":"asset";Ht&&!fi(Ne.next,Pe.next,ee)&&(Ne.next.push({path:ee,kind:gr}),Ne.changed=!0),K=Ne.changed||Pe.changed;let pr=ye.entries.filter(Lt=>So([Lt],W,ee).changed);return Ht&&!pr.some(Lt=>Lt.path===W)&&pr.push({path:W,kind:gr}),H=Pn(pr,(ye.exclude??[]).filter(Lt=>wo([Lt],W,ee).changed)),oe=j.base,j.pendingMoves.add(H),ye.entries=Ne.next,ye.exclude=Pe.next,se=Pn(ye.entries,ye.exclude),C(j,se),K})}catch(X){throw H&&j.pendingMoves.delete(H),C(j,j.base===se&&oe?oe:j.base),X}try{H&&await j.engine.notifyLocalMove(W,ee,()=>{j.pendingMoves.delete(H),C(j)},ue)}catch(X){throw H&&j.pendingMoves.delete(H),await gi(ye=>{let Ne=ye.entrySync?.find(Pe=>Pe.vaultRoot===P);if(!Ne)return!1;Ne.entries=So(Ne.entries,ee,W).next,Ne.exclude=wo(Ne.exclude??[],ee,W).next,C(j,Pn(Ne.entries,Ne.exclude))}),X}K&&S.get(P)===j&&ne()},Ce=P=>{let F=P.replace(/\\/g,"/");for(let{engine:L,plan:j}of m.values())if(F.startsWith(`${j.localRelDir}/`))return{engine:L,rel:F.slice(j.localRelDir.length+1)};return{engine:p,rel:F}};n.setMutationHooks((P,F)=>{if(k()){let L=Ce(P);L.engine.notifyLocal(L.rel,F);return}S.get(r()??"")?.engine.notifyLocal(P,F)},(P,F,L)=>{if(k()){let W=Ce(P),ee=Ce(F);if(W.engine===ee.engine)return W.engine.notifyLocalMove(W.rel,ee.rel,void 0,L);W.engine.notifyLocal(W.rel,"remove"),ee.engine.notifyLocal(ee.rel,"write");return}let j=r()??"",z=S.get(j);if(z)return me(j,P,F,z,L)},(P,F)=>{if(k()){let L=Ce(P),j=Ce(F),z=[L.engine.holdLocalMove(L.rel,j.rel)];return L.engine!==j.engine&&z.push(j.engine.holdLocalMove(L.rel,j.rel)),()=>{for(let W of z)W()}}return S.get(r()??"")?.engine.holdLocalMove(P,F)});let Be=()=>{let P=p.getStatus().pendingDeletions;for(let{engine:F}of m.values())P+=F.getStatus().pendingDeletions;for(let{engine:F}of S.values())P+=F.getStatus().pendingDeletions;return P},_e=P=>({...P,pendingDeletions:Be(),side:k()?"cloud":"local"}),ft=async()=>{if(!s)return p.getStatus();let P=new Promise(L=>{v(void 0,L).then(L,L)});for(let{engine:L}of m.values())L.syncNow();for(let{engine:L}of S.values())L.syncNow();let[F]=await Promise.all([p.syncNow(),P]);return F},at=async()=>{let P=++a;s=!1,i.reset(),l.stop();let F=[p.stop(),...[...m.values()].map(({engine:j})=>j.stop()),...[...S.values()].map(({engine:j})=>j.stop())];if(m.clear(),S.clear(),y=[],b=!1,_.clear(),R.clear(),c.clear(),u(),await Promise.all(F),await n.awaitPendingVaultWrites(),P!==a)return;let L=r();if(L&&pi(L)){let j=await ot();if(P!==a)return;let z=j.localVault&&!pi(j.localVault)?j.localVault:Kr.join(n.workspaceDir(),"Amadeus");if(await Ri.mkdir(z,{recursive:!0}),P!==a||(await kr({lastVault:z,localVault:z,lastPage:void 0}),P!==a))return;await n.activateRoot(z,!1)}P===a&&ne()},Ir=async()=>{let P=at(),F=a;await P,F===a&&(l=ed(),p=zo(f()),s=!0,await Promise.all([p.restart(),v(),Ee()]),F===a&&(ne(),t(et.status,_e(p.getStatus()))))};return jm({quiet:()=>s&&p.getStatus().state==="disabled"&&m.size===0&&!E,idle:()=>s&&b&&p.retirementIdle()&&!E&&[...m.values()].every(({engine:P})=>P.retirementIdle()),flush:async()=>{if(!s||!b||E)return!1;let P=[p,...[...m.values()].map(({engine:F})=>F)];try{return(await Promise.all(P.map(F=>F.flushForRetirement()))).every(Boolean)}catch{return!1}},sharePlans:()=>b?y:null,refreshShares:()=>v(),kick:P=>{if(!s)return;let F=new Set;for(let L of P){if(L===null){p.syncNow();continue}let j=m.get(L);j?j.engine.syncNow():F.add(L)}F.size&&v(F)}}),{handlers:{get:()=>_e(p.getStatus()),getAll:()=>{let P=Be(),F=k()?"cloud":"local",L=(j,z,W)=>({...j,ownPendingDeletions:j.pendingDeletions,pendingDeletions:P,side:W,...z});return{engines:[L(p.getStatus(),{},F),...[...m.entries()].map(([j,{engine:z}])=>L(z.getStatus(),{shareKey:j},F)),...[...S.entries()].map(([j,{engine:z}])=>L(z.getStatus(),{binding:j},"local"))],pendingDeletionsTotal:P}},setEnabled:async P=>{if(!s)throw new Error("Cloud account is changing");let F=a;return await p.setEnabled(P),F!==a?p.getStatus():(await Promise.all([...m.values(),...S.values()].map(({engine:L})=>L.restart())),_e(p.getStatus()))},syncNow:()=>ft(),resolveHeld:P=>{let F=Array.isArray(P?.paths)?P.paths.filter(ee=>typeof ee=="string"):[],L=typeof P?.binding=="string"?P.binding:null,j=!L&&typeof P?.shareKey=="string"?P.shareKey:null,z=L?S.get(L)?.engine:j?m.get(j)?.engine:p;if(!z)return{error:"binding-not-found"};let W=z.resolveHeld(F,P.choice);return L?{...W,binding:L}:j?{..._e(W),shareKey:j}:_e(W)},confirmDeletions:()=>{for(let{engine:P}of m.values())P.confirmMassDeletions();for(let{engine:P}of S.values())P.confirmMassDeletions();return _e(p.confirmMassDeletions())},entryGet:async()=>{let P=await ot(),F=ht(),L=await wm(F);return{vaults:P.entrySync??[],activeRoot:r(),cloudRoot:F,mirrorVaults:L.names,mirrorVaultDevices:L.devices,deviceId:P.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let P=r();if(!P)return null;let F=ht(),L=await ot(),j=P===F?L.localVault&&L.localVault!==F?L.localVault:null:F;if(!j)return null;let z=[],W=500,ee=async(K,H)=>{if(z.length>=W)return;let oe;try{oe=await Ri.readdir(K,{withFileTypes:!0})}catch{return}for(let se of oe){if(z.length>=W)break;if(se.name.startsWith(".")||se.isSymbolicLink())continue;let ue=H?`${H}/${se.name}`:se.name;if(se.isDirectory())await ee(Kr.join(K,se.name),ue);else if(se.isFile()&&/\.db$/i.test(se.name))try{z.push({rel:ue,source:await Ri.readFile(Kr.join(K,se.name),"utf8")})}catch{}}};return await ee(j,""),{root:j,vaultName:j===F?"\u4E91\u7AEF":Kr.basename(j),dbs:z}},entryEnable:async P=>{let F=a,L=l;if(!s||!Ye())return{error:"Sign in to enable cloud sync"};let j=r();if(!j||k())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let z=await ot(),W=z.entrySync??[],ee=W.find(K=>K.vaultRoot===j);if(!ee){let K=(P.cloudName??Kr.basename(j)).normalize("NFC").trim(),H=td(K,W.map(oe=>oe.cloudName));if(H)return{error:H};if(!P.merge)try{let oe=await L.ensureOwnVault(),se=await L.call("GET",`/vaults/${encodeURIComponent(oe)}/tree`);if((se.folders??[]).some(X=>X===K||X.startsWith(`${K}/`))||(se.entries??[]).some(X=>X.path===K||X.path.startsWith(`${K}/`)))return{conflict:K}}catch(oe){return{error:oe?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}ee={vaultRoot:j,cloudName:K,entries:[]},W.push(ee)}return F!==a||!s?{error:"Cloud account changed; retry from the current account"}:(await gi(K=>{if(F!==a||!s)return!1;let H=K.entrySync??[],oe=H.find(Pe=>Pe.vaultRoot===j);if(!oe){let Pe=td(ee.cloudName,H.map(Ht=>Ht.cloudName));if(Pe)throw new Error(Pe);oe={vaultRoot:j,cloudName:ee.cloudName,entries:[]},H.push(oe)}let se=Pe=>String(Pe??"").replace(/\\/g,"/").normalize("NFC"),ue=new Set;for(let Pe of P.entries??[]){let Ht=se(Pe.path);Ht&&(ue.add(Ht),!oe.entries.some(gr=>gr.path===Ht)&&oe.entries.push({path:Ht,kind:Pe.kind==="folder"||Pe.kind==="asset"?Pe.kind:"page"}))}let X=(P.exclude??[]).map(se).filter(Boolean),ye=new Set([...ue,...(P.include??[]).map(se).filter(Boolean)]);oe.exclude=[...new Set([...(oe.exclude??[]).filter(Pe=>!ye.has(Pe)),...X])];let Ne=new Set(X);oe.entries=oe.entries.filter(Pe=>!Ne.has(Pe.path)),K.entrySync=H,ee=oe},z.cloudAccountId),F!==a?{error:"Cloud account changed; retry from the current account"}:(await Ee(),S.get(j)?.engine.syncNow(),ne(),{ok:!0,cloudName:ee.cloudName}))},entryDisable:async P=>{let F=r(),L=!1,j=a;return await gi(z=>{if(j!==a||!s)return!1;let W=(z.entrySync??[]).find(H=>H.vaultRoot===F);if(!F||!W)return!1;let ee=String(P??"").replace(/\\/g,"/").normalize("NFC"),K=W.entries.length;if(W.entries=W.entries.filter(H=>H.path!==ee),fi(W.entries,W.exclude,ee))W.exclude=[...new Set([...W.exclude??[],ee])];else if(W.entries.length===K)return!1;L=!0}),!L||j!==a?{ok:!1}:(await Ee(),ne(),{ok:!0})},entryMark:async(P,F)=>{let L=String(P??"").normalize("NFC");if(!L||L.includes("/")||L.startsWith("."))return{error:"invalid name"};if(!s||!Ye())return{error:"Sign in first"};try{await $(L,j=>F?j?void 0:[]:j?null:void 0)}catch(j){return{error:j?.message||String(j)}}return p.syncNow(),{ok:!0}},entryClosure:(P,F)=>n.relatedClosure(String(P??""),F==="folder"?"folder":"page"),collabCall:async(P,F)=>{let L=l,j=async()=>L.ensureOwnVault(),z=ee=>String((F??[])[ee]??""),W=ee=>(F??[])[ee]??{};switch(P){case"listVaults":return(await L.call("GET","/vaults")).vaults;case"activeVaultId":return j();case"pageShare":return L.call("GET",`/vaults/${encodeURIComponent(await j())}/page-shares?path=${encodeURIComponent(z(0))}`);case"relatedItems":return L.call("GET",`/vaults/${encodeURIComponent(await j())}/page-shares/${encodeURIComponent(z(0))}/related`);case"setShareItem":return L.call("POST",`/vaults/${encodeURIComponent(await j())}/page-shares/${encodeURIComponent(z(0))}/items`,{path:z(1),included:(F??[])[2]===!0});case"createPageShare":return L.call("POST",`/vaults/${encodeURIComponent(await j())}/page-shares`,{path:z(0),...W(1)});case"updatePageShare":return L.call("PATCH",`/vaults/${encodeURIComponent(z(2)||await j())}/page-shares/${encodeURIComponent(z(0))}`,W(1));case"revokePageShare":return L.call("DELETE",`/vaults/${encodeURIComponent(await j())}/page-shares/${encodeURIComponent(z(0))}`);case"setParticipantRole":return L.call("PATCH",`/vaults/${encodeURIComponent(z(3)||await j())}/page-shares/${encodeURIComponent(z(0))}/members/${encodeURIComponent(z(1))}`,{role:z(2)});case"removeParticipant":return L.call("DELETE",`/vaults/${encodeURIComponent(z(2)||await j())}/page-shares/${encodeURIComponent(z(0))}/members/${encodeURIComponent(z(1))}`);case"sharedWithMe":{let ee=await L.sharedWithMe();return v(),ee}case"leaveShare":{let ee=L.myUserId();if(!ee)throw new Error("\u672A\u767B\u5F55");let K=await L.call("DELETE",`/vaults/${encodeURIComponent(z(1)||await j())}/page-shares/${encodeURIComponent(z(0))}/members/${encodeURIComponent(ee)}`);return v(),K}case"publishes":return L.call("GET",`/vaults/${encodeURIComponent(await j())}/shares`);case"listAllShares":{let ee=(await L.call("GET","/vaults")).vaults||[],K=L.myUserId(),H=[],oe=[];for(let se of ee){try{let ue=await L.call("GET",`/vaults/${encodeURIComponent(se.id)}/shares`);for(let X of ue.shares||[])H.push({...X,vaultId:se.id,vaultName:se.name||""})}catch(ue){n.log(`[connect] listAllShares publishes vault ${se.id} failed: ${ue?.message}`)}try{let ue=await L.call("GET",`/vaults/${encodeURIComponent(se.id)}/page-shares?expired=1`),X=ue?.shares||ue?.pageShares||(Array.isArray(ue)?ue:[]);for(let ye of X){let Ne=ye.created_by??ye.createdBy;(!K||!Ne||Ne===K)&&oe.push({...ye,vaultId:se.id,vaultName:se.name||""})}}catch(ue){n.log(`[connect] listAllShares pageShares vault ${se.id} failed: ${ue?.message}`)}}return{publishes:H,pageShares:oe,linkBase:await L.linkBase()}}case"createPublish":{let ee=await L.call("POST",`/vaults/${encodeURIComponent(await j())}/shares`,{mode:z(0),path:z(1)});return{...ee,url:`${await L.linkBase()}/share/${ee.token}`}}case"revokePublish":return L.call("DELETE",`/vaults/${encodeURIComponent(await j())}/shares/${encodeURIComponent(z(0))}`);case"revokePublishIn":return L.call("DELETE",`/vaults/${encodeURIComponent(z(0))}/shares/${encodeURIComponent(z(1))}`);case"revokePageShareIn":return L.call("DELETE",`/vaults/${encodeURIComponent(z(0))}/page-shares/${encodeURIComponent(z(1))}`);case"myUserId":return L.myUserId();case"linkBase":return L.linkBase();case"heartbeat":return L.heartbeat((F??[])[0]??null,y);default:throw new Error(`unknown collab fn: ${P}`)}},switchSide:async(P,F)=>{if(F==="cloud"){let W=Ye();if(!s||!W)throw new Error("Sign in to open cloud notes");let ee=await qd(n.homeDir(),W).catch(()=>{throw new Error("switch_failed")}),K=Ja(ee)?void 0:await ot(W);if(Ye()!==W)throw new Error("account_changed");if(Ja(ee)||ee==="clean"&&Ga(K)){let se=Wa();if(!se)throw new Error("renderer_unsupported");return await se.openCloudNotes(),{side:"cloud",online:!0}}let H=ht(W);if(await Ri.mkdir(H,{recursive:!0}),Ye()!==W)throw new Error("account_changed");if(await kr({lastVault:H,...K?.lastVault&&!pi(K.lastVault)?{localVault:K.lastVault}:{}},W),Ye()!==W)throw new Error("account_changed");let oe=await n.activateRoot(H,!1);return n.bindRenderer(P,H),{...oe,side:"cloud"}}let L=await ot(),j=L.localVault&&await Ri.stat(L.localVault).then(W=>W.isDirectory()).catch(()=>!1)?L.localVault:null;if(!j){let W=await n.ensureDefaultVault();return n.bindRenderer(P,W.root),{...W,side:"local"}}await kr({lastVault:j});let z=await n.activateRoot(j,!1);return n.bindRenderer(P,j),{...z,side:"local"}}},instance:{start:()=>{s=!0,p.start(),v(),Ee()},stopAllSync:at,restartAllSync:Ir,resolveSharedAsset:P=>eh(y,P)}}}import{randomUUID as ry}from"node:crypto";import*as Xd from"node:fs";import{basename as i0,dirname as o0,join as iy}from"node:path";var s0="extend-forced-update.json",oy="https://api.forsion.net",Ym=`${oy}/api/website/update-policy`,a0=24*36e5,l0=1e3,c0=3e3,d0=12e4,u0=3e4,f0=["suspend","resume","lock-screen"],g0=1e4,p0=16*1024,h0=168*36e5,Go=/^[0-9A-Za-z.+-]{1,40}$/,m0=/^[0-9a-f]{32}$/,Ai=ry(),Yd=new WeakMap;function Ya(n,e,t){let r=Yd.get(n);r||Yd.set(n,r=new Map);let i=r.get(e);return i||r.set(e,i=new Set),i.add(t),()=>{i.delete(t)}}function Xm(n){let e={sync:!1,transfers:!1};for(let[t,r]of Yd.get(n)??[])for(let i of r){let o=!0;try{o=i()===!0}catch{o=!0}if(o){e[t]=!0;break}}return e}var y0=n=>{if(!n||typeof n!="object")return!1;let e=n;return Number.isFinite(e.at)&&typeof e.policy=="string"&&typeof e.from=="string"&&typeof e.launch=="string"&&(e.failedAt===void 0||Number.isFinite(e.failedAt))};function Ka(n,e=Xd){let t;try{t=e.readFileSync(n,"utf8")}catch(r){return r?.code==="ENOENT"?{}:null}try{let r=JSON.parse(t);if(!r||typeof r!="object"||r.v!==1||!r.attempts||typeof r.attempts!="object"||Array.isArray(r.attempts))return null;let i={};for(let[o,a]of Object.entries(r.attempts)){if(!Go.test(o)||!y0(a))return null;i[o]={at:a.at,policy:a.policy,from:a.from,launch:a.launch,...a.failedAt!==void 0?{failedAt:a.failedAt}:{}}}return i}catch{return null}}function Zm(n,e,t=Xd,r=process.platform){let i=Buffer.from(JSON.stringify({v:1,attempts:e}),"utf8"),o=o0(n),a=iy(o,`.${i0(n)}.${ry()}.tmp`),s=null,l=!1;try{t.mkdirSync(o,{recursive:!0}),s=t.openSync(a,"wx",384),l=!0;for(let d=0;d<i.length;){let g=t.writeSync(s,i,d,i.length-d);if(!(g>0))throw new Error("short write");d+=g}t.fsyncSync(s),t.closeSync(s),s=null;let u=t.readFileSync(a);if(!Buffer.isBuffer(u)||!u.equals(i))throw new Error("temp file does not read back");t.renameSync(a,n),l=!1}catch{if(s!==null)try{t.closeSync(s)}catch{}if(l)try{t.rmSync(a,{force:!0})}catch{}return!1}if(!b0(o,t,r))return!1;let c=Ka(n,t);return!!c&&JSON.stringify(c)===JSON.stringify(e)}var w0=new Set(["EISDIR","EINVAL","ENOTSUP","EBADF"]);function b0(n,e,t){let r=null;try{return r=e.openSync(n,"r"),e.fsyncSync(r),!0}catch(i){let o=typeof i?.code=="string"?i.code:"";return w0.has(o)||o==="EPERM"&&t==="win32"}finally{if(r!==null)try{e.closeSync(r)}catch{}}}var Qm=null;function Zd(){return Qm??=import("electron").then(e=>e?.app?e:e?.default??null,()=>null),Qm}async function v0(){return(await Zd())?.app?.isPackaged===!0}async function S0(){let e=(await Zd())?.powerMonitor;if(typeof e?.getSystemIdleTime!="function")throw new Error("powerMonitor unavailable");return e.getSystemIdleTime()}async function k0(n){let e=(await Zd())?.powerMonitor;if(typeof e?.on=="function")for(let t of f0)try{e.on(t,()=>n(t))}catch{}}var ey=["did-navigate","render-process-gone","destroyed"];function ty(n,e){let t=n;if(typeof t?.on!="function")return()=>{};try{for(let r of ey)t.on(r,e)}catch{}return()=>{try{for(let r of ey)t.removeListener?.(r,e)}catch{}}}var Kd=n=>{try{let e=n;return typeof e?.isDestroyed=="function"&&e.isDestroyed()===!0}catch{return!0}},ny=n=>{let e=n?.owner;return typeof e=="string"&&m0.test(e)?e:null};function sy(n,e={}){let t=e.fetch??((...x)=>fetch(...x)),r=e.now??Date.now,i=e.fs??Xd,o={ok:!1,error:"untrusted"},a={ok:!1,error:"unsupported"},s=()=>{try{return typeof n.homeDir=="function"&&n.homeDir()?iy(n.homeDir(),s0):null}catch{return null}},l=null,c=()=>l??=(async()=>{try{return(e.sandbox??(()=>process.env.FORSION_SANDBOX==="1"))()?!1:await(e.packaged??v0)()===!0}catch{return!1}})(),u=async()=>{try{let x=await(e.systemIdle??S0)();return typeof x=="number"&&Number.isFinite(x)&&x>=0?x:null}catch{return null}},d=(x,$)=>{n.handle(x,async(O,q)=>{if(!n.isTrustedSender(O))return o;if(!await c())return a;try{return await $(O,q)}catch{return{ok:!1,error:"failed"}}})},g=null,f=(x,$)=>!!g&&g.sender===x.sender&&g.token===ny($),p=(x,$)=>{g===x&&(g=null,x.unwatch(),m&&m.owner===x.token&&!b(m)&&v(m,"aborted",$))};d("forcedUpdate:claim",(x,$)=>{let O=ny($);if(!O)return{ok:!1,error:"invalid"};if(g&&g.sender!==x.sender&&!Kd(g.sender))return{ok:!1,error:"other_owner"};m&&m.owner!==O&&v(m,"aborted","owner_changed"),g?.unwatch();let q={token:O,sender:x.sender,unwatch:()=>{}};return g=q,q.unwatch=ty(x.sender,()=>p(q,"owner_gone")),{ok:!0,launch:Ai}}),d("forcedUpdate:release",(x,$)=>f(x,$)?(p(g,"released"),{ok:!0}):{ok:!1,error:"not_owner"});let m=null,y=0,b=x=>x.state==="done"||x.state==="aborted",h=x=>({ok:!0,id:x.id,seq:x.seq,state:x.state,remaining:Math.max(0,x.total-x.ticks),...x.reason?{reason:x.reason}:{}}),E=x=>{x.seq++;let $=h(x),O=[...x.waiters];x.waiters.clear();for(let q of O)q($)};function v(x,$,O){b(x)||(x.state=$,O&&(x.reason=O),$==="done"&&(x.doneAt=r()),x.timer&&clearInterval(x.timer),x.timer=null,x.unwatch(),E(x))}let k=x=>ty(x.sender,()=>v(x,"aborted","owner_gone")),C=!1,S=()=>{if(C)return;C=!0;let x=()=>{let $=m;$&&($.state==="done"?$.spent=!0:v($,"aborted","power"))};try{Promise.resolve((e.powerEvents??k0)(x)).catch(()=>{})}catch{}},_=(x,$,O,q)=>{let ie=$?.countdownId,Y=m;if(!Y||typeof ie!="number"||Y.id!==ie||Y.state!=="done"||Y.spent||Y.doneAt===null||!f(x,$)||Y.owner!==g.token||Y.sender!==x.sender||Y.target!==O||Y.policyId!==q)return null;let ne=r()-Y.doneAt;return ne>=0&&ne<=u0?Y:null},R=async x=>{if(m!==x||b(x))return;let $=r(),O=$-x.last;if(x.last=$,O>c0||O<0)return v(x,"aborted","tick_gap");if(Kd(x.sender)||g?.token!==x.owner)return v(x,"aborted","owner_gone");if(x.heldAt!==null)return $-x.heldAt>d0?v(x,"aborted","hold_timeout"):E(x);if(x.checking)return;x.checking=!0;let q=await u();if(x.checking=!1,!(m!==x||b(x)||x.heldAt!==null)){if(q===null)return v(x,"aborted","os_unknown");if(q<x.idleSeconds)return v(x,"aborted","input_os");if(x.ticks++,x.ticks>=x.total)return v(x,"done");E(x)}},N=(x,$)=>{let O=$?.id;return f(x,$)&&m&&m.owner===g.token&&m.id===O?m:null};d("forcedUpdate:countdown:start",(x,$)=>{if(!f(x,$))return{ok:!1,error:"not_owner"};let O=$??{},q=typeof O.target=="string"&&Go.test(O.target)?O.target:null,ie=typeof O.policyId=="string"&&O.policyId.length>0&&O.policyId.length<=100?O.policyId:null,Y=typeof O.total=="number"&&Number.isFinite(O.total)?Math.min(600,Math.max(15,Math.round(O.total))):null,ne=typeof O.idleSeconds=="number"&&Number.isFinite(O.idleSeconds)?Math.max(120,O.idleSeconds):null;if(!q||!ie||Y===null||ne===null)return{ok:!1,error:"invalid"};m&&v(m,"aborted","replaced");let ce={id:++y,owner:g.token,sender:x.sender,target:q,policyId:ie,total:Y,idleSeconds:ne,ticks:0,last:r(),heldAt:null,state:"running",seq:0,checking:!1,doneAt:null,spent:!1,timer:null,waiters:new Set,unwatch:()=>{}};return S(),m=ce,ce.unwatch=k(ce),ce.timer=setInterval(()=>{R(ce).catch(()=>v(ce,"aborted","failed"))},l0),ce.timer.unref?.(),h(ce)}),d("forcedUpdate:countdown:next",(x,$)=>{if(!f(x,$))return{ok:!1,error:"not_owner"};let O=N(x,$);if(!O)return{ok:!0,id:$?.id??null,seq:Number.MAX_SAFE_INTEGER,state:"aborted",remaining:0,reason:"gone"};let q=Number($?.after);return b(O)||!(Number.isFinite(q)&&q>=O.seq)?h(O):new Promise(ie=>{O.waiters.add(ie)})}),d("forcedUpdate:countdown:hold",(x,$)=>{let O=N(x,$);return!O||b(O)?{ok:!1,error:"not_running"}:(O.heldAt===null&&(O.heldAt=r(),O.state="held",E(O)),{ok:!0})}),d("forcedUpdate:countdown:cancel",(x,$)=>{let O=N(x,$);if(!O)return{ok:!1,error:"not_running"};let q=$?.reason;return v(O,"aborted",typeof q=="string"&&/^[a-z_]{1,32}$/.test(q)?q:"cancelled"),{ok:!0}}),d("forcedUpdate:policy",async(x,$)=>{let O=$?.fresh===!0,q=!1;try{q=new URL(String((await n.getCloud()).base)).origin===oy}catch{q=!1}if(!q)return{ok:!1,error:"unofficial_cloud"};let ie=O?`${Ym}?t=${r()}`:Ym;try{let ne={headers:O?{Accept:"application/json","Cache-Control":"no-cache",Pragma:"no-cache"}:{Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(g0),...O?{cache:"no-store"}:{}},ce=await t(ie,ne);if(ce.status!==200)return{ok:!1,status:ce.status,error:"http"};let Re=await ce.text();return Re.length>p0?{ok:!1,status:ce.status,error:"too_large"}:{ok:!0,status:ce.status,json:JSON.parse(Re)}}catch(Y){return{ok:!1,error:Y?.name==="SyntaxError"?"bad_json":"network"}}}),d("forcedUpdate:busy",()=>({ok:!0,...Xm(n)})),d("forcedUpdate:systemIdle",async()=>{let x=await u();return x===null?{ok:!1,error:"unavailable"}:{ok:!0,seconds:x}}),d("forcedUpdate:attempts",()=>{let x=s();if(!x)return{ok:!1,error:"no_home"};let $=Ka(x,i);return $?{ok:!0,attempts:$,launch:Ai}:{ok:!1,error:"unreadable"}});let D=Promise.resolve(),M=x=>{let $=D.then(x,x);return D=$.catch(()=>{}),$};d("forcedUpdate:reserve",(x,$)=>M(async()=>{if(!f(x,$))return{ok:!1,reason:"not_owner"};let O=$??{},q=typeof O.target=="string"&&Go.test(O.target)?O.target:null,ie=typeof O.policyId=="string"&&O.policyId.length>0&&O.policyId.length<=100?O.policyId:null,Y=typeof O.from=="string"&&Go.test(O.from)?O.from:null,ne=O.idleSeconds===void 0?null:typeof O.idleSeconds=="number"&&Number.isFinite(O.idleSeconds)&&O.idleSeconds>0?O.idleSeconds:NaN;if(!q||!ie||!Y||Number.isNaN(ne))return{ok:!1,reason:"invalid"};if(O.launchId!==Ai)return{ok:!1,reason:"stale_launch"};if(ne!==null){if(!_(x,$,q,ie))return{ok:!1,reason:"countdown"};let ft=await u();if(ft===null)return{ok:!1,reason:"os_unknown"};if(ft<ne)return{ok:!1,reason:"input_os"}}let ce=Xm(n);if(ce.sync||ce.transfers)return{ok:!1,reason:"busy"};if(!f(x,$)||Kd(x.sender))return{ok:!1,reason:"not_owner"};if(O.launchId!==Ai)return{ok:!1,reason:"stale_launch"};let Re=ne===null?null:_(x,$,q,ie);if(ne!==null&&!Re)return{ok:!1,reason:"countdown"};let Ee=s();if(!Ee)return{ok:!1,reason:"no_home"};let me=Ka(Ee,i);if(!me)return{ok:!1,reason:"unreadable"};let Ce=r(),Be=me[q];if(Be&&Ce-Math.max(Be.at,Be.failedAt??0)<a0)return{ok:!1,reason:"cooldown"};let _e={};for(let[ft,at]of Object.entries(me))Ce-Math.max(at.at,at.failedAt??0)<h0&&(_e[ft]=at);return _e[q]={at:Ce,policy:ie,from:Y,launch:Ai},Zm(Ee,_e,i)?(Re&&(Re.spent=!0),{ok:!0,at:Ce,launch:Ai}):{ok:!1,reason:"write_failed"}})),d("forcedUpdate:attemptFailed",(x,$)=>M(async()=>{if(!f(x,$))return{ok:!1,error:"not_owner"};let O=typeof $?.target=="string"?$.target:"";if(!Go.test(O))return{ok:!1,error:"invalid"};let q=s();if(!q)return{ok:!1,error:"no_home"};let ie=Ka(q,i);if(!ie)return{ok:!1,error:"unreadable"};let Y=ie[O];if(!Y)return{ok:!1,error:"not_found"};if(Y.failedAt!==void 0)return{ok:!0,failedAt:Y.failedAt};let ne=r();return Zm(q,{...ie,[O]:{...Y,failedAt:ne}},i)?{ok:!0,failedAt:ne}:{ok:!1,error:"write_failed"}}))}var du=(n,e,t,r,i)=>JSON.stringify([n,e,t,r,i]),$n=(n,e,t)=>`${n}:${e}:${t}`,ly="Amadeus/.trash",cy=n=>({key:n.key,ns:n.ns,id:n.id,path:n.path,side:n.side}),Za=n=>fu("sha256").update(n.map(e=>e.key).sort().join(`
|
|
211
|
+
`)).digest("hex").slice(0,24),iu=n=>fu("sha256").update(JSON.stringify([n.id,n.version,n.file??null,n.revision,n.localHash])).digest("hex").slice(0,24),M0=(n,e)=>n.length===e.length&&n.every(t=>e.some(r=>t.prefix===r.prefix&&t.root===r.root&&(t.dev===void 0||Dt(t,r)))),ou=n=>{let e=fu("sha256").update("vault-folder\0"+n).digest("hex");return`${e.slice(0,8)}-${e.slice(8,12)}-5${e.slice(13,16)}-a${e.slice(17,20)}-${e.slice(20,32)}`},su=()=>({config:structuredClone(sp),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),ir=Zs,N0=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CLOSED"]),$0=n=>{let e=n;return!!e&&(e.name==="TypeError"&&/fetch failed/i.test(e.message??"")||N0.has(String(e.cause?.code??e.code??"")))},au=n=>{let e=n?.code;return e==="VAULT_MOVED"||e==="VAULT_DELETED"},L0=n=>{let e=n;return e&&e.code==="TOO_LARGE"&&Number.isSafeInteger(e.maxBytes)&&e.maxBytes>0?e.maxBytes:null},F0=n=>`l:${n.size}:${n.mtime}`,B0=10*6e4,j0=30*6e4,dy=1024*1024,Ie=(n,e)=>`${n}:${e}`,or=n=>n.includes("/")?n.slice(0,n.lastIndexOf("/")):"",Yr=n=>n.slice(n.lastIndexOf("/")+1),Ti=Ue(""),U0=n=>/\.db$/i.test(n)&&!/^(agents|human)(\/|$)/.test(n),Qa=n=>n==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(n),Rr=n=>n.split("/").length,Fe=n=>n instanceof Error?n.message:String(n),V0={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0};function z0(n){if(!n.enabled)return null;let e=Hn("Amadeus",n.rules);if(e&&e.target!=="off")return{kind:"vault"};let t=n.rules.filter(r=>r.source.startsWith("Amadeus/")&&r.target!=="off").length;return t?{kind:"items",count:t}:null}var H0={uploads:"uploaded",downloads:"downloaded",merges:"merged",renames:"renamed",deletesSent:"deletedCloud",deletesLocal:"deletedLocal"},lu=n=>n.file.replace(/\.json$/,".bases"),my=5e3,q0=3e4,uy=3e4,W0=3e3,Qo=10*6e4,G0=60*6e4,J0=10*6e4,K0=3*6e4,fy=2e3,Y0=1440*6e4,cu=n=>/^(agents|human)\//.test(n)?q0:my,X0=n=>Math.max(n.mtime,n.ctime);async function*Ar(n){let e=ru.now()+8;for(let t of n)ru.now()>=e&&(await O0(),e=ru.now()+8),yield t}var Z0=new Set([ut.apply,ut.pause,ut.rename,ut.archiveSeen,ut.confirmDeletes,ut.abandonDeletes]),uu=null;function gu(n){uu=n}var gy="content_sync_retired";function yy(n,e={}){if(!n.contentSync)return;let t=new el(n,e);for(let[i,o]of Object.entries({[ut.get]:(a,s)=>t.snapshot(a,s),[ut.status]:()=>t.status(),[ut.preview]:a=>t.preview(a),[ut.apply]:(a,s)=>t.apply(typeof a=="string"?a:"",s),[ut.run]:()=>{t.retrySoon(),t.touch(),t.kick()},[ut.pause]:a=>t.pause(a===!0),[ut.retry]:()=>{t.retryFailed(),t.touch(),t.kick()},[ut.rename]:a=>t.rename(a),[ut.setup]:a=>t.setup(a),[ut.archiveSeen]:()=>t.archiveSeen(),[ut.confirmDeletes]:a=>t.confirmDeletes(typeof a=="string"?a:""),[ut.abandonDeletes]:a=>t.abandonDeletes(typeof a=="string"?a:"")}))n.handle(i,async(a,...s)=>{if(!n.isTrustedSender(a))return{ok:!1,error:"untrusted"};let l=Z0.has(i);l&&t.mutating++;try{return{ok:!0,value:await o(...s)}}catch(c){return{ok:!1,error:Fe(c)}}finally{l&&t.mutating--}});let r=()=>t.busy()&&!t.quitting;return n.addQuitGuard?.(i=>r()?{message:i==="zh"?"\u8FD8\u6709\u5185\u5BB9\u6B63\u5728\u540C\u6B65":"Content is still syncing"}:null),Ya(n,"sync",r),n.addFlushHook?.(i=>t.flush(i)),Qh(()=>t.stats()),t.start(),t}function pu(n,e,t={}){if(!n.contentSync)throw Error("content sync host unavailable");return new el(n,t,e)}var el=class{bind=null;otherBacked=new Set;bindStats={adopted:0,filled:0,held:0,replaced:0,skippedOther:0,recoveryEvents:[],revived:0};revivePaths=new Set;serverRealMove=!1;movedOut=[];scopeExclusions=null;goneLinked=new Set;roundStats(){return structuredClone(this.bindStats)}failure=void 0;roundFailure(){return this.failure}bindPolicy=null;session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;activeAt=Date.now();lastRunAt=0;focused=!1;devices=[];others;deviceId="";customName="";serial=Promise.resolve();scheduled=null;tick=null;first=null;blocked=new Map;progress=new Ei;recorder=new _i;recordAccount=null;roundLocal=null;roundCloud=null;roundSettled=new Set;roundFirst=!1;activeJob=null;lastCompletedAt=null;phaseValue="idle";get phase(){return this.phaseValue}set phase(e){e==="scanning"&&this.phaseValue!=="scanning"?(this.progress.begin("checking"),this.roundSettled.clear(),this.roundLocal=null,this.roundCloud=null,this.activeJob=null):e==="syncing"&&this.phaseValue!=="syncing"&&this.planRound(),this.phaseValue=e}lastError;get error(){return this.lastError}set error(e){this.lastError=e,e&&this.fault(e)}runLog=new Lo;logAccount=null;runAccount=null;blockedError=void 0;live(){let e=this.host.accountId();return!!e&&e===this.logAccount&&(!this.running||!this.runAccount||this.runAccount===e)}tally(e){this.live()&&this.runLog.count(e);let t=H0[e];t&&this.progress.count(t)}fault(e,t=[]){this.live()&&this.runLog.fault(e,t)}health=Ia((e,t,r)=>Nt("content",e,t,r));httpStatus=0;closed=!1;runFinished=Promise.resolve();archiving=null;archiveRetry={account:"",at:0};resolving=!1;awaitingBytes=new Map;scanned={skipped:[],unscanned:[],skippedInodes:new Set};deleteStamps=[];failures=new Map;tooLarge=new Map;tooLargeSeen=null;recordsAccount=null;roundVisited=null;bypassBackoff=!1;bypassThisRound=!1;limitsByNs=new Map;round=null;uiLocale=null;running=!1;mutating=0;busy(){return this.running||this.resolving||this.applying>0||this.archiving!==null||this.flushing!==null||this.mutating>0||this.settingUp>0}settingUp=0;applying=0;quitting=!1;again=!1;flushing=null;flushRequest=0;flushThrough=0;dirty=new Map;flushAt=0;editFlushAt=0;releasedPaths=new Set;due=null;registered=null;devicesAt=0;changedAt=0;wroteLocal=!1;openJobs=new Set;host;options;accountGeneration=0;stopAccountWatch;constructor(e,t={},r=null){this.host=e,this.options=t,this.bind=r,r&&(this.deviceId=r.deviceId),this.stopAccountWatch=nm(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{this.idleSkip()||this.run()},3e4)).unref?.(),(this.first=setTimeout(()=>{this.run()},5e3)).unref?.()}locale(){if(this.uiLocale)return this.uiLocale;try{return/^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en"}catch{return"zh"}}archiveStep(e){if(e.stored.accountReview||e.stored.agentArchive?.state==="done"||this.archiveRetry.account===e.account&&Date.now()<this.archiveRetry.at)return Promise.resolve();let t=()=>{this.archiveRetry={account:e.account,at:Date.now()+Qo}};if(this.archiving)return this.archiving;let r=this.archiving=(async()=>{try{let o=this.host.readCreds();if(!o.token)return;let a=await this.gatedFetch(e,o.cloudUrl,"/api/remotesync/agent-archive",{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({locale:this.locale()})},6e4);if(this.guard(e),!a.ok){t();return}let s=await a.json();if(this.guard(e),s.state!=="done"&&s.state!=="running"){t();return}let l=e.stored.agentArchive,c=s.archive;l?.rewritten||this.turnAgentsOff(e);let u={rewritten:!0,seen:l?.seen??!1,state:s.state};s.state==="done"&&(c?.folderId?Object.assign(u,{folderId:c.folderId,name:c.name??void 0,shelfId:c.shelfId??void 0,shelfName:c.shelfName??void 0,files:c.files??0,at:c.at??Date.now()}):u.seen=!0),e.stored.agentArchive=u,await this.persist(e)}catch(o){if(Fe(o)==="account_changed"||e.abort.signal.aborted)return;t(),this.host.log?.(`[content-sync] agent archive: ${Fe(o)}`)}})(),i=()=>{this.archiving===r&&(this.archiving=null)};return r.then(i,i),r}turnAgentsOff(e){let t=e.stored.config;if(!t.enabled&&t.revision===0)return;let r=Nh(t);if(!r)return;e.stored.config=Zt(r,t.revision+1);let i=o=>o==="agents"||o.startsWith("agents/");for(let[o,a]of Object.entries(e.stored.files))i(a.path)&&(delete e.stored.files[o],delete e.stored.unconfirmed?.[o]);for(let[o,a]of Object.entries(e.stored.folders))i(a.path)&&delete e.stored.folders[o];for(let[o,a]of Object.entries(e.stored.pendingUploads??{}))i(a.path)&&delete e.stored.pendingUploads[o];this.previewValue=null}wantsClaim(e){return e.config.enabled||e.accountReview===!0}sealedShadow(e){return!!e&&sn(e.path)}async release(e){e.stored.owned=!1,e.stored.releasing=!0,await this.persist(e),await this.accountWrite(e,t=>this.host.contentSync.claim(!1,t)),delete e.stored.releasing,await this.persist(e)}async settleRelease(e){this.wantsClaim(e.stored)||!(e.stored.owned||e.stored.releasing)||await this.release(e).catch(t=>{if(Fe(t)==="account_changed"||e.abort.signal.aborted)throw t;this.host.log?.(`[content-sync] release: ${Fe(t)}`)})}async archiveSeen(){let e=await this.getSession();e.stored.agentArchive&&(e.stored.agentArchive.seen=!0,await this.persist(e))}async close(){for(this.closed=!0,this.stopAccountWatch(),this.tick&&clearInterval(this.tick),this.first&&clearTimeout(this.first),this.scheduled&&clearTimeout(this.scheduled),this.due&&clearTimeout(this.due),this.session?.abort.abort(),await this.watcher?.close(),await this.runFinished;this.resolving;)await new Promise(e=>setTimeout(e,50))}currentBinding(e){if(!e.binding)return!0;let t=Bo(e.binding.file);return t!==null&&!t.pending&&t.account===e.binding.account&&t.epoch===e.binding.epoch}guard(e,t=!0){if(this.closed)throw Error("content_sync_closed");if(this.bind?.account()!=="device"&&Pa(this.host),(this.bind?this.bind.account():this.host.accountId())!==e.account||this.session!==e||e.generation!==this.accountGeneration)throw Error("account_changed");if(!this.currentBinding(e))throw Error("content_account_changed_preview_required");t&&e.abort.signal.throwIfAborted()}ownerNow(){return this.bind?this.bind.account():this.host.accountId()}async accountWrite(e,t){let r=async()=>{this.guard(e),await t(e.account),this.guard(e)};this.host.accountTransition?await this.host.accountTransition(r):await r()}async persist(e,t=!1){let r=e.writes.catch(()=>{}).then(async()=>{this.guard(e,!1);let i=JSON.stringify(e.stored);if(t){await je(e.file,JSON.parse(i),()=>this.guard(e,!1)),e.persisted=i;return}if(i===e.persisted)return;await ay(Ii(e.file),{recursive:!0,mode:448});let o=e.file+".tmp-"+kn();try{await Xa(o,i,{mode:384,flag:"wx"}),this.guard(e,!1),await Ko(o,e.file),e.persisted=i}finally{await Xo(o).catch(()=>{})}});return e.writes=r,r}async getSession(){if(this.bind)return this.getBindingSession();let e=this.host.accountId();if(!e)throw this.logAccount&&(this.runLog.reset(),this.logAccount=null),this.session?.abort.abort(),this.session=null,Error("not_signed_in");if(uu&&await uu(e)==="retired")throw this.session&&(this.session.abort.abort(),this.session=null),Error(gy);let t=this.accountGeneration;return Pa(this.host),this.initializing?this.initializing.then(r=>(this.guard(r),r)):this.session?.account===e&&this.session.generation===t&&this.currentBinding(this.session)?(this.guard(this.session,!1),this.session):(this.session?.abort.abort(new Error("account_changed")),this.logAccount!==e&&(this.runLog.reset(),this.logAccount=e),this.initializing=(async()=>{await this.watcher?.close(),this.watcher=null,this.previewValue=null,this.sources=[],this.agentNames.clear(),this.cloudAgents=void 0,this.devices=[],this.dirty.clear(),this.registered=null,this.devicesAt=0,this.changedAt=0;let r=st(this.host.homeDir(),"content-sync"),i=st(r,Ue(e)+".json"),o=su();try{let c=JSON.parse(await Jo(i,"utf8"));Gn(c),o={...o,...c,config:Zt(c.config,c.config.revision)},o.jobs=Array.isArray(c.jobs)?c.jobs.slice(-200):[]}catch(c){if(c.code!=="ENOENT")throw Error("Invalid content sync state; original data was retained")}let a=await Da(this.host.homeDir());if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=a.id,this.customName=a.name??"";let s=await this.host.contentSync.roots();if(this.host.accountId()!==e)throw Error("account_changed");let l={account:e,generation:t,file:i,stored:o,roots:s,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map,tombstones:new Map};this.session=l,this.settingUp++;try{await this.bindAccount(l),await this.recoverTrash(l),this.guard(l),this.wantsClaim(o)?o.owned&&await this.accountWrite(l,c=>this.host.contentSync.claim(!0,c)):(o.owned||o.releasing)&&await this.release(l).catch(c=>{this.host.log?.(`[content-sync] release: ${Fe(c)}`)})}finally{this.settingUp--}return this.setSources(await this.scan(l,s).catch(c=>(this.error=Fe(c),[]))),await this.register(l,!0),await this.watchRoots(l),l})().catch(r=>{throw this.session?.account===e&&(this.session.abort.abort(),this.session=null),r}).finally(()=>{this.initializing=null}),this.initializing)}async getBindingSession(){let e=this.bind,t=e.account();if(!t)throw this.session?.abort.abort(),this.session=null,Error("not_signed_in");let r=this.accountGeneration;return e.account()!=="device"&&Pa(this.host),this.initializing?this.initializing.then(i=>(this.guard(i),i)):this.session?.account===t&&this.session.generation===r?(this.guard(this.session,!1),this.session):(this.session?.abort.abort(new Error("account_changed")),this.initializing=(async()=>{await this.watcher?.close(),this.watcher=null,this.dirty.clear();let i=su();try{let l=JSON.parse(await Jo(e.stateFile,"utf8"));Gn(l),i={...i,...l,config:Zt(l.config,l.config.revision)},i.jobs=Array.isArray(l.jobs)?l.jobs.slice(-200):[]}catch(l){if(l.code!=="ENOENT")throw Error("Invalid vault sync state; original data was retained")}let o=e.ns+"|"+(await e.roots()).map(l=>l.prefix).join(",");if(i.bindTarget!==void 0&&i.bindTarget!==o){let l=Date.now();for(let c of[e.stateFile,e.stateFile.replace(/\.json$/,".bases")])await Ko(c,`${c}.retired-${l}`).catch(u=>{if(u.code!=="ENOENT")throw u});i=su()}if(i.bindTarget=o,i.config={...i.config,enabled:!0},i.owned=!1,i.paused=!1,delete i.releasing,delete i.accountReview,e.account()!==t)throw Error("account_changed");let a=await e.roots();if(e.account()!==t)throw Error("account_changed");let s={account:t,generation:r,file:e.stateFile,stored:i,roots:a,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map,tombstones:new Map};this.session=s,this.settingUp++;try{await this.recoverTrash(s),this.guard(s)}finally{this.settingUp--}return await this.watchRoots(s),s})().catch(i=>{throw this.session?.account===t&&(this.session.abort.abort(),this.session=null),i}).finally(()=>{this.initializing=null}),this.initializing)}async bindAccount(e){let t=Ii(e.file),r=xd(this.host.homeDir()),i=Ue(e.account),o=Bo(r),a=!o?.account&&(await Yo(t).catch(l=>{if(l.code==="ENOENT")return[];throw l})).some(l=>/^[a-f0-9]{64}\.json$/.test(l)&&l!==i+".json"),s=o?.pending&&(e.stored.owned||e.stored.config.revision>0);if((o?.account&&o.account!==i||a||s)&&(e.stored.accountReview=!0,e.stored.owned=!0,e.stored.config.enabled&&(e.stored.config={...e.stored.config,enabled:!1,revision:e.stored.config.revision+1}),await this.persist(e)),o?.account!==i||o.pending){this.guard(e,!1);let l=Bo(r);if(l?.account!==o?.account||l?.epoch!==o?.epoch||l?.pending!==o?.pending)throw Error("account_changed");Td(r,{version:1,account:i,...o?.epoch?{epoch:o.epoch}:{}})}e.binding={file:r,account:i,epoch:o?.epoch},this.guard(e,!1)}async rootIdentity(e,t){let r=e.rootIdentities.get(t);if(r){let o=await eu(t).catch(()=>{throw Error("Sync root unavailable: "+t)});if(!o.isDirectory()||!hn(r,o))throw Error("Sync root changed; preview before rebinding");return r}let i=await dt(t).catch(o=>{throw o.code==="ENOENT"?Error("Sync root unavailable: "+t):o});return this.guard(e),e.rootIdentities.set(t,i),i}async scan(e,t=e.roots){let r=!1;for(let o of e.stored.roots??[]){let a=t.find(l=>l.prefix===o.prefix);if(!a)throw Error("content_roots_changed_preview_required");if(a.root!==o.root){if(!this.bind||o.dev===void 0)throw Error("content_roots_changed_preview_required");let l=await this.rootIdentity(e,a.root);if(!Dt(o,l))throw Error("content_roots_changed_preview_required");o.root=a.root,r=!0}let s=await this.rootIdentity(e,o.root);if(o.dev!==void 0&&!Dt(o,s))throw Error("Sync root changed; preview before rebinding");if(o.dev!==void 0&&o.dev!==s.dev){let l=String(o.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(l)&&Ze(t,c.path).root===o.root&&(c.inode=String(s.dev)+":"+c.inode.slice(l.length),delete c.stat,delete c.statAt)}JSON.stringify(o)!==JSON.stringify({...o,...s})&&(Object.assign(o,s),r=!0)}r&&await this.persist(e);let i=await bn(t,this.bind?{markers:!1}:{});if(this.scanned={skipped:i.skipped,unscanned:i.unscanned,skippedInodes:i.skippedInodes},this.bind)for(let o of i)o.kind==="folder"&&(o.localId=ou(o.path));return i}async write(e,t,r,i){this.guard(e),await Jc(e.roots,t,r,i,(o,a)=>this.lock(e,o,a)),await this.recordRoots(e)}async recordRoots(e){this.guard(e);let t=!1;for(let r of e.roots){if(e.stored.roots?.some(o=>o.prefix===r.prefix&&o.root===r.root))continue;await eu(r.root).catch(o=>{if(o.code==="ENOENT")return null;throw o})&&((e.stored.roots??=[]).push({...r,...await this.rootIdentity(e,r.root)}),t=!0)}t&&await this.persist(e)}lock(e,t,r,i=!1){let o=()=>{if(this.guard(e),e.stored.paused&&!i)throw Error("paused");for(let[a,s]of e.rootIdentities){let l;try{l=E0(a)}catch{throw Error("Sync root unavailable: "+a)}if(!l.isDirectory()||!hn(s,l))throw Error("Sync root changed; restart before retrying")}r(),this.wroteLocal=!0};return this.host.contentSync.withWriteLock?.(t,o)??Promise.resolve().then(o)}async previewScan(e,t){for(let r of e.stored.roots??[])t.some(i=>i.prefix===r.prefix&&i.root===r.root)&&await un(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return bn(t)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=wc(e.roots.map(t=>t.root),{ignoreInitial:!0,ignored:t=>{let r=t.split(/[\\/]/).at(-1)??"";return r.startsWith(".")&&r!==".memory-tombstones.json"||r==="node_modules"||r==="__pycache__"}}),this.watcher.on("all",(t,r)=>{let i=this.logical(e,r),o=Date.now();if(this.activeAt=o,i){let a=this.dirty.get(i);a?a.last=o:this.dirty.set(i,{first:o,last:o})}this.schedule(i?void 0:o+my)}))}logical(e,t){let r=null;for(let a of e.roots)(t===a.root||t.startsWith(a.root+xi))&&(!r||a.root.length>r.root.length)&&(r=a);if(!r)return null;let i=Zo(r.root,t).split(xi).join("/");return(r.prefix?i?`${r.prefix}/${i}`:r.prefix:i)||null}dueAt(e,t){return t.last<=this.flushAt?0:Math.min(t.last+cu(e),t.first+uy)}schedule(e){if(this.bind){this.due&&clearTimeout(this.due),this.due=null;return}let t=e??1/0;for(let[r,i]of this.dirty)t=Math.min(t,this.dueAt(r,i));this.due&&clearTimeout(this.due),this.due=null,!(t===1/0||this.closed)&&(this.due=setTimeout(()=>{this.due=null;let r=this.session;r?.stored.config.enabled&&!r.stored.paused&&this.kick()},Math.max(0,t-Date.now())+50),this.due.unref?.())}flushEdits(e){this.editFlushAt=Math.max(this.editFlushAt,e)}deferred(e){let t=1/0;for(let r of e){let i=this.dirty.get(r);i&&(t=Math.min(t,this.dueAt(r,i)))}if(t<1/0)try{this.bind.onDeferred?.(t)}catch{}}kick(){if(this.running){this.again=!0;return}this.run()}pendingChanges(){return this.dirty.size}idle(){return this.runFinished}currentError(){return this.error}lastSync(){return this.lastCompletedAt??null}touch(){this.activeAt=Date.now()}idleSkip(e=Date.now()){return e-this.activeAt>=J0&&e-this.lastRunAt<K0-5e3}flush(e){let t=this.session;if(!(this.closed||!this.host.accountId()||t&&(!t.stored.config.enabled||t.stored.paused)))return this.flushRequest++,this.flushThrough=Math.max(this.flushThrough,Date.now()),this.bypassBackoff=!0,e==="quit"&&(this.quitting=!0),this.flushAt=this.quitting?1/0:this.flushThrough,this.flushing?this.flushing:this.flushing=(async()=>{try{for(;!this.closed;){let r=this.serial;if(await r,r!==this.serial)continue;if(this.running){await this.runFinished;continue}let i=this.flushRequest;if(await this.run(),i===this.flushRequest)return}}finally{this.flushing=null,this.quitting=!1,this.flushAt=this.flushThrough}})()}async request(e,t,r="",i="GET",o,a,s){if(this.bind?.transport){this.guard(e);let l=r===""&&i==="GET"?j0:12e4,c=await this.bind.transport.request(t,r,i,o,{...s},AbortSignal.any([e.abort.signal,AbortSignal.timeout(l)]));if(this.guard(e),!c.ok&&!(c.status===304&&s?.["If-None-Match"])){let u=await c.json().catch(()=>({}));throw Object.assign(new Error(typeof u?.detail=="string"?u.detail:`content_http_${c.status}`),{status:c.status,...typeof u?.code=="string"?{code:u.code}:{},...Number.isSafeInteger(u?.maxBytes)&&u.maxBytes>0?{maxBytes:u.maxBytes}:{}})}return i==="DELETE"&&this.tally("deletesSent"),c}for(;;){this.guard(e);let l=this.host.readCreds();if(!l.token)throw Error("not_signed_in");let c=On(l.cloudUrl);await c.ready(e.abort.signal),this.guard(e);let u=l.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(t)}${r}`,d=this.bind?.caps?.length?[mr,...this.bind.caps].join(","):mr,g={Authorization:`Bearer ${l.token}`,"X-Content-Device":this.deviceId,"X-Content-Caps":d,...s},f;if(o instanceof Buffer){g["Content-Type"]="application/octet-stream",g["Content-Length"]=String(o.length);let y=async function*(){for(let b=0;b<o.length;b+=64*1024)e.abort.signal.throwIfAborted(),yield o.subarray(b,b+64*1024),a?.(Math.min(o.length,b+64*1024))};f=P0.from(y())}else o!==void 0&&(g["Content-Type"]="application/json",f=JSON.stringify(o));let p={method:i,headers:g,body:f,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...o instanceof Buffer?{duplex:"half"}:{}},m=await fetch(u,p);if(this.guard(e),!m.ok&&!(m.status===304&&s?.["If-None-Match"])){let y=await m.json().catch(()=>({}));if(c.observe(m.status,m.headers,y?.code,y?.retryAfterMs))continue;throw this.httpStatus=m.status,this.bind&&(m.status===409||m.status===423)&&y?.code==="VAULT_MOVED"&&this.noteMoved(e,typeof y.vaultId=="string"?y.vaultId:"",null),this.bind&&m.status===410&&y?.code==="VAULT_DELETED"&&this.bind.onDeleted?.({purgeAt:typeof y.purgeAt=="string"&&!Number.isNaN(Date.parse(y.purgeAt))?y.purgeAt:null,purging:y.purging===!0,purged:y.purged===!0,reverted:y.reverted===!0}),Object.assign(new Error(typeof y?.detail=="string"?y.detail:`content_http_${m.status}`),{status:m.status,...typeof y?.code=="string"?{code:y.code}:{},...Number.isSafeInteger(y?.maxBytes)&&y.maxBytes>0?{maxBytes:y.maxBytes}:{},...typeof y?.vaultId=="string"?{vaultId:y.vaultId}:{}})}return c.observe(m.status,m.headers),i==="DELETE"&&this.tally("deletesSent"),m}}async gatedFetch(e,t,r,i,o){let a=On(t);for(;;){await a.ready(e.abort.signal),this.guard(e);let s=await fetch(t.replace(/\/+$/,"")+r,{...i,headers:{...i.headers,"X-Content-Caps":mr},signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(o)])});if(s.status===429){let l=await s.clone().json().catch(()=>({}));if(a.observe(s.status,s.headers,l?.code,l?.retryAfterMs))continue}return a.observe(s.status,s.headers),s}}async json(e,t,r="",i="GET",o,a){let s=await(await this.request(e,t,r,i,o,void 0,a)).json();return this.guard(e),s}leftScope(e,t,r,i){let o=s=>s===ly||s.startsWith(ly+"/"),a=new Map;for(let[s,l]of Object.entries(e.stored.folders))s.startsWith(r+":")&&a.set(l.id,l.path);for(let s of i.nodes){if(s.deleted||s.kind!=="file"&&s.kind!=="folder")continue;let l=s.kind==="folder"?"folder":"file",c=l==="file"?e.stored.files[Ie(r,s.id)]?.path:a.get(s.id);c===void 0||c===s.path||!o(s.path)||this.route(s.path,t,l)===r||this.route(c,t,l)!==r||(s.deleted=!0,s.path=c)}}async manifests(e,t){let r=this.bind?.readScopeExclusions?await this.readBindingPrefixes(e):null,i=new Map;for(let a of this.bind?[this.bind.ns]:new Set(t.rules.filter(s=>s.target!=="off").map(s=>s.target))){let s=JSON.parse(await this.manifestText(e,a));vr(s,a),this.bind&&a===this.bind.ns&&(this.checkMoved(e,s),this.serverRealMove=s.realMove===!0,this.bind.liveRealMove&&this.bindPolicy&&(this.bindPolicy={...this.bindPolicy,realMove:this.serverRealMove})),await this.knownTombstones(e,a,s),i.set(a,s)}if(this.bind){let a=i.get(this.bind.ns);if(this.otherBacked=new Set,this.bind.transport){let s=a.otherPaths;if(Array.isArray(s))for(let l of s)typeof l=="string"&&e.roots.some(c=>l.startsWith(c.prefix+"/"))&&this.otherBacked.add(l)}else for(let s of a.nodes)s.kind==="file"&&!s.deleted&&s.version&&!s.file&&e.roots.some(l=>s.path.startsWith(l.prefix+"/"))&&this.otherBacked.add(s.path);return r?await this.refreshBindingScope(e,a,r):this.leftScope(e,t,this.bind.ns,a),this.running&&this.phaseValue==="scanning"&&(this.roundCloud=i),i}let o=[i.get("default"),i.get(`device-${this.deviceId}`)].filter(Boolean);return o.length&&(this.cloudAgents=[...new Set(o.flatMap(a=>a.nodes.filter(s=>!s.deleted&&s.kind==="file").map(s=>/^agents\/([^/]+)\/config\.toml$/.exec(s.path)?.[1]).filter(s=>!!s&&Oo.test(s))))].sort()),this.running&&this.phaseValue==="scanning"&&(this.roundCloud=i),i}followCloudGone(e,t){this.goneLinked=new Set;let r=e.stored.held;if(!r)return;let i=new Map;for(let[s,l]of Object.entries(r))l.cloudGone&&l.inode&&i.set(l.inode,[...i.get(l.inode)??[],s]);let o=[];for(let[s,l]of i){let c=t.filter(g=>g.kind==="file"&&g.inode===s&&!l.includes(g.path)).map(g=>g.path),u=l[0];if(l.length===1&&!t.some(g=>g.kind==="file"&&g.path===u)&&c.length===1&&!r[c[0]]&&!Object.values(e.stored.files).some(g=>g.path===c[0]))o.push([u,c[0]]);else for(let g of c)this.goneLinked.add(g)}let a=new Map;for(let[,s]of o)a.set(s,(a.get(s)??0)+1);for(let[s,l]of o){if(a.get(l)!==1){this.goneLinked.add(l);continue}let c=r[s];delete r[s],r[l]={...c,path:l}}}checkMoved(e,t){this.movedOut=[];let r=si(t);for(let i of e.roots){let o=i.prefix+"/",a=r.find(s=>s.prefix===o);if(a)throw a.vaultId?(this.noteMoved(e,a.vaultId,a.at),Object.assign(new Error("This folder is now a separate vault"),{code:"VAULT_MOVED",vaultId:a.vaultId})):Error("Invalid moved record for binding");for(let s of r)s.prefix.startsWith(o)&&this.movedOut.push(s.prefix.slice(0,-1))}}async readBindingPrefixes(e){this.scopeExclusions=null;let t=await this.bind.readScopeExclusions(e.abort.signal);return this.guard(e),t}async refreshBindingScope(e,t,r){let i=[...Object.values(e.stored.files),...Object.values(e.stored.folders),...Object.values(e.stored.held??{}),...Object.values(e.stored.pendingUploads??{})],o=await Ta(this.bind.vaultRoot,r,t,i.map(a=>a.path));this.guard(e),this.scopeExclusions=o}async recordScopeDepartures(e,t,r,i){let o=new Map(i.nodes.map(s=>[s.id,s])),a=!1;for(let[s,l]of[["file",e.stored.files],["folder",e.stored.folders]])for(let[c,u]of Object.entries(l)){if(!c.startsWith(r+":")||u.outsideScope)continue;let d=o.get(u.id);(this.route(u.path,t,s)!==r||d&&this.route(d.path,t,s)!==r)&&(u.outsideScope=!0,a=!0)}a&&await this.persist(e,!0)}underExclusion(e,t){return t.some(r=>e===r||e.startsWith(r+"/"))}async beginExpandedScope(e){let t=this.scopeExclusions;if(!t)return;let r=e.stored,i=r.scopeExclusions??[],o=c=>this.underExclusion(c,i)&&!this.underExclusion(c,t),a=i.filter(o);if(a.length){for(let[u,d]of Object.entries(r.files))o(d.path)&&(delete r.files[u],delete r.unconfirmed?.[u]);for(let[u,d]of Object.entries(r.folders))o(d.path)&&delete r.folders[u];for(let[u,d]of Object.entries(r.pendingUploads??{}))o(d.path)&&(delete r.pendingUploads[u],delete r.unconfirmed?.[u]);for(let[u,d]of Object.entries(r.held??{}))o(d.path)&&delete r.held[u];let c=r.deleteGuard;c&&(c.pending=c.pending.filter(u=>!o(u.path)),c.restore=c.restore?.filter(u=>!o(u.path)),c.confirmed=c.confirmed?.filter(u=>{try{let d=JSON.parse(u)?.[4];return typeof d!="string"||!o(d)}catch{return!0}})),r.scopeFirstRound=[...new Set([...r.scopeFirstRound??[],...a])]}let s=r.scopeFirstRound,l=this.bindPolicy;s&&l&&(this.bindPolicy={...l,deletes:!1,newerOnly:c=>!this.underExclusion(c,s)&&(l.newerOnly?.(c)??!0)}),(s||JSON.stringify(i)!==JSON.stringify(t)||!r.scopeExclusions)&&(r.scopeExclusions=t,await this.persist(e))}noteMoved(e,t,r){let i=e.roots[0]?.prefix;i!==void 0&&t&&this.bind?.onMoved?.({vaultId:t,prefix:i+"/",at:r})}async manifestText(e,t){let r=e.manifests.get(t),i=r&&Date.now()-r.at<G0?r:void 0,o=await this.request(e,t,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...i?{"If-None-Match":i.etag}:{}});if(o.status===304)return await o.body?.cancel(),i?i.text:(e.manifests.delete(t),this.manifestText(e,t));let a=await o.text();this.guard(e),vr(JSON.parse(a),t);let s=o.headers.get("etag");return r?.text!==a&&this.touch(),s?e.manifests.set(t,{etag:s,text:a,at:Date.now()}):e.manifests.delete(t),a}async knownTombstones(e,t,r){if(typeof r.tombstonesSince!="string")return;let i=new Set(r.nodes.map(u=>u.id)),o=new Set,a=u=>!this.scopeExclusions||!this.underExclusion(u,this.scopeExclusions);for(let[u,d]of Object.entries(e.stored.files))u.startsWith(t+":")&&a(d.path)&&o.add(d.id);for(let[u,d]of Object.entries(e.stored.folders))u.startsWith(t+":")&&a(d.path)&&o.add(d.id);for(let[u,d]of Object.entries(e.stored.pendingUploads??{}))u.startsWith(t+":")&&a(d.path)&&o.add(d.id);let s=e.tombstones.get(t);s||e.tombstones.set(t,s=new Map);for(let u of[...s.keys()])i.has(u)&&s.delete(u);let l=Date.now(),c=[...o].filter(u=>{if(i.has(u))return!1;let d=s.get(u);return!d||!d.node&&l-d.at>=Y0});for(let u=0;u<c.length;u+=fy){let d=c.slice(u,u+fy),g=new Set(d),f=await this.json(e,t,"/tombstones","POST",{ids:d}),p=new Map((Array.isArray(f?.nodes)?f.nodes:[]).filter(m=>yp(m)&&g.has(m.id)).map(m=>[m.id,m]));for(let m of d)s.set(m,{node:p.get(m)??null,at:l})}for(let u of o)if(!i.has(u)){let d=s.get(u)?.node;d&&r.nodes.push(structuredClone(d))}}route(e,t,r="file"){if(this.bind)return this.bindRoute(e,r);if(Ot(e)||sn(e)||nd(e,r)===!1)return null;let i=Hn(e,t.rules);return i&&i.target!=="off"?i.target:null}bindRoute(e,t){let r=this.bind,i=this.session?.roots.find(o=>e===o.prefix||e.startsWith(o.prefix+"/"));return!i||r.readScopeExclusions&&(!this.scopeExclusions||this.underExclusion(e,this.scopeExclusions))||this.movedOut.some(o=>e===o||e.startsWith(o+"/"))||this.otherBacked.has(e)?null:wy(i.prefix,e,t,r.inScope)?r.ns:null}effective(e,t){if(this.bind)return e;let r=new Map(t.filter(i=>i.localId).map(i=>[i.localId,i.path]));return{...e,rules:e.rules.map(i=>i.sourceId&&!sn(i.source)&&r.has(i.sourceId)?{...i,source:r.get(i.sourceId)}:i)}}deviceName(){return this.customName||Mr(tu())}setSources(e){this.running&&this.phaseValue==="scanning"&&(this.roundLocal=e);let t=new Map,r={files:0,size:0};for(let o of e)o.kind==="folder"&&t.set(o.path,{size:0,files:0});for(let o of e)if(o.kind==="file"){ap.some(a=>o.path.startsWith(a+"/"))||(r.files++,r.size+=o.size);for(let a=or(o.path);a;a=or(a)){let s=t.get(a);s&&(s.size+=o.size,s.files++)}}let i=new Map(e.filter(o=>o.kind==="file"&&/^agents\/[^/]+\/config\.toml$/.test(o.path)).map(o=>[o.path.slice(0,-12),o]));this.others=r,this.sources=[...t].sort(([o],[a])=>Rr(o)-Rr(a)||(o<a?-1:1)).slice(0,2e3).map(([o,a])=>({path:o,kind:"folder",size:a.size,files:a.files,...Mo(o)&&i.has(o)?{agent:!0}:{}})),this.sourcesAt=Date.now(),this.readAgentNames(i)}async readAgentNames(e){for(let t of this.agentNames.keys())e.has(t)||this.agentNames.delete(t);for(let[t,r]of e){let i=`${r.mtime}:${r.size}`;if(!(this.agentNames.get(t)?.key===i||r.size>256*1024))try{this.agentNames.set(t,{key:i,...Ih((await er(r)).toString("utf8"))})}catch{this.agentNames.set(t,{key:i})}}}async rename(e){let t=typeof e=="string"?e.trim():"";if(t.length>64||/[\u0000-\u001f\u007f]/.test(t))throw Error("Invalid device name");let r=await this.getSession(),i=this.host.homeDir(),o=t||Mr(tu());return await Si(i,async()=>{await zr(i,this.deviceId);let a=Tc(o,this.devices,this.deviceId);if(a)throw Error(a==="taken"?"device_name_taken":a==="reserved"?"device_name_reserved":"device_name_invalid");await this.json(r,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:o,unique:!0}),await this.saveName(t)}),await this.register(r,!0),this.deviceName()}async saveName(e){let t=Fo(this.host.homeDir()),r=t+".tmp-"+kn();try{await Xa(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await Ko(r,t)}finally{await Xo(r).catch(()=>{})}this.customName=e}async register(e,t=!1){let r=Date.now(),i=()=>t||this.registered?.name!==this.deviceName()||r-this.registered.at>=Qo;if(!i()){r-this.devicesAt>=Qo&&await this.refreshDevices(e);return}let o=this.host.homeDir();(await Si(o,async()=>(this.customName=(await zr(o,this.deviceId)).name??"",i()?(await this.registerDevice(e),this.registered={name:this.deviceName(),at:r},!0):!1))||r-this.devicesAt>=Qo)&&await this.refreshDevices(e)}async registerDevice(e){let t=(o,a)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:o,...a?{unique:!0}:{}}),r=async()=>(await this.json(e,"devices")).devices,i=o=>/device_name_(taken|reserved|invalid)/.test(Fe(o));try{await t(this.deviceName(),!0)}catch(o){if(!i(o))throw o;let a=!1;if(!this.customName){let s=Mr(tu());for(let l=0;l<5&&!a;l++){let c=await r(),u=null;for(let d=2;d<100&&!u;d++){let g=`${s} ${d}`;Tc(g,c,this.deviceId)||(u=g)}if(!u)break;try{await t(u,!0),await this.saveName(u),a=!0}catch(d){if(!i(d))throw d}}}a||await t(this.deviceName(),!1)}}async refreshDevices(e){this.devicesAt=Date.now(),this.devices=(await this.json(e,"devices")).devices,await this.cacheDevices()}cachedDevices="";async cacheDevices(){let e=st(this.host.homeDir(),"content-sync-devices.json"),t=[];try{let s=JSON.parse(await Jo(e,"utf8"));Array.isArray(s?.devices)&&(t=s.devices)}catch{}let r=new Map(t.filter(s=>s&&typeof s.id=="string").map(s=>[s.id,s])),i=this.devices.map(s=>{let l=r.get(s.id),c=[...Array.isArray(l?.aliases)?l.aliases:[],...l&&typeof l.name=="string"&&l.name!==s.name?[l.name]:[]],u=c.filter((d,g)=>typeof d=="string"&&d!==s.name&&c.lastIndexOf(d)===g).slice(-5);return{id:s.id,name:s.name,...u.length?{aliases:u}:{}}}),o=JSON.stringify({devices:i});if(o===this.cachedDevices)return;let a=e+".tmp-"+kn();try{await Xa(a,o,{mode:384,flag:"wx"}),await Ko(a,e),this.cachedDevices=o}catch(s){this.error=Fe(s)}finally{await Xo(a).catch(()=>{})}}async setup(e){let t=await this.getSession(),r=e&&typeof e=="object"?e:{};if(t.stored.config.enabled||t.stored.config.revision>0)return null;let i=yi(Oh(t.stored.config),"","off");for(let s of on)s.id!=="agents"&&r[s.id]===!1&&(i=yi(i,s.path,"off"));let o=new Set(this.sources.filter(s=>s.agent).map(s=>s.path.slice(7))),a=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(s=>typeof s=="string"&&o.has(s)):[];return this.preview(Mh(i,a))}retryFailed(){this.failures.clear(),this.tooLarge.clear(),this.bypassBackoff=!0}retrySoon(){this.bypassBackoff=!0}rateLimitedUntil(){let e=this.host.readCreds();return e.cloudUrl?On(e.cloudUrl).until():null}capFor(e,t,r){let i=Qt(t,e,r?.limits),o=this.tooLarge.get(e+"\0"+t)?.learned;return o&&o.published===i?Math.min(i,o.maxBytes):i}noteTooLarge(e,t,r,i,o,a){let s=t+"\0"+r,l=this.tooLarge.get(s);this.tooLargeSeen?.add(s),this.failures.delete(s),Nt("content","skippedTooLarge",1,r),l||this.progress.fail({path:r,reason:"too-large",size:i,maxBytes:o}),e.stored.jobs=e.stored.jobs.filter(c=>!(c.path===r&&c.target===t&&(c.state==="failed"||c.state==="paused")&&(c.direction==="upload"||c.direction==="download"))),this.tooLarge.set(s,{ns:t,path:r,size:i,maxBytes:o,...a??l?.learned?{learned:a??l.learned}:{}})}tooLargeList(){return[...this.tooLarge.values()].map(e=>({path:e.path,reason:"too-large",size:e.size,maxBytes:e.maxBytes}))}backingOff(e,t,r){let i=e+"\0"+t,o=this.failures.get(i);return this.roundVisited?.add(i),o?o.fp!==r?(this.failures.delete(i),!1):!this.bypassThisRound&&Date.now()<o.retryAt:!1}succeeded(e,t){this.failures.delete(e+"\0"+t),this.roundSettled.add(e+"\0"+t)}fileFailed(e,t,r,i,o,a){if(e.abort.signal.aborted||$0(i)||this.bind&&au(i))throw i;let s=t+"\0"+r,l=L0(i);if(this.roundSettled.add(s),l!==null){let p=i.size,m=Number.isSafeInteger(p)?p:a??0;this.noteTooLarge(e,t,r,m,l,{maxBytes:l,published:Qt(r,t,this.limitsByNs.get(t))});return}this.error=Fe(i);let c=this.failures.get(s),u=(c&&c.fp===o?c.count:0)+1,d=Date.now()+lp(u),g=i?.code;this.failures.set(s,{ns:t,path:r,reason:Fe(i),...typeof g=="string"?{code:g}:{},count:u,retryAt:d,fp:o}),this.progress.fail({path:r,reason:"failed",code:typeof g=="string"?g:Fe(i),retryAt:d});let f=e.stored.jobs.findLast(p=>p.path===r&&p.target===t&&p.state==="failed");f&&(f.retryAt=d)}failureList(){return[...this.failures.values()].sort((e,t)=>e.retryAt-t.retryAt).slice(0,200).map(e=>({path:e.path,target:e.ns,reason:e.reason,...e.code?{code:e.code}:{},count:e.count,retryAt:e.retryAt}))}planRound(){try{let e=this.session,t=this.roundLocal,r=this.roundCloud;if(this.progress.stage("transferring"),!e||!t||!r)return;let i=e.stored.config,o=new Set,a=0;for(let s of t)s.kind==="file"&&(o.add(s.path),this.route(s.path,i)&&a++);for(let[s,l]of r)for(let c of l.nodes)c.kind==="file"&&!c.deleted&&!c.busy&&!o.has(c.path)&&this.route(c.path,i)===s&&a++;this.roundFirst=!Object.keys(e.stored.files).length,this.progress.plan(a,null)}catch{}}roundProgress(){try{let e=this.progress.progress();if(!e)return null;if(e.stage==="transferring"&&e.files.total!==null){let r=new Set(this.roundSettled);for(let i of this.round?.undecided??[])r.add(i);e.files={done:Math.min(r.size,e.files.total),total:e.files.total}}let t=this.activeJob;return t&&t.state==="active"&&(e.current={path:t.path,op:t.direction==="delete"?"delete":t.direction,bytesDone:t.done,bytesTotal:t.size}),e}catch{return null}}endRound(e){try{let t=this.progress.end(e);if(this.activeJob=null,!t)return;e&&(this.lastCompletedAt=t.finishedAt);let r=this.runAccount;if(this.bind){let a=this.bind,s=this.bindPolicy,l=this.bindStats;if(!r||r!==a.account())return;let c=[...this.otherBacked].slice(0,50).map(d=>({path:this.session?this.relOf(this.session,d):d,reason:"other-backing"})),u=this.recorder.take({feed:`vault:${a.id}`,engine:"content",vault:a.vaultRoot,target:a.transport?"other":"penzor",...s?{kind:s.kind}:{},...l.replaced?{replaced:l.replaced}:{},...l.recoveryEvents.length?{recoveryEvents:[...l.recoveryEvents]}:{},...c.length?{skipped:c}:{}},t,{keepIdle:!0});u&&this.host.syncRecords?.append(u,r==="device"?null:r),s&&a.onRound?.({completed:e,wroteLocal:this.wroteLocal,summary:t,kind:s.kind,stats:{...l,recoveryEvents:[...l.recoveryEvents]}});return}if(!r||r!==this.host.accountId())return;this.recordAccount!==r&&(this.recorder.reset(),this.recordAccount=r);let i=this.session?.roots.find(a=>a.prefix==="Amadeus")?.root??null,o=this.recorder.take({feed:"content",engine:"content",vault:i,target:"penzor",...this.roundFirst?{first:!0}:{}},t,{keepIdle:!0});o&&this.host.syncRecords?.append(o,r)}catch{}}status(){let e=this.session;if(!e)return{available:!0,session:!1,owned:!1,enabled:!1,paused:!1,running:this.running,phase:this.phaseValue,notes:null,lastSyncAt:this.lastCompletedAt,pending:0,round:null,lastRound:this.progress.last()};let t=e.stored.config,r=e.stored.deleteGuard,i=[...this.scanned.skipped,...this.recordsAccount===e.account?this.tooLargeList():[]],o=this.rateLimitedUntil();return{available:!0,session:!0,account:Ue(e.account),owned:e.stored.owned,enabled:t.enabled,paused:e.stored.paused,running:this.running,phase:this.phaseValue,notes:z0(t),lastSyncAt:this.lastCompletedAt,pending:e.stored.jobs.filter(a=>a.state==="queued"||a.state==="active").length,round:this.running?this.roundProgress():null,lastRound:this.progress.last(),...e.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...r&&(r.latched||r.pending.length)?{deletes:{latched:r.latched,pending:r.pending.length,token:Za(r.pending),items:r.pending.slice(0,200).map(a=>({path:a.path,side:a.side}))}}:{},...i.length?{skipped:i.slice(0,200),skippedCount:i.length}:{},...o?{rateLimitedUntil:o}:{},...this.failures.size&&this.recordsAccount===e.account?{failures:this.failureList()}:{}}}async snapshot(e,t){(e==="zh"||e==="en")&&(this.uiLocale=e);let r=await this.getSession(),i=t&&typeof t=="object"?t:{};if(i.focused===!0){let o=!this.focused;this.focused=!0,this.touch(),o&&r.stored.config.enabled&&!r.stored.paused&&Date.now()-this.lastRunAt>3e4&&this.kick()}else i.focused===!1&&(this.focused=!1);return!r.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(r).then(o=>{this.session===r&&this.setSources(o)},()=>{})),i.devices===!0&&Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(r).catch(()=>{})),{available:!0,account:Ue(r.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(r.stored.config),running:this.running,paused:r.stored.paused,phase:this.phase,jobs:structuredClone(r.stored.jobs),devices:this.devices,sources:this.sources.map(o=>{let a=o.agent&&this.agentNames.get(o.path);return a?{...o,...a.name?{name:a.name}:{},...a.nameEn?{nameEn:a.nameEn}:{}}:o}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...r.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...r.stored.agentArchive?{agentArchive:(({rewritten:o,...a})=>a)(r.stored.agentArchive)}:{},...(o=>o&&(o.latched||o.pending.length)?{deletes:{latched:o.latched,pending:o.pending.length,token:Za(o.pending),items:o.pending.slice(0,200).map(a=>({path:a.path,side:a.side}))}}:{})(r.stored.deleteGuard),...(o=>o.length?{skipped:o.slice(0,200),skippedCount:o.length}:{})([...this.scanned.skipped,...this.recordsAccount===r.account?this.tooLargeList():[]]),...(o=>o?{rateLimitedUntil:o}:{})(this.rateLimitedUntil()),...this.failures.size&&this.recordsAccount===r.account?{failures:this.failureList()}:{},...this.running?{round:this.roundProgress()}:{},lastRound:this.progress.last()}}async confirmDeletes(e){await this.decideDeletes("confirm",e)}async abandonDeletes(e){await this.decideDeletes("restore",e)}deferredDecision=[];async decideDeletes(e,t){let r=await this.getSession(),i=this.bind?this.claimedDeletes():new Set,o=(r.stored.deleteGuard?.pending??[]).filter(s=>!i.has(s.key)),a=o.map(s=>s.key);if(t!==void 0&&t!==Za(o))throw Error("deletes_changed");if(!(!a.length&&!r.stored.deleteGuard?.latched)){if(this.bind?.readScopeExclusions){let s={kind:e,keys:a};(r.stored.deleteDecisions??=[]).push(s);try{await this.persist(r,!0)}catch(l){throw r.stored.deleteDecisions=r.stored.deleteDecisions?.filter(c=>c!==s),l}this.touch(),this.kick();return}if(this.running){this.deferredDecision.push({kind:e,keys:a}),this.again=!0;return}this.applyDecision(r,e,a),await this.persist(r),this.touch(),this.kick()}}applyDecision(e,t,r){let i=e.stored.deleteGuard;if(!i)return;let o=new Set(r),a=i.pending.filter(d=>!o.has(d.key)),s=i.pending.filter(d=>o.has(d.key)),l=[...new Set([...i.confirmed??[],...s.map(d=>d.key)])],c=[...new Map([...i.restore??[],...s].map(d=>[$n(d.side,d.ns,d.id),d])).values()],u={latched:a.length>0,pending:a,...t==="confirm"?{confirmed:l}:i.confirmed?.length?{confirmed:i.confirmed}:{},...t==="restore"?{restore:c}:i.restore?.length?{restore:i.restore}:{}};u.latched||u.pending.length||u.confirmed?.length||u.restore?.length?e.stored.deleteGuard=u:delete e.stored.deleteGuard,t==="confirm"&&(this.deleteStamps=[])}async replayDeleteDecisions(e){let t=e.stored.deleteDecisions;if(!t?.length)return;let r=e.stored.deleteGuard,i=this.deleteStamps;delete e.stored.deleteDecisions;for(let o of t)this.applyDecision(e,o.kind,o.keys);try{await this.persist(e,!0)}catch(o){throw e.stored.deleteGuard=r,this.deleteStamps=i,e.stored.deleteDecisions=[...t,...e.stored.deleteDecisions??[]],o}}stats(){let e=this.host.accountId(),t=e&&this.session?.account===e?this.session:null,r=t?.stored,i={},o=e&&e===this.logAccount?this.runLog.snapshot():new Lo().snapshot();for(let a of r?.jobs??[])i[a.state]=(i[a.state]??0)+1;return{deviceId:this.deviceId||null,session:!!t,enabled:!!r?.config.enabled,paused:!!r?.paused,running:!!t&&this.running,phase:t?this.phase:"idle",revision:r?.config.revision??0,rules:(r?.config.rules??[]).map(a=>({source:a.source,target:a.target})),backlog:r?{jobs:i,blocked:[...this.blocked.values()].reduce((a,s)=>a+s.length,0),pendingUploads:Object.keys(r.pendingUploads??{}).length,unconfirmed:Object.keys(r.unconfirmed??{}).length,trash:r.trash?.length??0,awaitingBytes:this.awaitingBytes.size,dirty:this.dirty.size}:null,archive:r?.agentArchive?.state??null,...o}}async preview(e){let t=await this.getSession();if(e?.revision!==t.stored.config.revision)throw Error("config_changed");let i=t.stored.config.revision+1,o=Zt(Ph(t.stored.config,Zt(e,i)),i),a=await this.host.contentSync.roots();if(this.guard(t),!t.stored.config.enabled&&t.stored.config.revision===0&&!o.enabled)throw Error("nothing_to_sync");let s=await this.previewScan(t,a),l=this.effective(o,s);if(t.stored.agentArchive?.state==="running"&&s.some(x=>x.kind==="file"&&x.path.startsWith("agents/")&&this.route(x.path,l)))throw Error("agent_archive_running");let c=await this.manifests(t,l);this.guard(t),this.setSources(s);let u=0,d=0,g=0,f=0,p=await this.bindingsOf(a),m=new Map,y=new Map;for(let[x,$]of Object.entries(t.stored.files))this.survives(t.stored,l,p,$.path)&&(m.set(x,$),y.set(x.slice(0,x.indexOf(":"))+"\0"+$.path,$));let b=t.stored.deleteGuard,h=new Set((b?.restore??[]).map(x=>$n(x.side,x.ns,x.id))),E=[],v=new Map,k=new Set(s.map(x=>x.path));for await(let x of Ar(s.filter($=>$.kind==="file"))){let $=this.route(x.path,l);if(!$)continue;let O=c.get($),q=O?.nodes.find(Y=>!Y.deleted&&Y.kind==="file"&&Y.path===x.path);if(x.size>Qt(x.path,$,O?.limits))continue;let ie=Ue(await er(x));if(this.guard(t),v.set(x.path,ie),!q){let Y=y.get($+"\0"+x.path),ne=Y&&O?.nodes.find(ce=>ce.id===Y.id&&ce.deleted);if(ne&&Y&&Qa(x.path)&&(Y.hash===ie||Y.memoryDeleted&&ie===Ti))continue;if(ne&&Y&&Y.hash===ie&&!h.has($n("local",$,Y.id))){E.push({ns:$,path:x.path});continue}}ie!==q?.hash&&(u++,f+=x.size,q?.version&&g++)}let C=o.enabled?this.agentAsks(t,s,l,c,v):[],S=E.length;for(let[x,$]of c)for await(let O of Ar($.nodes)){if(O.deleted||O.kind!=="file"||this.route(O.path,l)!==x||k.has(O.path))continue;let q=m.get(Ie(x,O.id)),ie=Br(s.unscanned,O.path)||!!q?.inode&&s.skippedInodes.has(q.inode);if(this.sealedShadow(q)||q&&q.path!==O.path&&k.has(q.path))continue;let Y=xc(O,q,!!t.stored.pendingUploads?.[Ie(x,O.id)],ie);Y==="download"?d++:Y==="delete"&&await this.absent(t,O.path,a)&&(h.has($n("cloud",x,O.id))?d++:E.push({ns:x,path:O.path}))}let _=E.length-S,R=[...m].map(([x,$])=>({ns:x.slice(0,x.indexOf(":")),path:$.path})),N=ea(this.guardPaths(t,E),this.guardPaths(t,R),{latched:!!b?.latched,recent:this.deleteStamps.filter(x=>Date.now()-x<Qs).length}),D=this.signature(s,c,a),M={token:kn(),config:l,upload:o.enabled?u:0,download:o.enabled?d:0,conflicts:o.enabled?g:0,bytes:o.enabled?f:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,deleteCloud:o.enabled?_:0,deleteLocal:o.enabled?S:0,...o.enabled&&N?{deletesHeld:!0}:{},...C.length?{agentAsks:C}:{}};return this.previewValue={value:M,account:t.account,signature:D},M}async bindingsOf(e){let t=[];for(let r of e)await eu(r.root).catch(o=>{if(o.code==="ENOENT")return null;throw o})&&t.push({...r,...await dt(r.root)});return t}survives(e,t,r,i,o="file"){return e.config.enabled===t.enabled&&M0(e.roots??r,r)&&this.route(i,e.config,o)===this.route(i,t,o)}signature(e,t,r){return Ue(JSON.stringify([r,e.map(i=>[i.path,i.size,i.mtime,i.inode]),[...t].map(([i,o])=>[i,o.nodes.map(a=>[a.id,a.revision,a.version,a.deleted])])]))}async apply(e,t){this.applying++;try{await this.applySerial(e,t)}finally{this.applying--}}async applySerial(e,t){let r=this.serial,i;this.serial=new Promise(o=>{i=o}),await r;try{let o=await this.getSession(),a=this.previewValue;if(!a||a.value.token!==e||a.account!==o.account||a.value.expiresAt<Date.now()||a.value.config.revision!==o.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let s=a.value.agentAsks??[],l=Q0(t);this.resolving=!0;try{let c=await this.host.contentSync.roots(),u=await this.previewScan(o,c),d=await this.manifests(o,a.value.config);if(this.signature(u,d,c)!==a.signature)throw Error("preview_changed");let g=await this.bindingsOf(c),f=structuredClone(a.value.config);for(let b of f.rules){if(sn(b.source))continue;let h=u.find(E=>E.kind==="folder"&&E.path===b.source);h&&(b.sourceId=await Gc(h))}let p=s.length?Zt(s.reduce((b,h)=>yi(b,`agents/${h.slug}`,"off"),f),f.revision):f;if(this.guard(o),this.previewValue!==a||a.value.config.revision!==o.stored.config.revision+1)throw Error("preview_expired");let m=structuredClone(o.stored),y=f.enabled;o.stored.config=p,o.stored.owned=y,o.stored.paused=!1,y?delete o.stored.releasing:(delete o.stored.accountReview,(m.owned||m.releasing)&&(o.stored.releasing=!0)),delete o.stored.unconfirmed;for(let[b,h]of Object.entries(o.stored.files))this.survives(m,o.stored.config,g,h.path)||delete o.stored.files[b];for(let[b,h]of Object.entries(o.stored.folders))this.survives(m,o.stored.config,g,h.path,"folder")||delete o.stored.folders[b];if(o.stored.roots=g,o.rootIdentities=new Map(g.map(b=>[b.root,b])),await this.persist(o),y)try{await this.accountWrite(o,b=>this.host.contentSync.claim(!0,b))}catch(b){throw o.stored=m,await this.persist(o),await this.accountWrite(o,h=>this.host.contentSync.claim(m.owned,h)).catch(()=>{}),b}else o.stored.releasing&&await this.release(o).catch(b=>{this.host.log?.(`[content-sync] release: ${Fe(b)}`)});if(this.previewValue=null,o.roots=c,await this.watchRoots(o),s.length)try{await this.resolveAsks(o,s,l,f)}catch(b){throw this.fault(Fe(b)),b}o.stored.accountReview&&(delete o.stored.accountReview,await this.persist(o))}finally{this.resolving=!1}}finally{i()}this.run()}async pause(e){let t=await this.getSession();if(!e&&t.stored.accountReview)throw Error("content_account_changed_preview_required");t.stored.paused=e,e?(t.abort.abort(new Error("paused")),this.phase="paused"):this.running||(t.abort=new AbortController),await this.persist(t),e||this.run()}job(e,t,r,i,o){let a=e.stored.jobs.findLast(l=>l.path===t&&l.target===r&&l.direction===i&&["failed","paused","queued"].includes(l.state));if(a)return Object.assign(a,{state:"active",done:0,size:o,at:Date.now(),error:void 0,finishedAt:void 0}),a;let s={id:kn(),path:t,target:r,direction:i,state:"active",done:0,size:o,at:Date.now()};return e.stored.jobs.push(s),e.stored.jobs=e.stored.jobs.slice(-200),s}done(e){e.state="done",e.done=e.size??e.done,e.finishedAt=Date.now()}async operation(e,t,r,i,o,a){if(this.guard(e),e.stored.paused)throw Error("paused");this.activeAt=Date.now();let s=this.job(e,t,r,i,o);this.activeJob=s;try{let l=await a(s);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(s),this.progress.addBytes(i==="delete"||i==="rename"?0:s.done),i==="upload"?Nt("content","uploads"):i==="download"&&Nt("content","downloads");let c=V0[i];return c&&this.tally(c),l}catch(l){throw s.state=e.stored.paused?"paused":"failed",s.error=Fe(l),s.finishedAt=Date.now(),l}}async run(){if(this.running||this.closed||this.resolving)return;this.running=!0;let e;this.runFinished=new Promise(l=>{e=l});let t=Date.now();this.lastRunAt=t,this.wroteLocal=!1,this.failure=void 0;let r=new Set,i,o=!1,a=!1,s=!this.bind?.readScopeExclusions;try{if(i=await this.getSession(),this.runAccount=i.account,i.stored.accountReview){this.error="content_account_changed_preview_required";return}if(this.bind||(wd("agents")||await this.archiveStep(i),await this.settleRelease(i)),!i.stored.config.enabled||i.stored.paused)return;this.bind&&(this.bindPolicy=this.bind.policy(),this.bindStats={adopted:0,filled:0,held:0,replaced:0,skippedOther:0,recoveryEvents:[],revived:0},this.revivePaths.clear()),i.abort.signal.aborted&&(i.abort=new AbortController),this.blocked.clear(),this.phase="scanning",this.error=void 0,o=!0,this.httpStatus=0,this.live()&&this.runLog.begin(t),this.bind?.readScopeExclusions&&await this.replayDeleteDecisions(i);let l=this.bind?await this.bind.roots():await this.host.contentSync.roots();this.guard(i),i.roots=l,this.tooLargeSeen=new Set,this.roundVisited=new Set,this.recordsAccount!==i.account&&(this.failures.clear(),this.tooLarge.clear(),this.recordsAccount=i.account),this.bypassThisRound=this.bypassBackoff,this.bypassBackoff=!1,!this.bind&&!wd("agents")&&(await this.host.contentSync.agentFiles?.prepare().catch(v=>{this.error=Fe(v)}),this.guard(i));let c=await this.scan(i,l);s&&await this.recordRoots(i);let u=this.effective(i.stored.config,c),d=await this.manifests(i,u);if(this.guard(i),this.limitsByNs=new Map([...d].map(([v,k])=>[v,k.limits])),!s){await this.beginExpandedScope(i),s=!0,await this.recordRoots(i);let v=this.bind.ns;await this.recordScopeDepartures(i,u,v,d.get(v))}let g=new Map;for(let[v,k]of d)for(let C of k.nodes)C.kind==="file"&&!C.deleted&&g.set(v+"\0"+C.path,C.version??"");let f=(v,k)=>`${F0(k)}|c:${g.get(v+"\0"+k.path)??""}`;this.bind?this.bindStats.skippedOther=this.otherBacked.size:await this.register(i),this.openJobs=new Set(i.stored.jobs.filter(v=>["failed","paused","active"].includes(v.state)&&["upload","download","merge"].includes(v.direction)).map(v=>v.target+"\0"+v.path)),await this.folders(i,u,c,d),await this.recordRoots(i),await this.fileRenames(i,u,c,d),c=await this.scan(i,l),u=this.effective(u,c),i.stored.config=u,this.setSources(c),this.phase="syncing",this.bind&&this.followCloudGone(i,c),this.round={plan:[],restore:new Map((i.stored.deleteGuard?.restore??[]).map(v=>[$n(v.side,v.ns,v.id),v])),restoreHit:new Set,restoreDone:new Set,tracked:Object.entries(i.stored.files).map(([v,k])=>({ns:v.slice(0,v.indexOf(":")),path:k.path})),undecided:new Set};let p=(v,k)=>this.round.undecided.add(v+"\0"+k);for(let v of[...i.stored.deleteGuard?.pending??[],...i.stored.deleteGuard?.restore??[]]){let k=i.stored.files[Ie(v.ns,v.id)];(sn(v.path)||this.sealedShadow(k))&&p(v.ns,v.path)}let m=v=>v.endsWith("/"+ko),y=new Set,b=new Set,h=v=>v.startsWith("agents/")?v.slice(0,v.lastIndexOf("/")+1):null,E=v=>v.endsWith("/MEMORY.md")&&b.has(h(v)??"");for(let[v,k]of d)for await(let C of Ar(k.nodes.filter(S=>S.kind==="file"&&!S.busy&&m(S.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(C.path,u)!==v||c.some(S=>S.path===C.path))){if(this.isBlocked(v,C.path)){b.add(h(C.path)??""),p(v,C.path);continue}if(this.backingOff(v,C.path,`c:${C.version??""}`)){b.add(h(C.path)??""),p(v,C.path);continue}y.add(C.id);try{await this.missing(i,C,v,c,u)==="unknown"?b.add(h(C.path)??""):this.succeeded(v,C.path)}catch(S){this.fileFailed(i,v,C.path,S,`c:${C.version??""}`,C.size),b.add(h(C.path)??""),p(v,C.path)}}}for await(let v of Ar(c.filter(k=>k.kind==="file").sort((k,C)=>+!m(k.path)-+!m(C.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");let k=this.route(v.path,u);if(k){if(E(v.path)){p(k,v.path);continue}if(this.isBlocked(k,v.path)){m(v.path)&&b.add(h(v.path)??""),p(k,v.path);continue}if(this.backingOff(k,v.path,f(k,v))){p(k,v.path),m(v.path)&&b.add(h(v.path)??"");continue}try{let C=await this.file(i,u,v,k,d.get(k));C==="held"?(r.add(v.path),p(k,v.path)):C==="undecided"?p(k,v.path):C==="too-large"?(p(k,v.path),m(v.path)&&b.add(h(v.path)??"")):this.succeeded(k,v.path)}catch(C){this.fileFailed(i,k,v.path,C,f(k,v),v.size),p(k,v.path),m(v.path)&&b.add(h(v.path)??"")}}}for(let[v,k]of d)for await(let C of Ar(k.nodes.filter(S=>S.kind==="file"&&!S.busy&&!y.has(S.id)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(C.path,u)!==v||c.some(S=>S.path===C.path))){if(this.isBlocked(v,C.path)||E(C.path)){p(v,C.path);continue}if(this.holdGone(C.path)){r.add(C.path),p(v,C.path);continue}if(this.backingOff(v,C.path,`c:${C.version??""}`)){p(v,C.path);continue}try{await this.missing(i,C,v,c,u),this.succeeded(v,C.path)}catch(S){this.fileFailed(i,v,C.path,S,`c:${C.version??""}`,C.size),p(v,C.path)}}}if(this.bind&&i.stored.held)for(let[v,k]of Object.entries(i.stored.held))k.cloudGone&&!c.some(C=>C.kind==="file"&&(C.path===v||!!k.inode&&C.inode===k.inode))&&!Br(this.scanned.unscanned,v)&&!(k.inode&&this.scanned.unscanned.length)&&delete i.stored.held[v];await this.executeDeletes(i,this.round),await this.cleanupFolders(i,u,d),!this.bind&&this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(i).catch(()=>{}),!this.bind&&(this.wroteLocal||Date.now()-this.changedAt>=Qo)&&(await this.accountWrite(i,v=>this.host.contentSync.changed(v)),this.changedAt=Date.now()),this.guard(i),delete i.stored.scopeFirstRound,await this.persist(i),await this.pruneBases(i),a=!0;for(let v of[...this.tooLarge.keys()])this.tooLargeSeen?.has(v)||this.tooLarge.delete(v);for(let v of[...this.failures.keys()])this.roundVisited?.has(v)||this.failures.delete(v);!this.error&&this.failures.size&&(this.error=[...this.failures.values()].reduce((v,k)=>v.retryAt>k.retryAt?v:k).reason)}catch(l){Fe(l)!==gy&&(this.error=Fe(l)),this.failure=l}finally{this.round=null,this.phase=i?.stored.paused?"paused":"idle";{let l=this.deferredDecision.splice(0);if(i&&this.ownerNow()===i.account)for(let c of l)this.applyDecision(i,c.kind,c.keys)}this.bind&&o&&(this.bindStats.deferred=r.size),o&&(this.noteHealth(t,a),this.live()&&this.runLog.end(a));for(let[l,c]of this.dirty)!r.has(l)&&c.last<t&&this.dirty.delete(l);i&&this.ownerNow()===i.account&&(s&&await this.persist(i).catch(()=>{}),!this.closed&&i.abort.signal.aborted&&!i.stored.paused&&i.stored.config.enabled&&(i.abort=new AbortController,this.again=!0)),this.running=!1,this.runAccount=null,this.again&&!this.closed?(this.again=!1,queueMicrotask(()=>void this.run())):(this.schedule(),this.bind&&!this.closed&&this.deferred(r)),e()}}noteHealth(e,t){this.endRound(t),t&&(Nt("content","cycles"),Nt("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?Ca(this.error,this.httpStatus):null;r?this.health.error(r):this.error||this.health.ok()}holdGone(e){let t=this.dirty.get(e);if(!t)return!1;let r=Date.now();return t.last>this.flushAt&&r-t.last<cu(e)&&r-t.first<uy}isBlocked(e,t){return(this.blocked.get(e)??[]).some(r=>t===r||t.startsWith(r+"/"))}block(e,t,r){if(this.bind&&au(r))throw r;if(this.blocked.set(e,[...this.blocked.get(e)??[],t]),this.lastError=Fe(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([t]);return}this.blockedError=r,this.fault(Fe(r),[t])}async folders(e,t,r,i){let o=r.filter(s=>s.kind==="folder"),a=new Map;for(let s of o)if(s.localId){if(a.has(s.localId))throw Error(`Duplicate folder sync identity: ${s.path}`);a.set(s.localId,s.path)}for(let[s,l]of i){for await(let c of Ar(l.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,d)=>Rr(u.path)-Rr(d.path))))if(!(this.isBlocked(s,c.path)||Br(this.scanned.unscanned,c.path)))try{let u=Object.entries(e.stored.folders).find(([g,f])=>g.startsWith(s+":")&&f.id===c.id&&!f.outsideScope)?.[1],d=(u?o.find(g=>g.localId===u.localId):null)??o.find(g=>g.path===c.path);if(u&&d&&c.path!==u.path&&d.path!==u.path&&c.path!==d.path)throw Error(`Concurrent folder rename: ${d.path}`);if(u&&d&&c.path!==u.path&&d.path===u.path){if(this.route(d.path,t,"folder")!==s||this.bindPolicy?.direction==="push"&&this.bind)continue;if(this.route(c.path,t,"folder")!==s)throw Error("Remote rename crosses a sync rule; review the destination");let g=new Set(r.filter(p=>p.kind==="file"&&p.path.startsWith(d.path+"/")).map(p=>p.path));await this.operation(e,d.path,s,"rename",null,()=>Kc(e.roots,d.path,c.path,(p,m)=>this.lock(e,p,m)));let f=d.path;for(let p of r)if(p.path===f||p.path.startsWith(f+"/")){let m=p.path;p.path=c.path+m.slice(f.length);let y=Ze(e.roots,p.path);p.physical=st(y.root,y.relative),this.bind&&p.kind==="folder"&&(p.localId=ou(p.path))}for(let[p,m]of Object.entries(e.stored.files))p.startsWith(s+":")&&m.path.startsWith(u.path+"/")&&(!this.bind||g.has(m.path))&&(m.path=c.path+m.path.slice(u.path.length));for(let p of t.rules)(p.source===u.path||p.source.startsWith(u.path+"/"))&&(p.source=c.path+p.source.slice(u.path.length));if(this.bind){let p=u.path;for(let[m,y]of Object.entries(e.stored.folders))if(m.startsWith(s+":")&&(y.path===p||y.path.startsWith(p+"/"))){let b=c.path+y.path.slice(p.length),h=ou(b);delete e.stored.folders[m],e.stored.folders[Ie(s,h)]={...y,localId:h,path:b}}}}if(!d&&this.route(c.path,t,"folder")===s&&!u&&!(this.bind&&this.bindPolicy.direction==="push")){await Hp(e.roots,c.path,(f,p)=>this.lock(e,f,p));let g=(await this.scan(e)).find(f=>f.path===c.path);g&&(r.push(g),o.push(g))}}catch(u){this.block(s,c.path,u),this.tally("folderConflicts");let d=Object.entries(e.stored.folders).find(([g,f])=>g.startsWith(s+":")&&f.id===c.id)?.[1];d&&this.block(s,d.path,u)}for await(let c of Ar(o.sort((u,d)=>Rr(u.path)-Rr(d.path))))if(!this.isBlocked(s,c.path))try{if(sn(c.path))continue;let u=this.route(c.path,t,"folder"),d=!this.bind&&t.rules.some(v=>v.target===s&&v.source.startsWith(c.path+"/"));if(u!==s&&!d||nd(c.path,"folder")===!1)continue;let g=this.bind?c.localId:await Gc(c),f=e.stored.folders[Ie(s,g)],p=this.sealedShadow(f),m=p||f?.outsideScope?void 0:f,y=m?l.nodes.find(v=>v.id===m.id):l.nodes.find(v=>v.path===c.path&&!v.deleted);if(y?.deleted){let v=(e.stored.deleteGuard?.restore??[]).some(k=>k.side==="local"&&k.ns===s&&k.path.startsWith(c.path+"/"));if(m&&!v){let k=!1;for(let C of r.filter(S=>S.kind==="file"&&S.path.startsWith(c.path+"/")&&this.route(S.path,t)===s)){let S=Object.entries(e.stored.files).find(([_,R])=>_.startsWith(s+":")&&R.path===C.path)?.[1];if(!S){k=!0;break}if(!this.sameAsShadow(S,C)){let _=Ue(await er(C));if(_!==S.hash&&!(S.memoryDeleted&&Qa(C.path)&&_===Ti)){k=!0;break}}}if(!k)continue}y=void 0}if(this.bind&&m&&y&&y.path!==c.path&&(y=void 0),!y&&this.bind&&this.bindPolicy.direction==="pull")continue;let b=or(c.path),h=b?l.nodes.find(v=>v.path===b&&v.kind==="folder"&&!v.deleted)?.id:"";if(b&&!h)throw Error("Cloud parent is unavailable");if(!y)y=await this.json(e,s,"/nodes","POST",{id:m||p||this.bind?kn():g,parentId:h,name:Yr(c.path),kind:"folder"}),e.tombstones.get(s)?.delete(y.id),l.nodes.push(y);else if(m&&y.path!==c.path){if(y.revision!==m.revision)throw Error(`Concurrent folder rename: ${c.path}`);let v=y.path,k=await this.operation(e,c.path,s,"rename",null,()=>this.json(e,s,`/nodes/${y.id}`,"PATCH",{parentId:h,name:Yr(c.path),revision:y.revision}));for(let C of l.nodes)C.path.startsWith(v+"/")&&(C.path=c.path+C.path.slice(v.length));Object.assign(y,k);for(let[C,S]of Object.entries(e.stored.files))C.startsWith(s+":")&&S.path.startsWith(v+"/")&&(S.path=c.path+S.path.slice(v.length))}let E=Ie(s,g);if(this.scopeExclusions)for(let[v,k]of Object.entries(e.stored.folders))v!==E&&v.startsWith(s+":")&&k.id===y.id&&k.outsideScope&&delete e.stored.folders[v];e.stored.folders[E]={id:y.id,localId:g,path:c.path,revision:y.revision,parentId:y.parentId,name:y.name}}catch(u){this.block(s,c.path,u);let d=c.localId?e.stored.folders[Ie(s,c.localId)]:void 0;d&&this.block(s,d.path,u),Nt("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,c.path,s,"rename",null);g.state="conflict",g.error=Fe(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,t,r){if(this.bind&&(!this.bindPolicy.deletes||this.bindPolicy.direction!=="both"))return;let i=await this.scan(e),o=[],a=new Set;for(let[c,u]of r)for await(let d of Ar(u.nodes.filter(g=>g.kind==="folder"&&!g.busy).sort((g,f)=>Rr(f.path)-Rr(g.path)))){if(this.isBlocked(c,d.path)||this.route(d.path,t,"folder")!==c||Br(this.scanned.unscanned,d.path))continue;let g=Object.entries(e.stored.folders).find(([p,m])=>p.startsWith(c+":")&&m.id===d.id);if(!g||this.sealedShadow(g[1])||g[1].outsideScope)continue;let f=i.find(p=>p.path===d.path&&p.kind==="folder");if(d.deleted&&f){if(i.some(y=>y.path.startsWith(d.path+"/")))continue;let p=y=>!!this.bind||y!==".forsion-sync-id.json";if((await Yo(f.physical)).some(p))continue;await this.operation(e,d.path,c,"delete",null,()=>this.lock(e,f.physical,()=>{wn(f.root,Zo(f.root,f.physical).split(xi).join("/"));let y=A0(f.physical);if(y.some(p))throw Error("Folder changed before deletion");let b=st(f.physical,".forsion-sync-id.json"),h=y.length?Ci(b):null;h&&Qd(b);try{C0(f.physical)}catch(E){if(h)try{I0(b,h,{flag:"wx",mode:384})}catch{}throw E}})),this.tally("deletesLocal"),delete e.stored.folders[g[0]]}else if(!d.deleted&&!f){if(e.stored.deleteGuard?.latched||e.stored.deleteGuard?.pending.length||e.stored.deleteGuard?.restore?.length||!await this.absent(e,d.path))continue;if(!this.bind){if(u.nodes.some(p=>p.parentId===d.id&&!p.deleted))continue;await this.operation(e,d.path,c,"delete",null,()=>this.json(e,c,`/nodes/${d.id}`,"DELETE",{revision:d.revision,version:null})),d.deleted=!0,delete e.stored.folders[g[0]];continue}if(u.nodes.some(p=>p.parentId===d.id&&!p.deleted&&!a.has(c+":"+p.id)))continue;o.push({ns:c,path:d.path,n:d,shadowKey:g[0]}),a.add(c+":"+d.id)}}if(!o.length)return;let s=Object.entries(e.stored.folders).map(([c,u])=>({ns:c.slice(0,c.indexOf(":")),path:u.path})),l=Date.now();if(this.deleteStamps=this.deleteStamps.filter(c=>l-c<Qs),ea(o,s,{latched:!1,recent:this.deleteStamps.length})){Nt("content","massDeleteGuard"),this.host.log?.(`[content-sync] ${o.length} empty cloud folder deletion(s) held back by the delete guard`);return}for(let c of o)await this.absent(e,c.path)&&(r.get(c.ns).nodes.some(u=>u.parentId===c.n.id&&!u.deleted)||(await this.operation(e,c.path,c.ns,"delete",null,()=>this.json(e,c.ns,`/nodes/${c.n.id}`,"DELETE",{revision:c.n.revision,version:null})),c.n.deleted=!0,delete e.stored.folders[c.shadowKey]))}async download(e,t,r,i){if(t.size!==void 0&&t.size>ir)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:ir});let o=await this.request(e,r,`/nodes/${t.id}/content`),a=[],s=0;if(o.body){let c=o.body.getReader();for(;;){let u=await c.read();if(u.done)break;if(this.guard(e),s+=u.value.length,s>ir)throw await c.cancel(),Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:ir});a.push(u.value),i.done=s}}let l=Buffer.concat(a);if(t.hash&&Ue(l)!==t.hash)throw Error("Cloud file changed during download");return l}async fileRenames(e,t,r,i){if(!(this.bind&&this.bindPolicy.direction==="push"))for(let[o,a]of i)for(let s of a.nodes.filter(l=>l.kind==="file"&&!l.deleted&&!l.busy)){let l=e.stored.files[Ie(o,s.id)];if(!l||l.outsideScope||l.path===s.path)continue;let c=r.find(u=>u.kind==="file"&&u.path===l.path);if(!(!c||this.route(c.path,t)!==o))try{if(this.route(s.path,t)!==o)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,c.path,o,"rename",null,()=>Kc(e.roots,c.path,s.path,(u,d)=>this.lock(e,u,d))),l.path=s.path}catch(u){this.block(o,c.path,u),this.block(o,s.path,u)}}}async upload(e,t,r,i,o,a){let s=this.capFor(r,t.path,{limits:this.limitsByNs.get(r)});if(i.length>s)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:s,size:i.length});let l=await this.request(e,r,`/nodes/${t.id}/content`,"PUT",i,d=>{o.done=d},{"X-Content-Version":t.version??"create",...t.version&&t.file?{"X-Content-File":t.file}:{},...this.bind?.transport&&a!==void 0&&Number.isFinite(a)&&a>0?{"X-Content-Mtime":String(Math.floor(a))}:{}}),c=await l.json(),u=l.headers.get("x-content-file");return u&&/^[A-Za-z0-9_-]{1,64}$/.test(u)&&(c.file=u),c}async shadow(e,t,r,i,o,a){let s=Ie(t,r.id),l=Ue(i),c=nu(i);c&&i.length>=dy&&await this.keepBase(e,l,i);for(let u of e.stored.jobs)u.path===r.path&&u.target===t&&["failed","paused","active"].includes(u.state)&&["upload","download","merge"].includes(u.direction)&&this.done(u);e.stored.pendingUploads&&delete e.stored.pendingUploads[s],delete e.stored.unconfirmed?.[s],e.stored.held?.[r.path]&&(delete e.stored.held[r.path],Object.keys(e.stored.held).length||delete e.stored.held),e.stored.files[s]={id:r.id,path:r.path,version:r.version,hash:l,...r.file?{file:r.file}:{},...c&&i.length<dy?{base:i.toString("utf8")}:{},...a?{inode:a.inode,stat:a.key,statAt:a.at}:o?{inode:o.inode}:{}}}async seen(e,t,r){let i=Ze(e.roots,t),o=await un(st(i.root,...i.relative.split("/"))).catch(()=>null);if(!o?.isFile())return;let a=Qn(o);return{key:ui(a),at:r,inode:a.inode}}sameAsShadow(e,t){return!this.dirty.has(t.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===ui(t)&&X0(t)<=e.statAt-W0}unchanged(e,t,r,i,o){let a=Ie(t,r.id),s=this.sameAsShadow(i,o)&&i.id===r.id&&i.path===o.path&&!r.busy&&!r.deleted&&r.version===i.version&&r.hash===i.hash&&co(i.file,r.file)&&!e.stored.unconfirmed?.[a]&&!e.stored.pendingUploads?.[a]&&!this.openJobs.has(t+"\0"+o.path);return s&&i.file===void 0&&r.file&&(i.file=r.file),s}hold(e,t){if(e.path.endsWith("/"+ko)||t?.stat===ui(e)||this.releasedPaths.delete(e.path))return!1;let r=e.mtime,i=Date.now(),o=this.dirty.get(e.path);if(Math.floor(r)<=Math.max(this.flushAt,this.editFlushAt))return!1;if(o)o.last=Math.max(o.last,r);else{if(i-r>=cu(e.path))return!1;o={first:Math.min(i,r),last:r},this.dirty.set(e.path,o)}return this.dueAt(e.path,o)>i}settled(e,t){let r=this.dirty.get(e);r&&(r.last<t?this.dirty.delete(e):r.first=t)}async keepBase(e,t,r){let i=lu(e),o=st(i,t);if(await un(o).then(()=>!0,()=>!1))return;await ay(i,{recursive:!0,mode:448});let a=o+".tmp-"+kn();try{await Xa(a,r,{mode:384,flag:"wx"}),await Ko(a,o)}finally{await Xo(a).catch(()=>{})}}async readBase(e,t){if(t.base!==void 0)return t.base;let r=await Jo(st(lu(e),t.hash)).catch(i=>{if(i.code==="ENOENT")return null;throw i});return r&&Ue(r)===t.hash?r.toString("utf8"):null}async pruneBases(e){let t=new Set(Object.values(e.stored.files).map(i=>i.hash)),r=lu(e);for(let i of await Yo(r).catch(()=>[]))t.has(i)||await Xo(st(r,i)).catch(()=>{})}async file(e,t,r,i,o){let a=this.bind?this.bindPolicy:null;if(r.size>ir)return this.noteTooLarge(e,i,r.path,r.size,ir),"too-large";let s=S=>{let _=this.capFor(i,r.path,o);return S.length<=_?!1:(this.noteTooLarge(e,i,r.path,S.length,_),!0)},l=o.nodes.find(S=>S.kind==="file"&&!S.deleted&&S.path===r.path);if(a&&this.goneLinked.has(r.path))return this.progress.count("held"),"undecided";let c=a?e.stored.held?.[r.path]:void 0;if(c?.cloudGone)if(l&&!(c.inode&&r.inode!==c.inode))delete e.stored.held[r.path],Object.keys(e.stored.held).length||delete e.stored.held;else{let S=await er(r);return this.guard(e),c.localHash=Ue(S),c.size=r.size,c.localMtime=r.mtime,this.bindStats.held++,this.progress.count("held"),"undecided"}if(!l&&(!a||a.realMove)){let S=Object.entries(e.stored.files).find(([_,R])=>_.startsWith(i+":")&&R.inode===r.inode&&R.path!==r.path&&!sn(R.path)&&!R.outsideScope)?.[1];if(S){let _=Ze(e.roots,S.path),R=await un(st(_.root,_.relative)).then(async D=>Qn(D).inode!==r.inode||or(S.path)!==or(r.path)?!0:(await Yo(Ii(r.physical))).includes(Yr(S.path)),D=>D.code==="ENOENT"?!1:Promise.reject(D)),N=o.nodes.find(D=>D.id===S.id&&!D.deleted);if(!R&&N)try{if(N.path!==S.path)throw Error(`Concurrent file rename: ${r.path}`);let D=or(r.path),M=D?o.nodes.find($=>$.path===D&&$.kind==="folder"&&!$.deleted)?.id:"";if(D&&!M)throw Error("Rename parent unavailable");let x=await this.operation(e,r.path,i,"rename",null,()=>this.json(e,i,`/nodes/${N.id}`,"PATCH",{name:Yr(r.path),parentId:M,revision:N.revision}));Object.assign(N,x),S.path=r.path,l=N}catch(D){for(let M of new Set([S.path,N.path,r.path]))this.block(i,M,D);throw D}}}let u=l?e.stored.files[Ie(i,l.id)]:Object.entries(e.stored.files).find(([S,_])=>S.startsWith(i+":")&&_.path===r.path)?.[1],d=!!l&&u?.outsideScope===!0;if(u?.outsideScope){if(!l)return"undecided";u=void 0}if(!a&&!u&&l?.version&&i==="default"&&(u=await this.legacyBaseline(r.path,l)),l&&u&&this.unchanged(e,i,l,u,r))return;if(!l&&!u&&r.size>this.capFor(i,r.path,o))return this.noteTooLarge(e,i,r.path,r.size,this.capFor(i,r.path,o)),"too-large";if(this.hold(r,u))return"held";let g=Date.now(),f=await er(r),p=Ue(f),m={key:ui(r),at:g,inode:r.inode};this.guard(e),this.settled(r.path,g);let y,b;if(!l){let S=u?o.nodes.find(x=>x.id===u.id&&x.deleted):null;if(S&&this.scopeExclusions&&this.route(S.path,t)!==i)return"undecided";if(S&&u&&a?.direction==="push"&&(u=void 0),S&&u&&(u.hash===p||u.memoryDeleted&&Qa(r.path)&&p===Ti)){if(a&&(!a.deletes||a.direction==="pull"))return"undecided";if(Qa(r.path)){await this.clearDeletedMemory(e,i,r,u,f,p);return}let x=$n("local",i,u.id),$=this.round;if(!$.restore.has(x)){$.plan.push({key:du("local",i,u.id,p,r.path),ns:i,id:u.id,path:r.path,side:"local",e:r,hash:p});return}$.restoreHit.add(x),y=x,b=Ie(i,u.id)}if(a&&S&&u&&!b&&(b=Ie(i,u.id)),a?.direction==="pull")return"undecided";if(s(f))return"too-large";let _=or(r.path),R=_?o.nodes.find(x=>x.path===_&&!x.deleted&&x.kind==="folder")?.id:"";if(_&&!R)throw Error("Parent folder is unavailable");let N=Object.entries(e.stored.pendingUploads??{}).find(([x,$])=>x.startsWith(i+":")&&$.path===r.path&&!o.nodes.some(O=>O.id===$.id))?.[1];for(let[x,$]of Object.entries(e.stored.pendingUploads??{}))x.startsWith(i+":")&&$.path===r.path&&o.nodes.some(O=>O.id===$.id&&O.deleted)&&delete e.stored.pendingUploads[x];let D=N?.id??kn(),M=Ie(i,D);(e.stored.pendingUploads??={})[M]={id:D,path:r.path},await this.persist(e),a&&o.nodes.some(x=>x.deleted&&x.kind==="file"&&x.path===r.path)&&this.revivePaths.add(r.path),l=await this.json(e,i,"/nodes","POST",{id:D,parentId:R,name:Yr(r.path),kind:"file"}),e.tombstones.get(i)?.delete(l.id),l.id!==D&&delete e.stored.pendingUploads[M],o.nodes.push(l),u=void 0}if(l.busy)return;let h=Ie(i,l.id);if(l.version&&this.awaitingBytes.delete(h),l.hash===p){a&&!u&&this.bindStats.adopted++,await this.shadow(e,i,l,f,r,m);return}if(!d&&l.hash&&e.stored.unconfirmed?.[h]===l.hash&&(await this.shadow(e,i,l,await this.operation(e,r.path,i,"download",l.size??null,S=>this.download(e,l,i,S)),r),u=e.stored.files[h]),!l.version&&u&&u.hash===p&&!e.stored.pendingUploads?.[h]){let S=this.awaitingBytes.get(h)??Date.now();if(this.awaitingBytes.set(h,S),Date.now()-S<B0)return}if(this.awaitingBytes.delete(h),!l.version||u&&l.version===u.version&&co(u.file,l.file)){if(a?.direction==="pull")return"undecided";if(s(f))return"too-large";a&&!u&&(this.bindStats.filled++,this.revivePaths.has(r.path)&&this.bindStats.revived++),(e.stored.unconfirmed??={})[h]=p,await this.persist(e);let S=await this.operation(e,r.path,i,"upload",f.length,_=>this.upload(e,l,i,f,_,r.mtime));Object.assign(l,S),await this.shadow(e,i,l,f,r,m),y&&this.round.restoreDone.add(y),b&&b!==h&&delete e.stored.files[b];return}if(a){if(!u){if(!d&&a.onDiffer==="newer"&&(a.newerOnly?.(r.path)??!0)&&a.direction==="both"&&l.mtime!==void 0&&Math.floor(l.mtime)!==Math.floor(r.mtime)){await this.takeSide(e,i,l,r,f,p,m,r.mtime>l.mtime?"local":"cloud","pair-newer");return}return this.holdDiffer(e,i,l,r,p)}if(u.hash!==p&&a.direction!=="both")return this.holdDiffer(e,i,l,r,p);if(u.hash===p&&a.direction==="push")return"undecided"}let E=await this.operation(e,r.path,i,"download",l.size??null,S=>this.download(e,l,i,S)),v=E,k=!1;if(!u||u.hash!==p){let S=f.toString("utf8"),_=E.toString("utf8"),R=u?await this.readBase(e,u):null,N=Buffer.from(S).equals(f)&&Buffer.from(_).equals(E)?this.host.contentSync.merge(r.path,S,R,_):null;if(N&&!N.conflict&&R!==null&&U0(r.path)&&!Jd(R,S,N.content)&&(N=null),N?(v=Buffer.from(N.content),k=N.conflict):k=!0,k&&a)return this.holdDiffer(e,i,l,r,p);if(k){await this.preserveConflict(e,r.path,f)&&(Nt("content","conflicts"),this.tally("conflictCopies"));let D=this.job(e,r.path,i,"merge",f.length);D.state="conflict",D.error="Both versions preserved",D.finishedAt=Date.now()}if(!v.equals(E)){let D=await this.operation(e,r.path,i,"merge",v.length,M=>this.upload(e,l,i,v,M));Object.assign(l,D)}}let C=Date.now();await this.write(e,r.path,v,p),await this.shadow(e,i,l,v,r,await this.seen(e,r.path,C))}holdDiffer(e,t,r,i,o){let a={path:i.path,ns:t,id:r.id,version:r.version??"",remoteHash:r.hash??null,...r.file?{file:r.file}:{},revision:r.revision,localHash:o,localMtime:i.mtime,remoteMtime:r.mtime??null,size:i.size,at:e.stored.held?.[i.path]?.at??Date.now()};return(e.stored.held??={})[i.path]=a,this.bindStats.held++,this.progress.count("held"),"undecided"}async takeSide(e,t,r,i,o,a,s,l,c){let u=this.bind,d=Ie(t,r.id),g=this.relOf(e,i.path),f=await this.operation(e,i.path,t,"download",r.size??null,m=>this.download(e,r,t,m)),p;if(l==="local"){let m=this.capFor(t,i.path,{limits:this.limitsByNs.get(t)});if(o.length>m)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:m,size:o.length});p=await u.recovery.record({bindingId:u.id,target:u.targetLabel,path:g,side:"cloud",bytes:f,reason:c}),this.guard(e),(e.stored.unconfirmed??={})[d]=a,await this.persist(e);let y=await this.operation(e,i.path,t,"upload",o.length,b=>this.upload(e,r,t,o,b,i.mtime));Object.assign(r,y),await this.shadow(e,t,r,o,i,s)}else{p=await u.recovery.record({bindingId:u.id,target:u.targetLabel,path:g,side:"local",bytes:o,reason:c}),this.guard(e);let m=Date.now();await this.write(e,i.path,f,a),await this.shadow(e,t,r,f,i,await this.seen(e,i.path,m))}return this.bindStats.replaced++,this.bindStats.recoveryEvents.push(p),p}relOf(e,t){let r=e.roots.find(i=>t===i.prefix||t.startsWith(i.prefix+"/"));return r?t.slice(r.prefix.length).replace(/^\//,""):t}bindingReview(e={deletes:20}){let t=this.session;if(!t||!this.bind)return null;let r=g=>this.relOf(t,g),i=this.running?this.roundProgress():null,o=i?{...i,current:i.current?{...i.current,path:r(i.current.path)}:null}:null,a=this.liveHeld(t).map(g=>({...g,generation:iu(g),rel:r(g.path)})),s=t.stored.deleteGuard,l=this.claimedDeletes(),c=(s?.pending??[]).filter(g=>!l.has(g.key)),u=s&&(c.length||s.latched&&!l.size)?{count:c.length,latched:!!s.latched,token:Za(c),items:c.slice(0,e.deletes).map(g=>({path:r(g.path),side:g.side}))}:null,d=[...[...this.tooLarge.values()].map(g=>({path:r(g.path),reason:"too-large",size:g.size,maxBytes:g.maxBytes,retryAt:null})),...this.scanned.skipped.map(g=>({path:r(g.path),reason:g.reason,retryAt:null})),...[...this.failures.values()].sort((g,f)=>g.retryAt-f.retryAt).map(g=>({path:r(g.path),reason:"failed",code:g.code??g.reason,retryAt:g.retryAt}))];return{progress:o,held:a,deletes:u,failures:d,rateLimitedUntil:this.bind.transport?null:this.rateLimitedUntil()}}async heldList(){let e=await this.getSession();return this.liveHeld(e).map(t=>({...t,generation:iu(t),rel:this.relOf(e,t.path)}))}liveHeld(e){return Object.values(e.stored.held??{}).filter(t=>this.route(t.path,e.stored.config,"file")===t.ns)}claimedDeletes(){return new Set([...this.deferredDecision,...this.session?.stored.deleteDecisions??[]].flatMap(e=>e.keys))}async resolveHeld(e,t,r){if(!this.bind)throw Error("binding_mode_only");for(;this.running||this.resolving;)await(this.running?this.runFinished:new Promise(i=>setTimeout(i,50)));if(this.closed)return{ok:!1,error:"content_sync_closed"};this.resolving=!0;try{let i=await this.getSession(),o=i.stored.held?.[e];if(!o)return{ok:!1,error:"not_found"};if(!this.bind.readScopeExclusions&&this.route(e,i.stored.config,"file")!==o.ns)return{ok:!1,error:"not_found"};if(iu(o)!==t)return{ok:!1,error:"stale"};if(i.abort.signal.aborted&&(i.abort=new AbortController),this.bindPolicy={...this.bind.policy(),onDiffer:"hold"},o.cloudGone&&!this.bind.readScopeExclusions)return await this.resolveCloudGone(i,o,r);let a=this.bind.readScopeExclusions?await this.readBindingPrefixes(i):null;i.manifests.delete(o.ns);let s=JSON.parse(await this.manifestText(i,o.ns));if(vr(s,o.ns),this.limitsByNs.set(o.ns,s.limits),o.ns===this.bind.ns)try{this.checkMoved(i,s)}catch(E){if(E?.code==="VAULT_MOVED")return{ok:!1,error:"vault_moving"};throw E}if(a){if(await this.refreshBindingScope(i,s,a),this.route(e,i.stored.config)!==o.ns||this.underExclusion(e,i.stored.scopeExclusions??[]))return{ok:!1,error:"not_found"};if(s.nodes.some(E=>E.path===e&&!E.deleted&&E.kind==="file"&&E.version&&!E.file))return{ok:!1,error:"not_found"};if(o.cloudGone)return await this.resolveCloudGone(i,o,r)}let l=s.nodes.find(E=>E.id===o.id&&!E.deleted&&E.kind==="file"&&E.path===o.path);if(!l||(l.version??"")!==o.version||l.revision!==o.revision||!co(o.file,l.file))return{ok:!1,error:"stale"};let c=Ze(i.roots,e),u=await un(st(c.root,...c.relative.split("/"))).catch(()=>null);if(!u?.isFile())return{ok:!1,error:"stale"};let d={path:e,physical:st(c.root,...c.relative.split("/")),root:c.root,kind:"file",...Qn(u),size:u.size},g=Date.now(),f=await er(d),p=Ue(f),m={key:ui(d),at:g,inode:d.inode};if(this.guard(i),p!==o.localHash)return{ok:!1,error:"stale"};let y;if(r==="newer"){if(l.mtime===void 0||Math.floor(l.mtime)===Math.floor(d.mtime))return{ok:!1,error:"cannot_decide"};y=d.mtime>l.mtime?"local":"cloud"}else y=r;let b=this.bindPolicy.direction;if(b==="push"&&y!=="local"||b==="pull"&&y!=="cloud")return{ok:!1,error:"direction_forbids"};if(y==="both"){let E=await this.operation(i,e,o.ns,"download",l.size??null,S=>this.download(i,l,o.ns,S)),v=await this.keepBothName(i,e);await this.write(i,v,E,null),await zp(i.roots,v);let k=await this.bind.recovery.record({bindingId:this.bind.id,target:this.bind.targetLabel,path:this.relOf(i,e),side:"cloud",bytes:E,reason:"held-resolve"});this.guard(i),(i.stored.unconfirmed??={})[Ie(o.ns,l.id)]=p,await this.persist(i);let C=await this.operation(i,e,o.ns,"upload",f.length,S=>this.upload(i,l,o.ns,f,S,d.mtime));return Object.assign(l,C),await this.shadow(i,o.ns,l,f,d,m),await this.persist(i),{ok:!0,recoveryEventId:k}}let h=await this.takeSide(i,o.ns,l,d,f,p,m,y,"held-resolve");return await this.persist(i),{ok:!0,recoveryEventId:h}}catch(i){return i?.name==="RecoveryError"?{ok:!1,error:"recovery_failed"}:i?.code==="VAULT_MOVED"?{ok:!1,error:"vault_moving"}:i?.code==="VAULT_DELETED"?{ok:!1,error:"vault_deleted"}:/changed during download|version|409/i.test(Fe(i))?{ok:!1,error:"stale"}:{ok:!1,error:Fe(i)}}finally{this.resolving=!1}}async resolveCloudGone(e,t,r){if(r==="newer")return{ok:!1,error:"cannot_decide"};e.manifests.delete(t.ns);let i=JSON.parse(await this.manifestText(e,t.ns));if(vr(i,t.ns),this.guard(e),i.nodes.some(f=>f.kind==="file"&&!f.deleted&&f.path===t.path))return{ok:!1,error:"stale"};let o=Ze(e.roots,t.path),a=st(o.root,...o.relative.split("/")),s=await un(a).catch(()=>null);if(!s?.isFile())return{ok:!1,error:"stale"};let l={path:t.path,physical:a,root:o.root,kind:"file",...Qn(s),size:s.size};if(t.inode&&l.inode!==t.inode)return{ok:!1,error:"stale"};let c=await er(l),u=Ue(c);if(this.guard(e),u!==t.localHash)return{ok:!1,error:"stale"};let d=()=>{e.stored.held&&(delete e.stored.held[t.path],Object.keys(e.stored.held).length||delete e.stored.held)};if(r!=="cloud")return d(),await this.persist(e),this.releasedPaths.add(t.path),{ok:!0};let g=await this.bind.recovery.record({bindingId:this.bind.id,target:this.bind.targetLabel,path:this.relOf(e,t.path),side:"local",bytes:c,reason:"held-resolve"});return this.guard(e),await this.operation(e,t.path,t.ns,"delete",l.size,()=>this.trashFile(e,l,u,t.inode)),d(),await this.persist(e),{ok:!0,recoveryEventId:g}}async keepBothName(e,t){let r=new Date,i=f=>String(f).padStart(2,"0"),o=`${r.getFullYear()}-${i(r.getMonth()+1)}-${i(r.getDate())}`,a=t.lastIndexOf("/"),s=t.slice(0,a+1),l=t.slice(a+1),c=l.lastIndexOf("."),u=c>0?l.slice(0,c):l,d=c>0?l.slice(c):"",g=this.locale()==="zh"?"\u4E91\u7AEF":"cloud";for(let f=1;;f++){let p=`${s}${u} (${g} ${o}${f>1?` ${f}`:""})${d}`,m=Ze(e.roots,p);if(!await un(st(m.root,...m.relative.split("/"))).then(()=>!0,y=>y.code==="ENOENT"?!1:Promise.reject(y)))return p}}async preserveConflict(e,t,r){let i=Ze(e.roots,t),o=await wt(i.root,i.relative),a=Yr(t),s=Ue(r);for(let l of await Yo(Ii(o))){if(l.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==a||!Ot(l))continue;let c=or(t)?or(t)+"/"+l:l,u=Ze(e.roots,c),d=await wt(u.root,u.relative),g=await un(d);if(g.isFile()&&g.size===r.length&&Ue(await Jo(d))===s)return!1}return await this.write(e,await this.copyName(e,t),r,null),!0}async copyName(e,t){let r=new Date;for(let i=1;;i++){let o=oh(t,r,i),a=Ze(e.roots,o);if(!await un(st(a.root,...a.relative.split("/"))).then(()=>!0,s=>s.code==="ENOENT"?!1:Promise.reject(s)))return o}}async legacyBaseline(e,t){let r=await this.host.contentSync.agentFiles?.baseline(e).catch(()=>null);if(!(!r||!t.version)&&!(r.pending&&Number(t.version.split(":")[0])!==r.seq))return{id:t.id,path:e,version:`${r.seq}:${r.hash}`,hash:r.hash,...r.base!==void 0?{base:r.base}:{}}}agentAsks(e,t,r,i,o){let a=[],s=l=>l.length?Math.max(...l):null;for(let l of t){let c=l.kind==="folder"?Mo(l.path):null;if(!c||Ra.has(c))continue;let u=`agents/${c}/`,d=this.route(u+"config.toml",r);if(!d||Object.entries(e.stored.files).some(([y,b])=>y.startsWith(d+":")&&b.path.startsWith(u)))continue;let g=(i.get(d)?.nodes??[]).filter(y=>!y.deleted&&y.kind==="file"&&y.version&&y.path.startsWith(u)&&this.route(y.path,r)===d),f=t.filter(y=>y.kind==="file"&&y.path.startsWith(u)&&this.route(y.path,r)===d);if(!g.length||!f.length)continue;let p=new Map(g.map(y=>[y.path,y])),m=f.filter(y=>{let b=p.get(y.path);return!!b&&o.get(y.path)!==b.hash}).length;!m&&f.length===g.length&&f.every(y=>p.has(y.path))||a.push({slug:c,namespace:d,cloudFiles:g.length,localFiles:f.length,differ:m,cloudMtime:s(g.map(y=>y.mtime??0)),localMtime:s(f.map(y=>y.mtime))})}return a}async resolveAsks(e,t,r,i){for(let o of t){try{await this.resolveAsk(e,o,r[o.slug]??"merge",i)}catch(c){throw this.dropShadows(e,o.namespace,`agents/${o.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Fe(c)}`)}let a=`agents/${o.slug}`,s=i.rules.find(c=>c.source===a),l=yi(e.stored.config,a,xh(i,a));s&&(l={...l,rules:l.rules.map(c=>c.source===a?{...s,target:c.target}:c)}),e.stored.config=Zt(l,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,t,r,i){let o=t.namespace,a=`agents/${t.slug}/`;if(this.dropShadows(e,o,a),r==="local"){await this.archiveAgent(e,o,t.slug),await this.persist(e);return}let s=await this.json(e,o);this.guard(e),vr(s,o);let l=new Map(s.nodes.filter(f=>!f.deleted&&!f.busy&&f.kind==="file"&&f.version&&f.path.startsWith(a)&&this.route(f.path,i)===o).map(f=>[f.path,f])),c=f=>f.endsWith("/"+ko),u=async(f,p,m)=>{let y=Date.now();return await this.write(e,f,p,m),this.seen(e,f,y)};for(let[f,p]of l){if(!c(f))continue;let m=Ze(e.roots,f);if(py(st(m.root,m.relative)))continue;let y=await this.operation(e,f,o,"download",p.size??null,b=>this.download(e,p,o,b));await this.shadow(e,o,p,y,void 0,await u(f,y,null))}let d=(await this.scan(e)).filter(f=>f.kind==="file"&&f.path.startsWith(a)&&this.route(f.path,i)===o&&f.size<=ir).sort((f,p)=>+!c(f.path)-+!c(p.path)),g=await this.removedDir(e,t.slug);for(let f of d){this.guard(e);let p=await er(f),m=Ue(p),y=l.get(f.path),b=f.path.slice(a.length);if(y&&y.hash===m){await this.shadow(e,o,y,p,f);continue}if(r==="cloud"){if(await this.keep(e,`${g}/${b}`,p),y){let C=await this.operation(e,f.path,o,"download",y.size??null,S=>this.download(e,y,o,S));await this.shadow(e,o,y,C,f,await u(f.path,C,m))}else b==="MEMORY.md"?await this.write(e,f.path,Buffer.alloc(0),m):await this.removeLocal(e,f,m);continue}if(!y)continue;let h=await this.operation(e,f.path,o,"download",y.size??null,C=>this.download(e,y,o,C)),E=o==="default"?await this.legacyBaseline(f.path,y):void 0;if(E?.hash===m){await this.shadow(e,o,y,h,f,await u(f.path,h,m));continue}let v=E?await this.readBase(e,E):null,k=nu(p)&&nu(h)?this.host.contentSync.merge(f.path,p.toString("utf8"),v,h.toString("utf8")):null;if(k&&!k.conflict){let C=Buffer.from(k.content);C.equals(p)||await this.write(e,f.path,C,m),await this.shadow(e,o,y,h)}else(y.mtime??0)>f.mtime?(await this.keep(e,`${g}/${b}`,p),await this.shadow(e,o,y,h,f,await u(f.path,h,m))):(await this.keep(e,`${g}/${b}`,h),await this.shadow(e,o,y,h))}await this.persist(e)}dropShadows(e,t,r){for(let[i,o]of Object.entries(e.stored.files))i.startsWith(t+":")&&o.path.startsWith(r)&&(delete e.stored.files[i],delete e.stored.unconfirmed?.[i])}async removedDir(e,t,r="agents"){let i=new Date,o=s=>String(s).padStart(2,"0"),a=`${i.getFullYear()}-${o(i.getMonth()+1)}-${o(i.getDate())} ${o(i.getHours())}${o(i.getMinutes())}`;for(let s=1;;s++){let l=`${r}/.removed/${t} ${a}${s>1?` ${s}`:""}`,c=Ze(e.roots,l);if(!await un(st(c.root,...c.relative.split("/"))).then(()=>!0,u=>u.code==="ENOENT"?!1:Promise.reject(u)))return l}}async keep(e,t,r){this.guard(e),await Jc(e.roots,t,r,null)}async removeLocal(e,t,r){await this.lock(e,t.physical,()=>{if(wn(t.root,Zo(t.root,t.physical).split(xi).join("/")),Ue(Ci(t.physical))!==r)throw Error("Local file changed before replacing");Qd(t.physical)})}async archiveAgent(e,t,r){let i=this.host.readCreds();if(!i.token)throw Error("not_signed_in");let o=await this.gatedFetch(e,i.cloudUrl,"/api/remotesync/agent-archive/agent",{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({namespace:t,slug:r,opId:kn(),locale:this.locale()})},12e4);this.guard(e);let a=await o.json().catch(()=>({}));if(this.guard(e),!o.ok||a?.state!=="done")throw Error(typeof a?.detail=="string"?a.detail:`agent_archive_http_${o.status}`)}async absent(e,t,r=e.roots){this.guard(e);let i=Ze(r,t),o=await wt(i.root,i.relative);try{return await un(o),!1}catch(a){if(a.code==="ENOENT")return!0;throw a}}async missing(e,t,r,i,o){let a=e.stored.files[Ie(r,t.id)];if(this.sealedShadow(a)||a?.outsideScope&&t.deleted)return this.round?.undecided.add(r+"\0"+t.path),this.round?.undecided.add(r+"\0"+a.path),"unknown";let s=a?.outsideScope?void 0:a,l=a?.outsideScope?void 0:e.stored.pendingUploads?.[Ie(r,t.id)];if(!t.deleted&&s?.inode&&this.blocked.has(r)&&i.some(h=>h.kind==="file"&&h.inode===s.inode&&this.isBlocked(r,h.path)&&this.route(h.path,o)===r)){this.round?.undecided.add(r+"\0"+t.path);return}let c=Br(this.scanned.unscanned,t.path)||!!s?.inode&&this.scanned.skippedInodes.has(s.inode),u=xc(t,s,!!l,c),d=this.round,g=()=>d.plan.some(h=>h.side==="local"&&h.ns===r&&h.id===t.id)||d.restore.has($n("local",r,t.id))||!!e.stored.deleteGuard?.pending.some(h=>h.side==="local"&&h.ns===r&&h.id===t.id);if(u==="forget"){s&&!g()&&delete e.stored.files[Ie(r,t.id)],l&&delete e.stored.pendingUploads[Ie(r,t.id)];return}if(u==="skip")return d.undecided.add(r+"\0"+t.path),s&&d.undecided.add(r+"\0"+s.path),c?"unknown":void 0;let f=this.bind?this.bindPolicy:null;if(u==="cancel"){if(f&&!f.deletes){d.undecided.add(r+"\0"+t.path);return}await this.absent(e,t.path)&&(await this.operation(e,t.path,r,"delete",null,()=>this.json(e,r,`/nodes/${t.id}`,"DELETE",{revision:t.revision,version:null})),delete e.stored.pendingUploads[Ie(r,t.id)],t.deleted=!0);return}let p,m=u==="delete"&&!!f&&!!s&&s.path!==t.path;if(u==="delete"&&!m){if(!await this.absent(e,t.path))return;if(f&&(!f.deletes||f.direction==="push")){d.undecided.add(r+"\0"+t.path);return}if(f&&!f.realMove&&s?.inode&&i.some(h=>h.kind==="file"&&h.inode===s.inode&&h.path!==t.path&&this.route(h.path,o)===r&&!Object.entries(e.stored.files).some(([E,v])=>E.startsWith(r+":")&&v.path===h.path&&v.inode===s.inode))){d.undecided.add(r+"\0"+t.path);return}if(f?.direction!=="pull"){let h=$n("cloud",r,t.id);if(!d.restore.has(h)){d.plan.push({key:du("cloud",r,t.id,t.version,t.path),ns:r,id:t.id,path:t.path,side:"cloud",node:t});return}d.restoreHit.add(h),p=h}}if(f?.direction==="push"){d.undecided.add(r+"\0"+t.path);return}if(t.size!==void 0&&t.size>ir){this.noteTooLarge(e,r,t.path,t.size,ir),d.undecided.add(r+"\0"+t.path);return}f&&!s&&this.bindStats.filled++;let y=await this.operation(e,t.path,r,"download",t.size??null,h=>this.download(e,t,r,h)),b=Date.now();await this.write(e,t.path,y,null),await this.shadow(e,r,t,y,void 0,await this.seen(e,t.path,b)),p&&d.restoreDone.add(p)}guardPaths(e,t){return this.bind?t.map(r=>{let i=e.roots.find(o=>r.path===o.prefix||r.path.startsWith(o.prefix+"/"));return i?{ns:r.ns,path:r.path===i.prefix?"":r.path.slice(i.prefix.length+1)}:r}):[...t]}async executeDeletes(e,t){this.bind&&(!this.bindPolicy.deletes||this.bindPolicy.direction!=="both")&&(t.plan=[]);let r=e.stored.deleteGuard,i=t.plan,o=new Set(i.map(h=>h.key)),a=new Set(i.map(h=>$n(h.side,h.ns,h.id))),s=new Set((r?.confirmed??[]).filter(h=>o.has(h))),l=Date.now();this.deleteStamps=this.deleteStamps.filter(h=>l-h<Qs);let c=i.filter(h=>!s.has(h.key)),u=ea(this.guardPaths(e,c),this.guardPaths(e,t.tracked),{latched:!!r?.latched,recent:this.deleteStamps.length});u&&!r?.latched&&Nt("content","massDeleteGuard");let d=h=>{let E=e.stored.files[Ie(h.ns,h.id)];return[h.path,...E?[E.path]:[]].some(k=>t.undecided.has(h.ns+"\0"+k)||Br(this.scanned.unscanned,k))||!!E?.inode&&this.scanned.skippedInodes.has(E.inode)},g=(r?.pending??[]).filter(h=>!a.has($n(h.side,h.ns,h.id))&&d(h)),f=[...t.restore].filter(([h,E])=>!t.restoreDone.has(h)&&(t.restoreHit.has(h)||d(E))).map(([,h])=>h),p={latched:u||g.length>0,pending:[...u?c.map(cy):[],...g],...s.size?{confirmed:[...s]}:{},...f.length?{restore:f}:{}},m=()=>{p.latched||p.pending.length||p.confirmed?.length||p.restore?.length?e.stored.deleteGuard=p:delete e.stored.deleteGuard};m(),await this.persist(e);let y=[...i.filter(h=>s.has(h.key)),...u?[]:c],b;for(let h=0;h<y.length;h++){let E=y[h],v=s.has(E.key);try{if(E.side==="cloud"){if(!await this.absent(e,E.path))continue;let k=E.node;await this.operation(e,E.path,E.ns,"delete",k.size??null,()=>this.json(e,E.ns,`/nodes/${k.id}`,"DELETE",{revision:k.revision,version:k.version,...k.file?{file:k.file}:{}},v?{"X-Content-Delete-Confirmed":"1"}:void 0)),delete e.stored.files[Ie(E.ns,k.id)],k.deleted=!0}else await this.operation(e,E.path,E.ns,"delete",E.e.size,()=>this.trashFile(e,E.e,E.hash)),this.tally("deletesLocal"),delete e.stored.files[Ie(E.ns,E.id)];v?p.confirmed=p.confirmed?.filter(k=>k!==E.key):this.deleteStamps.push(Date.now())}catch(k){if(this.bind&&au(k)){b=k;break}if(k?.code!=="MASS_DELETE_BLOCKED"){this.error=Fe(k);continue}p.latched||Nt("content","massDeleteGuard"),p.latched=!0,p.pending=[...p.pending,...y.slice(h).filter(C=>C.side==="cloud").map(cy)];for(let C of y.slice(h+1))if(C.side==="local")try{await this.operation(e,C.path,C.ns,"delete",C.e.size,()=>this.trashFile(e,C.e,C.hash)),this.tally("deletesLocal"),delete e.stored.files[Ie(C.ns,C.id)]}catch(S){this.error=Fe(S)}break}}if(m(),await this.persist(e),b)throw b}async recoverTrash(e){for(let t of[...e.stored.trash??[]]){if(t.parentId){let c=(await bn(e.roots)).find(u=>u.kind==="folder"&&u.localId===t.parentId);c&&(t.path=c.path+"/"+Yr(t.path))}let r=Ze(e.roots,t.path),i=await wt(r.root,r.relative);if(!/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage))throw Error("Invalid sync recovery journal");let o=t.stageRoot??r.root,a=await this.rootIdentity(e,o),s=t.stageIdentity??(t.stageDev===void 0?void 0:{dev:t.stageDev,ino:t.stageIno});if(s&&!Dt(s,a))throw Error("Sync recovery root changed; journal retained");let l=st(o,t.stage);await un(l).then(()=>!0,c=>c.code==="ENOENT"?!1:Promise.reject(c))&&await this.lock(e,i,()=>{if(wn(o,t.stage,!0),Ue(Ci(l))!==t.hash)throw Error("Sync recovery content changed");wn(r.root,r.relative),x0(Ii(i),{recursive:!0});let c=py(i)?i+` (sync recovery ${kn().slice(0,8)})`:i;try{R0(l,c)}catch(u){if(u.code!=="EXDEV")throw u;if(T0(l,c,D0.COPYFILE_EXCL),Ue(Ci(c))!==t.hash)throw Error("Sync recovery copy incomplete; original retained")}Qd(l)},!0),e.stored.trash=e.stored.trash.filter(c=>c!==t)}}async clearDeletedMemory(e,t,r,i,o,a){i.memoryDeleted&&i.hash===Ti&&a===Ti||(await this.operation(e,r.path,t,"delete",r.size,async()=>{if(!i.memoryDeleted&&o.length){let c=r.path==="human/MEMORY.md",u=await this.removedDir(e,c?"memory":r.path.split("/")[1],c?"human":"agents");await this.keep(e,`${u}/MEMORY.md`,o)}i.memoryDeleted=!0,await this.persist(e);let s=Date.now();o.length&&await this.write(e,r.path,Buffer.alloc(0),a);let l=await this.seen(e,r.path,s);e.stored.files[Ie(t,i.id)]={...i,hash:Ti,base:"",stat:void 0,statAt:void 0,...l?{inode:l.inode,stat:l.key,statAt:l.at}:{}}}),this.tally("deletesLocal"))}async trashFile(e,t,r,i){this.guard(e);let o=await wt(t.root,Zo(t.root,t.physical).split(xi).join("/")),a={path:t.path,stage:".forsion-sync-trash-"+kn(),hash:r},s=st(t.root,a.stage),l=await this.rootIdentity(e,t.root);if(a.stageRoot=t.root,a.stageDev=l.dev,a.stageIno=l.ino,a.stageIdentity=l,!this.bind)try{let c=JSON.parse(Ci(st(Ii(o),".forsion-sync-id.json"),"utf8")).id;/^[a-f0-9-]{36}$/i.test(c)&&(a.parentId=c)}catch{}(e.stored.trash??=[]).push(a),await this.persist(e);try{await this.lock(e,o,()=>{if(wn(t.root,Zo(t.root,o).split(xi).join("/")),Ue(Ci(o))!==r||i!==void 0&&Qn(hy(o)).inode!==i)throw Error("Local file changed before deletion");_0(o,s)}),await this.host.contentSync.trash(s),e.stored.trash=e.stored.trash.filter(c=>c!==a)}catch(c){throw this.ownerNow()===e.account&&!e.abort.signal.aborted&&await this.recoverTrash(e),c}}};function Q0(n){let e={};if(n&&typeof n=="object")for(let[t,r]of Object.entries(n))Oo.test(t)&&op.includes(r)&&(e[t]=r);return e}function py(n){try{return hy(n),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function wy(n,e,t,r){if(e===n)return t==="folder";if(!e.startsWith(n+"/"))return!1;let i=e.slice(n.length+1);return Ot(i)||i.split("/").some(o=>o.startsWith("."))?!1:r(e,t)}function by(n,e){Gn(n);let t=n,r={reattached:0,remoteChanged:0,cloudGone:0,noIdentity:0,pendingDeletes:0},i=new Map;for(let m of e.nodes)m.kind==="file"&&!m.deleted&&m.file&&m.version&&wy(e.toPrefix,m.path,"file",e.inScope)&&i.set(m.file,m);let o={},a={},s=new Map;for(let[m,y]of Object.entries(t.files)){if(!m.startsWith(e.fromNs+":")||!y.path.startsWith(e.fromPrefix+"/"))continue;let b=e.toPrefix+y.path.slice(e.fromPrefix.length);if(!y.file){r.noIdentity++;continue}let h=i.get(y.file);if(h){o[Ie(e.toNs,h.id)]={...y,id:h.id,path:b},s.set(y.id,{n:h,path:b}),r.reattached++,h.version!==y.version&&r.remoteChanged++;continue}a[b]={path:b,ns:e.toNs,id:y.id,version:y.version,remoteHash:null,file:y.file,revision:0,localHash:y.hash,localMtime:0,remoteMtime:null,size:0,at:e.now,cloudGone:!0,...y.inode?{inode:y.inode}:{}},r.cloudGone++}let l=t.deleteGuard,c=(m,y,b)=>{if(m!=="cloud"||y!==e.fromNs||typeof b!="string")return null;let h=s.get(b);return h?{key:du("cloud",e.toNs,h.n.id,h.n.version,h.path),ns:e.toNs,id:h.n.id,path:h.path,side:"cloud"}:null},u=new Map,d=new Map;for(let m of l?.pending??[]){let y=c(m.side,m.ns,m.id);y&&u.set(y.id,y)}for(let m of l?.confirmed??[]){let y;try{y=JSON.parse(m)}catch{continue}if(!Array.isArray(y))continue;let b=c(y[0],y[1],y[2]);b&&u.set(b.id,b)}for(let m of l?.restore??[]){let y=c(m.side,m.ns,m.id);y&&!u.has(y.id)&&d.set(y.id,y)}r.pendingDeletes=u.size;let g=u.size||d.size?{latched:u.size>0,pending:[...u.values()],...d.size?{restore:[...d.values()]}:{}}:null,f=t.roots?.map(m=>m.prefix===e.fromPrefix?{...m,prefix:e.toPrefix}:m),p={config:t.config,owned:!1,paused:!1,folders:{},files:o,jobs:[],bindTarget:`${e.toNs}|${e.toPrefix}`,...f?{roots:f}:{},...Object.keys(a).length?{held:a}:{},...g?{deleteGuard:g}:{}};return Gn(p),{state:p,stats:r}}import{createHash as eR}from"node:crypto";var tR=(n,e)=>`${n.generation}.${e}`;function tl(n,e){return e.map(t=>({ref:{bindingId:n.id,path:t.path,generation:tR(n,t.generation)},path:t.rel,localMtime:t.localMtime,remoteMtime:t.remoteMtime,size:t.size,at:t.at,...t.cloudGone?{cloudGone:!0}:{}}))}var nl=n=>eR("sha256").update(JSON.stringify(n.map(e=>[e.ref.path,e.ref.generation]).sort((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0))).digest("hex").slice(0,24),vy=n=>n.remoteMtime===null||Math.floor(n.localMtime/1e3)===Math.floor(n.remoteMtime/1e3)?null:n.localMtime>n.remoteMtime?"local":"remote";function Sy(n,e){let t=e.generation.indexOf(".");return t<0||e.bindingId!==n.id||e.generation.slice(0,t)!==String(n.generation)?null:e.generation.slice(t+1)}import{open as ol,readFile as Di,mkdir as nR,rename as rR,writeFile as iR,unlink as oR,readdir as sR}from"node:fs/promises";import{join as Pi,dirname as es,resolve as ky,sep as aR}from"node:path";import{createHash as rl,randomUUID as Ey}from"node:crypto";var Ay=/^[0-9a-f]{64}$/,lR=n=>{let e=n;return!!e&&typeof e=="object"&&typeof e.eventId=="string"&&typeof e.bindingId=="string"&&typeof e.path=="string"&&(e.side==="cloud"||e.side==="local")&&Ay.test(e.hash)&&Number.isFinite(e.at)&&Number.isSafeInteger(e.size)},il=new Map,_y=(n,e)=>{let t=(il.get(n)??Promise.resolve()).then(e,e),r=t.catch(()=>{});return il.set(n,r),r.then(()=>{il.get(n)===r&&il.delete(n)}),t};async function cR(n){try{let e=await ol(n,"r");try{await e.sync()}finally{await e.close()}}catch(e){if(!["EISDIR","EPERM","EINVAL"].includes(e.code??""))throw e}}async function Ry(n,e){let t=ky(e);for(let r=ky(n);;r=es(r))if(await cR(r),r===t||!r.startsWith(t+aR)||es(r)===r)return}function Oi(n,e){let t=()=>Pi(n(),"vault-sync","recovery",`${e}.jsonl`),r=()=>Pi(n(),"sync-recovery",e),i=Vo(e,n),o=async()=>{let c;try{c=await Di(t(),"utf8")}catch(g){if(g.code==="ENOENT")return[];throw g}let u=[],d=c.split(`
|
|
212
|
+
`);for(let g=0;g<d.length;g++){let f=d[g];if(!f.trim())continue;let p;try{p=JSON.parse(f)}catch{if(g===d.length-1)continue;throw Error("recovery_ledger_corrupt")}if(lR(p))u.push(p);else if(g!==d.length-1)throw Error("recovery_ledger_corrupt")}return u},a=c=>Di(c).then(()=>!0,()=>!1),s=async c=>{let u;try{u=await sR(r())}catch{return[]}let d=[];for(let g of u){if(!Ay.test(g))continue;let f;try{f=JSON.parse(await Di(Pi(r(),`${g}.json`),"utf8"))}catch{continue}if(!Array.isArray(f))continue;let p=0;try{p=(await Di(Pi(r(),g))).length}catch{continue}for(let m of f){if(!m||typeof m.binding!="string"||typeof m.path!="string"||m.side!=="cloud"&&m.side!=="local"||c.some(b=>b.hash===g&&b.path===m.path&&b.side===m.side&&b.bindingId===m.binding))continue;let y="orphan-"+rl("sha256").update(JSON.stringify([g,m.binding,m.path,m.side,m.savedAt])).digest("hex").slice(0,24);d.push({eventId:y,ns:e,bindingId:m.binding,target:"",path:m.path,side:m.side,hash:g,size:p,at:Number(m.savedAt)||0,reason:"held-resolve"})}}return d},l={async record(c){let u=Buffer.from(c.bytes),d=rl("sha256").update(u).digest("hex"),g=await i.save(u,{binding:c.bindingId,path:c.path,side:c.side});try{let p=await Di(g);if(rl("sha256").update(p).digest("hex")!==d)throw Error("recovery_bytes_mismatch");let m=await ol(g,"r+");try{await m.sync()}finally{await m.close()}}catch(p){throw p instanceof Wr?p:new Wr(p)}try{await Ry(es(g),n())}catch(p){throw new Wr(p)}let f={eventId:Ey(),ns:e,bindingId:c.bindingId,target:c.target,path:c.path,side:c.side,hash:d,size:u.length,at:Date.now(),reason:c.reason};return await _y(t(),async()=>{await nR(es(t()),{recursive:!0,mode:448});let p=!1;try{let b=await ol(t(),"r+");try{let{size:h}=await b.stat();if(h>0){let E=Buffer.alloc(Math.min(h,1048576)),v=h-E.length;if(await b.read(E,0,E.length,v),E[E.length-1]!==10){let k=E.lastIndexOf(10);if(k<0&&v>0)throw Error("recovery_ledger_corrupt");await b.truncate(k<0?0:v+k+1),await b.sync()}}}finally{await b.close()}}catch(b){if(b.code!=="ENOENT")throw b;p=!0}let m=Buffer.from(JSON.stringify(f)+`
|
|
213
|
+
`),y=await ol(t(),"a",384);try{let{bytesWritten:b}=await y.write(m);if(b!==m.length)throw Error("recovery_ledger_short_write");await y.datasync()}finally{await y.close()}p&&await Ry(es(t()),n())}),f.eventId},async list(c=0,u=Date.now()){let d=await o(),g=[...d,...await s(d)],f=[];for(let p of g)p.at<c||u-p.at>$a||await a(Pi(r(),p.hash))&&f.push(p);return f.sort((p,m)=>m.at-p.at)},async get(c){return(await l.list(0)).find(u=>u.eventId===c)??null},async bytes(c){let u=await Di(Pi(r(),c.hash));if(rl("sha256").update(u).digest("hex")!==c.hash)throw Error("recovery_bytes_changed");return u},async prune(c=Date.now()){await i.prune(c),await _y(t(),async()=>{let u;try{u=await o()}catch{return}let d=u.filter(f=>c-f.at<=$a);if(d.length===u.length)return;let g=`${t()}.tmp-${Ey()}`;try{await iR(g,d.map(f=>JSON.stringify(f)+`
|
|
214
|
+
`).join(""),{mode:384,flag:"wx"}),await rR(g,t())}finally{await oR(g).catch(()=>{})}})}};return l}var sl=class{cadence=null;timer=null;startTimer=null;lastRunAt=0;chain=Promise.resolve();closed=!1;runAll;opts;constructor(e,t={}){this.runAll=e,this.opts=t}now(){return this.opts.now?.()??Date.now()}queued=null;followUps=0;trigger(e,t={}){if(this.closed)return Promise.resolve();t.followUp||(this.followUps=0);let r=e==="scheduled"?void 0:Date.now();if(this.queued&&e!=="flush")return e==="manual"&&(this.queued.kind==="scheduled"&&(this.queued.kind="manual"),this.queued.flushAt=Math.max(this.queued.flushAt??0,r)),this.chain;let i=r===void 0?{kind:e}:{kind:e,flushAt:r};return this.queued=i,this.chain=this.chain.then(async()=>{this.queued===i&&(this.queued=null),this.lastRunAt=this.now(),await this.runAll(i.kind,i.flushAt===void 0?{}:{flushAt:i.flushAt}).catch(()=>{})}),this.chain}start(e){this.setCadence(e),this.startTimer=setTimeout(()=>void this.trigger("scheduled"),this.opts.startDelayMs??5e3),this.startTimer.unref?.()}setCadence(e){this.cadence&&JSON.stringify(this.cadence)===JSON.stringify(e)||(this.cadence=e,this.timer&&clearInterval(this.timer),this.timer=null,e.kind==="interval"?(this.timer=setInterval(()=>void this.trigger("scheduled"),e.minutes*6e4),this.timer.unref?.()):this.cancelLater())}manualOnly(){return this.cadence?.kind==="manual"}laterTimer=null;laterAt=1/0;later(e){this.closed||this.manualOnly()||e>=this.laterAt||this.followUps>=6||(this.laterTimer&&clearTimeout(this.laterTimer),this.laterAt=e,this.laterTimer=setTimeout(()=>{this.laterTimer=null,this.laterAt=1/0,!(this.closed||this.manualOnly())&&(this.followUps++,this.trigger("scheduled",{followUp:!0}))},Math.max(0,e-Date.now())+50),this.laterTimer.unref?.())}cancelLater(){this.laterTimer&&clearTimeout(this.laterTimer),this.laterTimer=null,this.laterAt=1/0}focus(){return this.now()-this.lastRunAt>=6e4?this.trigger("scheduled"):this.chain}idle(){return this.chain}close(){this.closed=!0,this.timer&&clearInterval(this.timer),this.startTimer&&clearTimeout(this.startTimer),this.cancelLater()}};import{lstat as dR,readFile as uR}from"node:fs/promises";import{join as fR}from"node:path";import{createHash as Dy,randomUUID as Cy}from"node:crypto";var At="Vault",ll="vault-remote",gR=720*60*6e4,Iy=5e4,pR=2*1024*1024,hR=32*1024*1024,mR=50,Mi=(n={})=>Object.assign(Object.create(null),n),Py=n=>({version:1,files:Mi(),gone:Mi(),folders:[],...n?{target:n}:{}}),Xr=n=>{let e=JSON.parse(JSON.stringify(n));return e.files=Mi(e.files),e.gone=Mi(e.gone),e},Zr=n=>`remote:${n.targetId}:${n.dir}`,mu=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,yu=/^[a-f0-9]{64}$/,xy=n=>Dy("sha256").update(n).digest("hex"),Oy=n=>{let e=Dy("sha256").update(n).digest("hex");return`${e.slice(0,8)}-${e.slice(8,12)}-5${e.slice(13,16)}-a${e.slice(17,20)}-${e.slice(20,32)}`},Ln=n=>Oy("remote-folder\0"+n),Ty=n=>Oy("remote-folder-gone\0"+n),Fn=n=>n.includes("/")?n.slice(0,n.lastIndexOf("/")):"",al=n=>n.slice(n.lastIndexOf("/")+1),sr=n=>n?`${At}/${n}`:At,cl=n=>n.split("/").some(e=>e.startsWith(".")),ts=n=>{if(!n)return!1;try{Xt(sr(n))}catch{return!1}return n.split("/").every(e=>Buffer.byteLength(e)<=255)};function yR(n){let e=n;if(!e||typeof e!="object"||e.version!==1||!e.files||typeof e.files!="object"||!e.gone||typeof e.gone!="object"||!Array.isArray(e.folders))return!1;for(let[t,r]of Object.entries(e.files))if(!t||!r||typeof r!="object"||typeof r.id!="string"||!mu.test(r.id)||typeof r.version!="string"||!r.version||!(r.hash===void 0||typeof r.hash=="string"&&yu.test(r.hash))||!Number.isSafeInteger(r.size)||r.size<0||!(r.excluded===void 0||r.excluded===!0)||!(r.wrote===void 0||r.wrote&&typeof r.wrote.version=="string"&&Number.isFinite(r.wrote.mtime)))return!1;for(let[t,r]of Object.entries(e.gone))if(!mu.test(t)||!r||typeof r.path!="string"||!r.path||!Number.isFinite(r.at))return!1;return e.folders.every(t=>typeof t=="string"&&!!t)&&(e.target===void 0||typeof e.target=="string")}var ns=class extends Error{code="REMOTE_NODE_MAP_UNREADABLE";file;constructor(e){super("remote_node_map_unreadable"),this.file=e,this.name="RemoteNodeMapError"}};async function bu(n){let e;try{e=await uR(n,"utf8")}catch(r){if(r.code==="ENOENT")return Py();throw new ns(n)}let t;try{t=JSON.parse(e)}catch{throw new ns(n)}if(!yR(t))throw new ns(n);return t.files=Mi(t.files),t.gone=Mi(t.gone),t}var Ni=n=>n.replace(/\.json$/,"")+".remote.json",En=(n,e=200)=>new Response(JSON.stringify(n),{status:e,headers:{"content-type":"application/json"}}),tt=(n,e,t,r={})=>En({code:e,detail:t,...r},n),wR=/^remote-(ignored-path|direction-pull|direction-push)$/;function hu(n){let e=n;if(n instanceof Nn||e?.code===Co)return tt(409,Co,"version_changed");if(e?.code==="TOO_LARGE"&&Number.isSafeInteger(e.maxBytes))return tt(413,"TOO_LARGE","content_too_large",{maxBytes:e.maxBytes});if(typeof e?.code=="string"&&wR.test(e.code))return tt(403,e.code,e.code);throw n}var wu=class{o;map=null;fileById=new Map;folderById=new Map;placeholders=new Map;kept=new Map;keptBytes=0;chain=Promise.resolve();constructor(e){this.o=e}now(){return this.o.now?.()??Date.now()}excludedPath(e){return!this.o.syncDotPaths&&cl(e)}async load(){if(this.map)return this.map;let e=await bu(this.o.mapFile);return e.target===this.o.targetLabel?this.map=e:((e.target!==void 0||Object.keys(e.files).length||Object.keys(e.gone).length)&&this.o.log?.(`[vault-sync] remote node map was for ${e.target??"an unlabeled target"}; starting fresh for ${this.o.targetLabel}`),this.map=Py(this.o.targetLabel))}async persist(e){try{await je(this.o.mapFile,e),this.map=e}catch(t){throw this.map=null,t}}open(){let e=this.o.target();if(!e)throw Object.assign(new Error("remote_target_not_open"),{code:"remote_target_not_open"});return e}request(e,t,r,i,o,a){let s=this.chain.then(()=>this.handle(t,r,i,o,a));return this.chain=s.catch(()=>{}),s}async handle(e,t,r,i,o){if(e===""&&t==="GET")return this.manifest(o);if(e==="/tombstones"&&t==="POST")return En({nodes:[]});if(e==="/nodes"&&t==="POST")return this.create(r);let a=/^\/nodes\/([^/]+)(\/content)?$/.exec(e);if(!a)return tt(404,"NOT_FOUND","unsupported_request");let s=decodeURIComponent(a[1]);return a[2]&&t==="GET"?this.readContent(s,o):a[2]&&t==="PUT"?this.writeContent(s,r,i,o):!a[2]&&t==="DELETE"?this.remove(s,r,i,o):!a[2]&&t==="PATCH"?tt(409,"REMOTE_NO_MOVE","remote targets have no move"):tt(404,"NOT_FOUND","unsupported_request")}async manifest(e){let t=this.open(),r=await this.load(),i=await t.list(e),o=Xr(r),a=this.now(),s=new Set,l=new Map,c=new Set,u=[],d=[];this.kept.clear(),this.keptBytes=0,this.placeholders.clear();let g=0,f=async S=>dR(fR(this.o.localRoot,...S.split("/"))).then(()=>!0,_=>_.code!=="ENOENT");for(let[S,_]of i.entries){if(s.add(S),_.kind==="folder"){ts(S)&&!this.excludedPath(S)&&this.o.inScope(S)&&d.push(S);continue}let R=r.files[S],N=_.backing==="other"||!ts(S);if(N||this.excludedPath(S)||!this.o.inScope(S)){N&&!this.excludedPath(S)&&u.push(sr(S)),R&&(o.files[S]={...R,excluded:!0});continue}let D=R?.id;if(!D)do D=Cy();while(o.gone[D]);let M=typeof _.hash=="string"&&yu.test(_.hash)?_.hash:R&&R.version===_.version&&R.hash?R.hash:void 0;if(!M&&!(this.o.direction==="push"&&!await f(S))){try{let $=await t.read(S,_.version,e);M=xy($.bytes);let O=Buffer.from($.bytes.buffer,$.bytes.byteOffset,$.bytes.byteLength);O.length<=pR&&this.keptBytes+O.length<=hR&&(this.kept.set(`${D}\0${_.version}`,O),this.keptBytes+=O.length)}catch($){if(e.aborted)throw await this.persist(Xr(o)).catch(()=>{}),$;this.o.log?.(`[vault-sync] remote hash ${S}: ${$.code??$?.name??"error"}`)}++g%mR===0&&await this.persist(Xr(o))}let x={id:D,version:_.version,size:_.size,...M?{hash:M}:{},...R?.wrote?{wrote:R.wrote}:{}};o.files[S]=x,l.set(S,x),M||c.add(S)}for(let[S,_]of Object.entries(r.files))s.has(S)||(_.excluded||(o.gone[_.id]={path:S,at:a}),delete o.files[S]);let p=new Set([...l.values()].map(S=>S.id));for(let[S,_]of Object.entries(o.gone))(a-_.at>gR||p.has(S))&&delete o.gone[S];let m=Object.entries(o.gone);if(m.length>Iy)for(let[S]of m.sort((_,R)=>_[1].at-R[1].at).slice(0,m.length-Iy))delete o.gone[S];let y=new Set([""]),b=S=>{for(let _=S;_;_=Fn(_))y.add(_)};for(let S of l.keys())b(Fn(S));for(let S of d)b(S);for(let S of[...l.keys()])y.has(S)&&(l.delete(S),c.delete(S),o.files[S]={...o.files[S],excluded:!0},u.push(sr(S)));let h=S=>{for(let _=S;_;_=Fn(_))if(l.has(_))return!0;return!1};o.folders=o.folders.filter(S=>!h(S));for(let S of o.folders)ts(S)&&!this.excludedPath(S)&&this.o.inScope(S)&&b(S);let E=[];this.folderById=new Map,this.fileById=new Map;for(let S of[...y].sort((_,R)=>(_?_.split("/").length:0)-(R?R.split("/").length:0)||_.localeCompare(R))){let _=Ln(S);this.folderById.set(_,S),E.push({id:_,parentId:S?Ln(Fn(S)):"",name:S?al(S):At,kind:"folder",revision:1,deleted:!1,path:sr(S)})}for(let[S,_]of l)this.fileById.set(_.id,S),E.push(this.fileNode(S,_,c.has(S),i.entries.get(S)?.mtime));let v=new Set,k=[];for(let[S,_]of Object.entries(o.gone))if(!(!ts(_.path)||this.excludedPath(_.path))){for(let R=Fn(_.path);R&&!y.has(R);R=Fn(R))v.add(R);k.push({id:S,parentId:this.parentIdOf(_.path,y),name:al(_.path),kind:"file",revision:1,deleted:!0,path:sr(_.path)})}for(let S of[...v].sort((_,R)=>_.split("/").length-R.split("/").length))E.push({id:Ty(S),parentId:this.parentIdOf(S,y),name:al(S),kind:"folder",revision:1,deleted:!0,path:sr(S)});E.push(...k),JSON.stringify(o)!==JSON.stringify(r)&&await this.persist(o),this.map=o;let C=i.limits.map(S=>({...S,prefix:S.prefix?`${At}/${S.prefix}`:""}));return En({schemaVersion:1,namespace:ll,folder:"remote",nodes:E,limits:C,otherPaths:u})}parentIdOf(e,t){let r=Fn(e);return t.has(r)?Ln(r):Ty(r)}fileNode(e,t,r,i){let o=t.wrote&&t.wrote.version===t.version&&(i===void 0||Math.abs(i-t.wrote.mtime)<2e3)?t.wrote.mtime:void 0;return{id:t.id,parentId:Ln(Fn(e)),name:al(e),kind:"file",revision:1,deleted:!1,path:sr(e),size:t.size,...r||!t.hash?{busy:!0}:{version:t.version,hash:t.hash},...o!==void 0?{mtime:o}:{}}}async create(e){let t=e,r=await this.load();if(!t||typeof t.name!="string"||t.kind!=="file"&&t.kind!=="folder")return tt(400,"INVALID","Invalid content node");let i=typeof t.parentId=="string"?this.folderById.get(t.parentId):void 0;if(i===void 0)return tt(409,"PARENT_UNAVAILABLE","Parent is unavailable");let o=i?`${i}/${t.name}`:t.name;if(!ts(o)||o.includes("\\"))return tt(400,"INVALID","Invalid content path");let a=r.files[o];if(t.kind==="folder"){if(a&&!a.excluded)return tt(409,"KIND","A different content type already has this name");if(!r.folders.includes(o)){let d=Xr(r);d.folders.push(o),await this.persist(d)}let u=Ln(o);return this.folderById.set(u,o),En({id:u,parentId:Ln(i?Fn(o):""),name:t.name,kind:"folder",revision:1,deleted:!1,path:sr(o)})}if(this.folderById.has(Ln(o)))return tt(409,"KIND","A different content type already has this name");if(a&&!a.excluded)return En(this.fileNode(o,a,!1,void 0));if(a?.excluded)return tt(409,"EXCLUDED","This path is not managed by this binding");let s=typeof t.id=="string"&&mu.test(t.id)?t.id.toLowerCase():Cy();if(r.gone[s])return tt(409,"DELETED","Content ID was deleted");let l=this.fileById.get(s);if(l!==void 0)return En(this.fileNode(l,r.files[l],!1,void 0));let c=s;return this.placeholders.set(c,o),En({id:c,parentId:Ln(i?Fn(o):""),name:t.name,kind:"file",revision:1,deleted:!1,path:sr(o)})}async readContent(e,t){let r=await this.load(),i=this.fileById.get(e),o=i===void 0?void 0:r.files[i];if(i===void 0||!o||o.excluded)return tt(404,"NOT_FOUND","Content node not found");let a=`${e}\0${o.version}`,s=this.kept.get(a);if(s)return this.kept.delete(a),this.keptBytes-=s.length,new Response(s);try{let l=await this.open().read(i,o.version,t);return new Response(Buffer.from(l.bytes.buffer,l.bytes.byteOffset,l.bytes.byteLength))}catch(l){return hu(l)}}async writeContent(e,t,r,i){let o=await this.load(),a=Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):null;if(!a)return tt(400,"INVALID","Body must be bytes");let s=r["X-Content-Version"],l,c;if(s==="create"){if(l=this.placeholders.get(e),c=null,l===void 0)return tt(409,"NOT_A_PLACEHOLDER","Content node has bytes or does not exist")}else{l=this.fileById.get(e);let m=l===void 0?void 0:o.files[l];if(l===void 0||!m||m.excluded||typeof s!="string"||!s)return tt(404,"NOT_FOUND","Content node not found");c=s}let u=Number(r["X-Content-Mtime"]),d=Number.isFinite(u)&&u>0?{mtimeMs:Math.floor(u)}:void 0,g;try{g=await this.open().write(l,a,c,i,d)}catch(m){return hu(m)}let f=yu.test(g.hash)?g.hash:xy(a),p=Xr(o);return p.files[l]={id:e,version:g.version,hash:f,size:a.length,...d?{wrote:{version:g.version,mtime:d.mtimeMs}}:{}},delete p.gone[e],this.placeholders.delete(e),this.fileById.set(e,l),await this.persist(p),En({version:g.version,hash:f})}async remove(e,t,r,i){let o=await this.load(),a=this.folderById.get(e);if(a!==void 0){if(a==="")return tt(409,"ROOT","The binding root cannot be deleted");if(Object.entries(o.files).some(([g,f])=>!f.excluded&&g.startsWith(a+"/")))return tt(409,"NOT_EMPTY","Folder is not empty");let d=Xr(o);return d.folders=d.folders.filter(g=>g!==a&&!g.startsWith(a+"/")),this.folderById.delete(e),await this.persist(d),En({ok:!0})}if(this.placeholders.delete(e))return En({ok:!0});let s=this.fileById.get(e),l=s===void 0?void 0:o.files[s];if(s===void 0||!l||l.excluded)return tt(404,"NOT_FOUND","Content node not found");let c=t?.version;if(typeof c!="string"||!c)return tt(409,Co,"version_changed");try{await this.open().remove(s,c,i,r["X-Content-Delete-Confirmed"]==="1")}catch(d){return hu(d)}let u=Xr(o);return delete u.files[s],u.gone[e]={path:s,at:this.now()},this.fileById.delete(e),await this.persist(u),En({ok:!0})}};function My(n){let e=n.binding,t=Vt(e.scope),r=null,i=null,o=async()=>r||(i??=n.open().then(l=>(r=l,l)).finally(()=>{i=null}),i),a=l=>!!r&&!!l&&(n.syncDotPaths||!cl(l))&&t(l)&&(r.inScope?.(l)??!0),s=new wu({target:()=>r,mapFile:Ni(n.stateFile),targetLabel:Zr(e.target),inScope:l=>!!r&&t(l)&&(r.inScope?.(l)??!0),direction:e.role==="backup"?"push":e.target.direction,localRoot:e.root,log:n.log,now:n.now,syncDotPaths:n.syncDotPaths});return{id:e.id,stateFile:n.stateFile,ns:ll,roots:async()=>(n.localOnly||await o(),[{prefix:At,root:e.root}]),inScope:l=>l===At||l.startsWith(At+"/")&&a(l.slice(At.length+1)),policy:n.policy,recovery:n.recovery,deviceId:n.deviceId,account:()=>"device",transport:s,vaultRoot:e.root,targetLabel:Zr(e.target),...n.onRound?{onRound:n.onRound}:{},...n.onDeferred?{onDeferred:n.onDeferred}:{},currentTarget:()=>r}}import{mkdir as kR,open as Ly,readFile as ER,rename as _R,unlink as RR}from"node:fs/promises";import{dirname as Fy,join as AR}from"node:path";import{randomUUID as CR}from"node:crypto";var bR="Amadeus/",vR=n=>!!n&&!Ot(n)&&!n.split("/").some(e=>e.startsWith("."));function Ny(n,e){let t=[];for(let r of n.libraries){if(r.deleted||r.kind==="legacy"&&!vR(r.name))continue;let i=r.devices.filter(o=>!e.includes(o.deviceId)).map(o=>o.name);t.push({id:r.vaultId,name:r.name,kind:r.kind,...r.kind==="legacy"?{prefix:r.prefix}:{},devices:i.length,deviceNames:i,files:r.files,libraryId:r.id})}return t}function SR(n,e,t){let r=e.toLowerCase();return n.filter(i=>i.vaults.some(o=>o.vaultId.toLowerCase()===r&&o.prefix===t)).map(i=>i.name)}function $y(n,e,t){if(!n.some(o=>typeof o.isDefault=="boolean")||e.some(o=>!Array.isArray(o.vaults)))return null;let r=ba(n);if(!r)return null;let i=e.filter(o=>!t.includes(o.id));return n.map(o=>{let a=SR(i,o.id,bR);return{id:o.id,name:o.name,kind:o.id===r.id?"default":"own",devices:a.length,deviceNames:a,files:null,libraryId:o.id}})}var IR="libraries.json",xR=6e4,TR=3e3,DR=3e4,By=6e4,PR=1e4,OR=6e4,MR=n=>n?.code==="ENOENT";async function NR(n,e,t,r){let i=n.libraryList??(n.libraries?async s=>({generatedAt:new Date(t()).toISOString(),libraries:await n.libraries(s)}):null);if(i)try{return{kind:"libraries",list:await i(e),fetchedAt:t()}}catch(s){if(!(s instanceof ze&&(s.status===404||s.code==="CLIENT_UPGRADE_REQUIRED")))throw s}let[o,a]=await Promise.allSettled([n.vaults(e),n.devices(e)]);for(let[s,l]of[["vaults",o],["devices",a]])l.status==="rejected"&&r?.(`[vault-sync] libraries fallback ${s}: ${String(l.reason?.message??l.reason)}`);return{kind:"unsupported",vaults:o.status==="fulfilled"?o.value:null,devices:a.status==="fulfilled"?a.value:null}}async function $R(n,e,t){await kR(Fy(n),{recursive:!0,mode:448});let r=`${n}.tmp-${CR()}`,i=!1;try{let o=await Ly(r,"wx",384);try{await o.writeFile(JSON.stringify(e)),await o.sync()}finally{await o.close()}t&&await t("before-rename").catch(a=>{throw i=!0,a}),await _R(r,n)}finally{i||await RR(r).catch(()=>{})}try{let o=await Ly(Fy(n),"r");try{await o.sync()}finally{await o.close()}}catch(o){if(!["EISDIR","EPERM","EINVAL"].includes(o.code??""))throw o}}async function LR(n,e){let t;try{t=await ER(n,"utf8")}catch(i){if(MR(i))return null;throw i}let r=JSON.parse(t);if(!r||r.version!==1||r.account!==ae(e)||!Number.isSafeInteger(r.fetchedAt)||r.fetchedAt<=0)throw Error("bad_libraries_cache");return{list:id(r.list),fetchedAt:r.fetchedAt}}var dl=class{entries=new Map;deps;closed=!1;constructor(e){this.deps=e}file(e){return AR(this.deps.home(),"vault-sync",ae(e),IR)}async reply(e,t={}){let r=this.entry(e);await this.loadDisk(r);let i=!1;if(t.refresh){let o=this.start(r,!0);o&&await o.done}else{let o=this.latest(r),a=r.doneSeq<r.want?r.flights.get(r.want)??null:this.due(r,DR)?this.start(r,!1):o&&o.seq>r.libSeq?o:null;a&&(await this.wait(r,a.seq,PR),i=r.flights.has(a.seq)&&a.seq>r.libSeq)}return this.result(r,i)}async views(e,t,r={}){let i=this.entry(e);await this.loadDisk(i);let o=this.due(i,xR)?this.start(i,!1):this.latest(i);if(!i.lib&&!this.unsupported(i)&&o&&r.wait!==!1){let a=o.startedAt+TR-this.deps.now();a>0&&await this.wait(i,o.seq,a)}return this.viewsOf(i,t)}refresh(e,t={}){let r=this.entry(e);if(t.dueMs!==void 0&&!this.due(r,t.dueMs))return;let i=this.start(r,!!t.mark,t.after);i&&t.mark&&(r.want=Math.max(r.want,i.seq))}fresh(e){let t=this.entries.get(e);return t?.lib&&t.libSeq>0&&t.libStartedAt!==null&&!this.unsupported(t)?{list:t.lib.list,startedAt:t.libStartedAt}:null}async idle(){for(;;){let e=[...this.entries.values()].flatMap(t=>[...t.flights.values()].map(r=>r.done));if(!e.length)break;await Promise.all(e)}await Promise.all([...this.entries.values()].map(e=>e.writes))}async close(){this.closed=!0,await Promise.all([...this.entries.values()].map(e=>e.writes))}entry(e){let t=this.entries.get(e);return t||(t={account:e,lib:null,libSeq:-1,libStartedAt:null,unsupportedSeq:-1,fbVaults:null,fbVaultsSeq:-1,fbDevices:null,fbDevicesSeq:-1,failSeq:0,failCode:null,disk:"unread",diskRead:null,seq:0,doneSeq:0,want:0,lastAttemptAt:null,flights:new Map,writes:Promise.resolve()},this.entries.set(e,t)),t}unsupported(e){return e.unsupportedSeq>e.libSeq}due(e,t){return e.lastAttemptAt===null||this.deps.now()-e.lastAttemptAt>=t}latest(e){let t=null;for(let r of e.flights.values())(!t||r.seq>t.seq)&&(t=r);return t}async loadDisk(e){e.lib||e.disk==="absent"||e.disk==="loaded"||(e.diskRead??=(async()=>{try{let t=await LR(this.file(e.account),e.account);if(e.lib)return;if(!t){e.disk="absent";return}e.lib={list:t.list,fetchedAt:t.fetchedAt},e.libSeq=-1,e.libStartedAt=null,e.disk="loaded"}catch(t){e.disk="unreadable",this.deps.log?.(`[vault-sync] libraries cache unreadable: ${String(t?.message??t)}`)}})().finally(()=>{e.diskRead=null}),await e.diskRead)}start(e,t,r){if(this.closed||this.deps.account()!==e.account)return null;if(!t){let f=this.latest(e);if(f)return f}let i=this.deps.api(),o=i.snapshot?.()??{account:this.deps.account(),api:i.pinned?.()??i};if(o.account!==e.account||this.deps.account()!==e.account)return null;let a=o.api,s=++e.seq,l=this.deps.now();e.lastAttemptAt=l;let c=AbortSignal.any([this.deps.signal(),AbortSignal.timeout(OR)]),u=()=>!this.closed&&this.deps.account()===e.account,d=Promise.resolve(r).catch(()=>{}).then(()=>NR(a,c,this.deps.now,this.deps.log)).then(f=>{if(u()){if(f.kind==="libraries"){if(s<=e.libSeq)return;e.lib={list:f.list,fetchedAt:f.fetchedAt},e.libSeq=s,e.libStartedAt=l,this.persist(e,f);try{this.deps.onFresh?.(e.account)}catch(p){this.deps.log?.(`[vault-sync] libraries onFresh: ${String(p?.message??p)}`)}return}e.unsupportedSeq=Math.max(e.unsupportedSeq,s),f.vaults&&s>e.fbVaultsSeq&&(e.fbVaults=f.vaults,e.fbVaultsSeq=s),f.devices&&s>e.fbDevicesSeq&&(e.fbDevices=f.devices,e.fbDevicesSeq=s)}},f=>{u()&&(s>e.failSeq&&(e.failSeq=s,e.failCode=f instanceof ze&&f.code==="not_signed_in"?"not_signed_in":null),this.deps.log?.(`[vault-sync] libraries: ${String(f?.message??f)}`))}).finally(()=>{e.doneSeq=Math.max(e.doneSeq,s),e.flights.delete(s)}),g={seq:s,startedAt:l,done:d};return e.flights.set(s,g),g}async wait(e,t,r){let i=e.flights.get(t);!i||r<=0||await new Promise(o=>{let a=setTimeout(o,r);a.unref?.(),i.done.then(()=>{clearTimeout(a),o()})})}persist(e,t){let r=this.file(e.account),i={version:1,account:ae(e.account),fetchedAt:t.fetchedAt,list:t.list};e.writes=e.writes.then(async()=>{this.closed||(await $R(r,i,this.deps.crash),e.disk="loaded")}).catch(o=>this.deps.log?.(`[vault-sync] libraries cache write: ${String(o?.message??o)}`))}result(e,t=!1){return this.unsupported(e)?{error:"server_unsupported"}:e.lib?{list:e.lib.list,fetchedAt:e.lib.fetchedAt,stale:t||e.failSeq>e.libSeq}:e.failCode==="not_signed_in"?{error:"not_signed_in"}:{error:e.disk==="unreadable"?"libraries_cache_unreadable":"not_fetched"}}viewsOf(e,t){return this.unsupported(e)?e.fbVaults&&e.fbDevices?$y(e.fbVaults,e.fbDevices,t):null:e.lib?Ny(e.lib.list,t):null}};import{stat as Nu,statfs as dA}from"node:fs/promises";import{basename as lw,dirname as uA,isAbsolute as cw,join as fA}from"node:path";import{readFile as tw,lstat as tA,unlink as nA}from"node:fs/promises";import{basename as lr}from"node:path";import{createHash as rA,randomUUID as is}from"node:crypto";import{isDeepStrictEqual as ew}from"node:util";import{isAbsolute as ul,join as FR,parse as vu,relative as BR,sep as Uy}from"node:path";import{readFile as jR}from"node:fs/promises";async function UR(n,e){let t;try{t=await n.host.syncTargets.list()}catch{throw Error("sync_targets_unreadable")}let r=Array.isArray(t)?t.find(o=>o?.id===e.targetId):void 0;if(!r||r.kind!=="folder"||typeof r.dirDefault!="string"||!ul(r.dirDefault))return null;let i=jy(await pe(r.dirDefault),r.dirDefault);return jy(await pe(e.dir?FR(i,...e.dir.split("/")):i),i)}var jy=(n,e)=>n&&ul(n)&&n!==vu(n).root.replace(/[\\/]+$/,"")?n:vu(ul(n)?n:e).root||Uy,VR=n=>vu(n).root===n;async function $i(n,e,t,r,i){if(r.kind!=="remote")return;let o=await UR(n,r);if(!o)return;let a;try{a=await n.host.syncTargets.vaults()}catch{throw Error("vault_list_unreadable")}let s=[t,...i.map(c=>c.root),...await Promise.all((Array.isArray(a)?a:[]).filter(c=>typeof c?.root=="string").map(c=>pe(c.root)))];e&&s.push(...await n.entrySyncRoots(e));try{s.push(ht(e))}catch{}let l=!1;try{l=pi(o)}catch{}if(VR(o)||l||s.some(c=>Jn(c,o)))throw Error("folder_target_nested")}async function Li(n,e,t){if(!e)return;let r=await n.manager.legacyContentState(e);if(r==="absent"||r==="off")return;let i;try{i=await n.host.contentSync.roots()}catch{throw Error("content_sync_active")}let o=await HR(n.manager.legacyContentFile(e)),a=[i,o?.roots??[]].map(s=>Array.isArray(s)?s.filter(l=>typeof l?.prefix=="string"&&typeof l?.root=="string"):[]);for(let s of a)for(let l of s)if(await zR(t,l,s,o?.rules??null))throw Error("content_sync_active")}async function zR(n,e,t,r){let i=await pe(e.root);if(!Jn(n,i))return!1;if(!r)return!0;let o=r.filter(c=>c.target!=="off"),a=c=>{if(!c)return!0;try{return Ze(t,c).root===e.root}catch{return!1}};if(o.some(c=>c.sourceId&&a(c.source)))return!0;let s=e.prefix;if(i.length<n.length){let c=BR(i,n).split(Uy).join("/");if(c.startsWith("..")||ul(c))return!0;s=c?e.prefix?`${e.prefix}/${c}`:c:e.prefix}let l=Hn(s,r);return l&&l.target!=="off"?!0:o.some(c=>!s||c.source===s||c.source.startsWith(s+"/"))}async function HR(n){try{let e=JSON.parse(await jR(n,"utf8"));return Gn(e),{rules:Zt(e.config,e.config.revision).rules,roots:e.roots??[]}}catch{return null}}import{lstat as XR,unlink as ZR}from"node:fs/promises";import{lstat as qR,readFile as WR}from"node:fs/promises";import{basename as GR,join as JR}from"node:path";var KR=(n,e)=>n.target.kind==="remote"?"device":ae(e??""),Su=n=>Object.assign(new Error(n),{code:n});async function Vy(n,e,t,r){let i;try{i=await WR(n.store.stateFile(e,t),"utf8")}catch(s){if(s.code==="ENOENT")return[];throw s}let o=JSON.parse(i).trash;if(o===void 0)return[];if(!Array.isArray(o))throw Su("state_unreadable");let a=[];for(let s of o){if(typeof s?.stage!="string")continue;let l=JR(typeof s.stageRoot=="string"?s.stageRoot:r,s.stage);await qR(l).then(()=>!0,c=>{if(c.code==="ENOENT")return!1;throw c})&&a.push(String(s.path??s.stage))}return a}async function Cr(n,e,t,r,i={}){if(!(await Vy(n,t,e.id,e.root)).length)return;await n.recoverLocalJournal(e,r,i);let o=await Vy(n,t,e.id,e.root);if(o.length)throw n.host.log?.(`[vault-sync] ${e.id}: unbind waits, ${o.length} local delete(s) not settled`),Su("local_pending")}async function pl(n,e,t,r){await mo(n.store,e,t,r)}async function zy(n,e,t,r,i,o){i&&await Cr(n,i,e,t),await pl(n,e,r,o.at),await n.crashUnbind("retired");let a=s=>{let l=s.bindings.filter(c=>c.id!==r);if(l.length!==s.bindings.length)return s.bindings=l,s};e==="device"?await n.store.updateDevice(a):t&&await n.store.updateAccount(t,a),await n.crashUnbind("removed"),await n.v3.update(e,s=>(delete s.marks[r],s.retired[r]={root:o.root,rootIdentity:o.rootIdentity,at:o.at},s))}async function Hy(n,e,t,r,i){let o=a=>{let s=a.bindings.find(l=>l.id===r);if(!(!s||s.generation!==i.generation))return s.enabled=!1,s.generation=i.generation+1,a};e==="device"?await n.store.updateDevice(o):await n.store.updateAccount(t,o)}var qy=n=>n.expectedTarget!==void 0||n.expectedGeneration!==void 0;function fl(n,{expectedTarget:e,expectedGeneration:t}){return!!n&&(t===void 0||n.generation===t)&&(e===void 0||n.target.kind==="penzor"&&n.target.vaultId===e?.vaultId&&n.target.prefix===e?.prefix)}var gl={ok:!1,error:"binding_changed"};async function YR(n,e,t,r){let i=r.binding,o=e??n.host.accountId(),a=qy(t);if(t.syncFirst===!0){if(!n.engineOf(i.id))return{ok:!1,error:"binding_not_running"};await n.runNow(i.id);let u=n.engineOf(i.id),d=(await n.bindings()).find(y=>y.b.id===i.id)?.b;if(a&&!fl(d,t))return gl;if(!u||!d||d.generation!==i.generation)return{ok:!1,error:"pending",pending:0,held:0,failures:0};let g;try{g=(await u.engine.heldList()).length}catch{return{ok:!1,error:"pending",pending:0,held:0,failures:0}}let f=u.engine.status(),p=u.engine.pendingChanges()+(f?.deletes?.pending??0),m=(f?.failures?.length??0)+(f?.skippedCount??0);if(p||g||m||!u.lastCompleted)return{ok:!1,error:"pending",pending:p,held:g,failures:m};i=d}let s=KR(i,e),l=await Ae(async()=>{if(a){let d=(await n.bindings()).find(g=>g.b.id===i.id);if(d?.account!==e||!fl(d.b,t)||d.b.generation!==i.generation)return gl;if(i=d.b,await ar(n,i.id))return{ok:!1,error:"move_in_progress"}}r.holding=!0;let u={at:n.now(),generation:i.generation,root:i.root,rootIdentity:i.rootIdentity};return await n.v3.update(s,d=>(d.marks[i.id]={...d.marks[i.id],unbinding:u},d)),await n.crashUnbind("intent"),await Hy(n,s,e,i.id,u),{ok:!0,intent:u}});if(!l.ok)return l;let{intent:c}=l;return await n.crashUnbind("disabled"),await n.refresh().catch(()=>{}),await n.stopEngineFor(i.id),await n.crashUnbind("stopped"),await zy(n,s,e,i.id,i,c),await n.refreshAfterBindingChange(o).catch(()=>{}),{ok:!0,root:i.root}}async function Wy(n,e){let t=e&&typeof e=="object"?e:{},{bindingId:r}=t;if(typeof r!="string")return{ok:!1,error:"binding_not_found"};let i=qy(t),o=f=>i&&!fl(f.binding,t)?gl:f.promise,a=n.unbinding.get(r);if(a)return o(a);let s=(await n.bindings()).find(f=>f.b.id===r);if(i&&!fl(s?.b,t))return gl;if(!s)return{ok:!1,error:"binding_not_found"};let{b:l,account:c}=s;if(l.state==="takeover"||l.firstRound==="takeover")return{ok:!1,error:"takeover_in_progress"};if(await ar(n,l.id))return{ok:!1,error:"move_in_progress"};let u=n.unbinding.get(r);if(u)return o(u);let d={root:l.root,binding:l,holding:!1};d.promise=YR(n,c,t,d).catch(f=>{if(f.code==="local_pending")return{ok:!1,error:"local_pending"};throw f});let g=d.promise;n.unbinding.set(r,d);try{return await g}finally{n.unbinding.get(r)===d&&n.unbinding.delete(r)}}async function Gy(n,e){let t=!1;for(let{scope:r,account:i}of e){let o=await n.v3.read(r),a=Object.entries(o.marks).filter(([,s])=>s.unbinding);if(a.length)for(let[s,l]of a){let c=l.unbinding,d=(r==="device"?(await n.store.readDevice()).bindings:(await n.store.readAccount(i)).bindings).find(g=>g.id===s);if(d?.enabled&&d.generation!==c.generation){await n.v3.update(r,g=>{let f=g.marks[s];return f&&(delete f.unbinding,Object.keys(f).length||delete g.marks[s]),g}),n.host.log?.(`[vault-sync] ${s}: unbind intent dropped (binding was re-enabled)`);continue}try{if(d?.enabled&&(await Ae(()=>Hy(n,r,i,s,c)),d=(r==="device"?(await n.store.readDevice()).bindings:(await n.store.readAccount(i)).bindings).find(g=>g.id===s),d?.enabled))continue;await zy(n,r,i,s,d,c),t=!0,n.host.log?.(`[vault-sync] ${s}: unbind resumed${d?` (${GR(d.root)})`:""}`)}catch(g){if(g.code!=="local_pending")throw g}}}return t}async function Jy(n,e,t){let r=(await n.v3.read(e)).retired[t];if(!r)return null;let i=await dt(r.root).catch(()=>null);if(!i||!Dt(r.rootIdentity,i))throw Su("root_changed");return r.root}var Yy={localOnly:!0},ku=n=>n.kind==="device"?"device":ae(n.account),QR=(n,e)=>n.kind==="remote"?{kind:"device"}:{kind:"account",account:e};async function Eu(n,e){return e.kind==="device"?(await n.store.readDevice()).bindings:(await n.store.readAccount(e.account)).bindings}async function hl(n,e,t){e.kind==="device"?await n.store.updateDevice(r=>t(r)?r:void 0):await n.store.updateAccount(e.account,r=>t(r)?r:void 0)}async function _u(n,e){let t=(await n.store.readDevice()).bindings.find(o=>o.id===e);if(t)return{b:t,ledger:{kind:"device"}};let r=n.host.accountId(),i=r?(await n.store.readAccount(r)).bindings.find(o=>o.id===e):void 0;return i?{b:i,ledger:{kind:"account",account:r}}:null}async function ar(n,e){if(n.kindMoving.has(e))return!0;let t=n.host.accountId();return(await n.v3.read("device")).marks[e]?.kindMove?!0:!!t&&!!(await n.v3.read(ae(t))).marks[e]?.kindMove}async function Ru(n,e,t){let r=n.host.accountId();if(!r)throw Error("not_signed_in");if(!n.full()||!["absent","off"].includes(await n.manager.legacyContentState(r)))throw Error("compat_mode");let i=[(await n.v3.read("device")).marks[e.id],(await n.v3.read(ae(r))).marks[e.id]];if(n.kindMoving.has(e.id)||i.some(o=>o?.kindMove))throw Error("move_in_progress");if(n.retargeting.has(e.id)||i.some(o=>o?.retarget))throw Error("retarget_in_progress");if(n.unbinding.has(e.id)||i.some(o=>o?.unbinding))throw Error("unbind_in_progress");if(e.state==="takeover"||e.firstRound==="takeover")throw Error("takeover_in_progress");if(e.state!=="active")throw Error("binding_not_active");if(e.enabled&&(e.firstRound==="pair"||e.firstRound==="scope"))throw Error("first_round_in_progress");if(t==="penzor"&&e.role==="backup")throw Error("backup_remote_only")}var eA=n=>{try{return[ht(n)]}catch{return[]}};async function Xy(n,e,t,r,i){if(t.kind!=="remote")return null;let o=yn.of(n.host);if(!o)return null;let a=i??await n.legacyAdmission();return await Yn({root:e.root,id:e.id,target:t},n.occupied(r.filter(s=>s.id!==e.id)),{released:await n.manager.releasedBindings(),legacy:a.occupant,identities:o}),o}async function Fi(n,e,t,r,i,o={mode:"all"},a){let s=p=>Error(p);if(jt(await n.entrySyncRoots(e),await pe(t.root)))return s("entry_sync_active");if((await n.manager.ledger.read()).entries.some(p=>p.source==="entry"&&p.bindingId===t.id&&p.phase==="reverted"))return s("takeover_in_progress");let l=n.occupied(i.filter(p=>p.id!==t.id)),c=Ke({root:t.root,id:t.id,role:t.role},l,r.kind==="penzor"?{mirrorDirs:eA(e)}:{});if(c)return s(c);let u=await n.legacyAdmission(),d=a===void 0?await Xy(n,t,r,i,u):a,g=null;if(r.kind==="remote")try{g=ho({root:t.root,id:t.id,target:r},l,{released:await n.manager.releasedBindings(),legacy:u.occupant,identities:d})}catch(p){return p}if(g)return Uc(g);if(tn(r,l,t.id))return s("already_local");let f=Bc(await pe(t.root),o,u.running);if(f)return new $r(f);if(r.kind==="remote")try{await $i(n,e,t.root,r,i),await Li(n,e,await pe(t.root))}catch(p){return p}return null}async function Ky(n,e,t){return n.unbinding.has(t)||!!(await n.v3.read(e)).marks[t]?.unbinding}async function rs(n,e,t){await n.v3.update(e,r=>{let i=r.marks[t];if(i?.kindMove)return delete i.kindMove,Object.keys(i).length||delete r.marks[t],r})}function Zy(n,e,t){if(n.kindMoving.has(e.id)||n.retargeting.has(e.id)||n.unbinding.has(e.id))return Promise.reject(Error("move_in_progress"));n.retargetEpoch(e.id);let r=(async()=>{let i=ku(t.from);await n.stopEngineFor(e.id),await Cr(n,e,i,t.from.kind==="account"?t.from.account:null,Yy),await n.crashKindMove("stopped"),await Ae(async()=>{if(n.host.accountId()!==t.account)throw Error("stale");let a=(await Eu(n,t.from)).find(l=>l.id===e.id);if(!a||a.generation!==e.generation)throw Error("stale");let s={to:t.target.kind==="remote"?"device":ae(t.account),generation:a.generation,at:n.now(),wasEnabled:a.enabled,target:t.target,scope:t.scope,onDiffer:t.onDiffer};await n.v3.update(i,l=>{let c=l.marks[e.id];if(c?.kindMove)throw Error("move_in_progress");if(c?.retarget)throw Error("retarget_in_progress");if(c?.unbinding)throw Error("unbind_in_progress");return l.marks[e.id]={...c,kindMove:s},l})}),n.kindMoveTried.set(e.id,n.now()),await n.crashKindMove("marked");let o=await Qy(n,i,e.id,t.seed);if(o==="stale")throw Error("stale");if(o==="waiting")throw Error(n.host.accountId()===t.account?"move_in_progress":"not_signed_in");return o==="done"})().finally(()=>{n.kindMoving.delete(e.id),n.retargetEpoch(e.id)});return n.kindMoving.set(e.id,{promise:r}),r}function Au(n,e,t){let r=n.kindMoving.get(t);if(r)return r.promise;n.retargetEpoch(t);let i=Qy(n,e,t).then(o=>o==="done").finally(()=>{n.kindMoving.delete(t),n.retargetEpoch(t)});return n.kindMoving.set(t,{promise:i}),i}async function Qy(n,e,t,r){let i=(await n.v3.read(e)).marks[t]?.kindMove;if(!i)return"unchanged";let o=n.host.accountId(),a=e==="device"?i.to:e;if(!o||ae(o)!==a)return"waiting";let s=e==="device"?{kind:"device"}:{kind:"account",account:o},l=QR(i.target,o);if(ku(l)!==i.to||ku(l)===e)return await rs(n,e,t),"stale";await n.stopEngineFor(t);let c=(await Eu(n,s)).find(g=>g.id===t),u=(await Eu(n,l)).find(g=>g.id===t);if(!u&&await Ky(n,i.to,t))return"waiting";let d=u?void 0:(await n.v3.read(i.to)).retired[t];if(d&&d.at>=i.at&&n.host.log?.(`[vault-sync] ${t}: moved binding was unbound at the new target meanwhile; finishing the move without rebuilding it`),!u&&!(d&&d.at>=i.at)){if(!n.full()||!["absent","off"].includes(await n.manager.legacyContentState(o)))return"waiting";if(!c||c.generation!==i.generation)return n.host.log?.(`[vault-sync] ${t}: kind move mark is stale (binding changed or gone), dropped`),await rs(n,e,t),"stale";await Cr(n,c,e,s.kind==="account"?s.account:null,Yy),await Ae(()=>hl(n,s,y=>{let b=y.bindings.find(h=>h.id===t);if(!(!b||b.generation!==i.generation||!b.enabled))return b.enabled=!1,y})),await n.crashKindMove("disabled"),await pl(n,e,t,i.at),await pl(n,i.to,t,i.at),await n.crashKindMove("retired");let g=Ni(n.store.stateFile("device",t)),f=!!r&&i.target.kind==="remote"&&!await XR(g).then(()=>!0,y=>y.code!=="ENOENT")&&await je(g,{version:1,files:r,gone:{},folders:[],target:Zr(i.target)}).then(()=>!0,()=>!1),p="stale",m=null;try{let y=i.target.kind==="remote"&&typeof n.host.syncTargets?.identity=="function"?await Xy(n,c,i.target,[...(await n.store.readAccount(o)).bindings,...(await n.store.readDevice()).bindings]):null;await Ae(async()=>{if(n.host.accountId()!==o){p="away";return}if(await Ky(n,i.to,t)){p="away";return}let[b,h]=[(await n.store.readAccount(o)).bindings,(await n.store.readDevice()).bindings];if(c=(s.kind==="device"?h:b).find(k=>k.id===t),(l.kind==="device"?h:b).some(k=>k.id===t)){p="written";return}if(!c||c.generation!==i.generation){p="stale";return}let E=await Fi(n,o,c,i.target,[...b,...h],i.scope,y);if(E){p=E.message,m=E;return}let v=c;await hl(n,l,k=>{if(k.bindings.some(S=>S.id===t))return;let C=v.role;return k.bindings.push({id:t,root:v.root,rootIdentity:v.rootIdentity,nameKey:v.nameKey,target:i.target,scope:i.scope,enabled:i.wasEnabled,paused:v.paused,state:"active",role:C,generation:v.generation+1,firstRound:"pair",firstRoundOnDiffer:i.onDiffer,createdAt:v.createdAt}),k}),p="written"})}finally{p!=="written"&&f&&await ZR(g).catch(()=>{})}if(p==="away")return"waiting";if(p==="stale")return n.host.log?.(`[vault-sync] ${t}: kind move mark is stale (binding changed or gone), dropped`),await rs(n,e,t),"stale";if(p!=="written")throw await Ae(()=>hl(n,s,y=>{let b=y.bindings.find(h=>h.id===t);if(!(!b||b.generation!==i.generation||b.firstRound))return b.firstRound="pair",b.firstRoundOnDiffer="hold",y})),await rs(n,e,t),n.host.log?.(`[vault-sync] ${t}: kind move refused at the new target (${p}); the binding stays stopped`),m??Error(p);await n.crashKindMove("written")}return await hl(n,s,g=>{let f=g.bindings.filter(p=>p.id!==t);if(f.length!==g.bindings.length)return g.bindings=f,g}),await n.crashKindMove("removed"),await rs(n,e,t),n.host.log?.(`[vault-sync] ${t}: moved to ${i.target.kind==="remote"?"the device ledger (folder / drive target)":"the account ledger (Penzor)"}`),"done"}var ml=10*6e4;function yl(n){try{return[ht(n)]}catch{return[]}}var cr=n=>n?`${n.root}\0${n.state}`:void 0,Cu={kind:"penzor",vaultId:"",ns:"vault-pending",prefix:"Amadeus/",placement:"own"},ss=n=>({kind:"penzor",vaultId:n,ns:`vault-${n.toLowerCase()}`,prefix:"Amadeus/",placement:"own"}),Du=n=>({kind:"penzor",vaultId:n,ns:"default",prefix:di,placement:"default"}),wl=new Map,Iu=new Map,Bi=n=>rA("sha256").update(n).digest("hex");function nw(n,e,t){if(t.placement!=="default")return n;let r=n.snapshot?.();if(r&&r.account!==e)throw Error("stale");return r?.api??n}function rw(n,e){if(e&&e.target.kind==="penzor"&&!(n.target.kind==="penzor"&&n.target.candidate))return{target:e.target};let r=n.target.candidate;if(!r)throw Error("candidate_required");if(r.kind==="new"){let i=lr(e?.root??n.root);if(qn(i))throw Error("invalid_name");if(r.name!==void 0&&(typeof r.name!="string"||Le(r.name)!==Le(i)))throw Error("name_mismatch");if(uo(i))throw Error("reserved");return{target:Cu,create:i}}if(r.kind==="own")return{target:ss(r.vaultId)};if(r.kind==="default"){if(typeof r.vaultId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(r.vaultId))throw Error("invalid_candidate");if(Le(lr(e?.root??n.root))!==Le(yr))throw Error("name_mismatch");return{target:Du(r.vaultId)}}if(r.kind!=="legacy"||typeof r.prefix!="string"||!r.prefix)throw Error("invalid_candidate");return{target:{kind:"penzor",vaultId:r.vaultId,ns:"default",prefix:r.prefix.endsWith("/")?r.prefix:r.prefix+"/",placement:"legacy-entry"}}}async function bl(n,e,t,r,i){let o=t.prefix.replace(/\/+$/,""),a=Vt(r),s=i?Vt(i):()=>!1,l=R=>!Ot(R)&&!R.split("/").some(N=>N.startsWith(".")),c=t===Cu?{nodes:[],limits:void 0}:await n.manifest(t.ns),u=t===Cu?[]:si(c);if(t.ns==="default"&&u.some(R=>R.prefix===t.prefix))throw Error("vault_moved");let d=[],g=[];t.placement==="default"&&(vr(c,t.ns),d=await Ta(e,await ca(n,t.vaultId),c),g=c.nodes.filter(R=>!R.deleted&&R.version&&!Eo(R)&&R.path.startsWith(t.prefix)).map(R=>R.path).sort());let f=new Set(g),p=R=>{let N=`${o}/${R}`;return l(R)&&a(R)&&!s(R)&&!f.has(N)&&!d.some(D=>N===D||N.startsWith(D+"/"))},m=new Map,y=[];for(let R of c.nodes){if(R.deleted||R.kind!=="file"||!Eo(R)||!R.path.startsWith(o+"/"))continue;let N=R.path.slice(o.length+1);p(N)&&m.set(N,{hash:R.hash,version:R.version,mtime:R.mtime,size:R.size})}let b=await bn([{prefix:o,root:e}],{markers:!1});if(b.unscanned.length)throw Error("scope_unreadable");let h=new Map;for(let R of b){if(R.kind!=="file")continue;let N=R.path.slice(o.length+1);if(!p(N))continue;let D=Qt(R.path,t.ns,c.limits);if(R.size>D){y.push({path:N,size:R.size,maxBytes:D});continue}h.set(N,{hash:Bi(await tw(R.physical)),mtime:R.mtime,size:R.size})}let E=0,v=0,k=0,C=[],S=[];for(let[R,N]of h){let D=m.get(R);if(S.push(`${R}\0${N.hash}\0${N.mtime}\0${D?.version??""}\0${D?.mtime??""}`),!D){v++;continue}if(D.hash===N.hash){E++;continue}C.push({path:R,newer:D.mtime===void 0||D.mtime===N.mtime?null:N.mtime>D.mtime?"local":"remote"})}for(let[R,N]of m)N.size!==void 0&&N.size>Qt(o+"/"+R,t.ns,c.limits)&&y.push({path:R,size:N.size,maxBytes:Qt(o+"/"+R,t.ns,c.limits)}),h.has(R)||(k++,S.push(`${R}\0\0\0${N.version??""}\0${N.mtime??""}`));return S.sort(),{value:{generation:Bi(JSON.stringify([t,r,i,d,g,S])).slice(0,32),match:t.placement==="legacy-entry"||t.placement==="legacy-root"?"legacy":t.placement,same:E,onlyLocal:v,onlyRemote:k,differ:C.sort((R,N)=>R.path.localeCompare(N.path)),tooLarge:y},excluded:[...d,...g]}}async function ji(n,e,t){if(t?.role!==void 0&&t.role!=="primary"&&t.role!=="backup")throw Error("invalid_role");if(t?.bindingId){let d=await _u(n,t.bindingId);if(d&&(t.target?.kind==="penzor"||t.target?.kind==="remote")&&d.b.target.kind!==t.target.kind)return lA(n,e,t,d);if(d&&await ar(n,d.b.id))throw Error("move_in_progress")}if(t?.target?.kind==="remote")return sA(n,t);if(t?.role==="backup"&&!t.bindingId)throw Error("backup_remote_only");let r=n.host.accountId();if(!r)throw Error("not_signed_in");if(t.target.kind!=="penzor")throw Error("invalid_target");let i=t.bindingId?(await n.store.readAccount(r)).bindings.find(d=>d.id===t.bindingId):void 0;if(t.bindingId&&!i)throw Error("binding_not_found");if(i&&(i.state==="takeover"||i.firstRound==="takeover"))throw Error("takeover_in_progress");if(!i){let d=await pe(t.root),g=Ke({root:d,role:"primary"},(await n.bindings()).map(f=>f.b));if(g)throw Error(g);nn(d,t.scope,(await n.legacyAdmission()).running)}let{target:o,create:a}=rw(t,i);if(i&&ai(i.target)!==ai(o))throw Error("default_retarget_unsupported");if(i&&po(i,t.scope,o)&&nn(await pe(i.root),t.scope,(await n.legacyAdmission()).running),a&&(await e.resolve(a).catch(g=>{throw g instanceof ze&&g.status===404?Error("server_unsupported"):g instanceof ze&&g.code==="RESERVED"?Error("reserved"):g})).length)throw Error("name_exists");let s=i&&JSON.stringify(i.target)===JSON.stringify(o),{value:l}=await bl(nw(e,r,o),i?.root??t.root,o,t.scope,s?i.scope:null),c=is(),u={token:c,expiresAt:Date.now()+ml,...l,...a?{match:"none"}:{}};return Iu.set(c,{args:t,target:o,...a?{create:a}:{},account:r,value:u,at:Date.now(),seen:cr(i)}),u}async function Ui(n,e,t,r={}){if(os.has(t.token))return cA(n,e,t,r);if(wl.has(t.token))return aA(n,t);let i=Iu.get(t.token);if(Iu.delete(t.token),i?.args.bindingId&&await ar(n,i.args.bindingId))throw Error("move_in_progress");let o=n.host.accountId(),a=()=>{if(r.expectedAccountId!==void 0&&n.host.accountId()!==r.expectedAccountId)throw Error("account_changed")};if(a(),!i||i.value.expiresAt<Date.now()||i.value.generation!==t.generation||i.account!==o||r.account!==void 0&&r.account!==o)return{error:"stale"};let s=i.args.bindingId?(await n.store.readAccount(o)).bindings.find(h=>h.id===i.args.bindingId):void 0;if(cr(s)!==i.seen)return{error:"stale"};let l=s&&JSON.stringify(s.target)===JSON.stringify(i.target),c=await bl(nw(e,o,i.target),s?.root??i.args.root,i.target,i.args.scope,l?s.scope:null);if(c.value.generation!==t.generation)return{error:"stale"};let u=t.onDiffer==="newer"?"newer":"hold",d=i.target.placement==="default"&&c.excluded.length?{firstRoundExclusions:c.excluded}:{},g=s?s.root:await pe(i.args.root);if(!s&&i.target.placement==="default"&&Le(lr(g))!==Le(yr))throw Error("name_mismatch");let f=async()=>{if(s)return;if(n.host.accountId()!==o)throw Error("stale");if(await n.v3.read("device"),await n.v3.read(Bi(o)),jt(await n.entrySyncRoots(o),g))throw Error("entry_sync_active");let h=n.occupied((await n.bindings()).map(v=>v.b)),E=Ke({root:g,role:"primary"},h,{mirrorDirs:yl(o)});if(E)throw Error(E);if(tn(i.target,h))throw Error("already_local");nn(g,i.args.scope,(await n.legacyAdmission()).running),await r.admit?.(g)};await f();let p=!!s&&po(s,i.args.scope,i.target),m=p?await pe(s.root):"";if(p&&nn(m,i.args.scope,(await n.legacyAdmission()).running),i.create){a();try{i.target=ss((await e.createVault(i.create)).id)}catch(h){if(h instanceof ze&&h.status===409&&(h.code==="EXISTS"||h.code==="LEGACY_PLACEMENT"))return{error:"stale"};throw h}}if(!s&&i.target.placement==="legacy-entry"){let h=n.host.contentSync.ownership,E=await h.get(o);E.entryRoots.map(v=>v.replace(/[\\/]+$/,"")).includes(g)||await h.set({...E,entryRoots:[...E.entryRoots,g]},o)}let y=s?.id??"",b=!s;return await Ae(async()=>{if(i.target.placement==="default"&&n.host.accountId()!==o)throw Error("stale");if(s){let v=(await n.store.readDevice()).bindings,k=p?(await n.legacyAdmission()).running:null;await n.store.updateAccount(o,C=>{let S=C.bindings.find(_=>_.id===s.id);if(!S||S.generation!==s.generation||cr(S)!==i.seen)throw Error("stale");if(S.state==="takeover"||S.firstRound==="takeover")throw Error("takeover_in_progress");if(!l&&tn(i.target,[...C.bindings,...v],S.id))throw Error("already_local");if(p&&nn(m,i.args.scope,k),b=!ew(S.target,i.target)||!ew(S.scope,i.args.scope),l?S.firstRoundPrevScope=S.scope:delete S.firstRoundPrevScope,i.target.placement==="default"&&(delete S.firstRoundExclusions,Object.assign(S,d)),S.scope=i.args.scope,S.target=i.target,S.generation+=1,S.firstRound=l?"scope":"pair",S.firstRoundOnDiffer=u,S.state==="needs-rename-answer"&&!l){let _=Ke({root:S.root,id:S.id,role:S.role},[...C.bindings.filter(R=>R.id!==S.id),...v]);if(_)throw Error(_);S.state="active",S.paused=!1,S.nameKey=Le(lr(S.root)),delete S.renamedFrom}return C});return}await f();let h=await dt(g),E=(await n.store.readDevice()).bindings;await n.store.updateAccount(o,v=>{a();let k=Ke({root:g,role:"primary"},n.occupied([...v.bindings,...E]),{mirrorDirs:yl(o)});if(k)throw Error(k);if(tn(i.target,[...v.bindings,...E]))throw Error("already_local");return y=li(),v.bindings.push({id:y,root:g,rootIdentity:h,nameKey:Le(lr(g)),target:i.target,scope:i.args.scope,enabled:!0,paused:!1,state:"active",role:"primary",generation:1,firstRound:"pair",firstRoundOnDiffer:u,...d,createdAt:Date.now()}),v})}),await n.refreshAfterBindingChange(b?o:null),n.runNow(y),{bindingId:y}}var iA=["both","push","pull"];function iw(n,e,t,r){let i=n.target;if(typeof i.targetId!="string"||!i.targetId)throw Error("invalid_target");let o=t?.target.kind==="remote"?t.target:null,a=typeof i.dir=="string"?i.dir.replace(/^\/+|\/+$/g,""):o&&o.targetId===i.targetId?o.dir:lr(e);if(a&&!Kn(a))throw Error("bad-target-dir");let s=i.direction??o?.direction??"both";if(!iA.includes(s))throw Error("invalid_direction");return{kind:"remote",targetId:i.targetId,dir:a,direction:r==="backup"?"push":s,ignore:o?[...o.ignore]:[],maxFileBytes:o?.maxFileBytes??null}}async function oA(n){let e=Io();if(!e)throw Object.assign(new Error("server_unsupported"),{code:"server_unsupported"});return e(n)}async function vl(n,e,t,r){let i=await oA(n),o=AbortSignal.timeout(30*6e4),a,s=!1;try{a=await i.list(o)}catch(_){if(!gh(_)||!r.newBinding)throw _;if(!i.mkdir)throw Object.assign(new Error("target_dir_missing"),{code:"target_dir_missing"});s=!0,a={entries:new Map,limits:i.limits()}}let l=Vt(e),c=t?Vt(t):()=>!1,u=_=>!!_&&!cl(_)&&l(_)&&!c(_)&&(i.inScope?.(_)??!0),d=a.limits.map(_=>({..._,prefix:_.prefix?`${At}/${_.prefix}`:""})),g=_=>Qt(`${At}/${_}`,ll,d),f=[],p=new Map;for(let[_,R]of a.entries)if(!(R.kind!=="file"||!u(_))){if(R.size>g(_)){f.push({path:_,size:R.size,maxBytes:g(_)});continue}R.backing!=="other"&&p.set(_,{version:R.version,size:R.size,...typeof R.hash=="string"&&/^[a-f0-9]{64}$/.test(R.hash)?{hash:R.hash}:{}})}let m=await bn([{prefix:At,root:n.root}],{markers:!1});if(m.unscanned.length)throw Error("scope_unreadable");let y=new Map;for(let _ of m){if(_.kind!=="file")continue;let R=_.path.slice(At.length+1);if(u(R)){if(_.size>g(R)){f.push({path:R,size:_.size,maxBytes:g(R)});continue}y.set(R,{hash:Bi(await tw(_.physical)),mtime:_.mtime,size:_.size})}}let b=0,h=0,E=0,v=[],k=[],C=Object.create(null);for(let[_,R]of y){let N=p.get(_);if(!N){h++,k.push(`${_}\0${R.hash}\0${R.mtime}\0\0`);continue}let D=r.map?.files[_],M=N.hash??(D&&D.version===N.version?D.hash:void 0)??r.hashes.get(`${_}\0${N.version}`);if(M||(M=await i.read(_,N.version,o).then($=>Bi($.bytes),()=>{}),M&&r.hashes.set(`${_}\0${N.version}`,M)),M&&(C[_]={id:is(),version:N.version,hash:M,size:N.size}),k.push(`${_}\0${R.hash}\0${R.mtime}\0${N.version}\0${M??""}`),M===R.hash){b++;continue}let x=D?.wrote&&D.wrote.version===N.version?D.wrote.mtime:void 0;v.push({path:_,newer:x===void 0||Math.floor(x)===Math.floor(R.mtime)?null:R.mtime>x?"local":"remote"})}for(let[_,R]of p)y.has(_)||(E++,k.push(`${_}\0\0\0${R.version}\0${R.hash??""}`),R.hash&&(C[_]={id:is(),version:R.version,hash:R.hash,size:R.size}));return k.sort(),{value:{generation:Bi(JSON.stringify([n.target,e,t,s,k,n.role])).slice(0,32),match:"none",same:b,onlyLocal:h,onlyRemote:E,differ:v.sort((_,R)=>_.path.localeCompare(R.path)),tooLarge:f},target:i,dirMissing:s,seed:C}}async function ow(n,e){let t=e.bindingId?(await n.store.readDevice()).bindings.find(g=>g.id===e.bindingId):void 0;if(e.bindingId&&!t)throw Error("binding_not_found");if(t&&(t.state==="takeover"||t.firstRound==="takeover"))throw Error("takeover_in_progress");let r=t?.root??e.root;if(typeof r!="string"||!r)throw Error("invalid_root");let i=t?r:await pe(r),o=t?t.role:e.role==="backup"?"backup":"primary",a=iw(e,i,t,o),s=!!t&&t.target.kind==="remote"&&t.target.targetId===a.targetId&&t.target.dir===a.dir,l={...t??{id:"preview",root:i,rootIdentity:{dev:0,ino:0},nameKey:Le(lr(i)),scope:e.scope,enabled:!0,paused:!1,state:"active",role:o,generation:0,createdAt:0},target:a},c=t&&s?await bu(Ni(n.store.stateFile("device",t.id))):null,u=c&&c.target===Zr(a)?c:null,d=t?await pe(i):i;return{existing:t,root:i,liveRoot:d,target:a,sameTarget:s,pseudo:l,map:u,role:o}}function sw(n,e,t,r){if(n.existing){n.sameTarget||Xn({root:n.existing.root,id:n.existing.id,target:n.target},e,t),po(n.existing,r,n.target)&&nn(n.liveRoot,r,t.running);return}let i=Ke({root:n.root,role:n.role},e);if(i)throw Error(i);Xn({root:n.root,target:n.target},e,t),nn(n.root,r,t.running)}async function xu(n,e,t){let r=n.host.accountId();(!e.existing||!e.sameTarget)&&await $i(n,r,e.existing?.root??e.root,e.target,t),e.existing||await Li(n,r,e.root)}var Tu=async(n,e)=>{let t=await n.legacyAdmission();return{released:await n.manager.releasedBindings(),legacy:t.occupant,running:t.running,identities:e}},aw=async(n,e,t,r)=>{let i=n.occupied(t);e.existing?e.sameTarget||await Yn({root:e.existing.root,id:e.existing.id,target:e.target},i,r):await Yn({root:e.root,target:e.target},i,r)};async function sA(n,e){let t=await ow(n,e),r=(await n.bindings()).map(c=>c.b),i=await Tu(n,yn.of(n.host));await aw(n,t,r,i),sw(t,r,i,e.scope),await xu(n,t,r);let o=new Map,{value:a}=await vl(t.pseudo,e.scope,t.sameTarget?t.existing.scope:null,{map:t.map,newBinding:!t.sameTarget,hashes:o}),s=is(),l={token:s,expiresAt:Date.now()+ml,...a};return wl.set(s,{args:e,target:t.target,value:l,at:Date.now(),hashes:o,seen:cr(t.existing)}),l}async function aA(n,e){let t=wl.get(e.token);if(wl.delete(e.token),!t||t.value.expiresAt<Date.now()||t.value.generation!==e.generation)return{error:"stale"};if(t.args.bindingId&&await ar(n,t.args.bindingId))throw Error("move_in_progress");let r=await ow(n,t.args);if(JSON.stringify(r.target)!==JSON.stringify(t.target)||cr(r.existing)!==t.seen)return{error:"stale"};let i=(await n.bindings()).map(d=>d.b),o=yn.of(n.host),a=await Tu(n,o);await aw(n,r,i,a),sw(r,i,a,t.args.scope),await xu(n,r,i);let s=await vl(r.pseudo,t.args.scope,r.sameTarget?r.existing.scope:null,{map:r.map,newBinding:!r.sameTarget,hashes:t.hashes});if(s.value.generation!==e.generation)return{error:"stale"};let l=e.onDiffer==="newer"?"newer":"hold";if(s.dirMissing){let d=AbortSignal.timeout(6e4);await s.target.mkdir("",d),await s.target.list(d)}let c=r.existing?.id??"",u=n.host.accountId();return await Ae(async()=>{let d=u?(await n.store.readAccount(u)).bindings:[],g=await Tu(n,o);if(await xu(n,r,(await n.bindings()).map(h=>h.b)),r.existing){let h=r.existing;await n.store.updateDevice(E=>{let v=E.bindings.find(k=>k.id===h.id);if(!v||v.generation!==h.generation||cr(v)!==t.seen)throw Error("stale");if(v.state==="takeover"||v.firstRound==="takeover")throw Error("takeover_in_progress");if(r.sameTarget||Xn({root:v.root,id:v.id,target:r.target},[...E.bindings,...d],g),po(v,t.args.scope,r.target)&&nn(r.liveRoot,t.args.scope,g.running),r.sameTarget?v.firstRoundPrevScope=v.scope:delete v.firstRoundPrevScope,v.scope=t.args.scope,v.target=r.target,v.generation+=1,v.firstRound=r.sameTarget?"scope":"pair",v.firstRoundOnDiffer=l,v.state==="needs-rename-answer"&&!r.sameTarget){let k=Ke({root:v.root,id:v.id,role:v.role},[...E.bindings.filter(C=>C.id!==v.id),...d]);if(k)throw Error(k);v.state="active",v.paused=!1,v.nameKey=Le(lr(v.root)),delete v.renamedFrom}return E});return}let f=r.root;if(u&&jt(await n.entrySyncRoots(u),f))throw Error("entry_sync_active");let p=await dt(f);c=li();let m=Ni(n.store.stateFile("device",c)),y={version:1,files:s.seed,gone:{},folders:[],target:Zr(r.target)},b=!await tA(m).then(()=>!0,h=>h.code!=="ENOENT")&&await je(m,y).then(()=>!0,()=>!1);await n.store.updateDevice(h=>{let E=n.occupied([...h.bindings,...d]),v=Ke({root:f,role:r.role},E);if(v)throw Error(v);return Xn({root:f,target:r.target},E,g),nn(f,t.args.scope,g.running),h.bindings.push({id:c,root:f,rootIdentity:p,nameKey:Le(lr(f)),target:r.target,scope:t.args.scope,enabled:!0,paused:!1,state:"active",role:r.role,generation:1,firstRound:"pair",firstRoundOnDiffer:l,createdAt:Date.now()}),h}).catch(async h=>{throw b&&await nA(m).catch(()=>{}),h})}),await n.refresh(),n.runNow(c),{bindingId:c}}var os=new Map;async function lA(n,e,t,r){let i=r.b,o=t.target.kind;if(ai(i.target)||t.target.kind==="penzor"&&t.target.candidate?.kind==="default")throw Error("default_retarget_unsupported");await Ru(n,i,o);let a=n.host.accountId(),s=(await n.bindings()).map(p=>p.b),l=is();if(o==="remote"){let p=iw(t,i.root,void 0,i.role),m=await Fi(n,a,i,p,s,t.scope);if(m)throw m;let y=new Map,{value:b}=await vl({...i,target:p},t.scope,null,{map:null,newBinding:!0,hashes:y}),h={token:l,expiresAt:Date.now()+ml,...b};return os.set(l,{args:t,kind:o,target:p,account:a,from:r.ledger.kind,gen:i.generation,seen:cr(i),value:h,hashes:y}),h}let{target:c,create:u}=rw({...t,root:i.root},void 0);if(u&&(await e.resolve(u).catch(m=>{throw m instanceof ze&&m.status===404?Error("server_unsupported"):m instanceof ze&&m.code==="RESERVED"?Error("reserved"):m})).length)throw Error("name_exists");let d=await Fi(n,a,i,c,s,t.scope);if(d)throw d;let{value:g}=await bl(e,i.root,c,t.scope,null),f={token:l,expiresAt:Date.now()+ml,...g,...u?{match:"none"}:{}};return os.set(l,{args:t,kind:o,target:c,...u?{create:u}:{},account:a,from:r.ledger.kind,gen:i.generation,seen:cr(i),value:f,hashes:new Map}),f}async function cA(n,e,t,r){let i=os.get(t.token);if(os.delete(t.token),!n.host.accountId())throw Error("not_signed_in");let o=await _u(n,i.args.bindingId);if(!o)throw Error("binding_not_found");await Ru(n,o.b,i.kind);let a=n.host.accountId(),s=o.b;if(i.value.expiresAt<Date.now()||i.value.generation!==t.generation||i.account!==a||r.account!==void 0&&r.account!==a||o.ledger.kind!==i.from||s.generation!==i.gen||cr(s)!==i.seen)return{error:"stale"};let l=t.onDiffer==="newer"?"newer":"hold",c=i.target,u;if(c.kind==="remote"){let g=await vl({...s,target:c},i.args.scope,null,{map:null,newBinding:!0,hashes:i.hashes});if(g.value.generation!==t.generation)return{error:"stale"};let f=await Fi(n,a,s,c,(await n.bindings()).map(p=>p.b),i.args.scope);if(f)throw f;if(g.dirMissing){let p=AbortSignal.timeout(6e4);await g.target.mkdir("",p),await g.target.list(p)}u=g.seed}else{if((await bl(e,s.root,c,i.args.scope,null)).value.generation!==t.generation)return{error:"stale"};let f=await Fi(n,a,s,c,(await n.bindings()).map(p=>p.b),i.args.scope);if(f)throw f;if(i.create){if(n.host.accountId()!==a)return{error:"stale"};try{c=ss((await e.createVault(i.create)).id)}catch(p){if(p instanceof ze&&p.status===409&&(p.code==="EXISTS"||p.code==="LEGACY_PLACEMENT"))return{error:"stale"};throw p}}if(c.placement==="legacy-entry"){let p=n.host.contentSync.ownership,m=await p.get(a);m.entryRoots.map(y=>y.replace(/[\\/]+$/,"")).includes(s.root)||await p.set({...m,entryRoots:[...m.entryRoots,s.root]},a)}}if(n.host.accountId()!==a)return{error:"stale"};let d;try{d=await Zy(n,s,{from:o.ledger,account:a,target:c,scope:i.args.scope,onDiffer:l,...u?{seed:u}:{}})}catch(g){if(g?.message==="stale")return{error:"stale"};throw g}return await n.refreshAfterBindingChange(d?a:null),n.runNow(s.id),{bindingId:s.id}}var xe=(n,e={})=>({ok:!1,error:n,...e}),dw=n=>n&&typeof n=="object"?n:{},Vi=class extends Error{failure;constructor(e){super(e.error),this.failure=e}},Sl=class extends Error{constructor(){super("stale")}},$u=n=>n instanceof TypeError||n?.name==="AbortError"||n?.name==="TimeoutError";async function uw(n){try{let e=await dA(n),t=Number(e.bavail)*Number(e.bsize);return Number.isFinite(t)?t:null}catch{return null}}async function Pu(n,e){if(!n.libraries)return xe("server_unsupported");let t;try{t=await n.libraries()}catch(i){if(i instanceof ze&&(i.status===404||i.code==="CLIENT_UPGRADE_REQUIRED"))return xe("server_unsupported");if(i instanceof ze&&i.code==="not_signed_in")return xe("not_signed_in");if($u(i))return xe("offline");throw i}let r=t.find(i=>i.id===e&&!i.deleted);return r?r.kind!=="default"&&(qn(r.name)||r.nameKey!==Le(r.name))?xe("name_mismatch"):r.kind==="default"&&(r.name!==yr||r.prefix!==di||r.id!==r.vaultId)?xe("library_not_found"):r:xe("library_not_found")}async function Ou(n){let e;try{e=await Nu(n)}catch(i){return i.code==="ENOENT"?"new":"root_unreadable"}if(!e.isDirectory())return"not_a_directory";let t=await bn([{prefix:"Amadeus",root:n}],{markers:!1}).catch(()=>null);if(!t||t.unscanned.length)return"root_unreadable";let r=i=>!!i&&!Ot(i)&&!i.split("/").some(o=>o.startsWith("."));return t.some(i=>i.kind==="file"&&r(i.path.slice(8)))?"nonempty":"empty"}async function Mu(n,e,t,r){let i=(await n.bindings()).map(c=>({...c,b:n.occupied([c.b])[0]})),o=e.kind==="own"?ss(e.vaultId):e.kind==="default"?Du(e.vaultId):{kind:"penzor",vaultId:e.vaultId,ns:"default",prefix:e.prefix,placement:"legacy-entry"},a=tn(o,i.map(c=>c.b));if(a)return xe("already_local",{root:a.root,bindingId:a.id});let s;try{s=await n.host.syncTargets.vaults()}catch{return xe("vault_list_unreadable")}for(let c of s){if(typeof c?.root!="string")continue;let u=await pe(c.root);if(u===t||Le(lw(u))!==fw(e))continue;let d=i.find(g=>g.b.root===u&&g.b.role==="primary");return xe("already_local",{root:u,...d?{bindingId:d.b.id}:{}})}let l=Ke({root:t,role:"primary"},i.map(c=>c.b),{mirrorDirs:yl(r)});return l?xe(l):jt(await n.entrySyncRoots(r),t)?xe("entry_sync_active"):null}var fw=n=>n.kind==="default"?Le(yr):n.nameKey,gA=n=>n.kind==="legacy"?{kind:"legacy",vaultId:n.vaultId,prefix:n.prefix}:n.kind==="default"?{kind:"default",vaultId:n.vaultId}:{kind:"own",vaultId:n.vaultId,name:n.name};async function gw(n,e,t){let r=n.host.accountId();if(!r)return xe("not_signed_in");let{libraryId:i,parent:o}=dw(t);if(typeof i!="string"||!i)return xe("library_not_found");if(typeof o!="string"||!cw(o))return xe("parent_missing");let a=await Pu(e,i);if("ok"in a)return a;if(!(await Nu(o).catch(()=>null))?.isDirectory())return xe("parent_missing");let l=fA(await pe(o),a.name),c=await Ou(l);if(c==="not_a_directory"||c==="root_unreadable")return xe(c);let u=await Mu(n,a,c==="new"?l:await pe(l),r);if(u)return u;let d=await n.freeBytes(o);return c!=="nonempty"&&d!==null&&a.bytes>d?xe("insufficient_space",{bytes:a.bytes,freeBytes:d}):{ok:!0,root:l,name:a.name,kind:a.kind,files:a.files,bytes:a.bytes,freeBytes:d,state:c}}async function pw(n,e,t){let r=n.host.accountId();if(!r)return xe("not_signed_in");let{libraryId:i,root:o}=dw(t);if(typeof i!="string"||!i)return xe("library_not_found");if(typeof o!="string"||!cw(o))return xe("root_missing");let a=await Pu(e,i);if("ok"in a)return a;for(let s=0;;s++){let l=await Nu(o).catch(y=>y.code==="ENOENT"?"missing":"unreadable");if(l==="missing")return xe("root_missing");if(l==="unreadable")return xe("root_unreadable");if(!l.isDirectory())return xe("not_a_directory");let c=await pe(o);if(Le(lw(c))!==fw(a))return xe("name_mismatch");let u=await Ou(c);if(u==="not_a_directory"||u==="root_unreadable")return xe(u);let d=await Mu(n,a,c,r);if(d)return d;let g={root:c,target:{kind:"penzor",candidate:gA(a)},scope:{mode:"all"}};if(u==="nonempty")return{ok:!0,next:"preview",preview:g};let f=await n.freeBytes(uA(c));if(f!==null&&a.bytes>f)return xe("insufficient_space",{bytes:a.bytes,freeBytes:f});if(n.host.accountId()!==r)throw Error("stale");let p=await ji(n,e,g),m;try{m=await Ui(n,e,{token:p.token,generation:p.generation,onDiffer:"hold"},{account:r,admit:async y=>{let b=await Pu(e,a.id);if("ok"in b)throw new Vi(b);if(b.kind!==a.kind||b.vaultId!==a.vaultId||b.prefix!==a.prefix||b.nameKey!==a.nameKey)throw new Vi(xe("library_not_found"));let h=await Mu(n,a,y,r);if(h)throw new Vi(h);if(await Ou(y)!=="empty")throw new Sl}})}catch(y){if(y instanceof Vi)return y.failure;if(y instanceof Sl){if(s>=1)throw Error("stale");continue}let b=String(y?.message??"");if(["already_local","root_nested","primary_exists","mirror_root","folder_target_nested","entry_sync_active","legacy_remote_same_root"].includes(b))return xe(b);throw y}if("bindingId"in m)return{ok:!0,bindingId:m.bindingId};if(s>=1)throw Error("stale")}}import{copyFile as _l,mkdir as yw,open as ww,readdir as Lu,readFile as Fu,rename as hw,rm as kl}from"node:fs/promises";import{dirname as bw,join as zi}from"node:path";var pA=/^[A-Za-z0-9_-]{1,64}$/,Bu="Amadeus/",as=(n,e)=>`${n}.pre-split-${e}`,ju=n=>n.replace(/\.json$/,".bases");async function Rl(n){try{let e=await ww(n,"r");try{await e.sync()}finally{await e.close()}}catch(e){if(!["EISDIR","EPERM","EINVAL"].includes(e.code??""))throw e}}async function Al(n){let e=await ww(n,"r+");try{await e.sync()}finally{await e.close()}}var Cl=n=>n.code==="ENOENT",vw=(n,e)=>n.state!=="needs-rename-answer"&&(e.root===void 0||n.root===e.root);async function hA(n,e){let t=as(n,e),r=`${t}.tmp`;await kl(r,{force:!0});try{await _l(n,r)}catch(l){if(!Cl(l))throw l;await je(r,null)}await Al(r),await hw(r,t);let i=ju(n),o=as(i,e),a=`${o}.tmp`;await kl(a,{recursive:!0,force:!0}),await kl(o,{recursive:!0,force:!0});let s=await Lu(i).catch(l=>{if(Cl(l))return null;throw l});if(s){await yw(a,{recursive:!0,mode:448});for(let l of s)await _l(zi(i,l),zi(a,l)),await Al(zi(a,l));await Rl(a),await hw(a,o)}await Rl(bw(n))}async function mA(n,e){let t=as(ju(n),e),r=ju(n),i=await Lu(t).catch(a=>{if(Cl(a))return[];throw a});if(!i.length)return;await yw(r,{recursive:!0,mode:448});let o=new Set(await Lu(r));for(let a of i)o.has(a)||(await _l(zi(t,a),zi(r,a)),await Al(zi(r,a)));await Rl(r)}async function El(n,e,t){await n.v3.update(e,r=>{let i=r.marks[t];if(i?.retarget)return delete i.retarget,Object.keys(i).length||delete r.marks[t],r})}function Sw(n,e,t,r){let i=e.target;if(!t||i.kind!=="penzor"||i.placement==="default"||i.ns!=="default"||r.prefix!==i.prefix||!pA.test(r.vaultId))return Promise.resolve(!1);let o=n.retargeting.get(e.id);if(o)return o.promise;n.retargetEpoch(e.id);let a=(async()=>{await n.stopEngineFor(e.id);let s=ae(t);if(n.host.accountId()!==t)return!1;if(!(await n.v3.read(s)).marks[e.id]?.retarget){let l=(await n.store.readAccount(t)).bindings.find(d=>d.id===e.id);if(!l||l.generation!==e.generation||l.target.kind!=="penzor"||l.target.ns!=="default"||l.target.prefix!==r.prefix)return!1;await Cr(n,l,s,t);let c=n.store.stateFile(s,l.id);await hA(c,r.vaultId),await n.crashRetarget("copied");let u={toVaultId:r.vaultId,fromVaultId:l.target.vaultId,fromNs:l.target.ns,fromPrefix:l.target.prefix,at:n.now(),movedAt:r.at,generation:l.generation,wasPaused:l.paused,root:l.root};await n.v3.update(s,d=>(d.marks[l.id]={...d.marks[l.id],retarget:u},d)),await n.crashRetarget("marked"),await Ae(()=>n.store.updateAccount(t,d=>{let g=d.bindings.find(f=>f.id===l.id);if(!(!g||g.generation!==l.generation||g.paused))return g.paused=!0,d})),await n.crashRetarget("paused"),n.host.log?.(`[vault-sync] ${l.id}: ${r.prefix} moved to vault ${r.vaultId}, retargeting`)}return kw(n,s,t,e.id)})().finally(()=>{n.retargeting.delete(e.id),n.retargetEpoch(e.id)});return n.retargeting.set(e.id,{promise:a}),a}function Uu(n,e,t){let r=n.retargeting.get(t);if(r)return r.promise;n.retargetEpoch(t);let i=kw(n,ae(e),e,t).finally(()=>{n.retargeting.delete(t),n.retargetEpoch(t)});return n.retargeting.set(t,{promise:i}),i}async function mw(n,e,t,r,i){let o=n.store.stateFile(e,r),a=`vault-${i.toVaultId}|${Bu.replace(/\/+$/,"")}`,s=await Fu(o,"utf8").then(c=>JSON.parse(c),c=>{if(Cl(c))return null;throw c});if(s&&typeof s=="object"&&s.bindTarget===a){let c=JSON.parse(await Fu(as(o,i.toVaultId),"utf8")),u=`${o}.retired-${n.now()}`;await _l(o,u),await Al(u),await Rl(bw(o)),c!==null?await je(o,c):await kl(o,{force:!0})}let l=!1;return await Ae(()=>n.store.updateAccount(t,c=>{let u=c.bindings.find(d=>d.id===r);if(!(!u||!u.paused||i.wasPaused||!vw(u,i)))return u.paused=!1,l=!0,c})),n.host.log?.(`[vault-sync] ${r}: retarget mark is stale (binding changed), dropped`),await El(n,e,r),l}async function kw(n,e,t,r){let i=(await n.v3.read(e)).marks[r]?.retarget;if(!i)return!1;let o=`vault-${i.toVaultId}`,a=(await n.store.readAccount(t)).bindings.find(h=>h.id===r);if(!a)return await El(n,e,r),!1;if(a.target.kind==="penzor"&&a.target.ns===o)return await El(n,e,r),!0;let s=h=>h.generation===i.generation&&h.target.kind==="penzor"&&h.target.ns===i.fromNs&&h.target.prefix===i.fromPrefix;if(!s(a))return mw(n,e,t,r,i);if(n.host.accountId()!==t)return!1;let l=await n.penzor.manifest(o),c=n.store.stateFile(e,r),u=JSON.parse(await Fu(as(c,i.toVaultId),"utf8")),d=null,g=null,f=Bu.replace(/\/+$/,""),p=Vt(a.scope),m=h=>h===f||h.startsWith(f+"/")&&p(h.slice(f.length+1));u!==null&&({state:d,stats:g}=by(u,{fromNs:i.fromNs,fromPrefix:i.fromPrefix.replace(/\/+$/,""),toNs:o,toPrefix:f,nodes:l.nodes,now:n.now(),inScope:m})),await mA(c,i.toVaultId);let y={kind:"penzor",vaultId:i.toVaultId,ns:o,prefix:Bu,placement:"own"},b="away";return await Ae(async()=>{if(n.host.accountId()!==t)return;let h=await n.store.readAccount(t),E=h.bindings.find(v=>v.id===r);if(!E||!s(E)){b="stale";return}if(tn(y,h.bindings,r)){b="duplicate";return}d!==null&&await je(c,d),await n.crashRetarget("written"),n.host.accountId()===t&&await n.store.updateAccount(t,v=>{let k=v.bindings.find(C=>C.id===r);if(!k||!s(k)){b="stale";return}return k.target=y,vw(k,i)&&(k.paused=i.wasPaused),k.generation+=1,k.firstRound||(k.firstRound="pair",k.firstRoundOnDiffer="hold"),b="switched",v})}),b==="stale"?mw(n,e,t,r,i):b==="duplicate"?(n.noteProblem(r,"vault_moved_duplicate"),n.host.log?.(`[vault-sync] ${r}: vault ${i.toVaultId} is already bound on this device, retarget waits`),!1):b!=="switched"?!1:(await n.crashRetarget("switched"),await El(n,e,r),n.host.log?.(`[vault-sync] ${r}: retargeted to ${o}`+(g?` (reattached ${g.reattached}, remote changed ${g.remoteChanged}, cloud gone ${g.cloudGone}, no identity ${g.noIdentity}, pending deletes ${g.pendingDeletes})`:"")),!0)}var Vu=(n,e)=>n.toLowerCase()===e.toLowerCase();function Il(n,e){return n.generation===e.generation&&n.target.kind==="penzor"&&Vu(n.target.vaultId,e.vaultId)&&n.target.prefix===e.prefix}function xl(n,e){return!e.purged&&!e.purging&&!e.reverted&&e.prefix==="Amadeus/"&&n.target.kind==="penzor"&&n.target.ns===`vault-${n.target.vaultId}`}var ls=(n,e)=>n.paused&&!e.wasPaused&&n.root===e.root&&n.state!=="needs-rename-answer",yA=(n,e,t)=>!!(t?.retarget||t?.kindMove||t?.unbinding)||n.retargeting.has(e)||n.kindMoving.has(e)||n.unbinding.has(e)||n.cloudMarking.has(e),wA=(n,e)=>n.libraries.some(t=>t.kind==="own"&&Vu(t.vaultId,e.vaultId)&&t.prefix===e.prefix&&!t.deleted);function Ew(n,e,t,r){let i=e.target;if(!t||i.kind!=="penzor")return Promise.resolve(!1);let o=n.cloudMarking.get(e.id);if(o)return o;n.retargetEpoch(e.id);let a=(async()=>{if(await n.stopEngineFor(e.id),n.host.accountId()!==t)return!1;let s=ae(t);await Cr(n,e,s,t).catch(u=>n.host.log?.(`[vault-sync] ${e.id}: cloud deleted, local deletes not settled yet: ${String(u?.message??u)}`));let l=!1,c=!1;return await Ae(async()=>{if(n.host.accountId()!==t)return;let d=(await n.v3.read(s)).marks[e.id];if(d?.retarget||d?.kindMove||d?.unbinding||n.retargeting.has(e.id)||n.kindMoving.has(e.id)||n.unbinding.has(e.id))return;let g=(await n.store.readAccount(t)).bindings.find(y=>y.id===e.id);if(!g||g.generation!==e.generation||g.target.kind!=="penzor"||!Vu(g.target.vaultId,i.vaultId)||g.target.prefix!==i.prefix)return;let f={purgeAt:r.purgeAt,purging:r.purging,purged:r.purged,reverted:r.reverted},p=d?.cloudDeleted,m=p&&Il(g,p)?{...p,...f}:{vaultId:i.vaultId,prefix:i.prefix,at:n.now(),...f,generation:g.generation,wasPaused:g.paused,root:g.root};await n.v3.update(s,y=>(y.marks[g.id]={...y.marks[g.id],cloudDeleted:m},y)),l=!0,await n.crashDeleted("marked"),await n.store.updateAccount(t,y=>{let b=y.bindings.find(h=>h.id===g.id);if(!(!b||b.generation!==g.generation||b.paused))return b.paused=!0,c=!0,y}),await n.crashDeleted("paused")}),l&&n.host.log?.(`[vault-sync] ${e.id}: cloud vault ${i.vaultId} was deleted${r.purged?" (purged)":r.reverted?" (split reverted)":""}; paused, local files untouched`),c})().finally(()=>{n.cloudMarking.delete(e.id),n.retargetEpoch(e.id)});return n.cloudMarking.set(e.id,a),a}async function _w(n,e,t){let r=ae(e),i=!1,o=!1,a=[];return await Ae(async()=>{if(n.host.accountId()!==e)return;let s=await n.v3.read(r),l=Object.keys(s.marks).filter(p=>s.marks[p]?.cloudDeleted);if(!l.length)return;let c=await n.store.readAccount(e),u=(await n.store.readDevice()).bindings,d=new Map,g=new Map,f=new Map;for(let p of l){let m=s.marks[p],y=m.cloudDeleted;if(yA(n,p,m))continue;let b=c.bindings.find(h=>h.id===p);if(!b){let h=u.find(E=>E.id===p);h&&ls(h,y)&&f.set(p,y),d.set(p,y);continue}if(!Il(b,y)){d.set(p,y),ls(b,y)&&g.set(p,y);continue}t&&t.startedAt>=y.at&&xl(b,y)&&wA(t.list,y)&&(d.set(p,y),ls(b,y)&&g.set(p,y))}if(d.size){g.size&&(await n.store.updateAccount(e,p=>{let m=0;for(let y of p.bindings){let b=g.get(y.id);b&&ls(y,b)&&(y.paused=!1,m++,a.push(y.id))}return m?p:void 0}),o=a.length>0),f.size&&await n.store.updateDevice(p=>{let m=0;for(let y of p.bindings){let b=f.get(y.id);b&&ls(y,b)&&(y.paused=!1,m++,a.push(y.id))}return m?p:void 0}),(g.size||f.size)&&await n.crashDeleted("unpaused"),await n.v3.update(r,p=>{let m=0;for(let[y,b]of d){let h=p.marks[y]?.cloudDeleted;!h||h.at!==b.at||h.generation!==b.generation||(delete p.marks[y].cloudDeleted,Object.keys(p.marks[y]).length||delete p.marks[y],m++)}return m?p:void 0}),i=!0;for(let p of d.keys())n.host.log?.(`[vault-sync] ${p}: cloud-deleted mark cleared${a.includes(p)?", resumed":""}`)}}),{changed:i,resumed:a,accountResumed:o}}var SA=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function zu(n){return n.contentSync?.ownership?n.syncTargets?n.syncRecords?{mode:"full"}:{mode:"compat",compatReason:"host-missing-sync-records"}:{mode:"compat",compatReason:"host-missing-sync-targets"}:{mode:"compat",compatReason:"host-missing-ownership"}}var kA=10*6e4,EA=6e4,_A=6e4,RA=6e4,AA=6e4;function Aw(n){let e=new Map;for(let t of n){let r=e.get(t.b.id);(!r||t.b.generation>r.b.generation)&&e.set(t.b.id,t)}return[...e.values()]}var Dl=n=>JSON.stringify([n.root,n.target,n.scope,n.generation]),CA=3e3,Pl=class{store;v3;manager;modeInfo;scheduler;engines=new Map;problems=new Map;inUseBy=new Map;legacyOverlap=new Map;ledgers=new Map;cadence=Lc;stateError=null;accountCompat=null;compatFor=null;deviceIdValue="";deviceName="";legacyDeviceIds=new Map;heartbeat=null;beatChain=Promise.resolve();beatQueued=null;beatWaiting=null;beatRetry=null;refreshChain=Promise.resolve();refreshQueued=null;refreshing=!1;abort=new AbortController;api;host;opts;constructor(e,t={}){this.host=e,this.opts=t,this.modeInfo=zu(e);let r=()=>e.homeDir();this.store=new oa(r),this.v3=this.store.v3,this.api=t.api?.()??_o(e,()=>this.deviceIdValue),this.manager=new _a({host:e,home:r,store:this.store,api:()=>this.api,log:i=>e.log?.(i),now:t.now,gateMs:t.gateMs,crashPoint:t.crashPoint}),this.scheduler=new sl((i,o)=>this.runAll(i,o),{startDelayMs:t.startDelayMs,now:t.now}),this.mirror=new qa({host:e,allowed:()=>this.full()&&!this.accountCompat&&!this.stateError,now:()=>this.now(),crash:async i=>{await this.opts.mirrorRetireCrash?.(i)}},r)}full(){return this.modeInfo.mode==="full"}now(){return this.opts.now?.()??Date.now()}freeBytes(e){return(this.opts.freeBytes??uw)(e)}async crashUnbind(e){await this.opts.unbindCrash?.(e)}async crashRetarget(e){await this.opts.retargetCrash?.(e)}async crashKindMove(e){await this.opts.kindMoveCrash?.(e)}async crashDeleted(e){await this.opts.deletedCrash?.(e)}mirror;async mirrorRetireSettled(){await this.mirror.idle()}async openCloudNotes(){let e=this.host.accountId();if(!e)throw Error("not_signed_in");if(!this.full()||this.accountCompat||this.stateError)throw Error("compat_mode");if(!Gr(this.host))throw Error("renderer_unsupported");let t=await this.libs.reply(e,{});if(this.host.accountId()!==e)throw Error("account_changed");let r="list"in t?t.list.libraries.find(o=>o.kind==="default"):void 0;if(!r)throw Error("libraries_unavailable");let i=Fa(r,ae(e));if(!i)throw Error("invalid_ref");if(!Gr(this.host)||!this.host.openLibrary)throw Error("renderer_unsupported");await this.host.openLibrary(i)}mirrorBridge={openCloudNotes:()=>this.openCloudNotes()};cloudMarking=new Map;deletedMarks=new Map;deletedChain=Promise.resolve();deletedQueued=null;kindMoving=new Map;kindMoveTried=new Map;movingMarked=new Set;retargeting=new Map;retargetWaits=new Map;retargetTried=new Map;noteProblem(e,t){this.retargetWaits.set(e,t),this.problems.set(e,t)}retargetEpochs=new Map;retargetEpoch(e){this.retargetEpochs.set(e,(this.retargetEpochs.get(e)??0)+1)}get penzor(){return this.api}stateUnreadable(){return this.stateError!==null}async legacyOccupant(){let e=await this.legacyView();return e==="unknown"?"unknown":Fc(e)}async legacyAdmission(){let e=await this.legacyView();if(e==="unknown")return{occupant:"unknown",running:"unknown"};let t=xp(e);return{occupant:Fc(e),running:t?{...t,root:await pe(t.root)}:null}}async legacyView(){let e=this.host.syncTargets;if(typeof e?.legacyRemoteSync!="function")return null;let t,r=new Promise(i=>{t=setTimeout(()=>i("unknown"),this.opts.legacyReadMs??CA)});try{return await Promise.race([Promise.resolve().then(()=>e.legacyRemoteSync()).catch(()=>"unknown"),r])}finally{clearTimeout(t)}}occupied(e){let t=r=>this.unbinding.has(r)||this.kindMoving.has(r)||this.movingMarked.has(r);return e.map(r=>t(r.id)&&!r.enabled?{...r,enabled:!0}:r)}async recoverLocalJournal(e,t,r={}){let i=this.buildEngine(e,t,r);if(i)try{await i.engine.heldList().catch(o=>this.host.log?.(`[vault-sync] ${e.id}: recover local journal: ${String(o?.message??o)}`))}finally{await i.engine.close().catch(()=>{})}}async resumeScope(e,t){if(this.resumed.has(e))return!1;let r=await Gy(this,[{scope:e,account:t}]);return this.resumed.add(e),r}unbinding=new Map;resumed=new Set;started=Promise.resolve();isMutating=()=>!1;deviceId(){return this.deviceIdValue}async start(){if(!this.full())return;gd((r,i)=>(i.cloudSync?.deviceId&&this.legacyDeviceIds.set(ae(r),i.cloudSync.deviceId),this.manager.gate(r,i).finally(()=>{this.refresh().then(()=>{[...this.engines.values()].some(o=>o.binding.firstRound==="takeover")&&this.scheduler.trigger("scheduled")})}))),gu(async r=>["absent","off"].includes(await this.manager.legacyContentState(r))?"retired":"run"),this.manager.attach({stopBinding:async r=>{await this.refresh().catch(()=>{}),await this.stopEngineFor(r)},runTakeoverRound:async r=>{await this.refresh();let i=this.engines.get(r);if(!i)throw this.problems.get(r)==="remote_dir_in_use"?Object.assign(new Error("remote_dir_in_use"),{code:"remote_dir_in_use",...this.inUseBy.has(r)?{inUseBy:{...this.inUseBy.get(r)}}:{}}):Error("binding_not_running");if(await this.runBinding(i,"takeover"),!i.lastCompleted)throw i.engine.roundFailure()??Object.assign(new Error("takeover_round_incomplete"),{code:"takeover_round_incomplete"});let o=i.lastStats;return{adopted:o?.adopted??0,filled:o?.filled??0,held:o?.held??0}}}),await this.loadDevice(),this.host.syncTargets.list().catch(r=>this.host.log?.(`[vault-sync] syncTargets handshake: ${String(r?.message??r)}`)),gm(this.host.homeDir(),Date.now()).catch(()=>{});let e=fd();e&&e.run(this.manager.remoteContext(),this.abort.signal).catch(r=>this.host.log?.(`[vault-sync] remote takeover: ${String(r?.message??r)}`)).finally(()=>void this.refresh()),this.host.addFlushHook?.(r=>r==="quit"&&!this.scheduler.manualOnly()?this.scheduler.trigger("flush"):void 0),this.host.addQuitCheck?.(()=>this.quitCheck()),await this.resumeScope("device",null).catch(r=>this.host.log?.(`[vault-sync] resume unbind: ${String(r?.message??r)}`));let t=this.host.accountId();t&&await this.resumeScope(ae(t),t).catch(r=>this.host.log?.(`[vault-sync] resume unbind: ${String(r?.message??r)}`)),t&&await this.resumeRetargets(t),await this.resumeKindMoves(),await this.refresh(),this.scheduler.start(this.cadence),zd(this.mirrorBridge),this.mirror.kick(),this.beat(),this.librariesKick(),this.heartbeat=setInterval(()=>void this.beat(),this.opts.heartbeatMs??kA),this.heartbeat.unref?.()}async close(){this.abort.abort(),this.scheduler.close(),this.heartbeat&&clearInterval(this.heartbeat),this.clearBeatRetry();for(let e of this.takeoverLater.values())clearTimeout(e.timer);this.takeoverLater.clear(),this.mirror.close(),Wa()===this.mirrorBridge&&zd(null),this.full()&&(gd(null),gu(null)),await Promise.all([...this.engines.keys()].map(e=>this.stopEngine(e))),await this.libs.close()}async loadDevice(){let e=await Da(this.host.homeDir());this.deviceIdValue=e.id,this.deviceName=e.name||Mr(Rw())}ledgerFor(e){let t=e?ae(e):fm,r=this.ledgers.get(t);return r||(r=Oi(()=>this.host.homeDir(),t),this.ledgers.set(t,r)),r}refresh(){if(!this.full())return Promise.resolve();if(this.refreshQueued)return this.refreshQueued;let e=this.refreshChain.then(async()=>{this.refreshQueued=null,this.refreshing=!0;try{await this.refreshOnce()}finally{this.refreshing=!1}});return this.refreshQueued=e,this.refreshChain=e.catch(()=>{}),e}async refreshAfterBindingChange(e){await this.refresh(),e&&this.beatAfterRefresh(e)}async refreshOnce(){let e=new Map(this.retargetEpochs),t=this.host.accountId();this.compatFor=null;let r=new Map,i=[],o=[],a=new Set,s=[],l=null;this.problems.clear(),this.inUseBy.clear(),this.legacyOverlap.clear();try{await this.manager.ledger.read();let d=await this.v3.read("device"),g=t?await this.v3.read(ae(t)):null;i=g?Object.keys(g.marks).filter(p=>g.marks[p]?.retarget):[],s=g?Object.entries(g.marks).flatMap(([p,m])=>m.cloudDeleted?[[p,m.cloudDeleted]]:[]):[],o=[...Object.keys(d.marks).filter(p=>d.marks[p]?.kindMove).map(p=>({scope:"device",id:p})),...g?Object.keys(g.marks).filter(p=>g.marks[p]?.kindMove).map(p=>({scope:ae(t),id:p})):[]],this.movingMarked=new Set(o.map(p=>p.id)),a=new Set([...this.movingMarked,...this.kindMoving.keys()]);let f=await this.store.readDevice();this.cadence=f.cadence,this.scheduler.setCadence(f.cadence);for(let p of f.bindings){let m=a.has(p.id)?p:await this.renamed(p,null);if(m.target.kind==="remote"&&m.enabled&&!Io()){this.problems.set(m.id,"server_unsupported");continue}await this.manager.mayRun(m,null)&&await this.runnable(m,null)&&r.set(m.id,{b:m,account:null})}for(let[p,m]of this.remoteDirBlocked(f.bindings,await this.manager.releasedBindings()))r.delete(p),this.problems.set(p,"remote_dir_in_use"),this.inUseBy.set(p,m);if(this.modeInfo.mode==="full"&&f.bindings.some(p=>p.target.kind==="remote"&&p.enabled&&p.state!=="takeover")){let p=await this.legacyOccupant();if(p&&p!=="unknown")for(let m of f.bindings)m.target.kind==="remote"&&m.enabled&&m.state!=="takeover"&&m.target.targetId===p.targetId&&this.legacyOverlap.set(m.id,{name:p.name,targetId:p.targetId})}if(this.accountCompat=null,t){let p=await this.manager.legacyContentState(t);if(p==="active")this.accountCompat="content-sync-active",this.compatFor=t;else if(p!=="unreadable"&&p!=="review"){await this.resumeScope(ae(t),t).catch(k=>this.host.log?.(`[vault-sync] resume unbind: ${String(k?.message??k)}`))&&this.beatAfterRefresh(t);let y=await this.store.readAccount(t);l=y.bindings;let b=new Set((await this.host.contentSync.ownership.get(t)).entryRoots.map(k=>k.replace(/[\\/]+$/,""))),h=await this.entrySyncRoots(t);for(let k of y.bindings){let C=a.has(k.id)?k:await this.renamed(k,t);if(C.target.kind==="penzor"&&C.target.placement==="legacy-entry"&&!b.has(C.root)){C.enabled&&this.problems.set(C.id,"double_engine");continue}if(C.target.kind==="penzor"&&jt(h,await pe(C.root))){C.enabled&&this.problems.set(C.id,"double_engine");continue}await this.manager.mayRun(C,t)&&await this.runnable(C,t)&&r.set(C.id,{b:C,account:t})}for(let[k,C]of[...r])C.account!==null||C.b.target.kind!=="remote"||jt(h,await pe(C.b.root))&&(r.delete(k),this.problems.set(k,"double_engine"));let E=[...r.values()].filter(({b:k,account:C})=>C===t&&k.target.kind==="penzor"&&k.target.placement!=="default").map(({b:k})=>k);for(let[k,{b:C,account:S}]of r)S!==t||C.target.kind!=="penzor"||C.target.placement!=="default"||Ke({root:C.root,id:k,role:C.role},E)&&(r.delete(k),this.problems.set(k,"double_engine"));let v=[...r.values()].filter(k=>k.account===t).map(k=>k.b);for(let[k,C]of[...r])C.account!==null||C.b.target.kind!=="remote"||Ke({root:C.b.root,id:C.b.id,role:C.b.role},v)&&(r.delete(k),this.problems.set(k,"remote_same_root"));this.compatFor=t}else await this.deviceOffEntryRoots(r,t);p==="active"&&await this.deviceOffEntryRoots(r,t)}this.stateError=null}catch(d){this.stateError=String(d?.message??d),await Promise.all([...this.engines.keys()].map(g=>this.stopEngine(g)));return}for(let[d,g]of[...this.engines]){let f=r.get(d);!f||f.account!==g.account||Dl(f.b)!==g.fingerprint?await this.stopEngine(d):g.binding=f.b}for(let d of[...r.keys()])this.unbinding.get(d)?.holding&&r.delete(d);this.deletedMarks.clear();let c=!1,u=!1;for(let[d,g]of s){let f=l?.find(p=>p.id===d);f&&Il(f,g)?(this.deletedMarks.set(d,g),xl(f,g)&&(u=!0)):l&&(c=!0)}for(let d of new Set([...this.deletedMarks.keys(),...this.cloudMarking.keys()]))r.delete(d),this.problems.set(d,"cloud_deleted"),this.engines.has(d)&&!this.cloudMarking.has(d)&&await this.stopEngine(d);for(let d of new Set([...i,...this.retargeting.keys()]))r.delete(d),this.problems.set(d,this.retargetWaits.get(d)??"vault_moving"),this.engines.has(d)&&!this.retargeting.has(d)&&await this.stopEngine(d);if(t)for(let d of i)this.retargeting.has(d)||this.now()-(this.retargetTried.get(d)??0)<_A||(this.retargetTried.set(d,this.now()),Uu(this,t,d).then(g=>this.afterRetarget(t,d,g),g=>this.host.log?.(`[vault-sync] ${d}: retarget waits: ${String(g?.message??g)}`)));for(let d of a)r.delete(d),this.problems.set(d,"move_in_progress"),this.engines.has(d)&&await this.stopEngine(d);for(let d of o)this.kindMoving.has(d.id)||this.now()-(this.kindMoveTried.get(d.id)??0)<RA||(this.kindMoveTried.set(d.id,this.now()),Au(this,d.scope,d.id).then(g=>this.refreshAfterBindingChange(g?t:null),g=>this.host.log?.(`[vault-sync] ${d.id}: kind move waits: ${String(g?.message??g)}`)));for(let[d,g]of[...this.engines])this.unbinding.get(d)?.holding&&!r.has(d)&&await this.stopEngine(d);for(let d of[...r.keys()])(this.retargetEpochs.get(d)??0)!==(e.get(d)??0)&&r.delete(d);for(let[d,g]of r)this.engines.has(d)||this.startEngine(g.b,g.account);if(c&&this.settleDeletedSoon(),u){let d=this.librariesAccount();d&&this.libs.refresh(d,{dueMs:AA})}}remoteDirBlocked(e,t){let r=e.filter(o=>o.target.kind==="remote"&&!jc(o,t)).sort((o,a)=>o.createdAt-a.createdAt||(o.id<a.id?-1:o.id>a.id?1:0)),i=new Map;return r.forEach((o,a)=>{if(!o.enabled&&o.state!=="takeover")return;let s=o.root.replace(/[\\/]+$/,""),l=ho(o,r.slice(0,a).filter(c=>c.root.replace(/[\\/]+$/,"")!==s));l&&i.set(o.id,l.holder)}),i}async deviceOffEntryRoots(e,t){let r=await this.entrySyncRoots(t);for(let[i,o]of[...e])o.account!==null||o.b.target.kind!=="remote"||jt(r,await pe(o.b.root))&&(e.delete(i),this.problems.set(i,"double_engine"))}async entrySyncRoots(e){try{Ve()}catch{return new Set}let t=await ot(e),r;try{r=(await this.host.contentSync.ownership.get(e)).entryRoots}catch(a){if(await this.manager.legacyContentState(e)!=="unreadable")throw a;this.host.log?.(`[vault-sync] ownership unreadable with the old content-sync state unreadable; treating every entry root as unmasked: ${String(a?.message??a)}`),r=[]}let i=new Set(await Promise.all(r.map(pe))),o=new Set;for(let a of t.entrySync??[]){if(!a?.entries?.length)continue;let s=await pe(a.vaultRoot);i.has(s)||o.add(s)}return o}async renamed(e,t){if(!e.enabled||e.state!=="active")return e;let r=null;try{r=await dt(e.root)}catch(a){if(a?.code!=="ENOENT")return e}if(r&&Dt(e.rootIdentity,r))return Le(Tl(e.root))===e.nameKey?e:this.markRenamed(e,t,e.root);let i;try{i=await this.host.syncTargets.vaults()}catch(a){return this.host.log?.(`[vault-sync] vaults() for rename check: ${String(a?.message??a)}`),e}let o=await pe(e.root);for(let a of i){if(typeof a?.root!="string")continue;let s=await dt(a.root).catch(()=>null);if(s&&Dt(e.rootIdentity,s)&&await pe(a.root)!==o)return this.markRenamed(e,t,a.root)}return e}async markRenamed(e,t,r){let i=await pe(r);if(i!==e.root){if(Ke({root:i,id:e.id,role:e.role},(await this.bindings()).map(a=>a.b).filter(a=>a.id!==e.id)))return this.problems.set(e.id,"root_renamed"),e;try{let a=(await this.manager.ledger.read()).entries.find(l=>l.source==="entry"&&l.bindingId===e.id&&l.phase!=="reverted"&&l.phase!=="refused"),s=e.target.kind==="penzor"&&e.target.placement==="legacy-entry";if(t&&(s||a))await this.manager.relocateRoot(t,e.id,e.root,i);else if(!t&&a){let l=this.host.accountId();if(!l||ae(l)!==a.account)return this.problems.set(e.id,"root_renamed"),e;await this.manager.relocateRoot(l,e.id,e.root,i)}}catch(a){return this.host.log?.(`[vault-sync] relocate ${e.id}: ${String(a?.message??a)}`),this.problems.set(e.id,"root_renamed"),e}}let o=e;return await Ae(async()=>{let a=(await this.bindings()).map(l=>l.b).filter(l=>l.id!==e.id);if(i!==e.root&&Ke({root:i,id:e.id,role:e.role},a)){this.problems.set(e.id,"root_renamed");return}let s=l=>{let c=l.bindings.find(u=>u.id===e.id);if(!(!c||c.generation!==e.generation||c.state!=="active"))return c.renamedFrom??=c.root,c.root=i,c.state="needs-rename-answer",c.paused=!0,o=structuredClone(c),l};t?await this.store.updateAccount(t,s):await this.store.updateDevice(s)}),o!==e&&(this.host.log?.(`[vault-sync] ${e.id}: vault folder renamed, paused until answered`),t&&!e.paused&&this.beatAfterRefresh(t)),o}async runnable(e,t){if(!e.enabled||e.paused||e.state!=="active"&&e.state!=="takeover"||e.target.kind==="remote"&&t!==null)return!1;try{let r=await dt(e.root);if(!Dt(e.rootIdentity,r))return this.problems.set(e.id,"root_renamed"),!1}catch{return this.problems.set(e.id,"root_missing"),!1}return!0}startEngine(e,t){let r=this.buildEngine(e,t);r&&this.engines.set(e.id,r)}buildEngine(e,t,r={}){if(e.target.kind==="remote")return this.buildRemoteEngine(e,r);let i=e.target,o=i.prefix.replace(/\/+$/,""),a=Vt(e.scope),s=this.ledgerFor(t),l={},c={id:e.id,stateFile:this.store.stateFile(this.store.scopeOf(e,t),e.id),ns:i.ns,roots:async()=>[{prefix:o,root:e.root}],inScope:u=>u===o||u.startsWith(o+"/")&&a(u.slice(o.length+1)),...i.placement==="default"?{readScopeExclusions:async u=>{let d=this.api.snapshot?.();if(this.host.accountId()!==t||d&&d.account!==t)throw Error("account_changed");return ca(d?.api??this.api,i.vaultId,u)}}:{},policy:()=>this.policyFor(l),onDeferred:u=>this.deferredAt(l,u),recovery:s,deviceId:this.deviceIdValue,account:()=>t&&this.host.accountId()===t?t:null,caps:[...wa],vaultRoot:e.root,targetLabel:`penzor:${i.vaultId}:${i.prefix}`,...i.placement==="default"?{}:{onMoved:u=>{l.moved??=u}},onDeleted:u=>{l.deleted??=u},liveRealMove:!0,onRound:u=>{l.after=l.after.then(()=>this.onRound(l,u.completed,u.wroteLocal,u.stats)).catch(d=>this.host.log?.(`[vault-sync] round bookkeeping: ${String(d?.message??d)}`))}};return Object.assign(l,{binding:e,account:t,engine:pu(this.host,c,{watch:this.opts.watch}),ledger:s,nextKind:"scheduled",after:Promise.resolve(),lastSyncAt:null,lastStats:null,lastCompleted:!1,fingerprint:Dl(e),lastRound:null}),l}buildRemoteEngine(e,t={}){let r=Io();if(!r)return this.problems.set(e.id,"server_unsupported"),null;let i=this.ledgerFor(null),o={},a=My({binding:e,open:()=>r(o.binding),stateFile:this.store.stateFile(this.store.scopeOf(e,null),e.id),policy:()=>this.policyFor(o),onDeferred:s=>this.deferredAt(o,s),recovery:i,deviceId:this.deviceIdValue,log:s=>this.host.log?.(s),...t.localOnly?{localOnly:!0}:{},onRound:s=>{o.after=o.after.then(()=>this.onRound(o,s.completed,s.wroteLocal,s.stats)).catch(l=>this.host.log?.(`[vault-sync] round bookkeeping: ${String(l?.message??l)}`))}});return Object.assign(o,{binding:e,account:null,engine:pu(this.host,a,{watch:this.opts.watch}),ledger:i,nextKind:"scheduled",after:Promise.resolve(),lastSyncAt:null,lastStats:null,lastCompleted:!1,fingerprint:Dl(e),lastRound:null}),o}async stopEngineFor(e){await this.stopEngine(e),await this.stopping.get(e)}stopping=new Map;async stopEngine(e){let t=this.engines.get(e);if(!t)return;this.engines.delete(e);let r=(async()=>{await t.engine.close().catch(()=>{}),await t.after.catch(()=>{})})();this.stopping.set(e,r);try{await r}finally{this.stopping.get(e)===r&&this.stopping.delete(e)}}policyFor(e){let t=e.binding,r=t.firstRound;e.roundGen=t.generation,e.roundStartedAt=this.now();let i=t.target.kind==="penzor"&&e.engine.serverRealMove,o=t.target.kind==="remote"?t.role==="backup"?"push":t.target.direction:"both";if(r){let a=r!=="takeover"&&t.firstRoundOnDiffer==="newer",s=t.target.kind==="penzor"?t.target.prefix.replace(/\/+$/,""):At,l=t.firstRoundPrevScope?Vt(t.firstRoundPrevScope):null,c=t.target.kind==="penzor"&&t.target.placement==="default"?t.firstRoundExclusions:void 0,u=a&&(l||c)?d=>d.startsWith(s+"/")&&!l?.(d.slice(s.length+1))&&!c?.some(g=>d===g||d.startsWith(g+"/")):void 0;return{deletes:!1,onDiffer:a?"newer":"hold",...u?{newerOnly:u}:{},realMove:i,direction:o,kind:r==="takeover"?"takeover":"pair"}}return{deletes:!0,onDiffer:"hold",realMove:i,direction:o,kind:e.nextKind}}async onRound(e,t,r,i){e.lastStats=i,e.lastCompleted=t;let o=this.now(),a=e.engine.status(),s=await e.engine.heldList().then(c=>c.length,()=>-1);e.lastRound={startedAt:e.roundStartedAt??o,endedAt:o,completed:t,failures:a?.failures?.length??0,skipped:a?.skippedCount??0,held:s},t&&(e.lastSyncAt=Date.now(),await this.rememberLastSync(e).catch(c=>this.host.log?.(`[vault-sync] last-sync: ${String(c?.message??c)}`)));let l=e.binding;if(l.firstRound==="takeover"){let c=(await e.engine.heldList().catch(()=>[])).length;await this.manager.roundFinished(l.id,e.account,t&&!i.deferred,{adopted:i.adopted,filled:i.filled,revived:i.revived},c,e.roundGen??l.generation)}else if(t&&l.firstRound){let c=e.roundGen??l.generation,u=d=>{d.id===l.id&&d.generation===c&&(delete d.firstRound,delete d.firstRoundOnDiffer,delete d.firstRoundPrevScope,delete d.firstRoundExclusions)};e.account?await this.store.updateAccount(e.account,d=>(d.bindings.forEach(u),d)):await this.store.updateDevice(d=>(d.bindings.forEach(u),d))}if(t&&l.firstRound){let u=(e.account?(await this.store.readAccount(e.account)).bindings:(await this.store.readDevice()).bindings).find(d=>d.id===l.id);u&&Dl(u)===e.fingerprint&&(e.binding=u)}r&&e.account&&await this.host.contentSync.ownership.touched(e.account).catch(()=>{})}async runBinding(e,t,r){e.binding.firstRound==="takeover"&&await this.manager.roundStarting(e.binding.id),e.nextKind=t,e.lastCompleted=!1,r!==void 0&&e.engine.flushEdits(r),await e.engine.run(),await e.engine.idle(),await e.after,await this.takeMoved(e),await this.takeDeleted(e)}async takeDeleted(e){let t=e.deleted;if(e.deleted=void 0,!t||!e.account)return;let r=await Ew(this,e.binding,e.account,t).catch(i=>this.host.log?.(`[vault-sync] ${e.binding.id}: cloud deleted: ${String(i?.message??i)}`));await this.refreshAfterBindingChange(r?e.account:null)}settleDeletedSoon(){if(this.deletedQueued)return this.deletedQueued;let e=this.deletedChain.then(async()=>{this.deletedQueued=null;let t=this.host.accountId();if(!t||!this.full()||this.stateError||this.accountCompat)return;let r=await _w(this,t,this.libs.fresh(t));if(r.changed){await this.refreshAfterBindingChange(r.accountResumed?t:null);for(let i of r.resumed)this.runNow(i).catch(o=>this.host.log?.(`[vault-sync] ${i}: run after resume: ${String(o?.message??o)}`))}}).catch(t=>this.host.log?.(`[vault-sync] cloud deleted settle: ${String(t?.message??t)}`));return this.deletedQueued=e,this.deletedChain=e,e}async cloudDeletedSettled(){for(;;){let e=this.deletedChain;if(await e,e===this.deletedChain)return}}async takeMoved(e){let t=e.moved;if(e.moved=void 0,!t||!e.account)return;let r=e.account;this.retargetTried.set(e.binding.id,this.now());let i=await Sw(this,e.binding,r,t).catch(o=>(this.host.log?.(`[vault-sync] ${e.binding.id}: retarget waits: ${String(o?.message??o)}`),!1));await this.afterRetarget(r,e.binding.id,i)}async afterRetarget(e,t,r){(await this.v3.read(ae(e)).catch(()=>null))?.marks[t]?.retarget||this.retargetWaits.delete(t),await this.refresh(),this.host.accountId()===e&&this.librariesChanged(r?this.beatAfterRefresh(e):void 0)}async resumeKindMoves(){let e=this.host.accountId();for(let t of["device",...e?[ae(e)]:[]]){let r=await this.v3.read(t).catch(()=>null);if(r)for(let i of Object.keys(r.marks))r.marks[i]?.kindMove&&(this.kindMoveTried.set(i,this.now()),await Au(this,t,i).catch(o=>this.host.log?.(`[vault-sync] ${i}: resume kind move: ${String(o?.message??o)}`)))}}async resumeRetargets(e){let t=await this.v3.read(ae(e)).catch(()=>null);if(t)for(let r of Object.keys(t.marks))t.marks[r]?.retarget&&(this.retargetTried.set(r,this.now()),await Uu(this,e,r).catch(i=>this.host.log?.(`[vault-sync] ${r}: resume retarget: ${String(i?.message??i)}`)),(await this.v3.read(ae(e)).catch(()=>null))?.marks[r]?.retarget||this.retargetWaits.delete(r))}takeoverLater=new Map;deferredAt(e,t){let r=e.binding.id,i=this.takeoverLater.get(r);if(e.binding.firstRound!=="takeover"||this.abort.signal.aborted||(i?.count??0)>=6){this.scheduler.later(t);return}if(i&&i.at<=t)return;i&&clearTimeout(i.timer);let o=setTimeout(()=>{let a=this.takeoverLater.get(r);a?.timer===o&&(a.at=1/0),!this.abort.signal.aborted&&this.refresh().then(()=>{let s=this.engines.get(r);if(s&&s.binding.firstRound==="takeover")return this.runBinding(s,"scheduled")}).catch(s=>this.host.log?.(`[vault-sync] takeover follow-up ${r}: ${String(s?.message??s)}`)).finally(()=>{let s=this.takeoverLater.get(r);s&&s.at===1/0&&this.engines.get(r)?.binding.firstRound!=="takeover"&&this.takeoverLater.delete(r)})},Math.max(0,t-Date.now())+50);o.unref?.(),this.takeoverLater.set(r,{at:t,timer:o,count:(i?.count??0)+(i&&i.at!==1/0?0:1)})}async runAll(e,t={}){await this.refresh();for(let r of[...this.engines.values()]){if(this.abort.signal.aborted)return;await this.runBinding(r,e,t.flushAt).catch(i=>this.host.log?.(`[vault-sync] round ${r.binding.id}: ${String(i?.message??i)}`))}this.abort.signal.aborted||this.mirror.kick({manual:e==="manual"})}async runNow(e){if(!e)return this.scheduler.trigger("manual");let t=Date.now();await this.refresh();let r=this.engines.get(e);r&&await this.runBinding(r,"manual",t)}engineOf(e){return this.engines.get(e)}beat(){return this.queueBeat(this.host.accountId(),!1)}canBeat(e){return this.full()&&!!this.deviceIdValue&&!this.abort.signal.aborted&&this.host.accountId()===e}beatAfterRefresh(e){if(!this.canBeat(e))return Promise.resolve();if(this.beatWaiting?.account===e)return this.beatWaiting.done;let t={account:e,done:Promise.resolve().then(()=>this.waitForBeatReadiness(t))};return this.beatWaiting=t,t.done}async waitForBeatReadiness(e){let{account:t}=e,r;do if(r=this.refreshChain,await r,this.beatWaiting!==e)return;while(r!==this.refreshChain&&this.canBeat(t));if(this.beatWaiting=null,!!this.canBeat(t)){if(this.compatFor!==t||this.stateError){this.retryBeat(t,!0);return}await this.queueBeat(t,!0)}}queueBeat(e,t){if(!e||!this.canBeat(e))return Promise.resolve();let r=this.beatQueued;if(r){let i=r.account===e;r.bindingsChanged=t||i&&r.bindingsChanged,r.periodic=!t||i&&r.periodic,r.account=e}else{let i={account:e,bindingsChanged:t,periodic:!t,attempt:this.beatChain.then(()=>this.runQueuedBeat(i))};this.beatQueued=r=i,this.beatChain=i.attempt.then(()=>{})}return r.attempt.then(i=>t?i?.followup:void 0)}async runQueuedBeat(e){this.beatQueued=null;let{account:t}=e;if(!this.canBeat(t))return;let r=e.bindingsChanged||this.beatRetry?.account===t&&this.beatRetry.bindingsChanged;this.clearBeatRetry();try{let i=await this.sendBeat(t,e.periodic);if(i==="refreshing")return{followup:this.beatAfterRefresh(t)};i==="unknown"&&r&&this.retryBeat(t,!0)}catch{this.retryBeat(t,r)}}clearBeatRetry(){this.beatRetry&&clearTimeout(this.beatRetry.timer),this.beatRetry=null}retryBeat(e,t){if(!this.canBeat(e)||this.beatRetry?.account===e&&(this.beatRetry.bindingsChanged||!t))return;this.clearBeatRetry();let r=setTimeout(()=>{this.beatRetry=null,t?this.beatAfterRefresh(e):this.queueBeat(e,!1)},EA);r.unref?.(),this.beatRetry={account:e,bindingsChanged:t,timer:r}}async sendBeat(e,t){let r=this.refreshChain,i=this.refreshing||!!this.refreshQueued;if(i&&!t)return"refreshing";let o=this.compatFor===e&&!this.stateError,a=ae(e),s=!i&&o&&!this.accountCompat?await this.store.readAccount(e).catch(()=>null):null,l=s?await this.lastSyncMap(a):null;return Si(this.host.homeDir(),async()=>{if(!this.canBeat(e))return"discarded";let c=await zr(this.host.homeDir(),this.deviceIdValue);this.deviceName=c.name||Mr(Rw());let u=i||this.refreshing||r!==this.refreshChain,d=o&&!u,g=d&&(!!this.accountCompat||s!==null);if(!t&&!g)return u?"refreshing":"unknown";let f=this.legacyDeviceIds.get(a),p={name:this.deviceName,clientVersion:this.host.appVersion?.()??"",...f?{legacyDeviceId:f}:{}};if(d&&(p.caps=ah(!this.accountCompat)),d&&s&&l&&(p.vaults=s.bindings.flatMap(y=>{let b=y.target;if(!y.enabled||b.kind!=="penzor"||!SA.test(b.vaultId))return[];let h=this.engines.get(y.id),E=(h?.account===e?h.lastSyncAt:null)??l[y.id]??null;return[{vaultId:b.vaultId,prefix:b.prefix,scope:y.scope.mode,lastSyncAt:E?new Date(E).toISOString():null}]})),!this.canBeat(e))return"discarded";let m=this.api.snapshot?.();return m?.account!==e?"discarded":(await m.api.putDevice(p,this.abort.signal),u?"refreshing":g?"sent":"unknown")})}lastSync=new Map;lastSyncFile(e){return this.store.stateFile(e,"last-sync")}loadLastSync(e){let t=this.lastSync.get(e);return t||(t=vA(this.lastSyncFile(e),"utf8").then(r=>{let i=JSON.parse(r);return i&&typeof i=="object"&&!Array.isArray(i)?Object.fromEntries(Object.entries(i).filter(([,o])=>Number.isSafeInteger(o)&&o>0)):null},r=>r.code==="ENOENT"?{}:null).catch(()=>null),this.lastSync.set(e,t)),t}async lastSyncMap(e){return await this.loadLastSync(e)??{}}lastSyncWrites=Promise.resolve();async rememberLastSync(e){let t=this.store.scopeOf(e.binding,e.account),r=e.lastSyncAt,i=async()=>{let a=await this.loadLastSync(t);if(a===null)return;let s={...a,[e.binding.id]:r};await je(this.lastSyncFile(t),s),this.lastSync.set(t,Promise.resolve(s))},o=this.lastSyncWrites.then(i,i);this.lastSyncWrites=o.catch(()=>{}),await o}async quitCheck(){let e=this.isMutating()?1:0,t=[];for(let r of this.engines.values()){e+=r.engine.pendingChanges()+(r.engine.busy()?1:0);let i=r.engine.currentError();i&&t.push({path:Tl(r.binding.root),reason:i})}return{state:t.length?"failed":e?"pending":"synced",pending:e,failed:t}}statusOf(e,t){let r=t?.engine.currentError(),i=this.problems.get(e.id)??(r===la?la:e.reason),o=i==="cloud_deleted"?this.deletedMarks.get(e.id):void 0,a=e.state==="takeover"?"takeover":e.state==="needs-choice"?"needs-choice":e.state==="needs-card"?"needs-card":void 0,s=t?.engine.status();return{phase:t?t.engine.busy()?s?.round?"transferring":"checking":t.engine.currentError()?"error":e.state==="takeover"?"checking":"idle":i==="vault_moving"||i==="move_in_progress"?"checking":i==="cloud_deleted"?"paused":i?"error":e.paused?"paused":"idle",lastSyncAt:t?.lastSyncAt??null,pendingChanges:t?.engine.pendingChanges()??0,held:0,deletesPending:s?.deletes?.pending??0,failures:s?.failures?.length??0,...t?.engine.currentError()?{error:t.engine.currentError()}:{},...a?{notice:a}:{},...i?{reason:i}:{},...i==="remote_dir_in_use"&&this.inUseBy.has(e.id)?{inUseBy:{...this.inUseBy.get(e.id)}}:{},...o?{cloudDeleted:{at:o.at,purgeAt:o.purgeAt,purging:o.purging,purged:o.purged,reverted:o.reverted,autoResume:xl(e,o)}}:{},...this.legacyOverlap.has(e.id)?{overlapsLegacy:{...this.legacyOverlap.get(e.id)}}:{}}}async view(e,t=[]){let r=this.engines.get(e.id),i=this.statusOf(e,r);r&&(i.held=(await r.engine.heldList().catch(()=>[])).length);let o=e.target;return{id:e.id,generation:e.generation,root:e.root,name:Tl(e.root),target:o.kind==="penzor"?{kind:"penzor",vaultId:o.vaultId,vaultName:null,placement:o.placement,prefix:o.prefix}:{kind:"remote",targetId:o.targetId,backend:t.find(a=>a.id===o.targetId)?.kind??"",label:t.find(a=>a.id===o.targetId)?.label??"",dir:o.dir,direction:o.direction,conditionalWrites:!1},scope:e.scope,enabled:e.enabled,paused:e.paused,state:e.state,role:e.role,status:i,...e.takeoverCard?{takeoverCard:e.takeoverCard}:{},...e.renamedFrom?{renamedFrom:Tl(e.renamedFrom)}:{},...e.firstRound?{firstRound:e.firstRound}:{},lastRound:r?.lastRound??null}}async bindings(){let e=this.host.accountId(),t=(await this.store.readDevice()).bindings.map(r=>({b:r,account:null}));if(e)for(let r of(await this.store.readAccount(e)).bindings)t.push({b:r,account:e});return t}libs=new dl({home:()=>this.host.homeDir(),api:()=>this.api,account:()=>this.host.accountId(),now:()=>this.opts.now?.()??Date.now(),signal:()=>this.abort.signal,log:e=>this.host.log?.(e),crash:e=>this.opts.librariesCrash?.(e)??Promise.resolve(),onFresh:e=>{this.host.accountId()===e&&this.deletedMarks.size&&this.settleDeletedSoon()}});librariesAccount(){let e=this.host.accountId();return e&&this.full()&&!this.accountCompat&&!this.stateError?e:null}async libraries(e){let t=this.host.accountId();if(!t)return{error:"not_signed_in"};if(this.accountCompat)throw Error("compat_mode");if(this.stateError)throw Error("state_unreadable");let r=await this.libs.reply(t,{refresh:e});return this.host.accountId()===t?r:{error:"not_fetched"}}librariesKick(){let e=this.librariesAccount();e&&this.libs.refresh(e,{dueMs:3e4})}librariesFocus(){let e=this.librariesAccount();e&&this.libs.refresh(e,{dueMs:By})}librariesChanged(e){let t=this.librariesAccount();t&&this.libs.refresh(t,{mark:!0,...e?{after:e}:{}})}async get(e={}){let t={version:2,cadence:this.cadence,sealed:{agents:!0,plugins:!0}};if(!this.full())return{...t,mode:"compat",compatReason:this.modeInfo.compatReason,bindings:[],localVaults:[],cloudVaults:null,serverCaps:{vaults:!1,realMove:!1},takeover:[],recoveryCount:0};if(this.stateError&&await this.refresh().catch(()=>{}),this.stateError)return{...t,mode:"compat",compatReason:"state-unreadable",bindings:[],localVaults:[],cloudVaults:null,serverCaps:{vaults:!1,realMove:!1},takeover:[],recoveryCount:0};let r=this.host.accountId(),i=r?[this.deviceIdValue,this.legacyDeviceIds.get(ae(r))??""].filter(Boolean):[],o=r&&!this.accountCompat&&this.deviceIdValue?this.libs.views(r,i,{wait:e.waitCloud!==!1}).catch(()=>null):Promise.resolve(null),a=Aw(await this.bindings()),s=await this.host.syncTargets.vaults().catch(()=>[]),l=(await this.manager.view(r)).filter(d=>d.source!=="content-off"),c=await this.ledgerFor(r).list().catch(()=>[]),u=a.some(d=>d.b.target.kind==="remote")?await this.host.syncTargets.list().catch(()=>[]):[];return{...t,mode:this.accountCompat?"compat":"full",...this.accountCompat?{compatReason:this.accountCompat}:{},device:{id:this.deviceIdValue,name:this.deviceName},bindings:await Promise.all(a.map(d=>this.view(d.b,u))),localVaults:s.map(({root:d,name:g})=>{let f=a.find(b=>b.b.root===d&&b.b.role==="primary")?.b,p={root:d,name:g};if(!f)return p;let m=f.target;if(this.host.accountId()!==r||m.kind!=="penzor"||!m.vaultId)return{...p,bindingId:f.id};let y=m.prefix==="Amadeus/"?m.vaultId:m.placement==="legacy-entry"?`${m.vaultId}:${m.prefix}`:void 0;return{...p,bindingId:f.id,...y?{libraryId:y}:{}}}),cloudVaults:await o.then(d=>this.host.accountId()===r?d:null),serverCaps:{vaults:!0,realMove:[...this.engines.values()].some(d=>d.engine.serverRealMove)},takeover:l,recoveryCount:c.length,...this.accountCompat?{}:await this.mirrorRetireField(r)}}async mirrorRetireField(e){let t=await this.mirror.view(e).catch(()=>{});return t?{mirrorRetire:t}:{}}async status(){if(!this.full())return{mode:"compat",...this.modeInfo.compatReason?{compatReason:this.modeInfo.compatReason}:{},bindings:[]};if(this.stateError&&await this.refresh().catch(()=>{}),this.stateError)return{mode:"compat",compatReason:"state-unreadable",bindings:[]};let e=await this.bindings().then(Aw,()=>null);return e?{mode:this.accountCompat?"compat":"full",...this.accountCompat?{compatReason:this.accountCompat}:await this.mirrorRetireField(this.host.accountId()),bindings:await Promise.all(e.map(async t=>{let r=await this.view(t.b);return{id:r.id,root:r.root,name:r.name,target:r.target,scope:r.scope,state:r.state,status:r.status,enabled:r.enabled,paused:r.paused,role:r.role,...r.firstRound?{firstRound:r.firstRound}:{},lastRound:r.lastRound??null,...this.reviewOf(t.b)}}))}:{mode:"compat",compatReason:"state-unreadable",bindings:[]}}reviewOf(e){let t=null;try{t=this.engines.get(e.id)?.engine.bindingReview()??null}catch(i){this.host.log?.(`[vault-sync] review ${e.id}: ${String(i?.message??i)}`)}let r=t?tl(e,t.held).sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0):[];return{progress:t?.progress??null,review:{differs:r.slice(0,50).map(i=>({path:i.path,newer:vy(i),ref:i.ref,size:i.size,localMtime:i.localMtime,remoteMtime:i.remoteMtime,...i.cloudGone?{cloudGone:!0}:{}})),differsTotal:r.length,differsToken:nl(r),deletes:t?.deletes??null},failures:(t?.failures??[]).slice(0,20),failuresTotal:t?.failures.length??0,rateLimitedUntil:t?.rateLimitedUntil??null}}async dismissTakeoverCard(e){let t=this.host.accountId(),r=i=>{for(let o of i.bindings)o.id===e&&delete o.takeoverCard;return i};t&&await this.store.updateAccount(t,r),await this.store.updateDevice(r)}};import{hostname as xA}from"node:os";async function cs(n,e){if(!n||!e)return{status:"offline"};let t=n.replace(/\/+$/,"");try{let r=await fetch(`${t}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let i=await r.json();if(!i)return{status:"offline"};let o=i.avatar||i.avatarUrl||i.avatar_url||void 0;return o&&/^\/(?!\/)/.test(o)&&(o=t+o),{status:"ok",user:{username:i.username||i.nickname||void 0,nickname:i.nickname||void 0,avatar:o,membershipTier:i.membershipTier||i.membership_tier||void 0}}}catch{return{status:"offline"}}}var Cw=n=>`${n.seq}:${n.hash}`,Ol=(n=xA())=>{let e=n.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},TA=n=>IA("sha256").update(n).digest("hex");function qu(n){if(n===null)return{baseSeq:0,baseHash:null};if(typeof n!="string")return;let e=n.indexOf(":"),t=Number(e===-1?n:n.slice(0,e));if(!Number.isInteger(t)||t<=0)return;let r=e===-1?"":n.slice(e+1);return{baseSeq:t,baseHash:/^[0-9a-f]{64}$/.test(r)?r:null}}function Ml(n){let e=n.baseUrl.replace(/\/+$/,""),t=o=>`${e}/api/remotesync/vaults/${encodeURIComponent(n.vault)}${o}`,r=Ol(),i=async(o,a)=>{let s=n.getToken();if(!s)throw new Error("penzor-not-logged-in");let l=await fetch(o,{...a,headers:{...a.headers,Authorization:`Bearer ${s}`}});if(l.status===409){let c=await l.json().catch(()=>({}));throw new Error(`cas-conflict ${String(c.code??"")}: seq=${String(c.seq??"?")}`)}if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`penzor ${a.method??"GET"} ${l.status}: ${c.slice(0,200)}`)}return l};return{kind:"penzor",async walk(o){let a=await i(t("/manifest"),{method:"GET",signal:o}),{files:s}=await a.json();return s.map(l=>({key:l.path,size:l.size,mtimeMs:l.mtimeMs,id:Cw(l),hash:l.hash}))},async readFile(o,a){let l=await(await i(t(`/file?path=${encodeURIComponent(o)}`),{method:"GET",signal:a})).json(),c=await fetch(l.url,{signal:a});if(!c.ok)throw new Error(`penzor blob GET ${c.status}: ${o}`);let u=Buffer.from(await c.arrayBuffer());if(TA(u)!==l.hash)throw new Error(`penzor hash mismatch: ${o}`);return u},async writeFile(o,a,s,l,c){let u=qu(c),d=new URLSearchParams({path:o,mtimeMs:String(Math.floor(s)||0)});u&&(d.set("baseSeq",String(u.baseSeq)),u.baseHash&&d.set("baseHash",u.baseHash));let f=await(await i(t(`/file?${d.toString()}`),{method:"PUT",body:new Uint8Array(a),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:l})).json();return{key:o,size:f.size,mtimeMs:f.mtimeMs,id:Cw(f)}},async rm(o,a,s){let l=qu(s),c=new URLSearchParams({path:o});l&&l.baseSeq>0&&(c.set("baseSeq",String(l.baseSeq)),l.baseHash&&c.set("baseHash",l.baseHash)),await i(t(`/file?${c.toString()}`),{method:"DELETE",signal:a})},async check(){try{return await i(t("/manifest"),{method:"GET"}),{ok:!0}}catch(o){return{ok:!1,error:String(o?.message||o)}}}}}var Nl="forsion-diagnostics",xw=50*1024*1024,Iw=new Map;async function DA(n,e){let t=Iw.get(e);if(t)return{id:t};let r=await cs(n,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let i=r.user?.username?.trim();return i?(Iw.set(e,i),{id:i}):{error:"penzor-auth-unverified"}}var PA=n=>zu(n).mode==="full"&&typeof n.syncTargets?.legacyRemoteSync=="function"&&typeof n.syncTargets?.open=="function",Wu=n=>typeof n.registerRemoteSyncBackend=="function"&&typeof n.readCreds=="function";function Gu(n){if(PA(n)){Ch(n),n.syncTargets.legacyRemoteSync().then(e=>{e?.config.backend==="penzor"?Hu(n):n.log('[forsion-extend] remote-sync backend "penzor" not registered (full mode, not the current remotesync backend)')},()=>Hu(n));return}Hu(n)}function Hu(n){n.registerRemoteSyncBackend("penzor",async e=>{let t=n.readCreds();if(!t.token||!t.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,i=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(i)||i===Nl)return{error:"penzor-bad-vault"};let o=await DA(t.cloudUrl,t.token);if("error"in o)return o;let a=t.token;return{remote:Ml({baseUrl:t.cloudUrl,vault:i,getToken:()=>a}),fingerprint:`penzor:${t.cloudUrl.replace(/\/+$/,"")}|u:${o.id}|${i}`,maxFileBytes:xw}}),n.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as MA}from"node:fs";import{access as NA,link as $A,lstat as LA,mkdir as FA,open as BA,readdir as jA,rename as UA,stat as $w,unlink as Yu}from"node:fs/promises";import{request as VA}from"node:http";import{request as zA}from"node:https";import{homedir as HA}from"node:os";import{basename as Lw,extname as qA,isAbsolute as WA,join as us}from"node:path";import{randomUUID as Ll}from"node:crypto";var ds=52428800;var Tw=["bytes","signed","text"],Dw=/^[A-Za-z0-9_-]{1,64}$/,Pw=/^[a-z0-9][a-z0-9-]{0,63}$/;function $l(n){if(typeof n!="string")return null;let t=(n.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f<>:"|?*]/g,"").trim().slice(0,200);return t&&t!=="."&&t!==".."?t:null}var OA={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".svg":"image/svg+xml",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Ow(n){let e=n.lastIndexOf(".");return OA[e>0?n.slice(e).toLowerCase():""]??"application/octet-stream"}function Mw(n,e,t,r){let i=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",o=encodeURIComponent(t).replace(/['()*]/g,s=>`%${s.charCodeAt(0).toString(16).toUpperCase()}`),a="";for(let[s,l]of Object.entries(e))a+=`--${n}\r
|
|
215
|
+
Content-Disposition: form-data; name="${s}"\r
|
|
201
216
|
\r
|
|
202
217
|
${l}\r
|
|
203
|
-
`;return a+=`--${
|
|
204
|
-
Content-Disposition: form-data; name="file"; filename="${i}"; filename*=UTF-8''${
|
|
218
|
+
`;return a+=`--${n}\r
|
|
219
|
+
Content-Disposition: form-data; name="file"; filename="${i}"; filename*=UTF-8''${o}\r
|
|
205
220
|
Content-Type: ${r}\r
|
|
206
221
|
\r
|
|
207
222
|
`,{head:a,tail:`\r
|
|
208
|
-
--${
|
|
209
|
-
`}}function zs(t,e){let n=t.filter(([o])=>e-o<=3e3);if(n.length<2)return 0;let[r,i]=n[0],[s,a]=n[n.length-1];return s>r?Math.max(0,(a-i)/(s-r)*1e3):0}function Bs(t,e){let n=e??{};return t===401?"not_signed_in":n.code==="STORAGE_QUOTA_EXCEEDED"?"quota":n.code==="STORAGE_BUSY"||n.code==="STORAGE_RECONCILIATION_REQUIRED"?"storage_unavailable":n.code==="FILE_TOO_LARGE"||t===413?"too_large":typeof n.detail=="string"&&/quota exceeded/i.test(n.detail)?"quota":n.code==="STORAGE_NOT_CONFIGURED"?"storage_unavailable":`http_${t}`}var dh=3,Ws=6e4,fh=200,ph=Ul;function Yl(t,e,n,r){let{head:i,tail:s}=ql(t,e,n,r);return{head:Buffer.from(i,"utf8"),tail:Buffer.from(s,"utf8")}}function hh(t,e,n,r,i,s,a,o){return new Promise((l,c)=>{let u=new URL(t),f=(u.protocol==="https:"?ah:oh)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+i+s.length)}},p=>{let m=[];p.on("data",y=>m.push(y)),p.on("end",()=>{let y=null;try{y=JSON.parse(Buffer.concat(m).toString("utf8"))}catch{}l({status:p.statusCode??0,body:y})}),p.on("error",c)}),g=()=>{f.destroy(new Error("aborted"))};if(o.aborted)return g();o.addEventListener("abort",g,{once:!0}),f.setTimeout(Ws,()=>f.destroy(new Error("timeout"))),f.on("error",p=>{o.removeEventListener("abort",g),c(p)}),(async()=>{try{f.write(n);let p=0;for await(let m of Zp(r)){let y=m;if(p+=y.length,p>i)throw new Error("changed");f.write(y)||await new Promise(b=>f.once("drain",b)),a(p)}if(p!==i)throw new Error("changed");f.end(s)}catch(p){f.destroy(p)}})()})}function Gs(t,e={}){let n=e.downloadsDir??(()=>ur(lh(),"Downloads")),r=e.post??hh,i=e.now??Date.now,s=[],a=new Map,o=Promise.resolve(),l=async()=>{let E=await t.getCloud(),D=typeof t.accountId=="function"?t.accountId():null;return{...E,account:D||`${E.base}|${E.token}`}},c=E=>{let{account:D,attempt:x,relDir:L,abort:V,samples:H,dl:N,...Y}=E;return{...Y,speed:E.state==="active"?zs(H,i()):0}},u=(E,D,x=null)=>{E.state=D,E.error=x,E.abort=null,E.finishedAt=i(),E.samples=[];let L=s.filter(V=>V.state==="done"||V.state==="canceled");for(let V of L.slice(0,Math.max(0,L.length-fh)))s.splice(s.indexOf(V),1);f()};function f(){for(let E of["up","down"]){let D=s.filter(x=>x.kind===E&&x.state==="active").length;for(let x of s){if(D>=dh)break;if(x.kind!==E||x.state!=="queued")continue;D++,x.state="active",x.startedAt=i(),x.done=0,x.samples=[[i(),0]],x.abort=new AbortController;let L=++x.attempt,V=()=>x.attempt===L&&x.state==="active";(E==="up"?_(x,V):T(x,V)).catch(H=>{V()&&u(x,"failed",g(H))})}}}let g=E=>{let D=String(E?.message||E);return D==="changed"||D==="too_large"||D==="quota"||D==="account_changed"||D==="not_signed_in"||D.startsWith("http_")||D==="bad_response"||D==="gone"?D:"network"},p=(E,D)=>{E.done=D;let x=i(),L=E.samples[E.samples.length-1];for((!L||x-L[0]>=200)&&E.samples.push([x,D]);E.samples.length>2&&x-E.samples[0][0]>3500;)E.samples.shift()};async function m(E){let D=await l();if(D.account!==E.account)throw new Error("account_changed");if(!D.token)throw new Error("not_signed_in");return D}async function y(E,D,x,L){let V=Nt(E,x);if(!V)throw new Error("bad_path");let H=await fetch(V,{method:L.method??"GET",headers:{Authorization:`Bearer ${D}`,...L.body!==void 0?{"Content-Type":"application/json"}:{},...L.projectSource?{"X-Project-Source":L.projectSource}:{}},body:L.body!==void 0?JSON.stringify(L.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:H.status,json:await H.json().catch(()=>null)}}function b(E,D,x){if(!E.relDir.length)return Promise.resolve(E.targetId);let L=a.get(E.batch);L||a.set(E.batch,L=new Map);let V=L,H=N=>{if(N===0)return Promise.resolve(E.targetId);let Y=E.relDir.slice(0,N).join("/"),ee=V.get(Y);return ee||(ee=H(N-1).then(async J=>{let se=E.relDir[N-1],te=await y(D,x,"/files",{method:"POST",body:{type:"directory",parentId:J,name:se},projectSource:E.projectSource});if(te.status===201&&typeof te.json?.id=="string")return te.json.id;if(te.status===409){let ae=await y(D,x,`/files${J==="ROOT"?"":`?parentId=${encodeURIComponent(J)}`}`,{projectSource:E.projectSource}),Q=Array.isArray(ae.json)?ae.json.find(me=>me?.fileType==="directory"&&me?.name===se):null;if(Q?.id)return String(Q.id)}throw new Error(te.status===401?"not_signed_in":`http_${te.status}`)}),ee.catch(()=>V.delete(Y)),V.set(Y,ee)),ee};return H(E.relDir.length)}async function _(E,D){let{base:x,token:L}=await m(E),V=await Gl(E.localPath).catch(()=>null);if(!V?.isFile())throw new Error("gone");if(V.size>52428800)throw new Error("too_large");E.size=V.size;let H=await b(E,x,L);if(!D())return;E.parentId=H;let N=Nt(x,"/files/upload");if(!N)throw new Error("bad_path");let Y=`----penzor${wi().replace(/-/g,"")}`,{head:ee,tail:J}=Yl(Y,{parentId:H,autoRename:"true"},E.name,Bl(E.name)),se=await r(N,{Authorization:`Bearer ${L}`,"Content-Type":`multipart/form-data; boundary=${Y}`,...E.projectSource?{"X-Project-Source":E.projectSource}:{}},ee,E.localPath,V.size,J,te=>{D()&&p(E,te)},E.abort.signal);D()&&(se.status===201||se.status===200?(E.fileId=typeof se.body?.id=="string"?se.body.id:null,p(E,E.size),u(E,"done")):u(E,"failed",Bs(se.status,se.body)))}function h(E,D,x,L){let V=async()=>{let N=ch(x),Y=N?x.slice(0,-N.length):x;for(let ee=0;ee<1e3;ee++){if(!L())throw new Error("aborted");let J=ur(D,ee===0?x:`${Y} (${ee})${N}`);try{await eh(E,J)}catch(se){let te=se.code;if(te==="EEXIST")continue;if(te!=="EPERM"&&te!=="ENOTSUP"&&te!=="EOPNOTSUPP"&&te!=="ENOSYS"&&te!=="EXDEV")throw se;if(await Qp(J).then(()=>!0,()=>!1))continue;await sh(E,J)}if(!L())throw await qs(J).catch(()=>{}),new Error("aborted");return await qs(E).catch(()=>{}),J}throw new Error("too many duplicates")},H=o.then(V,V);return o=H.catch(()=>{}),H}async function T(E,D){let x=E.dl,{base:L,token:V}=await m(E);if(!D())return;let H=Nt(L,x.path);if(!H)throw new Error("bad_path");let N=E.abort.signal,Y=x.subdir?ur(n(),x.subdir):n();await nh(Y,{recursive:!0});let ee=ur(Y,`.${E.id}-${E.attempt}.penzor-part`),J=await rh(ee,"wx"),se=!1;try{let te=new AbortController,ae=setTimeout(()=>te.abort(),Ws),Q=()=>{clearTimeout(ae),ae=setTimeout(()=>te.abort(),Ws)},me=AbortSignal.any([N,te.signal]);try{let ge=await fetch(H,{headers:{Authorization:`Bearer ${V}`},signal:me});if(!ge.ok)throw new Error(ge.status===401?"not_signed_in":`http_${ge.status}`);let Pe=ge.body,Ce=Number(ge.headers.get("content-length"))||E.size;if(x.mode!=="bytes"){let He=await ge.json().catch(()=>null);if(x.mode==="text"){if(typeof He?.content!="string")throw new Error("bad_response");let Ae=Buffer.from(He.content,"utf8");await J.writeFile(Ae),E.size=Ae.length,p(E,Ae.length),Pe=null}else{if(typeof He?.url!="string"||!/^https?:\/\//i.test(He.url))throw new Error("bad_response");let Ae=await fetch(He.url,{signal:me});if(!Ae.ok)throw new Error(`http_${Ae.status}`);Pe=Ae.body,Ce=Number(Ae.headers.get("content-length"))||E.size}}if(Pe){E.size=Ce;let He=0;for await(let Ae of Pe){Q();for(let ut=0;ut<Ae.length;){let{bytesWritten:M}=await J.write(Ae,ut,Ae.length-ut);if(M<=0)throw new Error("short_write");ut+=M}if(He+=Ae.length,!D())throw new Error("aborted");p(E,He)}He>E.size&&(E.size=He)}}finally{clearTimeout(ae)}if(await J.close(),!D()||(E.localPath=await h(ee,Y,x.name,D),se=!0,!D()))return;u(E,"done")}finally{se||(await J.close().catch(()=>{}),await qs(ee).catch(()=>{}))}}let v=(E,D)=>{let x={...E,id:wi(),attempt:0,done:0,state:D?"failed":"queued",error:D??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:D?i():null};return s.push(x),x};async function I(E){let D=[],x=async(L,V)=>{if(V.length>32)return!0;let H=await(V.length?th(L):Gl(L)).catch(()=>null);if(!H)return!0;if(H.isFile())return D.push({path:L,size:H.size,relDir:V}),D.length<=2e3;if(!H.isDirectory())return!0;let N=(await ih(L).catch(()=>[])).filter(Y=>!Y.startsWith(".")).sort();for(let Y of N)if(!await x(ur(L,Y),[...V,Vl(L)]))return!1;return!0};for(let L of E)if(!await x(L,[]))return"too_many";return D}return t.handle("penzor:device",E=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let D=hi();return{ok:!0,name:D?decodeURIComponent(D):null}}),t.handle("penzor:upload",async(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=Array.isArray(x.paths)?x.paths.filter(Q=>typeof Q=="string"&&uh(Q)):[],V=typeof x.parentId=="string"&&Hl.test(x.parentId)?x.parentId:null,H=typeof x.projectSource=="string"&&zl.test(x.projectSource)?x.projectSource:null;if(!L.length)return{ok:!1,error:"no_files"};if(!V||!H)return{ok:!1,error:"bad_target"};let{base:N,token:Y,account:ee}=await l();if(!Y)return{ok:!1,error:"not_signed_in"};let J=await I(L);if(J==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!J.length)return{ok:!1,error:"no_files"};let se=J.filter(Q=>Q.size<=52428800).reduce((Q,me)=>Q+me.size,0);try{let Q=await y(N,Y,"/storage/quota",{}),me=Number(Q.json?.used),ge=Number(Q.json?.quota);if(Q.status===200&&ge>0&&me+se>ge)return{ok:!1,error:"quota",short:me+se-ge}}catch{}if((await l()).account!==ee)return{ok:!1,error:"account_changed"};let te=wi(),ae=J.map(Q=>v({kind:"up",name:Vl(Q.path),size:Q.size,projectSource:H,parentId:Q.relDir.length?null:V,targetId:V,fileId:null,localPath:Q.path,batch:te,account:ee,relDir:Q.relDir},Q.size>52428800?"too_large":void 0).id);return f(),{ok:!0,ids:ae,batch:te}}),t.handle("penzor:download",async(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=ph.includes(x.mode)?x.mode:null,V=yi(x.name);if(!L)return{ok:!1,error:"bad_mode"};if(!V)return{ok:!1,error:"bad_name"};let{base:H,token:N,account:Y}=await l();if(typeof x.path!="string"||!Nt(H,x.path))return{ok:!1,error:"bad_path"};if(!N)return{ok:!1,error:"not_signed_in"};let ee=x.subdir==null?null:yi(x.subdir),J=v({kind:"down",name:V,size:Math.max(0,Number(x.size)||0),localPath:null,batch:typeof x.batch=="string"&&x.batch.length<=64?x.batch:wi(),account:Y,relDir:[],dl:{path:x.path,mode:L,name:V,subdir:ee}});return f(),{ok:!0,id:J.id}}),t.handle("penzor:transfers",E=>t.isTrustedSender(E)?{ok:!0,items:s.map(c)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=s.find(H=>H.id===x.id);if(!L)return{ok:!1,error:"not_found"};let V=()=>{L.abort?.abort(),L.abort=null,L.done=0,L.samples=[]};switch(x.op){case"pause":(L.state==="active"||L.state==="queued")&&(V(),L.state="paused",f());break;case"resume":L.state==="paused"&&(L.state="queued",f());break;case"cancel":(L.state==="active"||L.state==="queued"||L.state==="paused")&&(V(),u(L,"canceled"));break;case"retry":(L.state==="failed"||L.state==="canceled")&&(L.state="queued",L.error=null,L.finishedAt=null,L.done=0,f());break;case"dismiss":L.state!=="active"&&L.state!=="queued"&&s.splice(s.indexOf(L),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D?.which==="all";for(let L of[...s])(L.state==="done"||L.state==="canceled"||x&&L.state==="failed")&&s.splice(s.indexOf(L),1);return{ok:!0}}),t.addQuitGuard?.(E=>{let D=s.filter(x=>x.state==="active"||x.state==="queued"||x.state==="paused").length;return D?E==="zh"?{message:`\u8FD8\u6709 ${D} \u4E2A\u6587\u4EF6\u6CA1\u4F20\u5B8C`,detail:"\u73B0\u5728\u9000\u51FA\u4F1A\u4E2D\u65AD\uFF0C\u4E0B\u6B21\u6253\u5F00\u8981\u91CD\u65B0\u4F20\u3002"}:{message:D===1?"1 file hasn't finished transferring":`${D} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>s.map(c)}}import{readFileSync as kh,writeFileSync as Eh,mkdirSync as _h,chmodSync as Ch,renameSync as Ah}from"node:fs";import{join as xh}from"node:path";import{mkdirSync as gh,readFileSync as mh,renameSync as yh,unlinkSync as wh,writeFileSync as bh}from"node:fs";import{dirname as Sh,join as vh}from"node:path";import{randomUUID as Jl}from"node:crypto";var Ks=t=>vh(t,"content-sync","active-account.json"),Vs=()=>Error("Invalid content sync account binding; original data was retained");function dr(t){try{let e=JSON.parse(mh(t,"utf8"));if(e?.version!==1||!(e.account===null&&e.pending===!0||typeof e.account=="string"&&/^[a-f0-9]{64}$/.test(e.account))||e.epoch!==void 0&&(typeof e.epoch!="string"||!/^[a-f0-9-]{36}$/i.test(e.epoch))||e.pending!==void 0&&typeof e.pending!="boolean"||e.pending&&!e.epoch)throw Vs();return e}catch(e){if(e?.code==="ENOENT")return null;throw Vs()}}function Xs(t,e){gh(Sh(t),{recursive:!0,mode:448});let n=t+".tmp-"+Jl();try{bh(n,JSON.stringify(e),{flag:"wx",mode:384}),yh(n,t)}finally{try{wh(n)}catch{}}}var Ys=new WeakMap,Js=new WeakSet;function Kl(t,e){let n=Ys.get(t);return n||Ys.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function Zs(t){if(Js.has(t))throw Vs()}function En(t,e,n){if(!t.contentSync||e===n)return;let r=Ks(t.homeDir());try{let i=dr(r);Xs(r,{version:1,account:i?.account??null,epoch:Jl(),pending:!0}),Js.delete(t)}catch(i){throw Js.add(t),i}finally{for(let i of Ys.get(t)??[])i()}}function Th(t){let e=()=>xh(t(),"auth-accounts.json");return{read:()=>kh(e(),"utf8"),write:n=>{_h(t(),{recursive:!0});let r=`${e()}.tmp`;Eh(r,n,{encoding:"utf8",mode:384}),Ch(r,384),Ah(r,e())}}}var Zl=t=>Ga(t,Th(()=>t.homeDir())),Ql=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],Qs=t=>Ql.every(e=>typeof t[e]=="function");function eo(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=Zl(t),i=0,s=()=>{let l=t.readCreds();return rr(l.cloudUrl,l.token)},a=l=>Ve(l.cloudUrl??"",l.token??""),o=null;t.handle("auth:status",async l=>{if(!t.isTrustedSender(l))return n;let c=i,u=s(),{base:f}=await t.getCloud(),g=t.readCreds().token,p=g?await lr(f,g):null,m=await t.accountBackendState(),{base:y}=await t.getCloud(),b=t.readCreds(),_=rr(y,b.token)!==rr(f,g),h=rr(f,g);!_&&p?.status==="ok"&&p.user&&(o={key:h,user:p.user},r.rememberForsionAccount({...b,cloudUrl:f},p.user));let T=_?void 0:p?.status==="ok"?p.user:p?.status==="offline"&&o?.key===h?o.user:void 0;if(_)return{loggedIn:!!b.token,tokenValid:null,cloudUrl:y,accountId:Ve(y,b.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:b.token?"tangu-login":null,backendState:m};if(p?.status==="expired"){await t.accountTransition(async()=>{if(c!==i||s()!==u)return;let I=()=>{if(c!==i||s()!==u)throw Xl};try{await t.accountClear(I,()=>{En(t,t.accountId?.()??null,null),t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++i,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),o=null})}catch(E){if(E!==Xl)throw E}});let v=t.readCreds();return{loggedIn:!!v.token,tokenValid:null,cloudUrl:v.cloudUrl||f,accountId:Ve(v.cloudUrl||f,v.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:v.token?"tangu-login":null,backendState:m}}return{loggedIn:!!g,tokenValid:p&&p.status==="ok"?!0:null,cloudUrl:f,accountId:Ve(f,g),username:T?.username||null,nickname:T?.nickname||null,avatar:T?.avatar||null,membershipTier:T?.membershipTier||null,tokenSource:g?"tangu-login":null,backendState:m}}),t.handle("auth:accounts",l=>t.isTrustedSender(l)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(l,c)=>{if(!t.isTrustedSender(l))return e;if(typeof c!="string")throw new Error("Invalid account.");let u=++i;return r.cancelForsionLogin(),t.accountTransition(async()=>{let f=r.savedForsionAccount(c);return await t.accountCommit(f,()=>{if(u!==i)throw new Error("Account switch cancelled.")},()=>{En(t,t.accountId?.()??null,a(f)),r.rememberForsionAccount(f),o=null}),{ok:!0,cloudUrl:f.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(l,c)=>{if(!t.isTrustedSender(l))return e;let u=++i;r.cancelForsionLogin();let{base:f}=await t.getCloud();if(u!==i)throw new Error("Sign-in cancelled.");let g=(c||f||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(g,m=>t.broadcast("auth:device",m),(m,y)=>t.accountTransition(()=>t.accountCommit(m,()=>{if(y(),u!==i)throw new Error("Sign-in cancelled.")},()=>{En(t,t.accountId?.()??null,a(m)),r.rememberForsionAccount(m),o=null})))).cloudUrl}}),t.handle("auth:logout",async l=>t.isTrustedSender(l)?(++i,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:c}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{En(t,t.accountId?.()??null,null),r.forgetForsionAccount(u),o=null,c&&u.token&&fetch(`${c}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${u.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:l,current:c})=>{try{En(t,a(l),a(c))}catch{t.log("[content-sync] account transition could not be recorded; sync is stopped")}++i,r.cancelForsionLogin(),l.token&&!c.token&&r.forgetForsionAccount(l),o=null,r.rememberForsionAccount(c)}),t.setTokenRefresher(async l=>{let c=i,u=s(),f=t.readCreds().token;if(!ni(f))return;let{base:g}=await t.getCloud(),p=await ri(g,f,l,`desktop/${t.appVersion()}`);if(!p){t.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}c!==i||s()!==u||(r.rememberForsionAccount({cloudUrl:g,token:p}),t.writeCreds({cloudUrl:g,token:p}),t.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),t.log("[forsion-extend] account core registered")}var Xl=Symbol("stale-auth-intent");import{promises as Dn}from"node:fs";import dn from"node:path";import{execFile as dg}from"node:child_process";import fg from"node:os";var to=null;function ec(t){to=t}var tc=null;function nc(t){tc=t}var rc=()=>tc;function Le(){if(!to)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return to}var Be=()=>Le().accountId();function _n(t=Be()){return t?Ee().sha256Hex(t):"signed-out"}var ot=(t=Be())=>Le().readConfig(t),Pt=(t,e=Be())=>Le().writeConfig(t,e),Cn=(t,e=Be())=>Le().updateConfig(t,e),$t=(t=Be())=>Le().cloudVaultDir(t),bi=t=>Le().isManagedCloudVault(t);function Ih(t,e){let n=Object.create(null);for(let s=0;s<e.length;s++){let a=e[s];n[a]?n[a].push(s):n[a]=[s]}let i=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let s=0;s<t.length;s++){let a=t[s],o=n[a]||[],l=0,c=i[0];for(let u of o){let f;for(f=l;f<i.length&&!(i[f].buffer2index<u&&(f===i.length-1||i[f+1].buffer2index>u));f++);if(f<i.length){let g={buffer1index:s,buffer2index:u,chain:i[f]};if(l===i.length?i.push(c):i[l]=c,l=f+1,c=g,l===i.length)break}}i[l]=c}return i[i.length-1]}function ic(t,e){let n=Ih(t,e),r=[],i=t.length,s=e.length;for(let a=n;a!==null;a=a.chain){let o=i-a.buffer1index-1,l=s-a.buffer2index-1;i=a.buffer1index,s=a.buffer2index,(o||l)&&r.push({buffer1:[i+1,o],buffer1Content:t.slice(i+1,i+1+o),buffer2:[s+1,l],buffer2Content:e.slice(s+1,s+1+l)})}return r.reverse(),r}function Rh(t,e,n){let r=[];function i(l,c){r.push({ab:c,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}ic(e,t).forEach(l=>i(l,"a")),ic(e,n).forEach(l=>i(l,"b")),r.sort((l,c)=>l.oStart-c.oStart);let s=[],a=0;function o(l){l>a&&(s.push({stable:!0,buffer:"o",bufferStart:a,bufferLength:l-a,bufferContent:e.slice(a,l)}),a=l)}for(;r.length;){let l=r.shift(),c=l.oStart,u=l.oStart+l.oLength,f=[l];for(o(c);r.length;){let g=r[0],p=g.oStart;if(p>u)break;u=Math.max(u,p+g.oLength),f.push(r.shift())}if(f.length===1){if(l.abLength>0){let g=l.ab==="a"?t:n;s.push({stable:!0,buffer:l.ab,bufferStart:l.abStart,bufferLength:l.abLength,bufferContent:g.slice(l.abStart,l.abStart+l.abLength)})}}else{let g={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;f.length;){l=f.shift();let h=l.oStart,T=h+l.oLength,v=l.abStart,I=v+l.abLength,E=g[l.ab];E[0]=Math.min(v,E[0]),E[1]=Math.max(I,E[1]),E[2]=Math.min(h,E[2]),E[3]=Math.max(T,E[3])}let p=g.a[0]+(c-g.a[2]),m=g.a[1]+(u-g.a[3]),y=g.b[0]+(c-g.b[2]),b=g.b[1]+(u-g.b[3]),_={stable:!1,aStart:p,aLength:m-p,aContent:t.slice(p,m),oStart:c,oLength:u-c,oContent:e.slice(c,u),bStart:y,bLength:b-y,bContent:n.slice(y,b)};s.push(_)}a=u}return o(e.length),s}function sc(t,e,n,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof t=="string"&&(t=t.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof n=="string"&&(n=n.split(r.stringSeparator));let s=[],a=Rh(t,e,n),o=[];function l(){o.length&&s.push({ok:o}),o=[]}function c(u,f){if(u.length!==f.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==f[g])return!1;return!0}return a.forEach(u=>{u.stable?o.push(...u.bufferContent):r.excludeFalseConflicts&&c(u.aContent,u.bContent)?o.push(...u.aContent):(l(),s.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),l(),s}function Si(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),i=n<0?t:t.slice(n+1),s=i.lastIndexOf("."),a=s>0?i.slice(0,s):i,o=s>0?i.slice(s):"",l=u=>String(u).padStart(2,"0"),c=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${r}${a} (conflict ${c})${o}`}function Dh(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),i=r?t.slice(0,n):t,s=r?t.slice(n):"";return`${i}-${e}${s}`}function Oh(t){let e=3735928559,n=1103547991;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=Math.imul(e^s,2654435761),n=Math.imul(n^s,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let r=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${r.toString(36)}`}var An=(t,e)=>e.seq===t.seq&&e.hash!==null&&e.hash!==t.hash,oc=(t,e)=>e.seq!==t.seq||An(t,e);function vi(t,e,n){if(t===null&&e===null&&n===null)return{kind:"none"};if(n===null)return t===null?e?{kind:"dropShadow"}:{kind:"none"}:e?t===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(t===null)return e?oc(e,n)?{kind:"pull"}:{kind:"pushDelete"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"hold"};if(An(e,n))return t===n.hash?{kind:"adopt"}:t===e.hash?{kind:"pull"}:{kind:"hold"};let r=t!==e.hash,i=oc(e,n);return!r&&!i?{kind:"none"}:r?i?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function ac(t,e,n){let r=sc(t.split(`
|
|
210
|
-
`),e.split(`
|
|
211
|
-
`),n.split(`
|
|
212
|
-
`),{excludeFalseConflicts:!0}),i=[];for(let s of r){if(s.conflict)return null;s.ok&&i.push(...s.ok)}return i.join(`
|
|
213
|
-
`)}function fr(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var lc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function cc(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function no(t){let e=t??"";if(/^(?:ENOENT|EACCES|EPERM|EBUSY|EISDIR|ENOTDIR|EEXIST|EMFILE|ENFILE|ENOSPC|EROFS|EIO|ENAMETOOLONG)\b/.test(e))return"errOther";let n=/^(?:cloud|sse) http (\d{3})\b/i.exec(e);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|etimedout/i.test(e)?"errTimeout":!e||/fetch failed|econn|enotfound|eai_again|enetunreach|ehostunreach|enetdown|network|socket|terminated|other side closed|und_err|^cloud http 0\b/i.test(e)?"errOffline":"errOther"}function uc(t){if(!(t instanceof Error))return;let e=t.cause,n=e&&typeof e=="object"?[e.code,e.message].filter(r=>typeof r=="string"&&r).join(" "):"";return n?`${t.message} (${n})`:t.message}function dc(t,e){if(t==="offline")return no(e);if(t==="auth-required")return e==="not-logged-in"?null:"errAuth";if(t!=="error")return null;let n=e??"";return n.startsWith("vault-missing")?"errVaultMissing":n.startsWith("scan-failed")?"errScan":n.startsWith("mirror-missing")?"errMirrorMissing":"errOther"}function ki(t,e=0){if(/^(account_changed|content_sync_closed|paused)$/.test(t)||/^File exceeds \d+ MB/.test(t))return null;if(t==="not_signed_in"||e===401||e===403)return"errAuth";let n=/^content_http_(\d{3})$/.exec(t);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|aborted due to timeout/i.test(t)?"errTimeout":/fetch failed|econn|enotfound|eai_again|network|socket/i.test(t)?"errOffline":/^Sync root (unavailable|changed|is not a directory)|^content_roots_changed/.test(t)?"errVaultMissing":e?"errHttp":"errOther"}function Ei(t){let e=null;return{error(n){n!==e&&(e=n,t?.(n))},ok(){e=null}}}var Mh=/[\u0000-\u001f\u007f]/;function Yt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||Mh.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function ro(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Yt(n):n.startsWith(`${e}/`)?Yt(n.slice(e.length+1)):null}function fc(t,e){return e===""?t:`${e}/${t}`}function pr(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function De(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var qe=t=>t==="page"||t==="db";var Nh=t=>Math.max(3,Math.ceil(t*.1)),Ph=(t,e)=>t===429&&e!=="MASS_DELETE_BLOCKED";function $h(t,e=Date.now()){if(!t)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:Math.max(0,r-e)}function jh(t){let e=t.get("ratelimit"),n,r,i;if(e){let s=a=>Number(new RegExp(`(?:^|[;,\\s])${a}=(\\d+)`).exec(e)?.[1]??NaN);n=s("limit"),r=s("remaining"),i=s("reset")}else n=Number(t.get("ratelimit-limit")??NaN),r=Number(t.get("ratelimit-remaining")??NaN),i=Number(t.get("ratelimit-reset")??NaN);return![n,r,i].every(s=>Number.isFinite(s)&&s>=0)||n<=0?null:{limit:n,remaining:r,resetMs:i*1e3}}function Lh(t={}){let e=t.now??Date.now,n=0,r=null,i=new Set,s=()=>{for(let o of[...i])try{o()}catch{}},a=o=>{let l=e()+Math.min(Math.max(o,0),6e5);l<=n||(n=l,r&&clearTimeout(r),r=setTimeout(()=>{r=null,s()},n-e()),r.unref?.(),s())};return{until:()=>n>e()?n:null,async ready(o){for(;n>e();)o?.throwIfAborted(),await new Promise((l,c)=>{let u=setTimeout(f,n-e());function f(){o?.removeEventListener("abort",g),l()}function g(){clearTimeout(u),c(o.reason??new DOMException("Aborted","AbortError"))}o?.addEventListener("abort",g,{once:!0})});o?.throwIfAborted()},observe(o,l,c,u){let f=jh(l);if(Ph(o,c)){let g=$h(l.get("retry-after"),e())??(typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null)??(f&&f.remaining===0&&f.resetMs>0?f.resetMs:null);return a(Math.max(g??3e4,1e3)),!0}return f&&f.remaining<=Nh(f.limit)&&f.resetMs>0&&a(f.resetMs),!1},subscribe(o){return i.add(o),()=>{i.delete(o)}}}}var pc=new Map;function Jt(t){let e;try{e=new URL(t).origin}catch{e=t.replace(/\/+$/,"")}let n=pc.get(e);return n||(n=Lh(),pc.set(e,n)),n}var Fh=1024,ye=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},hc=t=>12e4+Math.ceil(t/256);function Uh(t,e){let n=AbortSignal.timeout(t);if(!e)return n;let r=new AbortController;for(let i of[n,e])i.addEventListener("abort",()=>r.abort(i.reason),{once:!0});return r.signal}function gc(t,e){if(!t||!e)return t??e;let n=new AbortController;for(let r of[t,e]){if(r.aborted){n.abort(r.reason);break}r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}function mc(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=t.gate??Jt(t.baseUrl),r=()=>t.getToken?.()??t.token,i=async(o,l)=>{let c=r();for(let u=0;;u++){let f={...l.headers,Authorization:`Bearer ${c}`},g=await fetch(o,{...l,headers:f});if(r(),g.status!==401||g.redirected)return g;let p=await g.text(),m=r();if(m===c||u>0)return new Response(p,{status:g.status,statusText:g.statusText,headers:g.headers});c=m}},s=async(o,l,c)=>{let u={Authorization:`Bearer ${t.token}`,...c?.headers};o!=="GET"&&(u["X-Amadeus-Client"]=t.clientId);let f;for(c?.json!==void 0?(u["Content-Type"]="application/json",f=JSON.stringify(c.json),f.length>=Fh&&(u["Content-Encoding"]="gzip",f=await qa(f))):c?.form&&(f=c.form);;){n.until()!==null&&await n.ready(gc(c?.signal,t.signal));let g=await i(l,{method:o,headers:u,body:f,signal:Uh(c?.timeoutMs??3e4,c?.signal)});if(!g.ok){let m=null;try{m=await g.json()}catch{}if(r(),n.observe(g.status,g.headers,m?.code,m?.retryAfterMs))continue;throw new ye(g.status,m,l)}n.observe(g.status,g.headers);let p=await g.json();return r(),p}},a=o=>new URLSearchParams(o).toString();return{clientId:t.clientId,async listVaults(){return((await s("GET",`${e}/vaults`)).vaults??[]).map(l=>({id:String(l.id),name:String(l.name),lastChangeSeq:Number(l.lastChangeSeq??0)}))},async tree(o){let l=await s("GET",`${e}/vaults/${o}/tree`);if(!Array.isArray(l.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:l.folders??[],seq:Number(l.seq??0),maxFileBytes:Number.isInteger(l.maxFileBytes)&&l.maxFileBytes>0?l.maxFileBytes:void 0,entries:l.entries.map(c=>({path:String(c.path),kind:c.kind,seq:Number(c.seq??0),hash:c.hash??null,size:Number(c.size??0),updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}))}},async getFile(o,l){let c=await s("GET",`${e}/vaults/${o}/file?${a({path:l})}`);return{content:String(c.content??""),seq:Number(c.seq??0),hash:c.hash??null,updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}},putFile(o,l,c,u,f=!1,g){return s("PUT",`${e}/vaults/${o}/file`,{json:{path:l,content:c,baseSeq:u,...f?{force:!0}:{},...g?{expectedHash:g}:{}}})},async deleteFile(o,l,c,u){let f={path:l};c!==void 0&&(f.baseSeq=String(c)),u?.expectedHash&&(f.expectedHash=u.expectedHash),await s("DELETE",`${e}/vaults/${o}/file?${a(f)}`,u?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(o,l,c){return s("POST",`${e}/vaults/${o}/move`,{json:{from:l,to:c}})},renameFolder(o,l,c){return s("POST",`${e}/vaults/${o}/folders/rename`,{json:{path:l,newName:c}})},moveFolder(o,l,c){return s("POST",`${e}/vaults/${o}/folders/move`,{json:{path:l,dest:c}})},async deleteFolder(o,l){await s("DELETE",`${e}/vaults/${o}/folders?${a({path:l})}`)},putBinary(o,l,c,u){let f=new FormData;return f.set("path",l),u?.ifAbsent&&f.set("ifAbsent","true"),u?.baseSeq!==void 0&&f.set("baseSeq",String(u.baseSeq)),u?.expectedHash&&f.set("expectedHash",u.expectedHash),f.set("file",new Blob([new Uint8Array(c)]),l.split("/").pop()||"file"),s("POST",`${e}/vaults/${o}/binary`,{form:f,timeoutMs:hc(c.length),signal:u?.signal})},async listVersions(o,l){return((await s("GET",`${e}/vaults/${o}/file/versions?${a({path:l})}`)).versions??[]).map(u=>({id:String(u.id),seq:Number(u.seq??0)}))},async getVersion(o,l){let c=await s("GET",`${e}/vaults/${o}/file/versions/${l}`);return String(c.content??"")},async getAsset(o,l,c){let u=new AbortController;c?.addEventListener("abort",()=>u.abort(c.reason),{once:!0});let f=()=>u.abort(new DOMException("Asset download timed out","TimeoutError")),g;try{let p;for(;;){if(clearTimeout(g),n.until()!==null&&await n.ready(gc(c,t.signal)),g=setTimeout(f,12e4),p=await i(`${e}/vaults/${o}/asset?${a({ref:l})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:u.signal}),p.status!==429){n.observe(p.status,p.headers);break}let y=await p.json().catch(()=>null);if(!n.observe(p.status,p.headers,y?.code,y?.retryAfterMs))break}if(!p.ok)throw new ye(p.redirected&&(p.status===401||p.status===403)?502:p.status,null,"asset:"+l);clearTimeout(g),g=setTimeout(f,hc(Number(p.headers.get("content-length"))||0));let m=new Uint8Array(await p.arrayBuffer());return r(),m}finally{clearTimeout(g)}},async changes(o,l){let c=await s("GET",`${e}/vaults/${o}/changes?${a({since:String(l)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function yc(t,e){let n=!1,r=0,i=null,s=null,a=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,o=(c,u=!1)=>{if(n)return;i?.abort(),e.onDown(c,u);let f=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,s=setTimeout(()=>void l(),f)},l=async()=>{if(n)return;i=new AbortController;try{await t.gate?.ready(i.signal)}catch{return}if(n)return;let c;try{if(c=await fetch(a(),{headers:{Authorization:`Bearer ${t.getToken?.()??t.token}`,Accept:"text/event-stream"},signal:i.signal}),n){await c.body?.cancel();return}t.getToken?.()}catch(_){o(_);return}if(c.status===429&&t.gate&&(c.body?.cancel().catch(()=>{}),t.gate.observe(c.status,c.headers))){if(n)return;s=setTimeout(()=>void l(),Math.max(0,(t.gate.until()??Date.now())-Date.now()));return}if(!c.ok||!c.body){o(new Error(`sse http ${c.status}`));return}t.gate?.observe(c.status,c.headers),r=0;let u=Date.now();e.onOpen();let f=c.body.getReader(),g=new TextDecoder,p="",m="",y=[],b=()=>{if(t.getToken?.(),!y.length&&!m)return;let _=y.join(`
|
|
214
|
-
`),h=m||"message";m="",y=[];let T=null;try{T=_?JSON.parse(_):null}catch{return}h==="hello"?e.onHello(Number(T?.seq??0)):h==="change"?e.onChange(T):h==="reset"?e.onReset():h==="presence"?e.onPresence?.(T):h==="presence-roster"&&e.onPresenceRoster?.(T)};try{for(;;){let{done:_,value:h}=await f.read();if(_)break;for(p+=g.decode(h,{stream:!0});;){let T=p.indexOf(`
|
|
215
|
-
`);if(T<0)break;let v=p.slice(0,T).replace(/\r$/,"");if(p=p.slice(T+1),v==="")b();else{if(v.startsWith(":"))continue;v.startsWith("event:")?m=v.slice(6).trim():v.startsWith("data:")&&y.push(v.slice(5).replace(/^ /,""))}}}}catch(_){n||o(_,Date.now()-u>=1e4);return}o(new Error("sse stream ended"),Date.now()-u>=1e4)};return l(),{stop:()=>{n=!0,s&&clearTimeout(s),i?.abort()}}}var un=t=>Ee().path.join(Le().userDataDir(),Le().isDevMode()?`${t}.dev.json`:`${t}.json`),io=un,St=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,ln=t=>typeof t=="string"&&Yt(t)===t,hr=t=>typeof t=="string"&&t.length>0,wc=t=>St(t)&&cn(t.seq)&&hr(t.hash)&&cn(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),bc=t=>typeof t=="number"&&Number.isFinite(t),Hh=t=>St(t)&&hr(t.localHash)&&cn(t.localSize)&&bc(t.localMtimeMs)&&cn(t.remoteSeq)&&(t.remoteHash===null||hr(t.remoteHash))&&(t.remoteUpdatedAt===null||typeof t.remoteUpdatedAt=="string")&&bc(t.since),zh=t=>St(t)&&ln(t.from)&&ln(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||St(t.hashes)&&Object.values(t.hashes).every(hr));async function so(t){let e;try{e=await Ee().fs.readFile(io(t),"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let n;try{n=JSON.parse(e)}catch{throw Error("Invalid cloud vault sync state; original data was retained")}if(!St(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Vt(n.rootIdentity)||n.mirrorMissing!==void 0&&n.mirrorMissing!==!0||n.mirrorRestore!==void 0&&n.mirrorRestore!=="list"&&(!St(n.mirrorRestore)||!Object.entries(n.mirrorRestore).every(([r,i])=>ln(r)&&St(i)&&cn(i.seq)&&(i.hash===null||hr(i.hash))))||!St(n.files)||!Object.entries(n.files).every(([r,i])=>ln(r)&&wc(i))||n.cursor!==void 0&&!cn(n.cursor)||n.lastSyncAt!=null&&!cn(n.lastSyncAt)||n.pending!==void 0&&(!St(n.pending)||!Object.entries(n.pending).every(([r,i])=>ln(r)&&(i==="local"||i==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(zh))||n.held!==void 0&&(!St(n.held)||!Object.entries(n.held).every(([r,i])=>ln(r)&&Hh(i)))||n.dormant!==void 0&&(!St(n.dormant)||!Object.entries(n.dormant).every(([r,i])=>ln(r)&&wc(i)))||n.dormantRoot!==void 0&&!Vt(n.dormantRoot))throw Error("Invalid cloud vault sync state; original data was retained");return{...n,cursor:n.cursor??0,lastSyncAt:n.lastSyncAt??null}}function Sc(t){let e=null,n=null,r=Promise.resolve(),i=null,s=()=>{if(!e)return r;let a=e,o=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let l=io(t),c=`${l}.tmp-${Ee().tmpTag()}-${Date.now()}-0`;await Ee().fs.writeFile(c,o,"utf8"),await Ee().fs.rename(c,l),i=null}catch(l){e??=a,i=l}}),r};return{save(a){e=a,!n&&(n=setTimeout(()=>{n=null,s()},500))},async flush(a=!1){if(n&&(clearTimeout(n),n=null),await s(),a&&i)throw i}}}async function vc(t){try{await Ee().fs.unlink(io(t))}catch{}}var gr=/^[0-9a-f]{64}$/;function kc(t){let e=Ee(),n=()=>un(t).replace(/\.json$/,".bases"),r=o=>e.path.join(n(),o),i=o=>e.fs.access(r(o)).then(()=>!0,()=>!1),s=new Map,a=(o,l)=>{let c=(s.get(o)??Promise.resolve()).then(l,l);return s.set(o,c),c.finally(()=>{s.get(o)===c&&s.delete(o)}),c};return{put(o,l){return gr.test(o)?a(o,async()=>{try{if(await i(o))return;await e.fs.mkdir(n(),{recursive:!0});let c=`${r(o)}.tmp-${e.tmpTag()}-${Date.now()}`;await e.fs.writeFile(c,l,"utf8"),await e.fs.rename(c,r(o))}catch{}}):Promise.resolve()},async get(o){if(!gr.test(o))return null;try{let l=await e.fs.readFile(r(o),"utf8");return e.sha256Hex(l)===o?l:null}catch{return null}},drop(o,l){return gr.test(o)?a(o,async()=>{if(!(l&&!l()))try{await e.fs.rm(r(o),{force:!0})}catch{}}):Promise.resolve()},async has(o){return gr.test(o)&&i(o)},async prune(o){let l;try{l=(await e.fs.readdir(n(),{withFileTypes:!0})).filter(c=>c.isFile()).map(c=>c.name)}catch{return}for(let c of l)if(!o.has(c)&&!(!gr.test(c)&&!/^[0-9a-f]{64}\.tmp-/.test(c)))try{await e.fs.rm(e.path.join(n(),c),{force:!0})}catch{}}}}var Bh=720*60*60*1e3,qh=/^[0-9a-f]{64}$/,_i=new Map,Ec=(t,e)=>{let n=(_i.get(t)??Promise.resolve()).then(e,e),r=n.catch(()=>{});return _i.set(t,r),r.then(()=>{_i.get(t)===r&&_i.delete(t)}),n},oo=class extends Error{constructor(e){super(`sync recovery save failed: ${e?.message??String(e)}`),this.name="RecoveryError"}};function _c(t){let e=Ee(),n=()=>e.path.join(Le().homeDir(),"sync-recovery",t),r=o=>e.fs.access(o).then(()=>!0,()=>!1),i=async(o,l)=>{let c=`${o}.tmp-${e.tmpTag()}-${Date.now()}`;try{await e.fs.writeFile(c,l),await e.fs.rename(c,o)}catch(u){throw await e.fs.rm(c,{force:!0}).catch(()=>{}),u}},s={async save(o,l){let c=n(),u=await Ec(c,async()=>{try{let f=e.path.join(c,e.sha256Hex(o));await e.fs.mkdir(c,{recursive:!0}),await r(f)||await i(f,o);let g=`${f}.json`,p=[];try{let m=JSON.parse(await e.fs.readFile(g,"utf8"));Array.isArray(m)&&(p=m)}catch{}return p.push({...l,savedAt:Date.now()}),await i(g,JSON.stringify(p)),f}catch(f){throw new oo(f)}});return s.prune(),u},prune(o=Date.now()){let l=n();return Ec(l,()=>a(l,o))}},a=async(o,l)=>{let c;try{c=(await e.fs.readdir(o,{withFileTypes:!0})).filter(u=>u.isFile()).map(u=>u.name)}catch{return}for(let u of c){if(!qh.test(u))continue;let f=e.path.join(o,u),g=0;try{let p=JSON.parse(await e.fs.readFile(`${f}.json`,"utf8"));g=Math.max(0,...p.map(m=>Number(m?.savedAt)||0))}catch{try{g=(await e.fs.stat(f)).mtimeMs}catch{continue}}if(!(l-g<=Bh))try{await e.fs.rm(f,{force:!0}),await e.fs.rm(`${f}.json`,{force:!0})}catch{}}};return s}var Wh=5*1024*1024,Gh=5*1024*1024,Vh=3e4,Yh=5e3,Jh=5*6e4,Kh=2500,Xh=3e3,Zh=5,Qh=256*1024,eg=5,Ci=1024*1024,Cc=200,tg=6e4,ng=50,rg=".sync-trash",Ye=t=>Ee().sha256Hex(t);function mr(t,e){let n=e??{localRoot:$t(),shadowName:`amadeus-sync-${_n()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]},r=d=>{let w=ro(d,"");if(!w)return null;for(let k of n.excludePrefixes??[])if(w===k.replace(/\/$/,"")||w.startsWith(k))return null;if(n.ignoreNames?.length&&w.split("/").some(k=>n.ignoreNames.includes(k)))return null;let S=n.serverDir?`${n.serverDir}/${w}`:w;return n.inScope&&!n.inScope(S,De(S))?null:S},i=d=>{let w;if(n.serverDir){if(!d.startsWith(`${n.serverDir}/`))return null;w=d.slice(n.serverDir.length+1)}else{for(let S of n.excludePrefixes??[])if(d.startsWith(S))return null;w=d}return w.split("/").some(S=>pr(S)||!!n.ignoreNames?.includes(S))?null:w},s=(d,w)=>!n.inScope||n.inScope(d,w),a=n.accountId??Be(),{fs:o,path:l,directoryIdentity:c}=Ee(),u=d=>o.access(d).then(()=>!0,()=>!1),f=!1,g=!1,p=0,m=Promise.resolve(),y=new Set,b="disabled",_=null,h=null,T=null,v=null,I=null,E=null,D=null,x=null,L=null,V=()=>{let d=t.loadCreds();if(!E||a!==Be()||!d.token||d.cloudUrl?.replace(/\/+$/,"")!==E.cloudUrl.replace(/\/+$/,""))throw new ye(401,{code:"ACCOUNT_CHANGED"},"sync-session");return d.token},H=null,N=0,Y=new Map,ee=null,J=Sc(n.shadowName),se=kc(n.shadowName),te=_c(_n(a)),ae=!1,Q=new Map,me=!1,ge=!1,Pe=[],Ce=(d,w,S)=>{try{t.onHealth?.(d,w,S)}catch{}},He=Ei(Ce),Ae=0,ut=()=>{ge||Ce("massDeleteGuard"),ge=!0},M=()=>{h&&(h.pending=Q.size?Object.fromEntries(Q):void 0,J.save(h))},U=()=>{ge=!1,Pe.length=0},C=()=>{if(ge)return!0;let d=Date.now();for(;Pe.length&&d-Pe[0]>tg;)Pe.shift();return Pe.length>=ng?(ut(),!0):!1},A=[],j=new Set,F=!1,z=null,q=null,ne=null,re=null,Z=()=>{!f||re||(re=setTimeout(()=>{re=null,t.onStatus(_t())},200))},ie=(d,w,S)=>{let k=b;b=d,w!==void 0&&(_=w),pe(k,d,S),Z()},oe=!1,pe=(d,w,S)=>{if(w==="syncing"&&d!=="syncing"&&(Ae=Date.now()),w==="idle"&&d==="syncing"&&(Ce("cycles"),Ce("cycleMsTotal",Math.max(0,Date.now()-Ae))),w==="idle"||w==="disabled"){oe=!1,He.ok();return}if(S===null)return;let k=S??dc(w,_);k&&He.error(k)},le=(d,w)=>{Y.set(d,w),Ce(cc(w),1,d)},X=(d,w=!1)=>{if(!(!f||!g)){if(d.key){if(j.has(d.key))return;j.add(d.key)}w?A.unshift(d):A.push(d),rf()}},ve=new Map,nn=d=>{if(!f)return;let w=(h?.files[d]?.size??0)>Qh,S=(n.pushQuietMs??Xh)*(w?eg:1),k=Date.now(),R=ve.get(d);R&&clearTimeout(R.timer);let P=R?.since??k,W=Math.max(0,Math.min(S,P+S*Zh-k)),O=setTimeout(()=>{ve.delete(d),X({key:d,run:()=>xe(d,!0)})},W);ve.set(d,{timer:O,since:P}),Z()},Jn=()=>{for(let{timer:d}of ve.values())clearTimeout(d);ve.clear()},yt=new Set(["EACCES","EPERM","EISDIR","ENOTDIR","ENAMETOOLONG","EILSEQ","EINVAL","ELOOP","EBUSY","EFBIG","EIO"]),os=d=>!(d instanceof ye)&&typeof d?.code=="string"&&yt.has(d.code),Ur=d=>!(d instanceof ye)||d.status>=500||d.status===0,tf=d=>!!d&&!d.startsWith("\0"),nf=d=>d instanceof ye?d.body?.code||`http ${d.status}`:d?.code??"error",Kn=d=>d instanceof ye&&(d.status===401||d.status===403),Hr=(d,w)=>{le(d,nf(w)),Z()},rf=async()=>{if(!F){F=!0;try{for(;A.length;){(b==="idle"||b==="starting")&&ie("syncing");let d=A.shift();d.key&&j.delete(d.key);try{await d.run()}catch(w){if(!f)return;if(Kn(w)){A.length=0,j.clear(),er(),ie("auth-required","login-expired");return}if(Ur(w)&&!(os(w)&&tf(d.key))){X(d,!0),er(),ie("offline",w?.message||"network error"),Xn();return}Hr(d.key??"(op)",w)}}f&&b==="syncing"&&(h&&(h.lastSyncAt=Date.now(),J.save(h)),ie("idle",null))}finally{F=!1;for(let d of y)d();y.clear()}}},Xn=()=>{!f||z||(z=setTimeout(()=>{z=null,tr()},Vh))},we=new Map,rn=0,Me=null,zr=()=>!!q||!!Me||!f,as=d=>d instanceof ye&&d.status>=500||d?.name==="TimeoutError",ma=n.pushRetryMs??Yh,ya=d=>{we.get(d)&&(we.delete(d),Y.delete(d))},Zn=(d,w)=>{(w||!we.has(d))&&we.set(d,w)},wa=(d,w,S)=>{le(d,w instanceof ye?`http ${w.status}`:"timeout"),Zn(d,S),rn=Math.min(rn*2||ma,Jh),q=setTimeout(Br,rn),Z()},ba=(d,w,S)=>{let k=new AbortController,R=w(k.signal).then(W=>()=>W,W=>()=>{throw W}),P={path:d,abort:k,after:[],settle:async()=>{let W=await R;if(Me===P){Me=null;try{await S(W)}catch(O){if(Kn(O)||Ur(O))throw O;Hr(d,O)}finally{for(let O of P.after)X(O);Sa(d)}}}};Me=P,R.then(()=>X({run:P.settle}))},Sn=(d,w)=>{for(let[S,k]of[...we])!k||!We(S,d)||(we.delete(S),Y.delete(S),w!==null&&we.set(w+S.slice(d.length),k));Z()},Br=()=>{q=null;let[d]=we;if(d===void 0)return;let[w]=d;j.delete(w),X({key:w,run:async()=>{if(Me?.path===w)return;let S=we.get(w),k=!S&&we.delete(w);(S||k)&&Y.delete(w);try{S?await Xe(w,S.seq):k&&await xe(w,!0)}finally{k&&je(w)&&Zn(w),Sa(w)}}})},Sa=d=>{if(!zr())if(we.has(d)){let w=we.get(d);we.delete(d),we.set(d,w),q=setTimeout(Br,rn||ma)}else Br()},$e=d=>{if(!H||!h)throw new Error("engine not bound");let w=i(d);if(w===null)throw new Error("path outside binding: "+d);let S=l.resolve(H,fc(w,h.folder)),k=l.relative(H,S);if(k.startsWith("..")||l.isAbsolute(k))throw new Error("path escapes vault: "+d);return S},qr=d=>({size:d,mtimeMs:-1}),va=async d=>{try{let w=await o.stat(d);return w.isFile()?{size:w.size,mtimeMs:Math.floor(w.mtimeMs)}:null}catch{return null}},ka=async d=>{if(!o.lstat||!H)return va(d);let w=l.relative(H,d).split(l.sep),S=H;for(let[k,R]of w.entries()){S=l.join(S,R);let P=await o.lstat(S).catch(W=>{if(W?.code==="ENOENT")return null;throw W});if(!P)return null;if(P.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(k===w.length-1&&P.isFile())return{size:P.size,mtimeMs:Math.floor(P.mtimeMs)};if(k===w.length-1||!P.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},sf=0,ls=async(d,w,S,k)=>{if(!await et())throw Error("Cloud vault sync root is unavailable or changed");let R=H&&T?{path:H,identity:T}:void 0;await o.mkdir(l.dirname(d),{recursive:!0});let P=`${d}.tmp-${Ee().tmpTag()}-${Date.now()}-${sf++}`;await o.writeFile(P,w);let W=await va(P)??qr(ei(w));try{if(!k())return null;let O=Ee().compareAndReplace;if(!O)throw new Error("Host does not support safe cloud download commits");let B=await O(P,d,S,k,R);if(!B&&!await et())throw Error("Cloud vault sync root is unavailable or changed");return B?W:null}finally{await et()&&await o.rm(P,{force:!0})}},Ea=async d=>{let w;try{w=await o.readdir(d,{withFileTypes:!0})}catch{return}for(let S of w)S.isDirectory()&&await Ea(l.join(d,S.name));try{await o.rmdir(d)}catch{}},dt=async d=>{let w=$e(d),S=await ka(w);if(!await et())throw Error("Cloud vault sync root is unavailable or changed");if(o.lstat&&!S)return null;let k;try{k=await o.readFile(w)}catch(P){if(P?.code!=="ENOENT")throw P;if(!await et())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:qe(De(d))?Ye(Ct(k)):Ye(k),size:S?.size??k.length,mtimeMs:S?.mtimeMs??-1,buf:k}},Qe=async(d,w,S,k,R)=>{if(!h)return;let P=h.files[d]?.hash;h.files[d]={seq:w,hash:S,size:k.size,mtimeMs:k.mtimeMs},h.mirrorRestore&&h.mirrorRestore!=="list"&&delete h.mirrorRestore[d],J.save(h),R!==void 0&&await _a(d,S,R),P&&P!==S&&await cs(P)},_a=async(d,w,S)=>{if(!qe(De(d))||ei(S)>Ci)return;let k=typeof S=="string"?S:Ct(S);Ye(k)===w&&await se.put(w,k)},cs=async d=>{let w=()=>!!h&&!Object.values(h.files).some(S=>S.hash===d)&&!Object.values(h.dormant??{}).some(S=>S.hash===d);w()&&await se.drop(d,w)},ft=d=>{if(h&&d in h.files){let w=h.files[d].hash;delete h.files[d],J.save(h),cs(w)}},pt=(d,w,S)=>{if(!h)return;let k=h.held?.[d];ft(d),h.held={...h.held,[d]:{localHash:w.hash,localSize:w.size,localMtimeMs:w.mtimeMs,remoteSeq:S.seq,remoteHash:S.hash,remoteUpdatedAt:S.updatedAt!==void 0?S.updatedAt:k&&k.remoteSeq===S.seq?k.remoteUpdatedAt:null,since:k?.since??Date.now()}},J.save(h),Z()},Se=d=>{if(!h?.held||!Object.hasOwn(h.held,d))return;let{[d]:w,...S}=h.held;h.held=Object.keys(S).length?S:void 0,J.save(h),Z()},Mt=d=>h?.held&&Object.hasOwn(h.held,d)?h.held[d]:void 0,kt=d=>i(d)!==null&&s(d,De(d)),us=d=>{!h||!Object.hasOwn(h.files,d)||(h.dormant={...h.dormant,[d]:h.files[d]},T&&(h.dormantRoot??=T),delete h.files[d],J.save(h))},Wr=d=>{if(!h?.dormant||!Object.hasOwn(h.dormant,d))return;let w=h.dormant[d].hash,{[d]:S,...k}=h.dormant;h.dormant=Object.keys(k).length?k:void 0,h.dormant||delete h.dormantRoot,J.save(h),cs(w)},Ca=d=>!!h?.dormant&&Object.hasOwn(h.dormant,d)&&!Object.hasOwn(h.files,d)&&kt(d),Aa=()=>X({key:"\0full",run:sn}),xa=()=>{if(h){for(let d of Object.keys(h.files))!kt(d)&&!je(d)&&us(d);for(let d of Object.keys(h.held??{}))!kt(d)&&!je(d)&&Se(d)}},Xe=async(d,w)=>{if(!v||!h||je(d))return;if(Ca(d)){Aa();return}let S=ke,k=De(d),R=Mt(d);if(R&&!qe(k)){ya(d),w!==null&&w!==R.remoteSeq&&pt(d,{hash:R.localHash,size:R.localSize,mtimeMs:R.localMtimeMs},{seq:w,hash:null,updatedAt:null});return}if(qe(k)){let B;try{B=await v.getFile(h.vaultId,d),Ce("downloads")}catch(K){if(K instanceof ye&&K.status===404){await ds(d);return}throw K}await Ta(d,k,B.content,B.seq,B.hash??Ye(B.content),S);return}if(zr()){Zn(d,{seq:w}),Z();return}let{vaultId:P}=h,W=v,O={seq:w};we.set(d,O),ba(d,B=>W.getAsset(P,d,B),async B=>{let K=we.get(d)===O,$;try{$=B(),rn=0,Ce("downloads")}catch(G){if(!K)return;if(we.delete(d),G instanceof ye&&G.status===404){le(d,"ASSET_404"),Z();return}if(as(G)){wa(d,G,{seq:w});return}throw G}K&&await Ta(d,k,$,w??0,Ye($),S)}),Z()},Ta=async(d,w,S,k,R,P)=>{if(!h)return;let W=async Ie=>{await Qe(d,k,R,Ie,S),we.get(d)&&(we.delete(d),Y.delete(d))},O=await dt(d);if(P!==ke||je(d))return;let B=h.mirrorRestore,K=B&&B!=="list"&&Object.hasOwn(B,d)?B[d]:void 0;if(K&&(K.hash!==R||K.seq!==k)){let Ie={...K};Object.assign(K,{hash:R,seq:k}),J.save(h);try{await J.flush(!0)}catch(nt){throw Object.assign(K,Ie),J.save(h),nt}if(!f||P!==ke||je(d))return}if(O&&O.hash===R){await W(O),Se(d);return}let $=h.files[d];if(O&&(!$||Mt(d)||An($,{seq:k,hash:R})&&O.hash!==$.hash)){ya(d),pt(d,O,{seq:k,hash:R});return}if(Se(d),O&&$&&R===$.hash&&O.hash!==$.hash){await W(qr($.size)),X({key:d,run:()=>xe(d)});return}let G=O?Ye(O.buf):null;if(O&&(!$||O.hash!==$.hash)){if($&&qe(w)&&typeof S=="string"&&await of(d,$,O,S,k,R,()=>P===ke&&!je(d))||P!==ke||je(d)||!await Ia(d,()=>P===ke&&!je(d)))return;G=null}let he=await ls($e(d),S,G,()=>f&&P===ke&&!je(d));if(!he){X({key:d,run:()=>xe(d)});return}await W(he)},of=async(d,w,S,k,R,P,W)=>{try{if(!v||!h||S.buf.length>Ci||k.length>Ci)return!1;let O=await se.get(w.hash);if(O===null){let G=(await v.listVersions(h.vaultId,d)).find(Ie=>Ie.seq===w.seq);if(!G)return!1;let he=await v.getVersion(h.vaultId,G.id);if(Ye(he)!==w.hash)return!1;O=he}let B=Ct(S.buf),K;if(De(d)==="db"){let $=rc(),G=$?$(d,B,O,k):null;K=G&&!G.conflict?G.content:null}else K=ac(B,O,k);return K===null?!1:await ls($e(d),K,Ye(S.buf),()=>f&&W())?(await Qe(d,R,P,qr(ei(K)),k),X({key:d,run:()=>xe(d)}),!0):(X({key:d,run:()=>xe(d)}),!0)}catch{return!1}},Ia=async(d,w)=>{let S=Yt(Si(d,new Date));if(!S)return!0;let k=S.lastIndexOf("."),R=k>S.lastIndexOf("/"),P=R?S.slice(0,k):S,W=R?S.slice(k):"",O=S,B=Ee().existsSync;if(B)for(let K=2;B($e(O));K++)O=`${P}-${K}${W}`;else for(let K=2;await u($e(O));K++)O=`${P}-${K}${W}`;if(!w())return!1;try{await o.rename($e(d),$e(O))}catch(K){if(K?.code==="ENOENT")return!0;throw K}return N++,Ce("conflicts"),X({key:O,run:()=>xe(O)}),Z(),!0},Ra=async d=>{if(!H)return;let w=$e(d),S=i(d)??d,k=l.join(H,rg,new Date().toISOString().slice(0,10),...S.split("/")),R=await u(k)?`${k}.${Date.now()}`:k;try{await o.mkdir(l.dirname(R),{recursive:!0}),await o.rename(w,R)}catch(P){if(P?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${w}: ${P?.message??String(P)}`)}},ds=async d=>{if(!h)return;Sn(d,null),Se(d),Wr(d);let w=await dt(d);if(je(d))return;let S=h.files[d]??null,k=vi(w?.hash??null,S,null);if(k.kind==="deleteLocal"){if(!me&&C()){Q.set(d,"local"),M(),Z();return}Pe.push(Date.now()),await Ra(d),ft(d)}else k.kind==="pushCreate"?(ft(d),X({key:d,run:()=>xe(d)})):ft(d)},Da=(d,w)=>{if(h){Sn(d,w);for(let S of Object.keys(h.files))if(S===d||S.startsWith(`${d}/`)){let k=w+S.slice(d.length);h.files[k]=h.files[S],delete h.files[S]}for(let S of[h.held,h.dormant])if(S)for(let k of Object.keys(S))(k===d||k.startsWith(`${d}/`))&&(S[w+k.slice(d.length)]=S[k],delete S[k]);J.save(h),Z()}},Oa=async d=>{if(!v||!h||d.seq<=h.cursor||!await et())return;if(d.origin.client&&v.clientId===d.origin.client){h.cursor=d.seq,J.save(h);return}let w=d.type==="structure"?"folder":d.type,S=R=>i(R)!==null&&s(R,w);if(!S(d.path)&&!(d.newPath&&S(d.newPath))){h.cursor=d.seq,J.save(h);return}let k=d.path;if(d.op!=="write"&&d.op!=="mkdir"){for(;Me&&(We(Me.path,k)||d.newPath&&We(Me.path,d.newPath));)await Me.settle();if(!f)return}switch(d.op){case"write":await Xe(k,d.fileSeq);break;case"delete":await ds(k);break;case"move":{let R=d.newPath;if(!R)break;let P=h.files[k],W=await dt(k),O=!!we.get(k);Sn(k,R),Wr(k),Mt(k)&&(Se(k),X({key:k,run:()=>xe(k)})),O&&Zn(R,{seq:d.fileSeq});let B=R!==k&&await ka($e(R)).then(K=>K!==null,()=>!0);if(W&&P&&B)await Xe(R,d.fileSeq);else if(W&&P)try{await o.mkdir(l.dirname($e(R)),{recursive:!0}),await o.rename($e(k),$e(R)),h.files[R]={...P,seq:O?P.seq:d.fileSeq??P.seq},delete h.files[k],J.save(h)}catch{await Xe(R,d.fileSeq)}else ft(k),await Xe(R,d.fileSeq);break}case"mkdir":await o.mkdir($e(k),{recursive:!0});break;case"rename-folder":case"move-folder":{let R=d.newPath;if(!R)break;try{await o.mkdir(l.dirname($e(R)),{recursive:!0}),await o.rename($e(k),$e(R))}catch{}Da(k,R);break}case"delete-folder":{let R=`${k}/`;for(let P of[...Object.keys(h.files),...Object.keys(h.held??{}),...Object.keys(h.dormant??{})])(P===k||P.startsWith(R))&&await ds(P);Sn(k,null),await Ea($e(k));break}}if(h.cursor=d.seq,J.save(h),d.op==="move"||d.op==="rename-folder"||d.op==="move-folder"||d.op==="delete"||d.op==="delete-folder")try{await t.onRemoteApplied?.(d)}catch{}},af=async(d,w,S)=>{let k=Number(w?.seq??0),R=w?.content??null,P;if(w?.seq===void 0&&v&&h)try{let B=await v.getFile(h.vaultId,d);k=B.seq,R=B.content,P=B.updatedAt}catch(B){if(!(B instanceof ye)||B.status!==404)throw B;k=0,R=null}if(R!==null&&Ye(R)===S.hash){await Qe(d,k,S.hash,S,R),Se(d);return}if(R===null&&k===0){if(!h?.files[d]){le(d,w?.code||"EXISTS"),Z();return}ft(d),X({key:d,run:()=>xe(d)});return}let W=h?.files[d],O=R===null?null:Ye(R);if(!W||An(W,{seq:k,hash:O})){pt(d,S,{seq:k,hash:O,updatedAt:P});return}await Xe(d,k)},Gr=async(d,w)=>{if(!v||!h)return;let S=await dt(d);if(!S){X({key:d,run:()=>xe(d)});return}if(S.size>Wh){le(d,"TOO_LARGE"),Z();return}let k=Ct(S.buf),R=w>0?h.files[d]?.hash:void 0;try{let P=await v.putFile(h.vaultId,d,k,w,!1,R);Ce("uploads"),Y.delete(d),await Qe(d,P.seq,P.hash??S.hash,S,S.buf),Se(d)}catch(P){if(P instanceof ye&&P.status===409){await af(d,P.body,S);return}throw P}},Vr=async(d,w)=>{if(!v||!h)return;let S=await dt(d);if(!S){X({key:d,run:()=>xe(d)});return}if(S.size>(ee??Gh)){le(d,"TOO_LARGE"),Z();return}if(Zn(d),Z(),zr())return;let{vaultId:k}=h,R=v,P=w>0?h.files[d]?.hash:void 0;ba(d,W=>R.putBinary(k,d,S.buf,{baseSeq:w,signal:W,expectedHash:P}),async W=>{if(h){we.get(d)||we.delete(d);try{let O=W();rn=0,Ce("uploads"),Y.delete(d),await Qe(d,O.seq,S.hash,S),Se(d)}catch(O){if(as(O)){wa(d,O);return}if(!(O instanceof ye)||O.status!==409)throw O;let B=Number(O.body?.seq??0),K=O.body?.hash??null;if(K!==null&&K===S.hash){await Qe(d,B,S.hash,S),Se(d);return}if(B===0){if(!h.files[d]){le(d,O.body?.code||"EXISTS"),Z();return}ft(d),X({key:d,run:()=>xe(d)});return}let $=h.files[d];if(!$||An($,{seq:B,hash:K})){pt(d,S,{seq:B,hash:K});return}await Xe(d,B)}}})},Ma=async d=>{if(!v||!h||je(d))return;let w=ke,S=h.files[d];if(S){if(qe(De(d)))try{let k=await v.getFile(h.vaultId,d);if(k.seq!==S.seq||k.hash!==null&&k.hash!==S.hash){await Xe(d,k.seq);return}}catch(k){if(k instanceof ye&&k.status===404){ft(d);return}throw k}if(!(!await et()||w!==ke||je(d))){try{await v.deleteFile(h.vaultId,d,S.seq,{confirmed:me,expectedHash:S.hash})}catch(k){if(k instanceof ye&&k.status===409){await Xe(d,Number(k.body?.seq??0)||null);return}if(k instanceof ye&&k.status===429&&k.body?.code==="MASS_DELETE_BLOCKED"){Q.set(d,"remote"),ut(),M(),Z();return}throw k}ft(d)}}},Yr=d=>o.stat(d).catch(w=>{if(w?.code==="ENOENT")return null;throw w}),fs=async d=>{let w=Le();if(e||!a||a!==Be()||d!==$t(a)||!w.isManagedCloudVault(d)||!o.lstat)return!1;let S=w.homeDir(),k=l.relative(S,d);if(!k||k.startsWith("..")||l.isAbsolute(k))return!1;let R=S;for(let P of k.split(l.sep)){R=l.join(R,P);let W=await o.lstat(R).catch(O=>{if(O.code==="ENOENT")return null;throw O});if(W&&(!W.isDirectory()||W.isSymbolicLink()))return!1}return!0},Gt=d=>(g=!1,me=!1,A.length=0,j.clear(),gs(),er(),ie("error",`${d}: ${H}`),Xn(),!1),ps=d=>{let w=T??h?.rootIdentity,S=d!==null&&d.isDirectory();return S&&(!w||bt(w,d))?!0:Gt(S?"vault-changed":"vault-missing")},et=async()=>!!H&&ps(await Yr(H)),ke=0,Jr=new Set,Kr=new Map,tt=d=>JSON.stringify([d.from,d.to]),We=(d,w)=>d===w||d.startsWith(`${w}/`),je=d=>[...h?.moves??[],...Jr].some(w=>We(d,w.from)||We(d,w.to)),Et=()=>!!(h?.moves?.length||Jr.size),Xr=async d=>{if(!v||!h)return;let{from:w,to:S,kind:k}=d;if(i(w)===null||i(S)===null)throw new Error("Invalid queued cloud move");if(Me&&(We(Me.path,w)||We(Me.path,S))){Me.after.push({key:`move:${tt(d)}`,run:()=>Xr(d)});return}if(d.hashes??=Object.fromEntries([...Object.entries(h.held??{}).filter(([O,B])=>We(O,w)&&B.remoteHash!==null).map(([O,B])=>[O.slice(w.length),B.remoteHash]),...Object.entries(h.files).filter(([O])=>We(O,w)).map(([O,B])=>[O.slice(w.length),B.hash])]),J.save(h),await J.flush(!0),!await et())return;let R,P=!1;try{if(k==="folder"){let O=l.posix.dirname(w)==="."?"":l.posix.dirname(w),B=l.posix.dirname(S)==="."?"":l.posix.dirname(S);O===B?await v.renameFolder(h.vaultId,w,l.posix.basename(S)):await v.moveFolder(h.vaultId,w,B)}else{let O=await v.move(h.vaultId,w,S);R=Number(O.seq)}}catch(O){if(!(O instanceof ye)||O.status!==404)throw O;let B=await v.tree(h.vaultId);if(B.entries.some(G=>We(G.path,w))||B.folders.some(G=>We(G,w)))throw O;let $=B.entries.find(G=>G.path===S);if(R=$?.seq,P=!$&&!B.entries.some(G=>We(G.path,S))&&!B.folders.some(G=>We(G,S)),!P){let G=Object.entries(d.hashes);if(!(G.length>0&&G.every(([Ie,nt])=>B.entries.some(Ge=>Ge.path===S+Ie&&Ge.hash===nt))))throw new ye(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(P){for(let O of Object.keys(h.files))We(O,w)&&delete h.files[O];for(let O of Object.keys(h.held??{}))We(O,w)&&Se(O);for(let O of Object.keys(h.dormant??{}))We(O,w)&&Wr(O);Sn(w,null)}else Da(w,S),R!==void 0&&h.files[S]&&!we.get(S)&&(h.files[S].seq=R);h.moves=(h.moves??[]).filter(O=>tt(O)!==tt(d)),J.save(h);try{await J.flush(!0)}catch(O){throw h.moves.unshift(d),J.save(h),O}let W=Kr.get(tt(d));Kr.delete(tt(d)),W?.(),je(S)||(k==="folder"?await hs():await xe(S))},xe=async(d,w=!1)=>{if(!h||je(d))return;if(Me?.path===d){Me.after.push({key:d,run:()=>xe(d,w)});return}if(!s(d,De(d))){us(d),Se(d);return}if(!await et())return;let S=await dt(d);if(je(d))return;let k=h.files[d]??null;if(!k&&Ca(d)){Aa();return}let R=Mt(d);if(R){S&&S.hash===R.remoteHash&&qe(De(d))?await Xe(d,null):S&&S.hash===R.remoteHash?(await Qe(d,R.remoteSeq,S.hash,S),Se(d)):S&&S.hash!==R.localHash&&pt(d,S,{seq:R.remoteSeq,hash:R.remoteHash});return}let P=vi(S?.hash??null,k,k?{seq:k.seq,hash:k.hash}:null);switch(P.kind){case"push":qe(De(d))?await Gr(d,P.baseSeq):await Vr(d,P.baseSeq);break;case"pushCreate":qe(De(d))?await Gr(d,0):await Vr(d,0);break;case"pushDelete":if(w){Qr();break}if(!me&&(Q.has(d)||C())){Q.set(d,"remote"),M(),Z();break}Pe.push(Date.now()),await Ma(d);break;case"dropShadow":ft(d);break;default:S&&k&&S.hash===k.hash&&S.mtimeMs>=0&&(k.size!==S.size||k.mtimeMs!==S.mtimeMs)&&await Qe(d,k.seq,k.hash,S,S.buf);break}},lf=async(d,w)=>{if(!v||!h)return;let S=await v.tree(h.vaultId);if(!h)return;let k=new Map(S.entries.map(R=>[R.path,R]));for(let R of d){if(!f||!h||!Mt(R)||je(R)||Me?.path===R)continue;if(!kt(R)){Se(R);continue}let P=await dt(R),W=k.get(R)??null;if(!P||!W){Se(R),P?X({key:R,run:()=>xe(R)}):await Xe(R,W?.seq??null);continue}if(P.hash===W.hash){await Qe(R,W.seq,P.hash,P,qe(De(R))?P.buf:void 0),Se(R);continue}let O;if(w==="newer"){let $=W.updatedAt?Date.parse(W.updatedAt):NaN;if(!Number.isFinite($)||P.mtimeMs<0)continue;O=P.mtimeMs>$?"local":"cloud"}else O=w;let B=ke,K=()=>f&&B===ke&&!je(R)&&kt(R);try{if(O==="both"){if(!await Ia(R,K))continue;Se(R),await Xe(R,W.seq);continue}let $=qe(De(R));if(!$&&zr())continue;O==="local"?await cf(R,P,W,$):await uf(R,P,W,$,K)}catch($){let G=$?.name==="RecoveryError";if(Kn($)||($ instanceof ye?$.status===0:!G&&!as($)&&Ur($)))throw $;le(R,$ instanceof ye?$.body?.code||`http ${$.status}`:$?.name==="TimeoutError"?"timeout":G?"RECOVERY_FAILED":"RESOLVE_FAILED"),Z()}}},cf=async(d,w,S,k)=>{if(!v||!h)return;let{vaultId:R}=h;if(k){let O=await v.getFile(R,d),B=Ye(O.content);if(O.seq!==S.seq||O.hash!==null&&O.hash!==B||S.hash!==null&&B!==S.hash){pt(d,w,{seq:O.seq,hash:O.hash??B,updatedAt:O.updatedAt});return}if(await te.save(O.content,{binding:n.shadowName,path:d,side:"cloud"}),!kt(d)){Se(d);return}try{let K=await v.putFile(R,d,Ct(w.buf),O.seq,!1,B);Ce("uploads"),Y.delete(d),await Qe(d,K.seq,K.hash??w.hash,w,w.buf),Se(d)}catch(K){if(!(K instanceof ye)||K.status!==409)throw K;await Na(d,w)}return}let P=await v.getAsset(R,d),W=Ye(P);if(S.hash!==null&&W!==S.hash){pt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}if(await te.save(P,{binding:n.shadowName,path:d,side:"cloud"}),!kt(d)){Se(d);return}try{let O=await v.putBinary(R,d,w.buf,{baseSeq:S.seq,expectedHash:W});Ce("uploads"),Y.delete(d),await Qe(d,O.seq,w.hash,w),Se(d)}catch(O){if(!(O instanceof ye)||O.status!==409)throw O;pt(d,w,{seq:Number(O.body?.seq??S.seq),hash:O.body?.hash??null,updatedAt:null})}},uf=async(d,w,S,k,R)=>{if(!v||!h)return;let{vaultId:P}=h,W,O,B;if(k){let $=await v.getFile(P,d);W=$.content,O=$.seq,B=Ye($.content)}else if(W=await v.getAsset(P,d),O=S.seq,B=Ye(W),S.hash!==null&&B!==S.hash){pt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}await te.save(w.buf,{binding:n.shadowName,path:d,side:"local"});let K=await ls($e(d),W,Ye(w.buf),R);if(!K){if(!kt(d)){Se(d);return}await Na(d,null);return}Ce("downloads"),Y.delete(d),await Qe(d,O,B,K,W),Se(d)},Na=async(d,w)=>{if(!v||!h)return;let S=w??await dt(d);if(!S){Se(d),await Xe(d,null);return}if(!qe(De(d))){let P=Mt(d);pt(d,S,{seq:P?.remoteSeq??0,hash:null});return}let k;try{k=await v.getFile(h.vaultId,d)}catch(P){if(!(P instanceof ye)||P.status!==404)throw P;Se(d),X({key:d,run:()=>xe(d)});return}let R=Ye(k.content);if(R===S.hash){await Qe(d,k.seq,S.hash,S,k.content),Se(d);return}pt(d,S,{seq:k.seq,hash:R,updatedAt:k.updatedAt})},Pa=async()=>{let d=new Map;if(!H||!h)return d;let w=H,S=null,k=async R=>{if(S)return;let P;try{P=await o.readdir(R,{withFileTypes:!0})}catch(W){S=`${R}: ${W?.message??String(W)}`;return}for(let W of P){if(pr(W.name)||W.isDirectory()&&n.ignoreNames?.includes(W.name))continue;let O=l.join(R,W.name);if(W.isDirectory())await k(O);else if(W.isFile()){let B=l.relative(w,O).split(l.sep).join("/"),K=r(B);if(!K)continue;try{let $=await o.stat(O);if(!$.isFile())continue;d.set(K,{size:$.size,mtimeMs:Math.floor($.mtimeMs)})}catch($){if($?.code==="ENOENT")continue;S=`${O}: ${$?.message??String($)}`;return}}}};return await k(w),S?(ie("error",`scan-failed: ${S}`),Xn(),null):d},hs=async()=>{let d=ke;if(Et()||d!==ke||!h||!await et())return;let w=await Pa();if(!w||Et()||d!==ke||!await et())return;let S=!1;for(let[P,W]of[...Q])(W==="remote"&&w.has(P)||W==="local"&&!w.has(P))&&(Q.delete(P),S=!0);Q.size||U();for(let[P,W]of w){let O=h.files[P];if(O&&O.size===W.size&&O.mtimeMs===W.mtimeMs)continue;let B=Mt(P);B&&B.localSize===W.size&&B.localMtimeMs===W.mtimeMs||X({key:P,run:()=>xe(P)})}for(let P of Object.keys(h.files))kt(P)||us(P);let k=Object.keys(h.files),R=k.filter(P=>!w.has(P));if(R.length&&!me&&(ge||fr(R.length,k.length,Cc))){ut();for(let P of R)Q.set(P,"remote");M(),Z();return}S&&(M(),Z());for(let P of R)Q.has(P)||X({key:P,run:()=>xe(P)})},df=async d=>{if(!h)return;let w=new Set;for(let[S,k]of Object.entries(h.files)){if(!qe(De(S))||k.size>Ci)continue;w.add(k.hash);let R=d.get(S);if(!(!R||R.size!==k.size||R.mtimeMs!==k.mtimeMs||await se.has(k.hash)))try{let P=await dt(S);P&&P.hash===k.hash&&await _a(S,k.hash,P.buf)}catch{}}for(let S of Object.values(h.dormant??{}))w.add(S.hash);await se.prune(w)},sn=async()=>{if(Me){Me.after.push({run:sn});return}let d=ke;if(Et()||d!==ke||!v||!h||!H||!await et())return;let w=await v.tree(h.vaultId);if(w.maxFileBytes!==void 0&&w.maxFileBytes!==ee&&(ee=w.maxFileBytes,Z()),Et()||d!==ke)return;let S=new Map;for(let $ of w.entries)i($.path)===null||!s($.path,$.kind)||S.set($.path,$);for(let[$,G]of[...we])G&&!S.has($)&&Sn($,null);let k=await Pa();if(!k||Et()||d!==ke||!await et())return;if(h.mirrorRestore==="list"){for(let G of Object.keys(h.files))!k.has(G)&&!Q.has(G)&&delete h.files[G];let $=Object.create(null);for(let[G,{seq:he,hash:Ie}]of S)Object.hasOwn(h.files,G)||($[G]={seq:he,hash:Ie});h.mirrorRestore=$,J.save(h);try{await J.flush(!0)}catch(G){throw h.mirrorRestore="list",J.save(h),G}}let R=h.mirrorRestore;if(xa(),h.dormant){let $=!h.dormantRoot||!T||an(h.dormantRoot,T);for(let[G,he]of Object.entries(h.dormant))kt(G)&&($&&k.has(G)&&S.has(G)&&!Object.hasOwn(h.files,G)?(h.files[G]=he,delete h.dormant[G]):Wr(G));h.dormant&&!Object.keys(h.dormant).length&&(delete h.dormant,delete h.dormantRoot),J.save(h)}ae||(ae=!0,await df(k));let P=new Set([...S.keys(),...k.keys(),...Object.keys(h.files),...Object.keys(R??{}),...Object.keys(h.held??{})]),W=Object.keys(h.files).length,O=[];for(let $ of P){if(Et()||d!==ke)return;let G=h.files[$]??null,he=S.get($)??null,Ie=k.get($)??null,nt=null,Ge=qr(Ie?.size??0);if(Ie)if(G&&G.size===Ie.size&&G.mtimeMs===Ie.mtimeMs)nt=G.hash,Ge=Ie;else{let rt;try{rt=await dt($)}catch(ze){if(!os(ze))throw ze;Hr($,ze);continue}rt&&(nt=rt.hash,Ge=rt)}if(R&&Object.hasOwn(R,$)){let rt=R[$];!G&&nt!==null&&rt.hash===nt&&(G=h.files[$]={seq:rt.seq,hash:nt,size:Ge.size,mtimeMs:Ge.mtimeMs}),(G||!he)&&delete R[$]}O.push({sp:$,d:vi(nt,G,he?{seq:he.seq,hash:he.hash}:null),rSeq:he?.seq??null,rHash:he?.hash??null,rUpdatedAt:he?.updatedAt??null,localHash:nt,localStat:Ge})}if(Et()||d!==ke)return;let B=O.filter($=>$.d.kind==="deleteLocal"||$.d.kind==="pushDelete").length,K=!me&&(ge||fr(B,W,Cc));K&&B&&ut(),Q.clear();for(let{sp:$,d:G,rSeq:he,rHash:Ie,rUpdatedAt:nt,localHash:Ge,localStat:rt}of O){if(Et()||d!==ke)return;if(G.kind!=="hold"&&Mt($)&&Se($),K&&(G.kind==="deleteLocal"||G.kind==="pushDelete")){Q.set($,G.kind==="deleteLocal"?"local":"remote");continue}try{if((G.kind==="deleteLocal"||G.kind==="pushDelete")&&((await dt($))?.hash??null)!==Ge){X({key:$,run:()=>xe($)});continue}if(Et()||d!==ke)return;switch(G.kind){case"adopt":{let ze=qe(De($))?await dt($):null;await Qe($,he,Ge,rt,ze&&ze.hash===Ge?ze.buf:void 0);break}case"pull":await Xe($,he);break;case"push":qe(De($))?await Gr($,G.baseSeq):await Vr($,G.baseSeq);break;case"pushCreate":qe(De($))?await Gr($,0):await Vr($,0);break;case"pushDelete":await Ma($);break;case"deleteLocal":await Ra($),ft($);break;case"conflict":await Xe($,he);break;case"hold":pt($,{hash:Ge,size:rt.size,mtimeMs:rt.mtimeMs},{seq:he,hash:Ie,updatedAt:nt});break;case"dropShadow":ft($);break;case"none":break}}catch(ze){if(!f||Kn(ze)||Ur(ze)&&!os(ze))throw ze;Hr($,ze)}}me&&(me=!1,Pe.length=0),Q.size||U(),M(),K&&Z();for(let $ of w.folders)if(!(i($)===null||!s($,"folder")))try{await o.mkdir($e($),{recursive:!0})}catch{}h.cursor=w.seq,h.lastSyncAt=Date.now(),R&&!Object.keys(R).length&&delete h.mirrorRestore,J.save(h)},ff=async()=>{if(!v||!h)return;let d=h.cursor,w=await v.changes(h.vaultId,d);if(w.changes.length===0&&w.seq>d||w.changes.length>0&&w.changes[0].seq!==d+1){await sn();return}for(let k of w.changes)await Oa(k)},Qn=null,$a=[],gs=()=>{Qn&&$a.push(Qn.close()),Qn=null},pf=()=>{if(!f||Qn||!H)return;let d=Ee();if(!d.watch)return;let w=S=>{if(!H)return;let k=l.relative(H,S);if(!k||k.startsWith(".."))return;let R=r(k);R&&nn(R)};Qn=d.watch(H,{depth:12,ignored:S=>{let k=l.basename(S);return pr(k)||!!n.ignoreNames?.includes(k)}},{change:w,add:w,unlink:()=>Qr(),unlinkDir:()=>Qr()})},er=()=>{I?.stop(),I=null},hf=()=>{if(!f||!v||!h||I)return;let d=E;d&&(I=yc({baseUrl:d.cloudUrl,vaultId:h.vaultId,token:d.token,getToken:V,gate:D??void 0},{getSince:()=>h?.cursor??0,onHello:w=>{h&&w>h.cursor&&X({run:ff})},onChange:w=>{X({run:()=>Oa(w)})},onReset:()=>{X({run:sn})},onOpen:()=>{(b==="offline"||b==="starting")&&ie("idle",null),X({run:hs})},onDown:(w,S)=>{let k=no(uc(w));b==="idle"||b==="syncing"?(ie("offline",void 0,S?null:k),oe=!!S):b==="offline"&&oe&&!S&&(oe=!1,He.error(k))},onPresence:w=>t.onPresence?.(h?.vaultId??"",w),onPresenceRoster:w=>t.onPresenceRoster?.(h?.vaultId??"",w)}))},gf=async()=>{let d=await ot(a);if(d.cloudSync?.deviceId)return d.cloudSync.deviceId;let w=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Pt({cloudSync:{...d.cloudSync??{},deviceId:w}},a),w},mf=async d=>{er(),gs(),T=null,A.length=0,j.clear(),Q.clear(),me=!1,ge=!1,Pe.length=0;let w=await ot(a);if(d!==p)return;let S=w.cloudSync;if(S?.enabled===!1){H=null,v=null,ie("disabled",null);return}if(!a||a!==Be()){ie("auth-required","not-logged-in");return}if(H=n.localRoot,n.requireRootExists){let W=await o.stat(H).then(O=>O.isDirectory()).catch(()=>!1);if(d!==p)return;if(!W){ie("error",`vault-missing: ${H}`),Xn();return}}if(d!==p)return;let k=t.loadCreds();if(!k.cloudUrl||!k.token){v=null,ie("auth-required","not-logged-in");return}ie("starting",null);let R=S?.deviceId??await gf();if(d!==p)return;let P=n.clientIdSuffix?`${R}#${n.clientIdSuffix}`:R;E={cloudUrl:k.cloudUrl,token:k.token},D=Jt(k.cloudUrl),x=new AbortController,L?.(),L=D.subscribe(Z),v=mc({baseUrl:k.cloudUrl,token:k.token,clientId:P,gate:D,signal:x.signal,getToken:()=>{if(d!==p)throw new ye(401,{code:"ACCOUNT_CHANGED"},"sync-session");return V()}});try{let W=n.vaultId==="first"?S?.vaultId:n.vaultId;if(!W){let $=await v.listVaults();if(d!==p)return;if(!$.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");W=$[0].id,await Pt({cloudSync:{...S??{},vaultId:W}},a)}if(d!==p)return;let O=await so(n.shadowName);if(d!==p||(h=O&&O.vaultRoot===H&&O.vaultId===W&&O.folder===""?O:{vaultRoot:H,folder:"",vaultId:W,cursor:0,lastSyncAt:null,files:{}},d!==p))return;for(let[$,G]of Object.entries(h.pending??{}))Q.set($,G);Q.size&&(ge=!0);let B=await Yr(H);if(d!==p)return;let K=()=>Et()||!!Object.keys(h?.pending??{}).length;if(!B&&!n.requireRootExists){if(h.rootIdentity||Object.keys(h.files).length||h.mirrorMissing||K()){let $=await fs(H);if(d!==p)return;if(!$||K()){Gt("vault-missing");return}if(h.mirrorMissing=!0,J.save(h),await J.flush(!0),d!==p)return;let G=await fs(H);if(d!==p)return;if(!G||K()){Gt("vault-missing");return}}if(await o.mkdir(H,{recursive:!0}),B=await Yr(H),d!==p)return}if(!B?.isDirectory()){ps(B);return}if(typeof B.dev=="number"&&Number.isInteger(B.dev)&&B.dev>=0&&typeof B.ino=="number"&&Number.isInteger(B.ino)&&B.ino>0){let $=c?await c(H):{dev:B.dev,ino:B.ino,...B.birthtimeMs&&B.birthtimeMs>0?{birthtimeMs:B.birthtimeMs}:{}};if(d!==p)return;if(!Vt($))throw Error("Invalid sync root identity; original state retained");let G=h.rootIdentity,he=G&&!an(G,$);if(!bt($,B)){Gt("vault-changed");return}let Ie=!G&&!e&&Le().isManagedCloudVault(H)&&(Object.keys(h.files).length>0||K());if(he||h.mirrorMissing||Ie){let Ge=(!G||(G.volumeId?G.volumeId===$.volumeId:G.dev===$.dev))&&await fs(H),rt=Ge&&(await o.readdir(H,{withFileTypes:!0})).every(Ua=>Ua.isDirectory()&&n.excludePrefixes?.includes(Ua.name+"/")),ze=rt&&await Yr(H);if(d!==p)return;if(rt){if(!ze||!bt($,ze)||K()){Gt("vault-changed");return}h.files={},h.cursor=0,h.lastSyncAt=null,h.mirrorRestore="list"}else if(he||h.mirrorMissing&&!G){Gt("vault-changed");return}else if(Ie){if(!Ge||K()){Gt("vault-changed");return}h.mirrorRestore="list"}}if(T=$,(h.mirrorMissing||JSON.stringify(G)!==JSON.stringify($))&&(delete h.mirrorMissing,h.rootIdentity=$,J.save(h),await J.flush(!0)),d!==p||!await et())return}else{if(h.mirrorMissing){Gt("vault-changed");return}if(!ps(B))return}if(d!==p)return;g=!0,pf();for(let $ of h.moves??[])X({key:`move:${tt($)}`,run:()=>Xr($)});X({run:sn}),X({run:async()=>{hf()}})}catch(W){if(d!==p)return;Kn(W)?ie("auth-required","login-expired"):(ie("offline",W?.message||String(W)),Xn())}},ja=()=>{f=!1,g=!1,er(),gs(),A.length=0,j.clear(),Jn();for(let d of[z,q,ne,re])d&&clearTimeout(d);z=q=ne=re=null,Me?.abort.abort(),Me=null,x?.abort(new DOMException("sync engine stopped","AbortError")),L?.(),L=null},La=async()=>{F&&await new Promise(d=>y.add(d)),await Promise.all($a.splice(0)),await J.flush(),h=null,T=null,v=null,E=null,D=null,x=null,H=null,N=0,Y.clear(),we.clear(),rn=0,ee=null,Q.clear(),me=!1,ge=!1,Pe.length=0,b="disabled",_=null},yf=()=>{Fa()},Zr=null,tr=()=>{ae=!1,Zr?.(),Zr=Le().onBeforeQuit(yf);let d=++p;ja();let w=m.catch(()=>{}).then(async()=>{await La(),d===p&&(f=!0,await mf(d))});return m=w,w},Fa=()=>{Zr?.(),Zr=null,++p,ja();let d=m.catch(()=>{}).then(La);return m=d,d},_t=()=>{let d=Object.entries(h?.held??{}).map(([w,S])=>({...S,path:w,local:i(w)??w}));return{enabled:b!=="disabled",state:b==="idle"&&(ve.size||we.size)?"syncing":b,lastSyncAt:h?.lastSyncAt??null,pending:A.length+ve.size+we.size,conflicts:N,skipped:[...[...Y].map(([w,S])=>({path:w,reason:S})),...d.map(w=>({path:w.path,reason:"HELD"}))],error:_,pendingDeletions:Q.size,maxFileBytes:ee,held:d,heldCount:d.length,rateLimitedUntil:b!=="disabled"?D?.until()??null:null}};return{getStatus:_t,start(){tr()},notifyLocal(d,w,S){if(!h||b==="disabled"||b==="auth-required")return;let k=r(d),R=S?r(S):null;if(w==="write"&&k){pr(k.split("/").pop()||"")||nn(k);return}if(w==="remove"){if(!k)return;let P=`${k}/`,W=!1;for(let O of Object.keys(h.files))(O===k||O.startsWith(P))&&(W=!0,X({key:O,run:()=>xe(O)}));!W&&k&&X({key:k,run:()=>xe(k)})}},holdLocalMove(d,w){let S=R=>n.serverDir?`${n.serverDir}/${R.replace(/\\/g,"/").normalize("NFC")}`:R.replace(/\\/g,"/").normalize("NFC"),k={from:S(d),to:S(w)};return++ke,Jr.add(k),()=>{Jr.delete(k)}},async notifyLocalMove(d,w,S,k){let R=r(d),P=r(w),W=h??await so(n.shadowName),O=ro(d,""),B=O&&(n.serverDir?`${n.serverDir}/${O}`:O);if(!R&&P&&B&&W&&Object.keys(W.files).some(K=>K===B||K.startsWith(`${B}/`))&&(R=B),!R&&!P){S?.();return}if(R&&P){let K=h??W;if(!K){S?.();return}let $=k??(Object.keys(K.files).some(he=>he.startsWith(`${R}/`))?"folder":"file"),G={from:R,to:P,kind:$};K.moves??=[],K.moves.some(he=>tt(he)===tt(G))||(K.moves.push(G),++ke),S&&Kr.set(tt(G),S),J.save(K);try{await J.flush(!0)}catch(he){throw K.moves=K.moves.filter(Ie=>tt(Ie)!==tt(G)),Kr.delete(tt(G)),J.save(K),he}h===K&&f&&b!=="disabled"&&b!=="auth-required"&&X({key:`move:${tt(G)}`,run:()=>Xr(G)});return}R&&this.notifyLocal(d,"remove"),P&&(X({key:P,run:()=>xe(P)}),Qr()),S?.()},async setEnabled(d){let w=await ot(a);return await Pt({cloudSync:{...w.cloudSync??{},enabled:d}},a),await tr(),_t()},async restart(){return await tr(),_t()},async syncNow(){if(Y.clear(),!g){let d=p;if(await m,d!==p)return _t()}if(b==="disabled"||b==="auth-required"||b==="error"||b==="offline"||!g||!v)await tr();else{q&&(clearTimeout(q),Br());for(let d of h?.moves??[])X({key:`move:${tt(d)}`,run:()=>Xr(d)});X({run:sn})}return _t()},resolveHeld(d,w){if(!g||!h?.held||!["local","cloud","both","newer"].includes(w))return _t();let S=[...new Set(d)].filter(k=>typeof k=="string"&&!!Mt(k));return S.length&&X({run:()=>lf(S,w)}),_t()},rescope(){f&&X({key:"\0rescope",run:async()=>xa()})},confirmMassDeletions(){return!g||!Q.size||(me=!0,X({run:sn})),_t()},stop:Fa};function Qr(){f&&(ne&&clearTimeout(ne),ne=setTimeout(()=>{ne=null,X({run:hs})},Kh))}}function ao(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function lo(t){return/\.md$/i.test(t)?ao(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function Ac(t,e,n){return!!(e===t.root||e.startsWith(t.fdPrefix)||`${e}/`===t.fdPrefix||n==="binary"&&e.startsWith(t.assetPrefix)||n==="folder"&&(`${e}/`===t.assetPrefix||e.startsWith(t.assetPrefix)))}var ig=t=>Ee().sha256Hex(t).slice(0,8),sg=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Ai="\u4E0E\u6211\u5171\u4EAB";function xc(t,e){let n=ig(`${t.vaultId}:${t.path}`),r=t.path.includes("/")?t.path.slice(0,t.path.lastIndexOf("/")):"";return{key:n,vaultId:t.vaultId,rootPath:t.path,title:t.title,localRelDir:`${Ai}/${sg(t.title)}-${n}`,serverDir:r,inScope:(i,s)=>e.some(a=>Ac(a,i,s)),scopeKey:e.map(i=>i.root).join("\0")}}function Tc(t){return xc(t,[ao(t.path),...(t.items??[]).map(lo)])}function Ic(t){let e=t.map(Tc),n=t.flatMap((i,s)=>{let a=e[s].serverDir?`${e[s].serverDir}/`:"";return(i.items??[]).filter(o=>!o.startsWith(a)).map(o=>xc({vaultId:i.vaultId,path:o,title:(o.split("/").pop()??o).replace(/\.md$/i,"")},[lo(o)]))}),r=new Map;for(let i of[...e,...n])r.has(i.key)||r.set(i.key,i);return[...r.values()]}var og=t=>{let e=[];for(let n of t.split("/"))!n||n==="."||(n===".."&&e.length&&e[e.length-1]!==".."?e.pop():e.push(n));return e.join("/")};function Rc(t,e){let n=l=>l.normalize("NFC"),r=n(e.replace(/\\/g,"/")),i=t.find(l=>r.startsWith(`${n(l.localRelDir)}/`));if(!i)return null;let s=r.slice(n(i.localRelDir).length+1),a=og(i.serverDir?`${i.serverDir}/${s}`:s);if(!a||a===".."||a.startsWith("../"))return null;let o=[i,...t].find(l=>l.vaultId===i.vaultId&&(!l.serverDir||a.startsWith(`${l.serverDir}/`))&&l.inScope(a,De(a)));return o?`${o.localRelDir}/${o.serverDir?a.slice(o.serverDir.length+1):a}`:null}function co(){let t=Le().readCreds(),e=Ve(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let f=Le().readCreds();if(n.signal.aborted||!e||Ve(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},i=()=>{let f=r();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},s=async(f,g,p)=>{let m=r();if(!m.cloudUrl||!m.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let y=await fetch(`${m.cloudUrl.replace(/\/+$/,"")}/api/amadeus${g}`,{method:f,headers:{Authorization:`Bearer ${m.token}`,...p!==void 0?{"Content-Type":"application/json"}:{}},body:p!==void 0?JSON.stringify(p):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!y.ok){let _=null;try{_=await y.json()}catch{}throw Object.assign(new Error(_?.detail||`http ${y.status}`),{status:y.status,code:_?.code})}let b=await y.json();return r(),b},a=null,o=async()=>(r(),a||(a=(await s("GET","/vaults")).vaults[0]?.id??"default",a)),l=()=>{try{let f=(r().token??"").split(".")[1],g=JSON.parse(Ct(ti(f)));return typeof g.userId=="string"?g.userId:null}catch{return null}},c=async()=>(await s("GET","/shared-with-me")).items.map(g=>{let p=Tc(g),m=g.path.split("/").pop()??g.path;return{...g,localPath:`${p.localRelDir}/${m}`}}),u=null;return{stop:()=>n.abort(),call:s,ensureOwnVault:o,myUserId:l,sharedWithMe:c,linkBase:async()=>{if(r(),u)return u;try{u=((await s("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||i()}catch{u=i()}return u},async heartbeat(f,g){let p=(f??"").replace(/\\/g,"/"),m,y=null,b=g.find(_=>p.startsWith(`${_.localRelDir}/`));b?(m=b.vaultId,y=b.serverDir?`${b.serverDir}/${p.slice(b.localRelDir.length+1)}`:p.slice(b.localRelDir.length+1)):(m=await o(),y=p||null),await s("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:y})}}}import{promises as Mc}from"node:fs";import ag from"node:path";var uo=".forsion-vault.md",Dc=t=>`${t}/${uo}`;function xi(t){let e=/^devices:\s*(\[.*\])\s*$/m.exec(t??"");if(!e)return null;try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(r=>!!r&&typeof r.id=="string"&&typeof r.name=="string").map(r=>({id:r.id,name:r.name,...typeof r.since=="string"?{since:r.since}:{}})):null}catch{return null}}var Oc=t=>`---
|
|
216
|
-
devices: ${JSON.stringify(t.map(e=>({id:e.id,name:e.name,...e.since?{since:e.since}:{}})))}
|
|
217
|
-
---
|
|
218
|
-
`;var at=t=>t.replace(/\\/g,"/").normalize("NFC");function fo(t){let e=at(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function xn(t,e,n){let r=at(n);if(!r)return!1;if(t.some(i=>at(i.path)===r))return!0;for(let i of e??[]){let s=at(i);if(!s)continue;let a=`${s.replace(/\.md$/i,"")}.fd`;if(r===s||r.startsWith(`${s}/`)||r===a||r.startsWith(`${a}/`))return!1}return t.some(i=>{let s=fo(i);return!!s&&r.startsWith(s)})}function po(t,e,n){let r=at(t),i=at(e);return r===i?at(n):r.startsWith(`${i}/`)?at(n)+r.slice(i.length):null}function yr(t,e,n){let r=!1,i=t.map(s=>{let a=po(s,e,n);return a===null?s:(r=!0,a)});return{changed:r,next:i}}async function Nc(t){let e=await Mc.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let i of e){if(!i.isDirectory()||i.name.startsWith("."))continue;let s=await Mc.readFile(ag.join(t,i.name,uo),"utf8").catch(()=>null);if(s===null)continue;n.push(i.name);let a=xi(s);a?.length&&(r[i.name]=a)}return{names:n.sort(),devices:r}}var Ne={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",resolveHeld:"amadeus:sync:resolve-held",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryMark:"amadeus:entry-sync:mark",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};var Ti=t=>Ee().sha256Hex(t).slice(0,8);function Pc(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Kt(t,e=[]){let n=[],r=[];for(let i of t){let s=at(i.path);if(!s)continue;r.push(s);let a=fo(i);a&&n.push(a)}return{entries:t,exclude:e,prefixes:n,paths:r}}function $c(t,e){let n=Pc(at(e));if(!n)return!1;if(xn(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let i of t.paths)if(i.startsWith(r))return!0;for(let i of t.prefixes)if(i.startsWith(r))return!0;return!1}function wr(t,e,n){let r=!1,i=t.map(s=>{let a=po(s.path,e,n);return a===null?s:(r=!0,{...s,path:a})});return{changed:r,next:i}}function jc(t,e,n,r){if(e==="delete"||e==="delete-folder"){let i=at(n),s=t.filter(a=>{let o=at(a.path);return!(o===i||e==="delete-folder"&&o.startsWith(`${i}/`))});return{changed:s.length!==t.length,next:s}}return r?wr(t,n,r):{changed:!1,next:t}}function ho(t,e){let n=Yt(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Ai?`\u300C${Ai}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(n)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}import{constants as lg,promises as Lc}from"node:fs";async function Fc(t,e){try{await Lc.copyFile(un(t),un(e),lg.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await Lc.unlink(un(t)).catch(()=>{}),!0}var cg=/^\d{4}-\d{2}-\d{2}$/,Uc=["vault","content"],Hc=new Set(lc),ug=40,Tn=t=>new Date(t).toISOString().slice(0,10),In=t=>typeof t=="string"&&cg.test(t),zc=!1,ht=Object.create(null),Rn=!1,go=()=>Date.now(),br=new Set,Ii="";function lt(t,e,n=1,r){try{if(!zc||!Hc.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let i=Tn(go());if(r!==void 0){i!==Ii&&(br.clear(),Ii=i);let o=`${t}\0${e}\0${r}`;if(br.has(o))return;br.add(o)}let s=ht[i]??={},a=s[t]??={};a[e]=(a[e]??0)+Math.round(n),Rn=!0}catch{}}function mo(t){zc=t}function Bc(t){if(ht=Object.create(null),br.clear(),Ii="",Rn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!In(e)||!n||typeof n!="object"))for(let r of Uc){let i=n[r];if(!i||typeof i!="object")continue;let s={};for(let[a,o]of Object.entries(i))Hc.has(a)&&typeof o=="number"&&Number.isFinite(o)&&o>0&&(s[a]=Math.round(o));Object.keys(s).length&&((ht[e]??={})[r]=s)}}}function qc(){let t=Tn(go()-ug*864e5),e={};for(let n of Object.keys(ht).sort()){if(n<t){delete ht[n];continue}e[n]=JSON.parse(JSON.stringify(ht[n]))}return e}var Wc=()=>Rn,Gc=()=>{Rn=!1};function Vc(t,e){let n=[];for(let r of Object.keys(ht).sort())if(!(r<=t||r>e))for(let i of Uc){let s=ht[r][i];s&&Object.keys(s).length&&n.push({day:r,system:i,counts:{...s}})}return n}function yo(t){for(let e of Object.keys(ht))e<=t&&(delete ht[e],Rn=!0)}function Yc(){Object.keys(ht).length&&(Rn=!0),ht=Object.create(null),br.clear(),Ii=""}function Jc(t){go=t}var Kc=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],wo=t=>Kc.every(e=>typeof t[e]=="function"),pg=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,held:[],heldCount:0,rateLimitedUntil:null,side:"local"});function bo(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Ne.get,()=>e?e.get():pg()),t.handle(Ne.setEnabled,(r,i)=>n().setEnabled(i)),t.handle(Ne.syncNow,()=>n().syncNow()),t.handle(Ne.confirmDeletions,()=>n().confirmDeletions()),t.handle(Ne.resolveHeld,(r,i)=>n().resolveHeld(i)),t.handle(Ne.entryGet,()=>n().entryGet()),t.handle(Ne.otherSideDbs,()=>n().otherSideDbs()),t.handle(Ne.entryEnable,(r,i)=>n().entryEnable(i)),t.handle(Ne.entryDisable,(r,i)=>n().entryDisable(i)),t.handle(Ne.entryMark,(r,i,s)=>n().entryMark(i,s)),t.handle(Ne.entryClosure,(r,i,s)=>n().entryClosure(i,s)),t.handle(Ne.collabCall,(r,i,s)=>n().collabCall(i,s)),t.handle(Ne.switchSide,(r,i)=>n().switchSide(r.sender.id,i)),t.setAmadeusSyncFactory(r=>{ec(r),nc(hg(t));let i=Xc(r);return e=i.handlers,i.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function hg(t){let e=t.contentSync?.merge;return e?(n,r,i,s)=>{if(!/\.db$/i.test(n)||/^(agents|human)(\/|$)/.test(n))return null;let a;try{a=e(n,r,i,s)}catch{return null}return a&&!a.conflict&&!So(i,r,a.content)?null:a}:null}function So(t,e,n){let r,i,s;try{[r,i,s]=[JSON.parse(t),JSON.parse(e),JSON.parse(n)]}catch{return!1}let a=c=>Array.isArray(c)&&c.every(u=>u&&typeof u=="object"&&typeof u.id=="string")?c.map(u=>u.id):null,o=(c,u)=>c.filter(f=>u.includes(f)),l=(c,u)=>c.length===u.length&&c.every((f,g)=>f===u[g]);for(let c of Object.keys(i)){let u=a(i[c]),f=a(r?.[c]);if(!u||!f||l(o(f,u),o(u,f)))continue;let g=a(s?.[c]);if(!g||!l(o(u,g),o(g,u)))return!1}return!0}function Xc(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,i=!1,s=co(),a=new Map,o=()=>{let M=Date.now();for(let[U,C]of a)M-C.at>7e4&&a.delete(U);e(Ne.presence,[...a.values()])},c={loadCreds:()=>t.readCreds(),onHealth:(M,U,C)=>lt("vault",M,U,C),onStatus:M=>e(Ne.status,{...M,pendingDeletions:me(),side:b()?"cloud":"local"}),onPresence:(M,U)=>{let C=U;C?.userId&&(a.set(C.userId,{userId:C.userId,username:String(C.username??"user"),page:C.page??null,at:Number(C.at)||Date.now()}),o())},onPresenceRoster:(M,U)=>{if(Array.isArray(U)){for(let C of U){let A=C;A?.userId&&a.set(A.userId,{userId:A.userId,username:String(A.username??"user"),page:A.page??null,at:Number(A.at)||Date.now()})}o()}}},u=()=>{let M=r;return{...c,onStatus:U=>{M===r&&c.onStatus(U)},onPresence:(U,C)=>{M===r&&c.onPresence(U,C)},onPresenceRoster:(U,C)=>{M===r&&c.onPresenceRoster(U,C)}}},f=mr(u()),g=new Map,p=[],m=0,y=async()=>{if(!i||!Be())return;let M=r,U=++m,C=s,A;try{A=await C.sharedWithMe()}catch{return}if(M!==r||!i||U!==m)return;let j=Ic(A);p=j;let F=new Map(j.map(z=>[z.key,z.scopeKey]));for(let[z,q]of g)if(F.get(z)!==q.plan.scopeKey){if(await q.engine.stop(),M!==r)return;g.delete(z)}for(let z of j){if(g.has(z.key))continue;let q=u(),ne=mr({...q,onStatus:re=>q.onStatus({...re,shareKey:z.key})},{localRoot:dn.join($t(),...z.localRelDir.split("/")),shadowName:`amadeus-sync-${_n()}-share-${z.key}`,vaultId:z.vaultId,serverDir:z.serverDir,inScope:z.inScope});g.set(z.key,{engine:ne,plan:z}),ne.start()}},b=()=>n()===$t(),_=(M,U=M.base)=>{M.base=U;let C=[U,...M.pendingMoves];M.scope.current=Kt(C.flatMap(A=>A.entries),C.flatMap(A=>A.exclude)),M.engine.rescope()},h=new Map,T=new Set,v=new Set,I=null,E=()=>I??=new Promise(M=>{let U=()=>fg.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return M(U());dg("scutil",["--get","ComputerName"],{timeout:1500},(C,A)=>M(!C&&String(A).trim()||U()))}),D=async()=>{let M=(await ot()).cloudSync?.deviceId;return M?{id:M,name:await E()}:null},x=new Map,L=(M,U,C)=>{let A=r,j=(x.get(M)??Promise.resolve()).catch(()=>{}).then(async()=>{A!==r||C&&!await C()||A!==r||await V(M,U,A)});return x.set(M,j),j.finally(()=>{x.get(M)===j&&x.delete(M)}).catch(()=>{}),j},V=async(M,U,C)=>{let A=s,j=encodeURIComponent(await A.ensureOwnVault()),F=Dc(M);for(let z=0;z<3;z++){let q=null;try{q=await A.call("GET",`/vaults/${j}/file?path=${encodeURIComponent(F)}`)}catch(re){if(re?.status!==404)throw re}let ne=U(!!q,q?xi(q.content):null);if(ne===void 0||C!==r)return;try{if(ne===null){q&&await A.call("DELETE",`/vaults/${j}/file?path=${encodeURIComponent(F)}&baseSeq=${q.seq}`);return}await A.call("PUT",`/vaults/${j}/file`,{path:F,content:Oc(ne),baseSeq:q?.seq??0});return}catch(re){if(re?.status!==409)throw re}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},H=async M=>!!(await ot()).entrySync?.some(U=>U.cloudName===M&&U.entries.length>0),N=(M,U)=>L(M,(C,A)=>{let j=A?.find(z=>z.id===U.id);if(j&&j.name===U.name)return;let F=j?.since??new Date().toISOString().slice(0,10);return[...(A??[]).filter(z=>z.id!==U.id),{...U,since:F}]},()=>H(M)),Y=(M,U)=>L(M,(C,A)=>{if(!C||!A?.some(F=>F.id===U))return;let j=A.filter(F=>F.id!==U);return j.length?j:null},async()=>!await H(M)),ee=()=>{e(Ne.entryChange)},J=async(M,U)=>{let C=h.get(M);if(!C)return;let A=z=>z&&z.startsWith(`${C.cloudName}/`)?z.slice(C.cloudName.length+1):null,j=A(U.path);if(!j)return;let F=!1;await Cn(z=>{if(h.get(M)!==C)return!1;let q=(z.entrySync??[]).find(oe=>oe.vaultRoot===M);if(!q)return!1;let ne=U.op,re=A(U.newPath),Z=jc(q.entries,ne,j,re),ie=re?yr(q.exclude??[],j,re):{changed:!1,next:q.exclude??[]};if(!Z.changed&&!ie.changed)return!1;F=!0,q.entries=Z.next,ie.changed&&(q.exclude=ie.next),_(C,Kt(q.entries,q.exclude??[]))}),F&&h.get(M)===C&&ee()},se=M=>{let U=r;return{...u(),onStatus:C=>{U===r&&e(Ne.status,{...C,pendingDeletions:me(),side:"local",binding:M})},onRemoteApplied:async C=>{U===r&&await J(M,C)}}},te=async()=>{let M=Be();if(!i||!M)return;let U=r,C=s,A=_n(M);await t.adoptLegacyCloudState(M,Fc);let j=await ot(M),F=j.entrySync??[];if(U!==r||!i||M!==Be())return;let z=new Map(F.map(q=>[q.vaultRoot,q]));for(let[q,ne]of h){let re=z.get(q);if(!(re&&re.cloudName===ne.cloudName)&&(await ne.engine.stop(),U!==r||(h.delete(q),re&&await vc(`amadeus-sync-${A}-entry-${Ti(q)}`),U!==r)))return}for(let q of F){let ne=h.get(q.vaultRoot);if(ne){_(ne,Kt(q.entries,q.exclude??[]));continue}let re={current:Kt(q.entries,q.exclude??[])},Z=q.cloudName,ie=mr(se(q.vaultRoot),{accountId:M,localRoot:q.vaultRoot,shadowName:`amadeus-sync-${A}-entry-${Ti(q.vaultRoot)}`,vaultId:"first",serverDir:Z,clientIdSuffix:`entry-${Ti(q.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:oe=>oe===Z?!0:oe.startsWith(`${Z}/`)?$c(re.current,oe.slice(Z.length+1)):!1});h.set(q.vaultRoot,{engine:ie,scope:re,cloudName:Z,base:re.current,pendingMoves:new Set}),ie.start()}if(j.cloudSync?.enabled!==!1)for(let q of F){let ne=q.entries.length>0,re=ne?T:v;re.has(q.cloudName)||((ne?v:T).delete(q.cloudName),(async()=>{try{let Z=await D();if(!Z||U!==r||(await(ne?N(q.cloudName,Z):Y(q.cloudName,Z.id)),U!==r))return;re.add(q.cloudName),(ne?v:T).delete(q.cloudName)}catch{}})())}},ae=async(M,U,C,A,j)=>{let F=U.replace(/\\/g,"/").normalize("NFC"),z=C.replace(/\\/g,"/").normalize("NFC"),q=!1,ne,re,Z,ie=j??"file";try{await Cn(async oe=>{if(h.get(M)!==A)return!1;let pe=(oe.entrySync??[]).find(yt=>yt.vaultRoot===M);if(!pe)return!1;let le=wr(pe.entries,F,z),X=yr(pe.exclude??[],F,z),ve=xn(pe.entries,pe.exclude,F);!j&&await Dn.stat(dn.join(M,...z.split("/"))).then(yt=>yt.isDirectory(),()=>!1)&&(ie="folder");let nn=ie==="folder"?"folder":/\.md$/i.test(z)?"page":"asset";ve&&!xn(le.next,X.next,z)&&(le.next.push({path:z,kind:nn}),le.changed=!0),q=le.changed||X.changed;let Jn=pe.entries.filter(yt=>wr([yt],F,z).changed);return ve&&!Jn.some(yt=>yt.path===F)&&Jn.push({path:F,kind:nn}),ne=Kt(Jn,(pe.exclude??[]).filter(yt=>yr([yt],F,z).changed)),re=A.base,A.pendingMoves.add(ne),pe.entries=le.next,pe.exclude=X.next,Z=Kt(pe.entries,pe.exclude),_(A,Z),q})}catch(oe){throw ne&&A.pendingMoves.delete(ne),_(A,A.base===Z&&re?re:A.base),oe}try{ne&&await A.engine.notifyLocalMove(F,z,()=>{A.pendingMoves.delete(ne),_(A)},ie)}catch(oe){throw ne&&A.pendingMoves.delete(ne),await Cn(pe=>{let le=pe.entrySync?.find(X=>X.vaultRoot===M);if(!le)return!1;le.entries=wr(le.entries,z,F).next,le.exclude=yr(le.exclude??[],z,F).next,_(A,Kt(le.entries,le.exclude))}),oe}q&&h.get(M)===A&&ee()},Q=M=>{let U=M.replace(/\\/g,"/");for(let{engine:C,plan:A}of g.values())if(U.startsWith(`${A.localRelDir}/`))return{engine:C,rel:U.slice(A.localRelDir.length+1)};return{engine:f,rel:U}};t.setMutationHooks((M,U)=>{if(b()){let C=Q(M);C.engine.notifyLocal(C.rel,U);return}h.get(n()??"")?.engine.notifyLocal(M,U)},(M,U,C)=>{if(b()){let F=Q(M),z=Q(U);if(F.engine===z.engine)return F.engine.notifyLocalMove(F.rel,z.rel,void 0,C);F.engine.notifyLocal(F.rel,"remove"),z.engine.notifyLocal(z.rel,"write");return}let A=n()??"",j=h.get(A);if(j)return ae(A,M,U,j,C)},(M,U)=>{if(b()){let C=Q(M),A=Q(U),j=[C.engine.holdLocalMove(C.rel,A.rel)];return C.engine!==A.engine&&j.push(A.engine.holdLocalMove(C.rel,A.rel)),()=>{for(let F of j)F()}}return h.get(n()??"")?.engine.holdLocalMove(M,U)});let me=()=>{let M=f.getStatus().pendingDeletions;for(let{engine:U}of g.values())M+=U.getStatus().pendingDeletions;for(let{engine:U}of h.values())M+=U.getStatus().pendingDeletions;return M},ge=M=>({...M,pendingDeletions:me(),side:b()?"cloud":"local"}),Pe=()=>{if(!i)return Promise.resolve(f.getStatus());y();for(let{engine:M}of g.values())M.syncNow();for(let{engine:M}of h.values())M.syncNow();return f.syncNow()},Ce=async()=>{let M=++r;i=!1,s.stop();let U=[f.stop(),...[...g.values()].map(({engine:A})=>A.stop()),...[...h.values()].map(({engine:A})=>A.stop())];if(g.clear(),h.clear(),p=[],T.clear(),v.clear(),a.clear(),o(),await Promise.all(U),await t.awaitPendingVaultWrites(),M!==r)return;let C=n();if(C&&bi(C)){let A=await ot();if(M!==r)return;let j=A.localVault&&!bi(A.localVault)?A.localVault:dn.join(t.workspaceDir(),"Amadeus");if(await Dn.mkdir(j,{recursive:!0}),M!==r||(await Pt({lastVault:j,localVault:j,lastPage:void 0}),M!==r))return;await t.activateRoot(j,!1)}M===r&&ee()};return{handlers:{get:()=>ge(f.getStatus()),setEnabled:async M=>{if(!i)throw new Error("Cloud account is changing");let U=r;return await f.setEnabled(M),U!==r?f.getStatus():(await Promise.all([...g.values(),...h.values()].map(({engine:C})=>C.restart())),ge(f.getStatus()))},syncNow:()=>Pe(),resolveHeld:M=>{let U=Array.isArray(M?.paths)?M.paths.filter(z=>typeof z=="string"):[],C=typeof M?.binding=="string"?M.binding:null,A=!C&&typeof M?.shareKey=="string"?M.shareKey:null,j=C?h.get(C)?.engine:A?g.get(A)?.engine:f;if(!j)return{error:"binding-not-found"};let F=j.resolveHeld(U,M.choice);return C?{...F,binding:C}:A?{...ge(F),shareKey:A}:ge(F)},confirmDeletions:()=>{for(let{engine:M}of g.values())M.confirmMassDeletions();for(let{engine:M}of h.values())M.confirmMassDeletions();return ge(f.confirmMassDeletions())},entryGet:async()=>{let M=await ot(),U=$t(),C=await Nc(U);return{vaults:M.entrySync??[],activeRoot:n(),cloudRoot:U,mirrorVaults:C.names,mirrorVaultDevices:C.devices,deviceId:M.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let M=n();if(!M)return null;let U=$t(),C=await ot(),A=M===U?C.localVault&&C.localVault!==U?C.localVault:null:U;if(!A)return null;let j=[],F=500,z=async(q,ne)=>{if(j.length>=F)return;let re;try{re=await Dn.readdir(q,{withFileTypes:!0})}catch{return}for(let Z of re){if(j.length>=F)break;if(Z.name.startsWith(".")||Z.isSymbolicLink())continue;let ie=ne?`${ne}/${Z.name}`:Z.name;if(Z.isDirectory())await z(dn.join(q,Z.name),ie);else if(Z.isFile()&&/\.db$/i.test(Z.name))try{j.push({rel:ie,source:await Dn.readFile(dn.join(q,Z.name),"utf8")})}catch{}}};return await z(A,""),{root:A,vaultName:A===U?"\u4E91\u7AEF":dn.basename(A),dbs:j}},entryEnable:async M=>{let U=r,C=s;if(!i||!Be())return{error:"Sign in to enable cloud sync"};let A=n();if(!A||b())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let j=await ot(),F=j.entrySync??[],z=F.find(q=>q.vaultRoot===A);if(!z){let q=(M.cloudName??dn.basename(A)).normalize("NFC").trim(),ne=ho(q,F.map(re=>re.cloudName));if(ne)return{error:ne};if(!M.merge)try{let re=await C.ensureOwnVault(),Z=await C.call("GET",`/vaults/${encodeURIComponent(re)}/tree`);if((Z.folders??[]).some(oe=>oe===q||oe.startsWith(`${q}/`))||(Z.entries??[]).some(oe=>oe.path===q||oe.path.startsWith(`${q}/`)))return{conflict:q}}catch(re){return{error:re?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}z={vaultRoot:A,cloudName:q,entries:[]},F.push(z)}return U!==r||!i?{error:"Cloud account changed; retry from the current account"}:(await Cn(q=>{if(U!==r||!i)return!1;let ne=q.entrySync??[],re=ne.find(X=>X.vaultRoot===A);if(!re){let X=ho(z.cloudName,ne.map(ve=>ve.cloudName));if(X)throw new Error(X);re={vaultRoot:A,cloudName:z.cloudName,entries:[]},ne.push(re)}let Z=X=>String(X??"").replace(/\\/g,"/").normalize("NFC"),ie=new Set;for(let X of M.entries??[]){let ve=Z(X.path);ve&&(ie.add(ve),!re.entries.some(nn=>nn.path===ve)&&re.entries.push({path:ve,kind:X.kind==="folder"||X.kind==="asset"?X.kind:"page"}))}let oe=(M.exclude??[]).map(Z).filter(Boolean),pe=new Set([...ie,...(M.include??[]).map(Z).filter(Boolean)]);re.exclude=[...new Set([...(re.exclude??[]).filter(X=>!pe.has(X)),...oe])];let le=new Set(oe);re.entries=re.entries.filter(X=>!le.has(X.path)),q.entrySync=ne,z=re},j.cloudAccountId),U!==r?{error:"Cloud account changed; retry from the current account"}:(await te(),h.get(A)?.engine.syncNow(),ee(),{ok:!0,cloudName:z.cloudName}))},entryDisable:async M=>{let U=n(),C=!1,A=r;return await Cn(j=>{if(A!==r||!i)return!1;let F=(j.entrySync??[]).find(ne=>ne.vaultRoot===U);if(!U||!F)return!1;let z=String(M??"").replace(/\\/g,"/").normalize("NFC"),q=F.entries.length;if(F.entries=F.entries.filter(ne=>ne.path!==z),xn(F.entries,F.exclude,z))F.exclude=[...new Set([...F.exclude??[],z])];else if(F.entries.length===q)return!1;C=!0}),!C||A!==r?{ok:!1}:(await te(),ee(),{ok:!0})},entryMark:async(M,U)=>{let C=String(M??"").normalize("NFC");if(!C||C.includes("/")||C.startsWith("."))return{error:"invalid name"};if(!i||!Be())return{error:"Sign in first"};try{await L(C,A=>U?A?void 0:[]:A?null:void 0)}catch(A){return{error:A?.message||String(A)}}return f.syncNow(),{ok:!0}},entryClosure:(M,U)=>t.relatedClosure(String(M??""),U==="folder"?"folder":"page"),collabCall:async(M,U)=>{let C=s,A=async()=>C.ensureOwnVault(),j=z=>String((U??[])[z]??""),F=z=>(U??[])[z]??{};switch(M){case"listVaults":return(await C.call("GET","/vaults")).vaults;case"activeVaultId":return A();case"pageShare":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/page-shares?path=${encodeURIComponent(j(0))}`);case"relatedItems":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}/related`);case"setShareItem":return C.call("POST",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}/items`,{path:j(1),included:(U??[])[2]===!0});case"createPageShare":return C.call("POST",`/vaults/${encodeURIComponent(await A())}/page-shares`,{path:j(0),...F(1)});case"updatePageShare":return C.call("PATCH",`/vaults/${encodeURIComponent(j(2)||await A())}/page-shares/${encodeURIComponent(j(0))}`,F(1));case"revokePageShare":return C.call("DELETE",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}`);case"setParticipantRole":return C.call("PATCH",`/vaults/${encodeURIComponent(j(3)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(j(1))}`,{role:j(2)});case"removeParticipant":return C.call("DELETE",`/vaults/${encodeURIComponent(j(2)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(j(1))}`);case"sharedWithMe":{let z=await C.sharedWithMe();return y(),z}case"leaveShare":{let z=C.myUserId();if(!z)throw new Error("\u672A\u767B\u5F55");let q=await C.call("DELETE",`/vaults/${encodeURIComponent(j(1)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(z)}`);return y(),q}case"publishes":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/shares`);case"listAllShares":{let z=(await C.call("GET","/vaults")).vaults||[],q=C.myUserId(),ne=[],re=[];for(let Z of z){try{let ie=await C.call("GET",`/vaults/${encodeURIComponent(Z.id)}/shares`);for(let oe of ie.shares||[])ne.push({...oe,vaultId:Z.id,vaultName:Z.name||""})}catch(ie){t.log(`[connect] listAllShares publishes vault ${Z.id} failed: ${ie?.message}`)}try{let ie=await C.call("GET",`/vaults/${encodeURIComponent(Z.id)}/page-shares?expired=1`),oe=ie?.shares||ie?.pageShares||(Array.isArray(ie)?ie:[]);for(let pe of oe){let le=pe.created_by??pe.createdBy;(!q||!le||le===q)&&re.push({...pe,vaultId:Z.id,vaultName:Z.name||""})}}catch(ie){t.log(`[connect] listAllShares pageShares vault ${Z.id} failed: ${ie?.message}`)}}return{publishes:ne,pageShares:re,linkBase:await C.linkBase()}}case"createPublish":{let z=await C.call("POST",`/vaults/${encodeURIComponent(await A())}/shares`,{mode:j(0),path:j(1)});return{...z,url:`${await C.linkBase()}/share/${z.token}`}}case"revokePublish":return C.call("DELETE",`/vaults/${encodeURIComponent(await A())}/shares/${encodeURIComponent(j(0))}`);case"revokePublishIn":return C.call("DELETE",`/vaults/${encodeURIComponent(j(0))}/shares/${encodeURIComponent(j(1))}`);case"revokePageShareIn":return C.call("DELETE",`/vaults/${encodeURIComponent(j(0))}/page-shares/${encodeURIComponent(j(1))}`);case"myUserId":return C.myUserId();case"linkBase":return C.linkBase();case"heartbeat":return C.heartbeat((U??[])[0]??null,p);default:throw new Error(`unknown collab fn: ${M}`)}},switchSide:async(M,U)=>{let C=await ot();if(U==="cloud"){if(!i||!Be())throw new Error("Sign in to open cloud notes");let F=$t();await Dn.mkdir(F,{recursive:!0}),C.lastVault&&!bi(C.lastVault)&&await Pt({localVault:C.lastVault}),await Pt({lastVault:F});let z=await t.activateRoot(F,!1);return t.bindRenderer(M,F),{...z,side:"cloud"}}let A=C.localVault&&await Dn.stat(C.localVault).then(F=>F.isDirectory()).catch(()=>!1)?C.localVault:null;if(!A){let F=await t.ensureDefaultVault();return t.bindRenderer(M,F.root),{...F,side:"local"}}await Pt({lastVault:A});let j=await t.activateRoot(A,!1);return t.bindRenderer(M,A),{...j,side:"local"}}},instance:{start:()=>{i=!0,f.start(),y(),te()},stopAllSync:Ce,restartAllSync:async()=>{let M=Ce(),U=r;await M,U===r&&(s=co(),f=mr(u()),i=!0,await Promise.all([f.restart(),y(),te()]),U===r&&(ee(),e(Ne.status,ge(f.getStatus()))))},resolveSharedAsset:M=>Rc(p,M)}}}import{hostname as gg}from"node:os";var mg=256*1024;function Zc(t,e,n){if(n?.hasSecHeaders&&!n.gatewayStreamsSecHeaders)return!1;if(t.includes("text/event-stream"))return!0;let r=Number(e||NaN);return!Number.isFinite(r)||r>mg}var vo=45e3,yg=3e3,wg=16*1024,bg=6e4,Ri=t=>`${t.replace(/\/+$/,"")}/api`,Sr=class{deps;ctrl=null;conn=null;wake=null;redialNow=!1;inflight=new Map;connected=!1;lastError=null;hubCaps=new Set;constructor(e){this.deps=e}hubFetch(e,n){return(this.deps.hubFetch??fetch)(e,n)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??bg}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(n),r.ctrl.abort())}sleep(e){return new Promise(n=>{let r=setTimeout(i,e);function i(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,i()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,i=()=>r.abort();e.signal.addEventListener("abort",i,{once:!0}),this.conn=r;try{let{cloudUrl:s,token:a}=this.deps.getCreds();if(!a)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let o=this.deps.getPairing();if(!o){if(o=await this.register(s,a,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(o),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${o.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let c=this.deps.readIdleMs??vo,u=c?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(c/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},c):null,f;try{f=await this.hubFetch(`${Ri(s)}/units/${o.unitId}/channel`,{headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":o.secret,...l?{"X-Unit-Lan-Url":l}:{}},signal:r.signal})}finally{u&&clearTimeout(u)}if(f.status===403||f.status===404){let g=Number(f.headers.get("content-length"))>wg,p=setTimeout(()=>r.abort(),g?0:yg),m=await f.json().then(y=>y?.code,()=>null);throw clearTimeout(p),m==="UNIT_NOT_FOUND"||m==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${f.status} ${m}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${f.status} (not a hub verdict; keeping pairing and retrying)`)}if(!f.ok||!f.body)throw new Error(`channel HTTP ${f.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(f.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(s){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(s?.message||s),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",i),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,r){let i=this.deps.readIdleMs??vo,s=i?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(i/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},i):null;try{let a=await this.hubFetch(`${Ri(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:gg(),platform:process.platform}),signal:r.signal});if(!a.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${a.status}`);let o=await a.json();if(!o.unitId||!o.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:o.unitId,secret:o.secret}}finally{s&&clearTimeout(s)}}async consume(e,n){let r=e.getReader(),i=new TextDecoder,s="",a=this.deps.readIdleMs??vo,o=null,l=()=>{a&&(o&&clearTimeout(o),o=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(a/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),n.abort(),r.cancel().catch(()=>{})},a))};l();try{for(;;){let{done:c,value:u}=await r.read();if(c||n.signal.aborted)return;l(),s=this.parseFrames(s+i.decode(u,{stream:!0}),n)}}finally{o&&clearTimeout(o)}}parseFrames(e,n){let r=e,i;for(;(i=r.indexOf(`
|
|
223
|
+
--${n}--\r
|
|
224
|
+
`}}function Ju(n,e){let t=n.filter(([s])=>e-s<=3e3);if(t.length<2)return 0;let[r,i]=t[0],[o,a]=t[t.length-1];return o>r?Math.max(0,(a-i)/(o-r)*1e3):0}function Ku(n,e){let t=e??{};return n===401?"not_signed_in":t.code==="STORAGE_QUOTA_EXCEEDED"?"quota":t.code==="STORAGE_BUSY"||t.code==="STORAGE_RECONCILIATION_REQUIRED"?"storage_unavailable":t.code==="FILE_TOO_LARGE"||n===413?"too_large":typeof t.detail=="string"&&/quota exceeded/i.test(t.detail)?"quota":t.code==="STORAGE_NOT_CONFIGURED"?"storage_unavailable":`http_${n}`}var GA=3,Xu=6e4,JA=200,KA=Tw;function Fw(n,e,t,r){let{head:i,tail:o}=Mw(n,e,t,r);return{head:Buffer.from(i,"utf8"),tail:Buffer.from(o,"utf8")}}function YA(n,e,t,r,i,o,a,s){return new Promise((l,c)=>{let u=new URL(n),d=(u.protocol==="https:"?zA:VA)(u,{method:"POST",headers:{...e,"Content-Length":String(t.length+i+o.length)}},f=>{let p=[];f.on("data",m=>p.push(m)),f.on("end",()=>{let m=null;try{m=JSON.parse(Buffer.concat(p).toString("utf8"))}catch{}l({status:f.statusCode??0,body:m})}),f.on("error",c)}),g=()=>{d.destroy(new Error("aborted"))};if(s.aborted)return g();s.addEventListener("abort",g,{once:!0}),d.setTimeout(Xu,()=>d.destroy(new Error("timeout"))),d.on("error",f=>{s.removeEventListener("abort",g),c(f)}),(async()=>{try{d.write(t);let f=0;for await(let p of MA(r)){let m=p;if(f+=m.length,f>i)throw new Error("changed");d.write(m)||await new Promise(y=>d.once("drain",y)),a(f)}if(f!==i)throw new Error("changed");d.end(o)}catch(f){d.destroy(f)}})()})}function Zu(n,e={}){let t=e.downloadsDir??(()=>us(HA(),"Downloads")),r=e.post??YA,i=e.now??Date.now,o=[],a=new Map,s=Promise.resolve(),l=async()=>{let S=await n.getCloud(),_=typeof n.accountId=="function"?n.accountId():null;return{...S,account:_||`${S.base}|${S.token}`}},c=S=>{let{account:_,attempt:R,relDir:N,abort:D,samples:M,dl:x,...$}=S;return{...$,speed:S.state==="active"?Ju(M,i()):0}},u=(S,_,R=null)=>{S.state=_,S.error=R,S.abort=null,S.finishedAt=i(),S.samples=[];let N=o.filter(D=>D.state==="done"||D.state==="canceled");for(let D of N.slice(0,Math.max(0,N.length-JA)))o.splice(o.indexOf(D),1);d()};function d(){for(let S of["up","down"]){let _=o.filter(R=>R.kind===S&&R.state==="active").length;for(let R of o){if(_>=GA)break;if(R.kind!==S||R.state!=="queued")continue;_++,R.state="active",R.startedAt=i(),R.done=0,R.samples=[[i(),0]],R.abort=new AbortController;let N=++R.attempt,D=()=>R.attempt===N&&R.state==="active";(S==="up"?b(R,D):E(R,D)).catch(M=>{D()&&u(R,"failed",g(M))})}}}let g=S=>{let _=String(S?.message||S);return _==="changed"||_==="too_large"||_==="quota"||_==="account_changed"||_==="not_signed_in"||_.startsWith("http_")||_==="bad_response"||_==="gone"?_:"network"},f=(S,_)=>{S.done=_;let R=i(),N=S.samples[S.samples.length-1];for((!N||R-N[0]>=200)&&S.samples.push([R,_]);S.samples.length>2&&R-S.samples[0][0]>3500;)S.samples.shift()};async function p(S){let _=await l();if(_.account!==S.account)throw new Error("account_changed");if(!_.token)throw new Error("not_signed_in");return _}async function m(S,_,R,N){let D=Tt(S,R);if(!D)throw new Error("bad_path");let M=await fetch(D,{method:N.method??"GET",headers:{Authorization:`Bearer ${_}`,...N.body!==void 0?{"Content-Type":"application/json"}:{},...N.projectSource?{"X-Project-Source":N.projectSource}:{}},body:N.body!==void 0?JSON.stringify(N.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:M.status,json:await M.json().catch(()=>null)}}function y(S,_,R){if(!S.relDir.length)return Promise.resolve(S.targetId);let N=a.get(S.batch);N||a.set(S.batch,N=new Map);let D=N,M=x=>{if(x===0)return Promise.resolve(S.targetId);let $=S.relDir.slice(0,x).join("/"),O=D.get($);return O||(O=M(x-1).then(async q=>{let ie=S.relDir[x-1],Y=await m(_,R,"/files",{method:"POST",body:{type:"directory",parentId:q,name:ie},projectSource:S.projectSource});if(Y.status===201&&typeof Y.json?.id=="string")return Y.json.id;if(Y.status===409){let ne=await m(_,R,`/files${q==="ROOT"?"":`?parentId=${encodeURIComponent(q)}`}`,{projectSource:S.projectSource}),ce=Array.isArray(ne.json)?ne.json.find(Re=>Re?.fileType==="directory"&&Re?.name===ie):null;if(ce?.id)return String(ce.id)}throw new Error(Y.status===401?"not_signed_in":`http_${Y.status}`)}),O.catch(()=>D.delete($)),D.set($,O)),O};return M(S.relDir.length)}async function b(S,_){let{base:R,token:N}=await p(S),D=await $w(S.localPath).catch(()=>null);if(!D?.isFile())throw new Error("gone");if(D.size>52428800)throw new Error("too_large");S.size=D.size;let M=await y(S,R,N);if(!_())return;S.parentId=M;let x=Tt(R,"/files/upload");if(!x)throw new Error("bad_path");let $=`----penzor${Ll().replace(/-/g,"")}`,{head:O,tail:q}=Fw($,{parentId:M,autoRename:"true"},S.name,Ow(S.name)),ie=await r(x,{Authorization:`Bearer ${N}`,"Content-Type":`multipart/form-data; boundary=${$}`,...S.projectSource?{"X-Project-Source":S.projectSource}:{}},O,S.localPath,D.size,q,Y=>{_()&&f(S,Y)},S.abort.signal);_()&&(ie.status===201||ie.status===200?(S.fileId=typeof ie.body?.id=="string"?ie.body.id:null,f(S,S.size),u(S,"done")):u(S,"failed",Ku(ie.status,ie.body)))}function h(S,_,R,N){let D=async()=>{let x=qA(R),$=x?R.slice(0,-x.length):R;for(let O=0;O<1e3;O++){if(!N())throw new Error("aborted");let q=us(_,O===0?R:`${$} (${O})${x}`);try{await $A(S,q)}catch(ie){let Y=ie.code;if(Y==="EEXIST")continue;if(Y!=="EPERM"&&Y!=="ENOTSUP"&&Y!=="EOPNOTSUPP"&&Y!=="ENOSYS"&&Y!=="EXDEV")throw ie;if(await NA(q).then(()=>!0,()=>!1))continue;await UA(S,q)}if(!N())throw await Yu(q).catch(()=>{}),new Error("aborted");return await Yu(S).catch(()=>{}),q}throw new Error("too many duplicates")},M=s.then(D,D);return s=M.catch(()=>{}),M}async function E(S,_){let R=S.dl,{base:N,token:D}=await p(S);if(!_())return;let M=Tt(N,R.path);if(!M)throw new Error("bad_path");let x=S.abort.signal,$=R.subdir?us(t(),R.subdir):t();await FA($,{recursive:!0});let O=us($,`.${S.id}-${S.attempt}.penzor-part`),q=await BA(O,"wx"),ie=!1;try{let Y=new AbortController,ne=setTimeout(()=>Y.abort(),Xu),ce=()=>{clearTimeout(ne),ne=setTimeout(()=>Y.abort(),Xu)},Re=AbortSignal.any([x,Y.signal]);try{let Ee=await fetch(M,{headers:{Authorization:`Bearer ${D}`},signal:Re});if(!Ee.ok)throw new Error(Ee.status===401?"not_signed_in":`http_${Ee.status}`);let me=Ee.body,Ce=Number(Ee.headers.get("content-length"))||S.size;if(R.mode!=="bytes"){let Be=await Ee.json().catch(()=>null);if(R.mode==="text"){if(typeof Be?.content!="string")throw new Error("bad_response");let _e=Buffer.from(Be.content,"utf8");await q.writeFile(_e),S.size=_e.length,f(S,_e.length),me=null}else{if(typeof Be?.url!="string"||!/^https?:\/\//i.test(Be.url))throw new Error("bad_response");let _e=await fetch(Be.url,{signal:Re});if(!_e.ok)throw new Error(`http_${_e.status}`);me=_e.body,Ce=Number(_e.headers.get("content-length"))||S.size}}if(me){S.size=Ce;let Be=0;for await(let _e of me){ce();for(let ft=0;ft<_e.length;){let{bytesWritten:at}=await q.write(_e,ft,_e.length-ft);if(at<=0)throw new Error("short_write");ft+=at}if(Be+=_e.length,!_())throw new Error("aborted");f(S,Be)}Be>S.size&&(S.size=Be)}}finally{clearTimeout(ne)}if(await q.close(),!_()||(S.localPath=await h(O,$,R.name,_),ie=!0,!_()))return;u(S,"done")}finally{ie||(await q.close().catch(()=>{}),await Yu(O).catch(()=>{}))}}let v=(S,_)=>{let R={...S,id:Ll(),attempt:0,done:0,state:_?"failed":"queued",error:_??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:_?i():null};return o.push(R),R};async function k(S){let _=[],R=async(N,D)=>{if(D.length>32)return!0;let M=await(D.length?LA(N):$w(N)).catch(()=>null);if(!M)return!0;if(M.isFile())return _.push({path:N,size:M.size,relDir:D}),_.length<=2e3;if(!M.isDirectory())return!0;let x=(await jA(N).catch(()=>[])).filter($=>!$.startsWith(".")).sort();for(let $ of x)if(!await R(us(N,$),[...D,Lw(N)]))return!1;return!0};for(let N of S)if(!await R(N,[]))return"too_many";return _}n.handle("penzor:device",S=>{if(!n.isTrustedSender(S))return{ok:!1,error:"untrusted"};let _=Ol();return{ok:!0,name:_?decodeURIComponent(_):null}}),n.handle("penzor:upload",async(S,_)=>{if(!n.isTrustedSender(S))return{ok:!1,error:"untrusted"};let R=_??{},N=Array.isArray(R.paths)?R.paths.filter(ce=>typeof ce=="string"&&WA(ce)):[],D=typeof R.parentId=="string"&&Dw.test(R.parentId)?R.parentId:null,M=typeof R.projectSource=="string"&&Pw.test(R.projectSource)?R.projectSource:null;if(!N.length)return{ok:!1,error:"no_files"};if(!D||!M)return{ok:!1,error:"bad_target"};let{base:x,token:$,account:O}=await l();if(!$)return{ok:!1,error:"not_signed_in"};let q=await k(N);if(q==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!q.length)return{ok:!1,error:"no_files"};let ie=q.filter(ce=>ce.size<=52428800).reduce((ce,Re)=>ce+Re.size,0);try{let ce=await m(x,$,"/storage/quota",{}),Re=Number(ce.json?.used),Ee=Number(ce.json?.quota);if(ce.status===200&&Ee>0&&Re+ie>Ee)return{ok:!1,error:"quota",short:Re+ie-Ee}}catch{}if((await l()).account!==O)return{ok:!1,error:"account_changed"};let Y=Ll(),ne=q.map(ce=>v({kind:"up",name:Lw(ce.path),size:ce.size,projectSource:M,parentId:ce.relDir.length?null:D,targetId:D,fileId:null,localPath:ce.path,batch:Y,account:O,relDir:ce.relDir},ce.size>52428800?"too_large":void 0).id);return d(),{ok:!0,ids:ne,batch:Y}}),n.handle("penzor:download",async(S,_)=>{if(!n.isTrustedSender(S))return{ok:!1,error:"untrusted"};let R=_??{},N=KA.includes(R.mode)?R.mode:null,D=$l(R.name);if(!N)return{ok:!1,error:"bad_mode"};if(!D)return{ok:!1,error:"bad_name"};let{base:M,token:x,account:$}=await l();if(typeof R.path!="string"||!Tt(M,R.path))return{ok:!1,error:"bad_path"};if(!x)return{ok:!1,error:"not_signed_in"};let O=R.subdir==null?null:$l(R.subdir),q=v({kind:"down",name:D,size:Math.max(0,Number(R.size)||0),localPath:null,batch:typeof R.batch=="string"&&R.batch.length<=64?R.batch:Ll(),account:$,relDir:[],dl:{path:R.path,mode:N,name:D,subdir:O}});return d(),{ok:!0,id:q.id}}),n.handle("penzor:transfers",S=>n.isTrustedSender(S)?{ok:!0,items:o.map(c)}:{ok:!1,error:"untrusted"}),n.handle("penzor:transfer",(S,_)=>{if(!n.isTrustedSender(S))return{ok:!1,error:"untrusted"};let R=_??{},N=o.find(M=>M.id===R.id);if(!N)return{ok:!1,error:"not_found"};let D=()=>{N.abort?.abort(),N.abort=null,N.done=0,N.samples=[]};switch(R.op){case"pause":(N.state==="active"||N.state==="queued")&&(D(),N.state="paused",d());break;case"resume":N.state==="paused"&&(N.state="queued",d());break;case"cancel":(N.state==="active"||N.state==="queued"||N.state==="paused")&&(D(),u(N,"canceled"));break;case"retry":(N.state==="failed"||N.state==="canceled")&&(N.state="queued",N.error=null,N.finishedAt=null,N.done=0,d());break;case"dismiss":N.state!=="active"&&N.state!=="queued"&&o.splice(o.indexOf(N),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),n.handle("penzor:transfers:clear",(S,_)=>{if(!n.isTrustedSender(S))return{ok:!1,error:"untrusted"};let R=_?.which==="all";for(let N of[...o])(N.state==="done"||N.state==="canceled"||R&&N.state==="failed")&&o.splice(o.indexOf(N),1);return{ok:!0}});let C=()=>o.filter(S=>S.state==="active"||S.state==="queued"||S.state==="paused").length;return Ya(n,"transfers",()=>C()>0),n.addQuitGuard?.(S=>{let _=C();return _?S==="zh"?{message:`\u8FD8\u6709 ${_} \u4E2A\u6587\u4EF6\u6CA1\u4F20\u5B8C`,detail:"\u73B0\u5728\u9000\u51FA\u4F1A\u4E2D\u65AD\uFF0C\u4E0B\u6B21\u6253\u5F00\u8981\u91CD\u65B0\u4F20\u3002"}:{message:_===1?"1 file hasn't finished transferring":`${_} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>o.map(c)}}import{readFileSync as XA,writeFileSync as ZA,mkdirSync as QA,chmodSync as eC,renameSync as tC}from"node:fs";import{join as nC}from"node:path";function rC(n){let e=()=>nC(n(),"auth-accounts.json");return{read:()=>XA(e(),"utf8"),write:t=>{QA(n(),{recursive:!0});let r=`${e()}.tmp`;ZA(r,t,{encoding:"utf8",mode:384}),eC(r,384),tC(r,e())}}}var jw=n=>ig(n,rC(()=>n.homeDir())),Uw=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],Qu=n=>Uw.every(e=>typeof n[e]=="function");function ef(n){let e={ok:!1,error:"untrusted"},t={loggedIn:!1,error:"untrusted"},r=jw(n),i=0,o=()=>{let l=n.readCreds();return ro(l.cloudUrl,l.token)},a=l=>rt(l.cloudUrl??"",l.token??""),s=null;n.handle("auth:status",async l=>{if(!n.isTrustedSender(l))return t;let c=i,u=o(),{base:d}=await n.getCloud(),g=n.readCreds().token,f=g?await cs(d,g):null,p=await n.accountBackendState(),{base:m}=await n.getCloud(),y=n.readCreds(),b=ro(m,y.token)!==ro(d,g),h=ro(d,g);!b&&f?.status==="ok"&&f.user&&(s={key:h,user:f.user},r.rememberForsionAccount({...y,cloudUrl:d},f.user));let E=b?void 0:f?.status==="ok"?f.user:f?.status==="offline"&&s?.key===h?s.user:void 0;if(b)return{loggedIn:!!y.token,tokenValid:null,cloudUrl:m,accountId:rt(m,y.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:y.token?"tangu-login":null,backendState:p};if(f?.status==="expired"){await n.accountTransition(async()=>{if(c!==i||o()!==u)return;let k=()=>{if(c!==i||o()!==u)throw Bw};try{await n.accountClear(k,()=>{ki(n,n.accountId?.()??null,null),n.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++i,r.cancelForsionLogin(),r.forgetForsionAccount(n.readCreds()),s=null})}catch(C){if(C!==Bw)throw C}});let v=n.readCreds();return{loggedIn:!!v.token,tokenValid:null,cloudUrl:v.cloudUrl||d,accountId:rt(v.cloudUrl||d,v.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:v.token?"tangu-login":null,backendState:p}}return{loggedIn:!!g,tokenValid:f&&f.status==="ok"?!0:null,cloudUrl:d,accountId:rt(d,g),username:E?.username||null,nickname:E?.nickname||null,avatar:E?.avatar||null,membershipTier:E?.membershipTier||null,tokenSource:g?"tangu-login":null,backendState:p}}),n.handle("auth:accounts",l=>n.isTrustedSender(l)?r.forsionAccounts():[]),n.handle("auth:switchAccount",async(l,c)=>{if(!n.isTrustedSender(l))return e;if(typeof c!="string")throw new Error("Invalid account.");let u=++i;return r.cancelForsionLogin(),n.accountTransition(async()=>{let d=r.savedForsionAccount(c);return await n.accountCommit(d,()=>{if(u!==i)throw new Error("Account switch cancelled.")},()=>{ki(n,n.accountId?.()??null,a(d)),r.rememberForsionAccount(d),s=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),n.handle("auth:forsionLogin",async(l,c)=>{if(!n.isTrustedSender(l))return e;let u=++i;r.cancelForsionLogin();let{base:d}=await n.getCloud();if(u!==i)throw new Error("Sign-in cancelled.");let g=(c||d||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(g,p=>n.broadcast("auth:device",p),(p,m)=>n.accountTransition(()=>n.accountCommit(p,()=>{if(m(),u!==i)throw new Error("Sign-in cancelled.")},()=>{ki(n,n.accountId?.()??null,a(p)),r.rememberForsionAccount(p),s=null})))).cloudUrl}}),n.handle("auth:logout",async l=>n.isTrustedSender(l)?(++i,r.cancelForsionLogin(),n.accountTransition(async()=>{let{base:c}=await n.getCloud(),u=n.readCreds();return await n.accountClear(void 0,()=>{ki(n,n.accountId?.()??null,null),r.forgetForsionAccount(u),s=null,c&&u.token&&fetch(`${c}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${u.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),n.onExternalCredsChange(({previous:l,current:c})=>{try{ki(n,a(l),a(c))}catch{n.log("[content-sync] account transition could not be recorded; sync is stopped")}++i,r.cancelForsionLogin(),l.token&&!c.token&&r.forgetForsionAccount(l),s=null,r.rememberForsionAccount(c)}),n.setTokenRefresher(async l=>{let c=i,u=o(),d=n.readCreds().token;if(!$s(d))return;let{base:g}=await n.getCloud(),f=await Ls(g,d,l,`desktop/${n.appVersion()}`);if(!f){n.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}c!==i||o()!==u||(r.rememberForsionAccount({cloudUrl:g,token:f}),n.writeCreds({cloudUrl:g,token:f}),n.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),n.log("[forsion-extend] account core registered")}var Bw=Symbol("stale-auth-intent");import{hostname as iC}from"node:os";var oC=256*1024;function Vw(n,e,t){if(t?.hasSecHeaders&&!t.gatewayStreamsSecHeaders)return!1;if(n.includes("text/event-stream"))return!0;let r=Number(e||NaN);return!Number.isFinite(r)||r>oC}var tf=45e3,sC=3e3,aC=16*1024,lC=6e4,Fl=n=>`${n.replace(/\/+$/,"")}/api`,fs=class{deps;ctrl=null;conn=null;wake=null;redialNow=!1;inflight=new Map;connected=!1;lastError=null;hubCaps=new Set;constructor(e){this.deps=e}hubFetch(e,t){return(this.deps.hubFetch??fetch)(e,t)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??lC}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(t){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${t?.message||t}`)}}abortEnvelope(e){let t=this.inflight.get(e);return t?(this.inflight.delete(e),t.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[t,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(t),r.ctrl.abort())}sleep(e){return new Promise(t=>{let r=setTimeout(i,e);function i(){clearTimeout(r),t()}this.wake=()=>{this.wake=null,i()}})}async loop(e){let t=1e3;for(;!e.signal.aborted;){let r=new AbortController,i=()=>r.abort();e.signal.addEventListener("abort",i,{once:!0}),this.conn=r;try{let{cloudUrl:o,token:a}=this.deps.getCreds();if(!a)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let s=this.deps.getPairing();if(!s){if(s=await this.register(o,a,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(s),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${s.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let c=this.deps.readIdleMs??tf,u=c?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(c/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},c):null,d;try{d=await this.hubFetch(`${Fl(o)}/units/${s.unitId}/channel`,{headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":s.secret,...l?{"X-Unit-Lan-Url":l}:{}},signal:r.signal})}finally{u&&clearTimeout(u)}if(d.status===403||d.status===404){let g=Number(d.headers.get("content-length"))>aC,f=setTimeout(()=>r.abort(),g?0:sC),p=await d.json().then(m=>m?.code,()=>null);throw clearTimeout(f),p==="UNIT_NOT_FOUND"||p==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${d.status} ${p}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${d.status} (not a hub verdict; keeping pairing and retrying)`)}if(!d.ok||!d.body)throw new Error(`channel HTTP ${d.status}`);this.connected=!0,this.lastError=null,t=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(d.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(o){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(o?.message||o),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(t/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",i),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,t=1e3;continue}if(await this.sleep(t),this.redialNow){this.redialNow=!1,t=1e3;continue}t=Math.min(t*2,3e4)}}async register(e,t,r){let i=this.deps.readIdleMs??tf,o=i?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(i/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},i):null;try{let a=await this.hubFetch(`${Fl(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:iC(),platform:process.platform}),signal:r.signal});if(!a.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${a.status}`);let s=await a.json();if(!s.unitId||!s.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:s.unitId,secret:s.secret}}finally{o&&clearTimeout(o)}}async consume(e,t){let r=e.getReader(),i=new TextDecoder,o="",a=this.deps.readIdleMs??tf,s=null,l=()=>{a&&(s&&clearTimeout(s),s=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(a/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),t.abort(),r.cancel().catch(()=>{})},a))};l();try{for(;;){let{done:c,value:u}=await r.read();if(c||t.signal.aborted)return;l(),o=this.parseFrames(o+i.decode(u,{stream:!0}),t)}}finally{s&&clearTimeout(s)}}parseFrames(e,t){let r=e,i;for(;(i=r.indexOf(`
|
|
219
225
|
|
|
220
|
-
`))>=0;){let
|
|
221
|
-
`).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(
|
|
222
|
-
`).find(o=>o.startsWith("data: "))?.slice(6);if(a)try{let o=JSON.parse(a);this.dispatch(o,n).catch(l=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${l?.message||l}`))}catch{}}return r}async dispatch(e,n){let r=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let i={ctrl:r,conn:n};this.inflight.set(e.id,i);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===i&&this.inflight.delete(e.id)}}async handle(e,n){let r=this.deps.getUnitWeb();if(!r.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,n.signal);return}let i={"x-unit-internal":r.internalSecret};e.ct&&(i["Content-Type"]=e.ct),e.accept&&(i.Accept=e.accept);let s;try{let u=new URL(`${r.url}${e.path}`);Object.assign(i,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:u,proxyCaller:e.proxyCaller,proxyOperator:e.proxyOperator})),s=await fetch(u,{method:e.method,headers:i,body:e.body??void 0,signal:n.signal})}catch(u){if(n.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${u?.message||u}`})),void 0,n.signal);return}let a=s.headers.get("content-type")||"",o={};for(let u of["content-security-policy","x-content-type-options"]){let f=s.headers.get(u);f&&(o[u]=f)}let l=a||"application/octet-stream";s.body&&Zc(a,s.headers.get("content-length"),{hasSecHeaders:Object.keys(o).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,s,n,l,o):await this.respond(e.id,s.status,l,Buffer.from(await s.arrayBuffer()),o,n.signal)}async respond(e,n,r,i,s,a){if(a?.aborted)return;let{cloudUrl:o,token:l}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let u=this.requestTimeoutMs*2,f=[...u?[AbortSignal.timeout(u)]:[],...a?[a]:[]],g=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${Ri(o)}/units/${c.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":c.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":r,...s},bodyB64:i.toString("base64")}),...g?{signal:g}:{}}).then(p=>{p.body?.cancel().catch(()=>{})}).catch(p=>{a?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${p?.name==="TimeoutError"?`${Math.round(u/1e3)}s \u672A\u5B8C\u6210`:p?.message||p}`)})}async streamBack(e,n,r,i,s){let{cloudUrl:a,token:o}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let c=s?.["content-security-policy"],u=s?.["x-content-type-options"],f=`${Ri(a)}/units/${l.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(i)}`+(c?`&csp=${encodeURIComponent(c)}`:"")+(u?`&xcto=${encodeURIComponent(u)}`:""),g=n.body;if(!g)return;let p=g.getReader(),m=0,y=this.requestTimeoutMs,b=y?setTimeout(()=>{m>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(y/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},y):null,_=new ReadableStream({async pull(h){++m===2&&b&&clearTimeout(b);let{done:T,value:v}=await p.read();T?h.close():h.enqueue(v)},cancel(h){return p.cancel(h)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${o}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:_,signal:r.signal,duplex:"half"})}catch(h){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${h?.message||h}`);try{await p.cancel()}catch{}}finally{b&&clearTimeout(b)}}};function Sg(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(typeof n!="string"||n.length===0||n.length>64)&&!e.includes(n)&&(e.push(n),e.length>=16))break;return e}var vr=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}capsChanged(){this.engineChanged()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(c){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${c?.message||c}`);return}let n={engine:e,tools:[]};if(typeof this.d.features=="function"){let c=[];try{c=this.d.features()}catch(u){this.d.log(`[unit-caps] \u8BFB\u80FD\u529B\u58F0\u660E\u5931\u8D25:${u?.message||u}`)}n.features=Sg(c)}let r=JSON.stringify(n);if(r===this.lastSent)return;let i=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!i||!s.token||!s.cloudUrl)return;let a=this.gen;this.inflight=!0;let o=new AbortController,l=setTimeout(()=>o.abort(),this.d.timeoutMs??1e4);try{let c=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(i.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(c,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":i.secret,"Content-Type":"application/json"},body:r,signal:o.signal});try{await u.text()}catch{}if(a!==this.gen)return;u.ok?(this.lastSent=r,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}${n.features?`(\u80FD\u529B\u58F0\u660E ${n.features.length} \u9879)`:""}`)):u.status===404||u.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${u.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):u.status===400||u.status===401||u.status===403?this.warned.has(u.status)||(this.warned.add(u.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${u.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${u.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(c){a===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${o.signal.aborted?"\u8D85\u65F6":c?.message||c}`)}finally{clearTimeout(l),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var Qc=["setUnitHubFactory"],ko=t=>Qc.every(e=>typeof t[e]=="function");function eu(t){let e=new vr({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),...typeof t.capsFeatures=="function"?{features:()=>t.capsFeatures()}:{},log:r=>t.log(r)}),n=new Sr({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged(),capsChanged:()=>e.capsChanged()}}function Eo(t){let e=async(n,r,i)=>{let{base:s,token:a}=await t.getCloud();if(!a)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let o=await fetch(`${s}/api${r}`,{method:n,headers:{Authorization:`Bearer ${a}`,...i!==void 0?{"Content-Type":"application/json"}:{}},body:i!==void 0?JSON.stringify(i):void 0});return{status:o.status,json:await o.json().catch(()=>null)}}catch(o){return{status:0,json:{detail:String(o?.message||o)}}}};t.handle("units:list",(n,r)=>e("GET",r!=null&&typeof r=="object"&&r.shared===!0?"/units?shared=1":"/units")),t.handle("units:update",(n,r,i)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:i?.name,icon:i?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:i,token:s}=await t.getCloud();await t.openExternal(`${i}/api/units/${r}/open${s?`#token=${encodeURIComponent(s)}`:""}`)}),t.setUnitHubFactory(eu),t.log("[forsion-extend] unit hub registered")}import{createHash as Gg}from"node:crypto";import{constants as Au,mkdirSync as Vg,readFileSync as Yg,renameSync as Jg,writeFileSync as Kg}from"node:fs";import{lstat as Ft,open as Uu,readFile as Xg,readdir as Hu,statfs as Zg}from"node:fs/promises";import{cpus as Qg,freemem as em,homedir as xu,hostname as zu,release as tm,totalmem as nm}from"node:os";import{basename as Bu,join as de}from"node:path";var vg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,kr=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,i="Z";if(typeof e=="string"){let s=e.match(vg);s?(s[1]||(n=!1,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=!1,n.#e=null,n}};function kg(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Eg(t,e,n){let r=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let a=e-1;a<=e+1;a++){let o=r[a-1];o&&(i+=a.toString().padEnd(s," "),i+=": ",i+=o,i+=`
|
|
223
|
-
`,a===e&&(i+=" ".repeat(
|
|
224
|
-
`))}return i}var
|
|
226
|
+
`))>=0;){let o=r.slice(0,i);if(r=r.slice(i+2),o.includes("event: ready")){let s=o.split(`
|
|
227
|
+
`).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(s||"{}").caps;this.hubCaps=new Set(Array.isArray(l)?l.map(String):[])}catch{this.hubCaps=new Set}t.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!o.includes("event: dispatch"))continue;let a=o.split(`
|
|
228
|
+
`).find(s=>s.startsWith("data: "))?.slice(6);if(a)try{let s=JSON.parse(a);this.dispatch(s,t).catch(l=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${l?.message||l}`))}catch{}}return r}async dispatch(e,t){let r=new AbortController;if(t.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let i={ctrl:r,conn:t};this.inflight.set(e.id,i);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===i&&this.inflight.delete(e.id)}}async handle(e,t){let r=this.deps.getUnitWeb();if(!r.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,t.signal);return}let i={"x-unit-internal":r.internalSecret};e.ct&&(i["Content-Type"]=e.ct),e.accept&&(i.Accept=e.accept);let o;try{let u=new URL(`${r.url}${e.path}`);Object.assign(i,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:u,proxyCaller:e.proxyCaller,proxyOperator:e.proxyOperator})),o=await fetch(u,{method:e.method,headers:i,body:e.body??void 0,signal:t.signal})}catch(u){if(t.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${u?.message||u}`})),void 0,t.signal);return}let a=o.headers.get("content-type")||"",s={};for(let u of["content-security-policy","x-content-type-options"]){let d=o.headers.get(u);d&&(s[u]=d)}let l=a||"application/octet-stream";o.body&&Vw(a,o.headers.get("content-length"),{hasSecHeaders:Object.keys(s).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,o,t,l,s):await this.respond(e.id,o.status,l,Buffer.from(await o.arrayBuffer()),s,t.signal)}async respond(e,t,r,i,o,a){if(a?.aborted)return;let{cloudUrl:s,token:l}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let u=this.requestTimeoutMs*2,d=[...u?[AbortSignal.timeout(u)]:[],...a?[a]:[]],g=d.length>1?AbortSignal.any(d):d[0];await this.hubFetch(`${Fl(s)}/units/${c.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":c.secret,"Content-Type":"application/json"},body:JSON.stringify({status:t,headers:{"content-type":r,...o},bodyB64:i.toString("base64")}),...g?{signal:g}:{}}).then(f=>{f.body?.cancel().catch(()=>{})}).catch(f=>{a?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${f?.name==="TimeoutError"?`${Math.round(u/1e3)}s \u672A\u5B8C\u6210`:f?.message||f}`)})}async streamBack(e,t,r,i,o){let{cloudUrl:a,token:s}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let c=o?.["content-security-policy"],u=o?.["x-content-type-options"],d=`${Fl(a)}/units/${l.unitId}/stream/${e}?status=${t.status}&ct=${encodeURIComponent(i)}`+(c?`&csp=${encodeURIComponent(c)}`:"")+(u?`&xcto=${encodeURIComponent(u)}`:""),g=t.body;if(!g)return;let f=g.getReader(),p=0,m=this.requestTimeoutMs,y=m?setTimeout(()=>{p>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(m/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},m):null,b=new ReadableStream({async pull(h){++p===2&&y&&clearTimeout(y);let{done:E,value:v}=await f.read();E?h.close():h.enqueue(v)},cancel(h){return f.cancel(h)}},{highWaterMark:0});try{await this.hubFetch(d,{method:"POST",headers:{Authorization:`Bearer ${s}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:b,signal:r.signal,duplex:"half"})}catch(h){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${h?.message||h}`);try{await f.cancel()}catch{}}finally{y&&clearTimeout(y)}}};function cC(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(!(typeof t!="string"||t.length===0||t.length>64)&&!e.includes(t)&&(e.push(t),e.length>=16))break;return e}var gs=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}capsChanged(){this.engineChanged()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(c){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${c?.message||c}`);return}let t={engine:e,tools:[]};if(typeof this.d.features=="function"){let c=[];try{c=this.d.features()}catch(u){this.d.log(`[unit-caps] \u8BFB\u80FD\u529B\u58F0\u660E\u5931\u8D25:${u?.message||u}`)}t.features=cC(c)}let r=JSON.stringify(t);if(r===this.lastSent)return;let i=this.d.getPairing(),o;try{o=this.d.getCreds()}catch{return}if(!i||!o.token||!o.cloudUrl)return;let a=this.gen;this.inflight=!0;let s=new AbortController,l=setTimeout(()=>s.abort(),this.d.timeoutMs??1e4);try{let c=`${o.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(i.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(c,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"X-Unit-Secret":i.secret,"Content-Type":"application/json"},body:r,signal:s.signal});try{await u.text()}catch{}if(a!==this.gen)return;u.ok?(this.lastSent=r,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}${t.features?`(\u80FD\u529B\u58F0\u660E ${t.features.length} \u9879)`:""}`)):u.status===404||u.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${u.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):u.status===400||u.status===401||u.status===403?this.warned.has(u.status)||(this.warned.add(u.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${u.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${u.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(c){a===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${s.signal.aborted?"\u8D85\u65F6":c?.message||c}`)}finally{clearTimeout(l),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var zw=["setUnitHubFactory"],nf=n=>zw.every(e=>typeof n[e]=="function");function Hw(n){let e=new gs({getCreds:()=>n.getCreds(),getPairing:()=>n.getPairing(),current:()=>n.engineCaps(),...typeof n.capsFeatures=="function"?{features:()=>n.capsFeatures()}:{},log:r=>n.log(r)}),t=new fs({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>n.getCreds(),getUnitWeb:()=>n.getUnitWeb(),callerHeaders:r=>n.callerHeaders(r),getLanUrl:()=>n.getLanUrl(),getPairing:()=>n.getPairing(),savePairing:r=>n.savePairing(r),clearPairing:()=>n.clearPairing(),log:r=>n.log(r)});return{start:()=>t.start(),stop:()=>t.stop(),reconnect:r=>t.reconnect(r),status:()=>t.status(),engineChanged:()=>e.engineChanged(),capsChanged:()=>e.capsChanged()}}function rf(n){let e=async(t,r,i)=>{let{base:o,token:a}=await n.getCloud();if(!a)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let s=await fetch(`${o}/api${r}`,{method:t,headers:{Authorization:`Bearer ${a}`,...i!==void 0?{"Content-Type":"application/json"}:{}},body:i!==void 0?JSON.stringify(i):void 0});return{status:s.status,json:await s.json().catch(()=>null)}}catch(s){return{status:0,json:{detail:String(s?.message||s)}}}};n.handle("units:list",(t,r)=>e("GET",r!=null&&typeof r=="object"&&r.shared===!0?"/units?shared=1":"/units")),n.handle("units:update",(t,r,i)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:i?.name,icon:i?.icon})),n.handle("units:remove",(t,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),n.handle("units:openInBrowser",async(t,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:i,token:o}=await n.getCloud();await n.openExternal(`${i}/api/units/${r}/open${o?`#token=${encodeURIComponent(o)}`:""}`)}),n.setUnitHubFactory(Hw),n.log("[forsion-extend] unit hub registered")}import{createHash as _C}from"node:crypto";import{constants as Zw,mkdirSync as RC,readFileSync as AC,renameSync as CC,writeFileSync as IC}from"node:fs";import{lstat as ur,open as fb,readFile as xC,readdir as gb,statfs as TC}from"node:fs/promises";import{cpus as DC,freemem as PC,homedir as Qw,hostname as pb,release as OC,totalmem as MC}from"node:os";import{basename as hb,join as ve}from"node:path";var dC=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,ps=class n extends Date{#t=!1;#n=!1;#e=null;constructor(e){let t=!0,r=!0,i="Z";if(typeof e=="string"){let o=e.match(dC);o?(o[1]||(t=!1,e=`0000-01-01T${e}`),r=!!o[2],r&&e[10]===" "&&(e=e.replace(" ","T")),o[2]&&+o[2]>23?e="":(i=o[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=t,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,t="Z"){let r=new n(e);return r.#e=t,r}static wrapAsLocalDateTime(e){let t=new n(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new n(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new n(e);return t.#t=!1,t.#e=null,t}};function uC(n,e){let t=n.slice(0,e).split(/\r\n|\n|\r/g);return[t.length,t.pop().length+1]}function fC(n,e,t){let r=n.split(/\r\n|\n|\r/g),i="",o=(Math.log10(e+1)|0)+1;for(let a=e-1;a<=e+1;a++){let s=r[a-1];s&&(i+=a.toString().padEnd(o," "),i+=": ",i+=s,i+=`
|
|
229
|
+
`,a===e&&(i+=" ".repeat(o+t+2),i+=`^
|
|
230
|
+
`))}return i}var we=class extends Error{line;column;codeblock;constructor(e,t){let[r,i]=uC(t.toml,t.ptr),o=fC(t.toml,r,i);super(`Invalid TOML document: ${e}
|
|
225
231
|
|
|
226
|
-
${
|
|
227
|
-
`?e++:
|
|
228
|
-
`&&(e+=2));let a="",
|
|
229
|
-
`||
|
|
230
|
-
`))l=l&&3;else{if(
|
|
231
|
-
`;else if(
|
|
232
|
-
`,e);return
|
|
233
|
-
`)return
|
|
234
|
-
`)return
|
|
235
|
-
`||i==="\r"&&
|
|
236
|
-
`);)e++;if(r||i!=="#")break;e=
|
|
237
|
-
`||a==="\r"&&
|
|
238
|
-
`))return
|
|
239
|
-
`&&
|
|
240
|
-
`&&a!=="\r"){let
|
|
241
|
-
`&&
|
|
242
|
-
`&&t[o]!=="\r")throw new ce("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:o});o=At(t,o)}return r}var $i=14,Ig=1440*6e4,Rg=12e4,Dg=15e3,_o=1792*1024,Og=7,jt=t=>t.toISOString().slice(0,10),xt=t=>Date.parse(jt(t))-(Og-1)*Ig,ou=["sessions","activity"],Pi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Co(t,e,n){let r=t?.day===jt(n)?t:void 0;return Object.fromEntries(ou.map(i=>[i,Pi(r?.[i])??Math.min(Math.max(Pi(e[i])??0,xt(n)),n.getTime())]))}function Ao(t,e,n,r,i,s){let a=e?.day===jt(r)?e:void 0,o={sent:{...t},file:{day:jt(r)}};for(let l of ou){let c=l in i&&!s.includes(l)&&!(`${l}Error`in i),u=Pi(a?.[l]);c?(o.file[l]=n[l],o.sent[l]=r.getTime()):u!==void 0&&(o.sent[l]=Math.min(Pi(t[l])??u,u))}return o}function au(t,e=[]){let n={...t},r=nr(JSON.stringify(n));for(let i of["activity","sessions","memory","runs","engine"]){if(r.length<=_o)break;i in n&&(delete n[i],e.push(i),r=nr(JSON.stringify({...n,truncated:e})))}return r.length>_o?null:r}async function xo(t,e,n,r=new Date){let i=AbortSignal.timeout(Rg);await t.writeFile(`${e}/${jt(r)}.json`,n,r.getTime(),i);try{let s=jt(new Date(r.getTime()-$i*24*60*6e4));for(let a of await t.walk(i)){let o=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(a.key);o&&o[1]===e&&o[2]<s&&await t.rm(a.key,i)}}catch{}}var To={mode:"scheduled",intervalHours:24,requestedAt:0};function _r(t){let e=t&&typeof t=="object"?t:{},n=Number(e.intervalHours),r=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(n)&&n>=1&&n<=720?n:To.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Io(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Dg)});return e.status===404?{...To}:e.ok?_r(await e.json()):null}catch{return null}}var uu=["merge","cloud","local"],du={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Xt(t,e=!1){if(typeof t!="string"||!t&&!e||t.length>512||t.startsWith("/")||/[\\\u0000-\u001f\u007f]/.test(t)||t&&t.split("/").some(n=>!n||n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||n.startsWith(".forsion-sync")))throw Error("Invalid content path");return t}function Mg(t){if(t==="default"||t==="off"||typeof t=="string"&&/^device-[A-Za-z0-9_-]{1,64}$/.test(t))return t;throw Error("Invalid content target")}function Zt(t,e){let n=t;if(!n||n.version!==1||typeof n.enabled!="boolean"||!Array.isArray(n.rules)||n.rules.length>512)throw Error("Invalid content sync configuration");let r=new Set,i=new Set,s=n.rules.map(a=>{let o=Xt(a.source,!0),l=Mg(a.target);if(typeof a.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(a.id)||i.has(a.id)||r.has(o))throw Error("Duplicate or invalid sync rule");return i.add(a.id),r.add(o),{id:a.id,source:o,target:l,...a.sourceId&&/^[a-f0-9-]{36}$/i.test(a.sourceId)?{sourceId:a.sourceId}:{}}});return{version:1,revision:e,enabled:n.enabled,rules:s}}function Mn(t,e){let n=null;for(let r of e)(!r.source||t===r.source||t.startsWith(r.source+"/"))&&(!n||r.source.length>n.source.length)&&(n=r);return n}var gt={get:"penzor:sync:get",preview:"penzor:sync:preview",apply:"penzor:sync:apply",run:"penzor:sync:run",pause:"penzor:sync:pause",retry:"penzor:sync:retry",rename:"penzor:sync:rename",setup:"penzor:sync:setup",archiveSeen:"penzor:sync:archiveSeen",confirmDeletes:"penzor:sync:confirmDeletes",abandonDeletes:"penzor:sync:abandonDeletes"},lu=200,Ro=6e4,Ng=50;function Do(t,e,n,r){return t.deleted?"forget":t.busy||r?"skip":t.version?e&&e.version===t.version&&Li(e.file,t.file)?"delete":"download":n?"cancel":"skip"}var Li=(t,e)=>t===void 0||e===void 0||t===e,Pg=(t,e)=>{let n=e.indexOf("/");return t+":"+(n<0?"":e.slice(0,n))};function Oo(t,e,n){if(!t.length)return!1;if(n.latched||t.length>=lu||n.recent+t.length>Ng)return!0;let r=a=>{let o=new Map;for(let l of a){let c=Pg(l.ns,l.path);o.set(c,(o.get(c)??0)+1)}return o},i=r(t),s=r(e);for(let[a,o]of i)if(fr(o,s.get(a)??0,lu))return!0;return!1}var Fi=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,cu=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Mo=(t,e,n)=>{let r=cu(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(i=>i.id!==n&&cu(i.name)===r)?"taken":null:null},fu=["Amadeus","agents","human","Plugins"],fn=1024*1024,ji=50*fn,$g=[{prefix:"Amadeus/",ext:[".md",".db"],maxBytes:5*fn},{prefix:"Amadeus/",maxBytes:5*fn},{prefix:"agents/",maxBytes:5*fn},{prefix:"human/",maxBytes:5*fn},{prefix:"",maxBytes:50*fn}],jg=[{prefix:"",maxBytes:50*fn}];function Ui(t,e,n){let r=Array.isArray(n)&&n.length?n:e==="default"?$g:jg,i=t.toLowerCase();for(let s of r)if(!(!s||typeof s.prefix!="string"||!Number.isSafeInteger(s.maxBytes)||s.maxBytes<=0)&&t.startsWith(s.prefix)&&!(Array.isArray(s.ext)&&s.ext.length&&!s.ext.some(a=>typeof a=="string"&&i.endsWith(a.toLowerCase()))))return Math.min(s.maxBytes,ji);return ji}var Lg=6e4,Fg=10*6e4,pu=t=>t<=1?0:Math.min(Lg*2**(t-2),Fg),No="delete-guard";var Lt=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var Cr=/^[a-z0-9][a-z0-9-]{0,63}$/,Hi=new Set(["muse"]),Ar=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&Cr.test(e[1])?e[1]:null},Ug=t=>[...Hi].some(e=>Po(t,`agents/${e}`));function hu(t){let e=t.split(/^\s*\[/m)[0]??"",n=s=>{let a=new RegExp(`^[ \\t]*${s}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(a?.[1]!=null?a[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):a?.[2])?.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,80)||void 0},r=n("name"),i=n("name_en");return{...r?{name:r}:{},...i?{nameEn:i}:{}}}var Nn=(t,e)=>Mn(e,t)?.target??"off",Po=(t,e)=>t===e||t.startsWith(e+"/"),Hg=t=>Lt.some(e=>Po(t,e.path)),$o=t=>t.some(e=>e.id==="default")?zi():"default",gu=(t,e)=>t.enabled?Nn(t.rules,e):"off";function mu(t,e,n){n==="off"&&(t=t.filter(s=>e?!s.source.startsWith(e+"/"):!s.source||Hg(s.source)));let r=t.find(s=>s.source===e),i=t.filter(s=>s!==r);return e&&Nn(i,e)===n?i:r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:e?zi():$o(t),source:e,target:n}]}function Pn(t,e,n,r=!1){if(Ug(e))return t;let i=t.rules;if(!t.enabled){let s=i.find(o=>!o.source),a=e?i.filter(o=>o.source&&Po(o.source,e)):[];i=[{id:s?.id??$o(a),source:"",target:"off"},...a],e!=="agents"&&(i=jo(i,"agents","off"))}if(!e)for(let s of Lt)i.some(a=>a.source===s.path)||(i=[...i,{id:zi(),source:s.path,target:Nn(i,s.path)}]);return yu({...t,rules:mu(i,e,n)},r)}function yu(t,e=!1){let n=r=>Nn(t.rules,r)!=="off";return{...t,enabled:Lt.some(r=>n(r.path))||t.rules.some(r=>r.source&&r.target!=="off")||e&&n("")}}function wu(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:$o(t.rules),source:"",target:"default"},...t.rules];for(let n of Lt)n.id!=="agents"&&Nn(e,n.path)==="off"&&(e=mu(e,n.path,"default"));return e=jo(e,"agents","off"),{...t,enabled:!0,rules:e}}function jo(t,e,n){let r=t.find(i=>i.source===e);return r?t.map(i=>i===r?{...i,target:n}:i):[...t,{id:zi(),source:e,target:n}]}function bu(t,e){let n=t;for(let r of new Set(e))Cr.test(r)&&!Hi.has(r)&&(n=Pn(n,`agents/${r}`,"default"));return n}function Su(t){let e=Nn(t.rules,"agents")!=="off"||t.rules.some(i=>i.source.startsWith("agents/")&&i.target!=="off"),n=t.rules.some(i=>i.source.startsWith("agents/"));if(!e&&!n)return null;let r=jo(t.rules.filter(i=>!i.source.startsWith("agents/")),"agents","off");return t.enabled?yu({...t,rules:r},!0):{...t,rules:r}}var zg=0,zi=()=>`rule-${Date.now().toString(36)}-${(zg++).toString(36)}`;var vu=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var Bg=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function ku(t,e=[]){let n=t;for(let r of[...e].filter(i=>i&&i.length>=2).sort((i,s)=>s.length-i.length))n=n.split(r).join("[path]");return n.replace(/^(Duplicate folder sync identity|Concurrent (?:folder|file) rename): [\s\S]*$/,"$1: [path]")}var xr=class{since;cur=null;last=null;runs=[];totals={runs:0,completedRuns:0,idleRuns:0};errors=[];clock;constructor(e=Date.now){this.clock=e,this.since=e()}reset(){this.since=this.clock(),this.cur=null,this.last=null,this.runs=[],this.errors=[],this.totals={runs:0,completedRuns:0,idleRuns:0}}begin(e=this.clock()){this.cur={at:e,counts:{}}}count(e,n=1){n>0&&(this.cur&&(this.cur.counts[e]=(this.cur.counts[e]??0)+n),this.totals[e]=(this.totals[e]??0)+n)}fault(e,n=[],r=this.clock()){if(!e||Bg.test(e))return;this.count("errors"),/^File exceeds \d+ MB/.test(e)&&this.count("tooLarge");let i=this.errors[this.errors.length-1];if(i&&i.text===e){i.n++,i.at=r,this.addPaths(n);return}this.errors.push({first:r,at:r,n:1,text:e}),this.addPaths(n),this.errors.length>20&&this.errors.shift()}addPaths(e){let n=this.errors[this.errors.length-1],r=e.filter(i=>typeof i=="string"&&i);!n||!r.length||(n.paths=[...new Set([...n.paths??[],...r])].slice(0,8))}end(e,n=this.clock()){let r=this.cur;if(!r)return;this.cur=null;let i={at:r.at,ms:Math.max(0,n-r.at),completed:e,counts:r.counts};this.last=i,this.totals.runs++,e&&this.totals.completedRuns++,!e||Object.keys(r.counts).length?(this.runs.push(i),this.runs.length>20&&this.runs.shift()):this.totals.idleRuns++}snapshot(){let e=n=>({...n,counts:{...n.counts}});return{since:this.since,lastRun:this.last&&e(this.last),runs:this.runs.map(e),totals:{...this.totals},errors:this.errors.map(n=>({...n,...n.paths?{paths:[...n.paths]}:{}}))}}},Eu=null;function _u(t){Eu=t}function Cu(){try{return Eu?.()??null}catch{return null}}var rm=(t,e=[])=>{let n=au(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},qu=60*6e4,im=2*6e4,sm=10*6e4,Tu=qu,om=4*1024*1024,am=256*1024,Iu=["user","teamwork","discussion","delegate"],lm=/^(?:New remarks in the team chat:|You are activated now \()/,Wu={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Fo=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,Gu=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,i)=>Fo.test(i)||e&&!/\s/.test(i)?n:`${r}[path]${r}`),Vu=t=>Gu(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>Fo.test(e)?e:"[path]"),Rr=4e3,qi=(t,e)=>typeof t=="string"&&t?It(Vu(Rt(t.slice(0,Rr))),e):void 0,cm={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},um=64*1024,Lo=500,dm={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},fm=256*1024,Ru=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],pm=["description","developer_instructions"],hm=["memory","harness","project_memory","human","dream","log_appended"],gm=["homeDir","readCreds","accountId","appVersion"],Uo=t=>gm.every(e=>typeof t[e]=="function"),Du=xu().length>3?xu():null;function Rt(t){return typeof t=="string"?(Du?t.split(Du).join("~"):t).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,(e,n,r)=>/^[a-f0-9]{48}$/.test(e)&&/(?:^|[^\w-])pr-$/.test(r.slice(Math.max(0,n-4),n))?e:`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(t)?t.map(Rt):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":Rt(n)])):t}var mm=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ue=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,ym=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function $n(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[r,[i,s]]of Object.entries(t).slice(0,100).entries())n[ym(i,r)]=mm.test(i)&&ue(s,80)!==void 0?s:$n(s,e+1);return n}var wm={"":/^(?:name|version|description|model|model_reasoning_effort|approval_mode|max_iterations|tools|enabled_skill_ids|enabled_mcp_servers|library_order|apps|avatar|share_default_memory|cloud_sync|activity_access|tools_strict|tools_mode|tools_list|created_by|created_at|developer_instructions|compaction|lead|slug|members|mode|max_rounds)$/,compaction:/^(?:enabled|reserveTokens|thresholdPercent|keepRecentTokens|summaryMaxTokens|thinking|model|instructions|prompt)$/,members:/^(?:slug|role)$/},Ou={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},bm=/^(?:apps|enabled_skill_ids)$/,Mu=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Sm(t){try{let e=Ni(t),n=[],r=[],i=8192,s=(l,c)=>i<=0?!1:(i-=c.length+1,l.push(c),!0),a=(l,c,u)=>{let f=wm[l].test(c)?c:`[key:${c.length}]`,g=Ou[l].test(c),p;return typeof u=="boolean"||typeof u=="number"?p=String(u):g&&typeof u=="string"&&!/[\r\n]/.test(u)&&JSON.stringify(u).length<=120?p=JSON.stringify(u):g&&u instanceof Date?p=u.toISOString():l===""&&bm.test(c)&&Array.isArray(u)&&u.every(m=>typeof m=="string"&&!/[\r\n]/.test(m))&&JSON.stringify(u).length<=2e3&&(p=`[${u.map(m=>JSON.stringify(m)).join(", ")}]`),`${f} = ${p??`"[text:${typeof u=="string"?u.length:JSON.stringify(u).length}]"`}`},o=(l,c,u)=>{if(s(r,c)){for(let[f,g]of Object.entries(u))if(!s(r,a(l,f,g)))return}};for(let[l,c]of Object.entries(e)){let u=l!==""&&Object.hasOwn(Ou,l);if(u&&Mu(c))o(l,`[${l}]`,c);else if(u&&Array.isArray(c)&&c.length>0&&c.every(Mu))for(let f of c)o(l,`[[${l}]]`,f);else s(n,a("",l,c));if(i<=0)break}return[...n,...r].join(`
|
|
243
|
-
`)}catch{return`[unparsed:${
|
|
244
|
-
`)+1):a}finally{await
|
|
245
|
-
`).filter(
|
|
246
|
-
`)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:
|
|
232
|
+
${o}`,t),this.line=r,this.column=i,this.codeblock=o}};var gC=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,pC=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,hC=/^[+-]?0[0-9_]/;function Bl(n,e){let t=n[e++],r=t,i=t==="'",o=t===n[e]&&t===n[e+1];o&&(n[e+=2]===`
|
|
233
|
+
`?e++:n[e]==="\r"&&n[e+1]===`
|
|
234
|
+
`&&(e+=2));let a="",s=e,l=0;for(let c=e;c<n.length;c++)if(t=n[c],o&&(t===`
|
|
235
|
+
`||t==="\r"&&n[c+1]===`
|
|
236
|
+
`))l=l&&3;else{if(t<" "&&t!==" "||t==="\x7F")throw new we("control characters are not allowed in strings",{toml:n,ptr:c});if((!l||l===3)&&t===r&&(!o||n[c+1]===r&&n[c+2]===r))return o&&(n[c+3]===r&&c++,n[c+3]===r&&c++),[l?a:a+n.slice(s,c),c+(o?3:1)];if(!l)!i&&t==="\\"&&(a+=n.slice(s,s=c),l=1);else if(l===1)if(t==="x"||t==="u"||t==="U"){let u=0,d=t==="x"?2:t==="u"?4:8;for(let g=0;g<d;g++,c++){let f=n.charCodeAt(c+1),p=f>=48&&f<=57?f-48:f>=65&&f<=70?f-65+10:f>=97&&f<=102?f-97+10:-1;if(p<0)throw new we("invalid non-hex character in unicode escape",{toml:n,ptr:c+1});u=u<<4|p}if(u<0||u>1114111||u>=55296&&u<=57343)throw new we("invalid unicode escape",{toml:n,ptr:c});a+=String.fromCodePoint(u),s=c+1,l=0}else if(t===" "||t===" ")l=2;else{if(t==="b")a+="\b";else if(t==="t")a+=" ";else if(t==="n")a+=`
|
|
237
|
+
`;else if(t==="f")a+="\f";else if(t==="r")a+="\r";else if(t==="e")a+="\x1B";else if(t==='"')a+='"';else if(t==="\\")a+="\\";else throw new we("unrecognized escape sequence",{toml:n,ptr:c});s=c+1,l=0}else if(t!==" "&&t!==" "){if(l===2)throw new we("invalid escape: only line-ending whitespace may be escaped",{toml:n,ptr:s});l=!i&&t==="\\"?1:0,s=c}}throw new we("unfinished string",{toml:n,ptr:e})}function qw(n,e,t,r){if(n==="true")return!0;if(n==="false")return!1;if(n==="-inf")return-1/0;if(n==="inf"||n==="+inf")return 1/0;if(n==="nan"||n==="+nan"||n==="-nan")return NaN;if(n==="-0")return r?0n:0;let i=gC.test(n);if(i||pC.test(n)){if(hC.test(n))throw new we("leading zeroes are not allowed",{toml:e,ptr:t});n=n.replace(/_/g,"");let a=+n;if(isNaN(a))throw new we("invalid number",{toml:e,ptr:t});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new we("integer value cannot be represented losslessly",{toml:e,ptr:t});(i||r===!0)&&(a=BigInt(n))}return a}let o=new ps(n);if(!o.isValid())throw new we("invalid value",{toml:e,ptr:t});return o}function jl(n,e=0,t=n.length){let r=n.indexOf(`
|
|
238
|
+
`,e);return n[r-1]==="\r"&&r--,r<=t?r:-1}function Hi(n,e){for(let t=e;t<n.length;t++){let r=n[t];if(r===`
|
|
239
|
+
`)return t;if(r==="\r"&&n[t+1]===`
|
|
240
|
+
`)return t+1;if(r<" "&&r!==" "||r==="\x7F")throw new we("control characters are not allowed in comments",{toml:n,ptr:e})}return n.length}function Bn(n,e,t,r){let i;for(;;){for(;(i=n[e])===" "||i===" "||!t&&(i===`
|
|
241
|
+
`||i==="\r"&&n[e+1]===`
|
|
242
|
+
`);)e++;if(r||i!=="#")break;e=Hi(n,e)}return e}function Ww(n,e,t,r,i=!1){if(!r)return e=jl(n,e),e<0?n.length:e;for(let o=e;o<n.length;o++){let a=n[o];if(a==="#")o=jl(n,o);else{if(a===t)return o+1;if(a===r||i&&(a===`
|
|
243
|
+
`||a==="\r"&&n[o+1]===`
|
|
244
|
+
`))return o}}throw new we("cannot find end of structure",{toml:n,ptr:e})}function mC(n,e,t){let r=n.slice(e,t),i=r.indexOf("#");return i>-1&&(Hi(n,i),r=r.slice(0,i)),[r.trimEnd(),i]}function hs(n,e,t,r,i){if(r===0)throw new we("document contains excessively nested structures. aborting.",{toml:n,ptr:e});let o=n[e];if(o==="["||o==="{"){let[l,c]=o==="["?Jw(n,e,r,i):Gw(n,e,r,i);if(t){if(c=Bn(n,c),n[c]===",")c++;else if(n[c]!==t)throw new we("expected comma or end of structure",{toml:n,ptr:c})}return[l,c]}if(o==='"'||o==="'"){let[l,c]=Bl(n,e);if(t){if(c=Bn(n,c),n[c]&&n[c]!==","&&n[c]!==t&&n[c]!==`
|
|
245
|
+
`&&n[c]!=="\r")throw new we("unexpected character encountered",{toml:n,ptr:c});n[c]===","&&c++}return[l,c]}let a=Ww(n,e,",",t),s=mC(n,e,a-(n[a-1]===","?1:0));if(!s[0])throw new we("incomplete key-value declaration: no value specified",{toml:n,ptr:e});return t&&s[1]>-1&&(a=Bn(n,e+s[1]),n[a]===","&&a++),[qw(s[0],n,e,i),a]}var yC=/^[a-zA-Z0-9-_]+[ \t]*$/;function Ul(n,e,t="="){let r=e-1,i=[],o=n.indexOf(t,e);if(o<0)throw new we("incomplete key-value: cannot find end of key",{toml:n,ptr:e});do{let a=n[e=++r];if(a!==" "&&a!==" ")if(a==='"'||a==="'"){if(a===n[e+1]&&a===n[e+2])throw new we("multiline strings are not allowed in keys",{toml:n,ptr:e});let[s,l]=Bl(n,e);r=n.indexOf(".",l);let c=n.slice(l,r<0||r>o?o:r),u=jl(c);if(u>-1)throw new we("newlines are not allowed in keys",{toml:n,ptr:e+r+u});if(c.trimStart())throw new we("found extra tokens after the string part",{toml:n,ptr:l});if(o<l&&(o=n.indexOf(t,l),o<0))throw new we("incomplete key-value: cannot find end of key",{toml:n,ptr:e});i.push(s)}else{r=n.indexOf(".",e);let s=n.slice(e,r<0||r>o?o:r);if(!yC.test(s))throw new we("only letter, numbers, dashes and underscores are allowed in keys",{toml:n,ptr:e});i.push(s.trimEnd())}}while(r+1&&r<o);return[i,Bn(n,o+1,!0,!0)]}function Gw(n,e,t,r){let i={},o=new Set,a;for(e++;(a=n[e++])!=="}"&&a;){if(a===",")throw new we("expected value, found comma",{toml:n,ptr:e-1});if(a==="#")e=Hi(n,e);else if(a!==" "&&a!==" "&&a!==`
|
|
246
|
+
`&&a!=="\r"){let s,l=i,c=!1,[u,d]=Ul(n,e-1);for(let p=0;p<u.length;p++){if(p&&(l=c?l[s]:l[s]={}),s=u[p],(c=Object.hasOwn(l,s))&&(typeof l[s]!="object"||o.has(l[s])))throw new we("trying to redefine an already defined value",{toml:n,ptr:e});!c&&s==="__proto__"&&Object.defineProperty(l,s,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new we("trying to redefine an already defined value",{toml:n,ptr:e});let[g,f]=hs(n,d,"}",t-1,r);o.add(g),l[s]=g,e=f}}if(!a)throw new we("unfinished table encountered",{toml:n,ptr:e});return[i,e]}function Jw(n,e,t,r){let i=[],o;for(e++;(o=n[e++])!=="]"&&o;){if(o===",")throw new we("expected value, found comma",{toml:n,ptr:e-1});if(o==="#")e=Hi(n,e);else if(o!==" "&&o!==" "&&o!==`
|
|
247
|
+
`&&o!=="\r"){let a=hs(n,e-1,"]",t-1,r);i.push(a[0]),e=a[1]}}if(!o)throw new we("unfinished array encountered",{toml:n,ptr:e});return[i,e]}function Kw(n,e,t,r){let i=e,o=t,a,s=!1,l;for(let c=0;c<n.length;c++){if(c){if(i=s?i[a]:i[a]={},o=(l=o[a]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=i.length-1;i=i[u],o=o[u].c}}if(a=n[c],(s=Object.hasOwn(i,a))&&o[a]?.t===0&&o[a]?.d)return null;s||(a==="__proto__"&&(Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})),o[a]={t:c<n.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(l=o[a],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,i[a]=[]),i[a].push(i={}),l.c[l.i++]=l={t:1,d:!1,i:0,c:{}}),l.d))return null;if(l.d=!0,r===1)i=s?i[a]:i[a]={};else if(r===0&&s)return null;return[a,i,l.c]}function Vl(n,{maxDepth:e=1e3,integersAsBigInt:t}={}){let r={},i={},o=r,a=i;for(let s=Bn(n,0);s<n.length;){if(n[s]==="["){let l=n[++s]==="[",c=Ul(n,s+=+l,"]");if(l){if(n[c[1]-1]!=="]")throw new we("expected end of table declaration",{toml:n,ptr:c[1]-1});c[1]++}let u=Kw(c[0],r,i,l?2:1);if(!u)throw new we("trying to redefine an already defined table or value",{toml:n,ptr:s});a=u[2],o=u[1],s=c[1]}else{let l=Ul(n,s),c=Kw(l[0],o,a,0);if(!c)throw new we("trying to redefine an already defined table or value",{toml:n,ptr:s});let u=hs(n,l[1],void 0,e,t);c[1][c[0]]=u[0],s=u[1]}if(s=Bn(n,s,!0),n[s]&&n[s]!==`
|
|
248
|
+
`&&n[s]!=="\r")throw new we("each key-value declaration must be followed by an end-of-line",{toml:n,ptr:s});s=Bn(n,s)}return r}var Hl=14,wC=1440*6e4,bC=12e4,vC=15e3,of=1792*1024,SC=7,dr=n=>n.toISOString().slice(0,10),jn=n=>Date.parse(dr(n))-(SC-1)*wC,Yw=["sessions","activity"],zl=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function sf(n,e,t){let r=n?.day===dr(t)?n:void 0;return Object.fromEntries(Yw.map(i=>[i,zl(r?.[i])??Math.min(Math.max(zl(e[i])??0,jn(t)),t.getTime())]))}function af(n,e,t,r,i,o){let a=e?.day===dr(r)?e:void 0,s={sent:{...n},file:{day:dr(r)}};for(let l of Yw){let c=l in i&&!o.includes(l)&&!(`${l}Error`in i),u=zl(a?.[l]);c?(s.file[l]=t[l],s.sent[l]=r.getTime()):u!==void 0&&(s.sent[l]=Math.min(zl(n[l])??u,u))}return s}function Xw(n,e=[]){let t={...n},r=no(JSON.stringify(t));for(let i of["activity","sessions","memory","runs","engine"]){if(r.length<=of)break;i in t&&(delete t[i],e.push(i),r=no(JSON.stringify({...t,truncated:e})))}return r.length>of?null:r}async function lf(n,e,t,r=new Date){let i=AbortSignal.timeout(bC);await n.writeFile(`${e}/${dr(r)}.json`,t,r.getTime(),i);try{let o=dr(new Date(r.getTime()-Hl*24*60*6e4));for(let a of await n.walk(i)){let s=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(a.key);s&&s[1]===e&&s[2]<o&&await n.rm(a.key,i)}}catch{}}var cf={mode:"scheduled",intervalHours:24,requestedAt:0};function ms(n){let e=n&&typeof n=="object"?n:{},t=Number(e.intervalHours),r=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(t)&&t>=1&&t<=720?t:cf.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function df(n){try{let e=await fetch(`${n.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${n.token}`},signal:AbortSignal.timeout(vC)});return e.status===404?{...cf}:e.ok?ms(await e.json()):null}catch{return null}}var NC=(n,e=[])=>{let t=Xw(n,e);return t&&Buffer.from(t.buffer,t.byteOffset,t.byteLength)},mb=60*6e4,$C=2*6e4,LC=10*6e4,eb=mb,FC=4*1024*1024,BC=256*1024,tb=["user","teamwork","discussion","delegate"],jC=/^(?:New remarks in the team chat:|You are activated now \()/,yb={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},ff=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,wb=(n,e)=>n.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(t,r,i)=>ff.test(i)||e&&!/\s/.test(i)?t:`${r}[path]${r}`),bb=n=>wb(n,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>ff.test(e)?e:"[path]"),bs=4e3,Wl=(n,e)=>typeof n=="string"&&n?Vn(bb(zn(n.slice(0,bs))),e):void 0,UC={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},VC=64*1024,uf=500,zC={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},HC=256*1024,nb=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],qC=["description","developer_instructions"],WC=["memory","harness","project_memory","human","dream","log_appended"],GC=["homeDir","readCreds","accountId","appVersion"],gf=n=>GC.every(e=>typeof n[e]=="function"),rb=Qw().length>3?Qw():null;function zn(n){return typeof n=="string"?(rb?n.split(rb).join("~"):n).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,(e,t,r)=>/^[a-f0-9]{48}$/.test(e)&&/(?:^|[^\w-])pr-$/.test(r.slice(Math.max(0,t-4),t))?e:`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(n)?n.map(zn):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":zn(t)])):n}var JC=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,be=(n,e=120)=>typeof n=="string"&&n.length<=e?n:void 0,KC=(n,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(n)?n:`[key:${e}]`;function qi(n,e=0){if(typeof n=="boolean"||typeof n=="number"||n===null||n===void 0)return n??null;if(typeof n=="string")return`[string:${n.length}]`;if(Array.isArray(n))return`[array:${n.length}]`;if(typeof n!="object"||e>=4)return"[object]";let t={};for(let[r,[i,o]]of Object.entries(n).slice(0,100).entries())t[KC(i,r)]=JC.test(i)&&be(o,80)!==void 0?o:qi(o,e+1);return t}var YC={"":/^(?:name|version|description|model|model_reasoning_effort|approval_mode|max_iterations|tools|enabled_skill_ids|enabled_mcp_servers|library_order|apps|avatar|share_default_memory|cloud_sync|activity_access|tools_strict|tools_mode|tools_list|created_by|created_at|developer_instructions|compaction|lead|slug|members|mode|max_rounds)$/,compaction:/^(?:enabled|reserveTokens|thresholdPercent|keepRecentTokens|summaryMaxTokens|thinking|model|instructions|prompt)$/,members:/^(?:slug|role)$/},ib={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},XC=/^(?:apps|enabled_skill_ids)$/,ob=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date);function ZC(n){try{let e=Vl(n),t=[],r=[],i=8192,o=(l,c)=>i<=0?!1:(i-=c.length+1,l.push(c),!0),a=(l,c,u)=>{let d=YC[l].test(c)?c:`[key:${c.length}]`,g=ib[l].test(c),f;return typeof u=="boolean"||typeof u=="number"?f=String(u):g&&typeof u=="string"&&!/[\r\n]/.test(u)&&JSON.stringify(u).length<=120?f=JSON.stringify(u):g&&u instanceof Date?f=u.toISOString():l===""&&XC.test(c)&&Array.isArray(u)&&u.every(p=>typeof p=="string"&&!/[\r\n]/.test(p))&&JSON.stringify(u).length<=2e3&&(f=`[${u.map(p=>JSON.stringify(p)).join(", ")}]`),`${d} = ${f??`"[text:${typeof u=="string"?u.length:JSON.stringify(u).length}]"`}`},s=(l,c,u)=>{if(o(r,c)){for(let[d,g]of Object.entries(u))if(!o(r,a(l,d,g)))return}};for(let[l,c]of Object.entries(e)){let u=l!==""&&Object.hasOwn(ib,l);if(u&&ob(c))s(l,`[${l}]`,c);else if(u&&Array.isArray(c)&&c.length>0&&c.every(ob))for(let d of c)s(l,`[[${l}]]`,d);else o(t,a("",l,c));if(i<=0)break}return[...t,...r].join(`
|
|
249
|
+
`)}catch{return`[unparsed:${n.length}]`}}var vb=async n=>{try{return(await ur(n)).isFile()?await xC(n,"utf8"):null}catch{return null}},ws=n=>ur(n).then(e=>e.isDirectory(),()=>!1),Wi=async n=>{try{return JSON.parse(await vb(n)??"null")}catch{return null}},Un=async(n,e=200)=>{try{return(await gb(n)).filter(t=>!t.startsWith(".")&&t.length<=120).sort().slice(0,e)}catch{return[]}};async function QC(n,e){if(!(await ur(n)).isFile())return"";let t=await fb(n,"r");try{let{size:r}=await t.stat(),i=Math.max(0,r-e),o=Buffer.alloc(r-i);await t.read(o,0,o.length,i);let a=o.toString("utf8");return i>0?a.slice(a.indexOf(`
|
|
250
|
+
`)+1):a}finally{await t.close()}}function eI(n){if(!n||typeof n!="object")return{};let e=t=>t&&typeof t=="object"?Object.entries(t).slice(0,100):[];return{defaultModel:be(n.cloud?.defaultModel)??null,models:qi(n.models),tts:qi(n.tts),asr:qi(n.asr),specialAgents:qi(n.specialAgents),pluginSettings:qi(n.plugins?.global),providers:(Array.isArray(n.providers)?n.providers:[]).slice(0,50).map(t=>({providerId:be(t?.providerId)??null,models:(Array.isArray(t?.modelIds)?t.modelIds:[]).filter(r=>be(r)!==void 0).slice(0,100)})),mcpServers:e(n.mcp?.mcpServers).map(([t,r])=>({name:be(t,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(n.channels).map(([t,r])=>({name:be(t,64)??"[name]",enabled:r?.enabled===!0}))}}var tI=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function sb(n){let e=[];for(let t of await Un(n,100)){let r=ve(n,t);if(!await ws(r))continue;let i=await vb(ve(r,"config.toml"));e.push({id:t,config:i===null?null:ZC(i).slice(0,4096),files:(await Un(r,400)).filter(o=>tI.has(o))})}return e}async function ab(n){let e=[];for(let t of await Un(n,300)){let r=await Wi(ve(n,t,"manifest.json"));r&&e.push({id:be(r.id)??t,version:be(r.version,40)??null,name:be(r.nameEn)??be(r.name)??null})}return e}var Qr=n=>String(n?.code||n?.message||n).slice(0,120);async function nI(n,e,t,r=BC){let i=g=>String(g).padStart(2,"0"),o=g=>{let f=new Date(g);return`${f.getFullYear()}${i(f.getMonth()+1)}${i(f.getDate())}${i(f.getHours())}${i(f.getMinutes())}`},a=g=>`${g.slice(0,4)}-${g.slice(4,6)}-${g.slice(6,8)}.log`,s=o(t),l=o(e.getTime()),c=[],u=r,d=!1;try{let g=(await gb(n)).filter(f=>/^\d{4}-\d{2}-\d{2}\.log$/.test(f)&&f>=a(s)&&f<=a(l)).sort().reverse();for(let f of g){if(d)break;let m=(await QC(ve(n,f),FC).catch(b=>{if(b?.code==="ENOENT")return"";throw b})).split(`
|
|
251
|
+
`).filter(b=>/^\d{12} /.test(b)&&b.slice(0,12)>=s&&b.slice(0,12)<l),y=m.length;for(;y>0&&Buffer.byteLength(m[y-1])+1<=u;)u-=Buffer.byteLength(m[--y])+1;y>0&&(d=!0),y<m.length&&c.push({date:f.slice(0,10),log:m.slice(y).join(`
|
|
252
|
+
`)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:Qr(g)}}return{activity:c.reverse(),...d?{activityTruncated:!0}:{}}}var Vn=(n,e)=>{if(!(typeof n!="string"||!n))return n.length>e?`${n.slice(0,e)}\u2026[+${n.length-e}]`:n},lb=n=>{try{let e=typeof n=="string"?JSON.parse(n):n;return Array.isArray(e)?e:[]}catch{return[]}},Gi=n=>new Date(n).toISOString().slice(0,19).replace("T"," ");async function rI(n,e,t=yb,r=jn(e)){let i=ve(n,"tangu","state.db"),o=await ur(i).then(s=>s.isFile(),s=>s?.code==="ENOENT"?!1:Qr(s));if(o!==!0)return o===!1?{sessions:[]}:{sessions:[],sessionsError:o};let a;try{let{DatabaseSync:s}=await import("node:sqlite");a=new s(i,{readOnly:!0}),a.exec("PRAGMA busy_timeout = 1500");let c="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",u=[Gi(r),Gi(e.getTime()),jn(e)],d=a.prepare(`SELECT s.id, s.kind, s.parent_session_id, s.app_id, s.title, s.model_id, s.project_name, s.archived, s.created_at, s.updated_at, MAX(m.updated_at) AS changed_at
|
|
247
253
|
FROM chat_messages m JOIN chat_sessions s ON s.id = m.session_id
|
|
248
|
-
WHERE s.kind IN (${
|
|
249
|
-
FROM chat_messages m WHERE m.session_id = ? AND ${c} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),
|
|
254
|
+
WHERE s.kind IN (${tb.map(()=>"?").join(", ")}) AND ${c} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...tb,...u,t.sessions+1),g=a.prepare(`SELECT m.role, m.content, m.reasoning, m.timestamp, m.model_id, m.is_error, m.tool_calls, length(m.tool_results) AS tool_result_chars, m.attachments, m.agent_slug
|
|
255
|
+
FROM chat_messages m WHERE m.session_id = ? AND ${c} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),f=[],p=0,m=d.length>t.sessions;for(let y of d.slice(0,t.sessions)){let b=g.all(y.id,...u,t.messages+1),h=b.length>t.messages,E=[],v=0;for(let S of b.slice(0,t.messages)){let _=lb(S.tool_calls),R=y.kind==="teamwork"&&S.role==="user"&&jC.test(String(S.content??"")),N={role:be(S.role,16)??null,at:Number(S.timestamp)||null,agent:be(S.agent_slug,64),model:be(S.model_id,128),error:S.is_error?!0:void 0,text:R?void 0:Vn(S.content,t.textChars),relayChars:R?String(S.content??"").length:void 0,reasoning:Vn(S.reasoning,t.textChars),tools:_.length?_.map(M=>be(M?.function?.name??M?.name,80)??"?"):void 0,toolArgChars:_.length?_.reduce((M,x)=>M+String(x?.function?.arguments??"").length,0):void 0,toolResultChars:Number(S.tool_result_chars)||void 0,attachments:lb(S.attachments).length||void 0},D=Buffer.byteLength(JSON.stringify(N));if(v+D>t.sessionBytes){h=!0;break}v+=D,E.push(N)}let k={id:be(y.id,64)??null,kind:be(y.kind,16)??null,parent:be(y.parent_session_id,64),app:be(y.app_id,50)??null,title:Vn(y.title,200)??null,model:be(y.model_id,128)??null,project:Vn(y.project_name,120),archived:y.archived?!0:void 0,createdAt:be(y.created_at,40)??null,updatedAt:be(y.updated_at,40)??null,messages:E.reverse(),...h?{olderMessagesDropped:!0}:{}},C=Buffer.byteLength(JSON.stringify(k));if(p+C>t.totalBytes){m=!0;break}p+=C,f.push(k)}return{sessions:f,...m?{sessionsTruncated:!0}:{}}}catch(s){return{sessions:[],sessionsError:Qr(s)}}finally{try{a?.close()}catch{}}}async function iI(n,e,t=UC){let r=ve(n,"tangu","state.db"),i=await ur(r).then(a=>a.isFile(),a=>a?.code==="ENOENT"?!1:Qr(a));if(i!==!0)return i===!1?{runs:[]}:{runs:[],runsError:i};let o;try{let{DatabaseSync:a}=await import("node:sqlite");o=new a(r,{readOnly:!0}),o.exec("PRAGMA busy_timeout = 1500");let l=o.prepare(`SELECT r.id, r.session_id, r.app_id, r.status, r.current_step, r.model_id, substr(r.error, 1, ${bs}) AS error, r.tokens_total, r.created_at, r.updated_at, s.kind
|
|
250
256
|
FROM agent_runs r LEFT JOIN chat_sessions s ON s.id = r.session_id
|
|
251
|
-
WHERE r.updated_at >= ? AND r.updated_at < ? ORDER BY r.updated_at DESC, r.id LIMIT ?`).all(
|
|
257
|
+
WHERE r.updated_at >= ? AND r.updated_at < ? ORDER BY r.updated_at DESC, r.id LIMIT ?`).all(Gi(jn(e)),Gi(e.getTime()),t.runs+1),c=o.prepare(`SELECT e.type, json_extract(e.payload, '$.name') AS name, json_extract(e.payload, '$.isError') AS failed, json_extract(e.payload, '$.elapsedMs') AS ms,
|
|
252
258
|
json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
|
|
253
259
|
json_extract(e.payload, '$.reasoningTokens') AS reasoning, json_extract(e.payload, '$.llmMs') AS llm_ms, json_extract(e.payload, '$.ttftMs') AS ttft_ms,
|
|
254
|
-
json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${
|
|
255
|
-
FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),u=
|
|
256
|
-
`),...
|
|
257
|
-
WHERE created_at >= ? AND created_at < ? AND (${
|
|
258
|
-
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(Ln(xt(e)),Ln(e.getTime()),n.activity+1);b.length>n.activity&&(a.truncated=!0);for(let _ of b.slice(0,n.activity))if(!l(a.activity,{at:ue(_.created_at,40)??null,agent:ue(_.agent,64)??null,action:ue(_.action,64)??null,detail:typeof _.detail=="string"&&_.detail?It(Rt(_.detail),n.detailChars):void 0,session:ue(_.session_ref,64)}))break}catch(m){a.activityError=pn(m)}finally{try{p?.close()}catch{}}}for(let p of await Tt(de(r,"project-memory"),100)){let m=de(r,"project-memory",p);if(!await Ir(m))continue;let y=await Tr(de(m,"MEMORY.md"),n.fileChars),b=await Fu(m);if(!y&&!b)continue;let _=(await jn(de(m,"PROJECT.json")))?.project;if(!l(a.projects,{id:ue(p,64)??null,name:typeof _=="string"?ue(Bu(_.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:b,memory:y}))break}for(let p of await Tt(de(r,"teams"),100)){if(!await Ir(de(r,"teams",p)))continue;let m=await Tr(de(r,"teams",p,"TEAM.md"),n.fileChars);if(m&&!l(a.teams,{id:p,files:{"TEAM.md":m}}))break}let g=[];for(let p of await Tt(de(r,"agents"),100)){let m=de(r,"agents",p);await Ir(m)&&g.push({id:p,dir:m,at:Math.max(0,...await Promise.all([...Ru,".memory-state.json"].map(y=>i(de(m,y)))))})}for(let{id:p,dir:m,at:y}of g.sort((b,_)=>_.at-b.at||b.id.localeCompare(_.id))){let b={};for(let I of Ru){let E=await Tr(de(m,I),n.fileChars);E&&(b[I]=E)}let _=[];if(await Ir(de(m,"LOG")))for(let I of(await Tt(de(m,"LOG"),400)).filter(E=>/^\d{4}-\d{2}-\d{2}\.md$/.test(E)&&E.slice(0,10)>=s&&E.slice(0,10)<=jt(e))){let E=await Tr(de(m,"LOG",I),n.logChars);E&&_.push({date:I.slice(0,10),text:E})}let h=(await jn(de(m,".memory-dream.json")))?.last,T=await Fu(m),v=await Lm(m,n.fileChars);!Object.keys(b).length&&!_.length&&!T&&!v||l(a.agents,{id:p,updatedAt:y?new Date(y).toISOString():null,config:v,state:T,dream:h&&typeof h=="object"?{state:ue(h.state,32),startedAt:ue(h.startedAt,40),finishedAt:ue(h.finishedAt,40),calls:typeof h.calls=="number"?h.calls:void 0,detail:typeof h.detail=="string"?It(Rt(h.detail),n.detailChars):void 0}:void 0,files:Object.keys(b).length?b:void 0,log:_.length?_:void 0})}return a}async function Xu(t){let e=(await jn(de(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Gg("sha256").update(zu()).digest("hex").slice(0,8)}`}async function Um(t){let{home:e}=t,n=de(e,"tangu"),r=t.now??new Date,i=a=>t.since?.[a]??xt(r),s=Tm(t.engineLogs);return Rt({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:tm(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:Bu(e),cloudUrl:t.cloudUrl},device:{id:await Xu(e),name:zu()},system:await xm(e),config:km(await jn(de(e,"config.json"))),agents:await Nu(de(n,"agents")),teams:await Nu(de(n,"teams")),plugins:{desktop:await Pu(de(e,"plugins")),engine:await Pu(de(n,"plugins"))},inventory:{skills:await Tt(de(n,"skills")),spaces:await Tt(de(e,"spaces")),themes:await Tt(de(e,"themes"))},...t.activity?{...await _m(de(e,"activity"),r,i("activity")),activitySince:new Date(i("activity")).toISOString()}:{},...t.sessions?{...await Cm(e,r,Wu,i("sessions")),sessionsSince:new Date(i("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await Fm(e,r)}:{},...await Am(e,r),runsSince:new Date(xt(r)).toISOString(),...s?{engine:s}:{},sync:{content:Pm(t.contentSync),legacy:$m(t.engineLogs)}})}function Zu(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(v=>gi({baseUrl:v.cloudUrl,vault:mi,getToken:()=>v.token})),i=e.policyFor??Io,s=()=>de(t.homeDir(),"extend-diagnostics.json"),a=()=>{let v=I=>I&&typeof I=="object"?I:{};try{let I=JSON.parse(Yg(s(),"utf8"));return{accounts:v(I?.accounts),sent:v(I?.sent)}}catch{return{accounts:{},sent:{}}}},o=()=>a().accounts,l=(v,I,E)=>{let D=a();D.accounts[v]={...D.accounts[v],...I},Object.assign(D.sent,E),Vg(t.homeDir(),{recursive:!0});let x=`${s()}.${process.pid}.tmp`;Kg(x,JSON.stringify(D,null,2),{encoding:"utf8",mode:384}),Jg(x,s())},c=()=>{let v=t.readCreds();return v.token&&v.cloudUrl?t.accountId():null},u=()=>{let v=c(),I=v?o()[v]??{}:{},E=_r(I.policy);return{signedIn:!!v,enabled:I.enabled===!0,activity:I.activity!==!1,sessions:I.sessions??I.enabled!==!0,memory:I.memory??I.enabled!==!0,lastUploadAt:I.lastUploadAt??null,lastError:I.lastError??null,retainDays:$i,mode:E.mode,intervalHours:E.intervalHours}},f=()=>{try{return ju(t)?t.diagnosticLogs():null}catch{return null}},g=null,p=new Map,m=async()=>{let v=c();if(!v)return!1;if(g)return g.id===v?g.done:(await g.done,m());let I={...t.readCreds()},E=n(),D=a(),x=D.accounts[v],L=I.cloudUrl.replace(/\/+$/,""),V=Co(x?.file,D.sent[L]??{},E),H=(async()=>{try{let N=await Um({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:I.cloudUrl,activity:x?.activity!==!1,sessions:x?.sessions===!0,now:E,since:V,engineLogs:f(),contentSync:Cu(),memory:()=>{let ae=c()===v?o()[v]:void 0;return ae?.enabled===!0&&ae.memory===!0}}),Y=await Xu(t.homeDir()),ee=o()[v];if(c()!==v||ee?.enabled!==!0)return!1;if(ee.activity===!1)for(let ae of["activity","activityTruncated","activityError","activitySince"])delete N[ae];if(ee.sessions!==!0)for(let ae of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete N[ae];ee.memory!==!0&&delete N.memory;let J=[],se=rm(N,J);if(!se)throw new Error("snapshot too large");await xo(r(I),Y,se,E),p.delete(v);let te=Ao(a().sent[L]??{},x?.file,V,E,N,J);return l(v,{lastUploadAt:n().getTime(),lastError:void 0,file:te.file},{[L]:te.sent}),t.log(`[forsion-extend] diagnostics uploaded (${se.length} bytes)`),!0}catch(N){p.set(v,n().getTime());let Y=String(N?.message||N).slice(0,300);try{l(v,{lastError:Y})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${Y}`),!1}finally{g=null}})();return g={id:v,done:H},H},y=async()=>{try{let v=c();if(!v||o()[v]?.enabled!==!0)return;let I=await i({...t.readCreds()}),E=c()===v?o()[v]:void 0;if(E?.enabled!==!0)return;I&&(I.mode!==E.policy?.mode||I.intervalHours!==E.policy?.intervalHours)&&l(v,{policy:{mode:I.mode,intervalHours:I.intervalHours}}),I&&E.requestSeen===void 0&&l(v,{requestSeen:I.requestedAt});let D=I??{..._r(E.policy),requestedAt:0},x=D.requestedAt>(E.requestSeen??D.requestedAt),L=E.lastUploadAt??0,V=!L||D.mode==="scheduled"&&n().getTime()-L>=D.intervalHours*qu;if(!x&&!V||n().getTime()-(p.get(v)??-Tu)<Tu)return;await m()&&x&&l(v,{requestSeen:D.requestedAt})}catch(v){t.log(`[forsion-extend] diagnostics tick failed: ${String(v?.message||v)}`)}},b=Promise.resolve(),_={ok:!1,error:"untrusted"};t.handle("diagnostics:get",v=>t.isTrustedSender(v)?u():_),t.handle("diagnostics:set",(v,I)=>{if(!t.isTrustedSender(v))return _;let E=c();if(!E)return u();let D={};typeof I?.enabled=="boolean"&&(D.enabled=I.enabled),D.enabled&&(D.requestSeen=void 0),typeof I?.activity=="boolean"&&(D.activity=I.activity),typeof I?.sessions=="boolean"&&(D.sessions=I.sessions),typeof I?.memory=="boolean"&&(D.memory=I.memory);let x=o()[E];for(let L of["sessions","memory"])D[L]!==void 0||x?.[L]!==void 0||(x?.enabled===!0?D[L]=!1:D.enabled&&(D[L]=!0));return l(E,D),D.enabled&&(p.delete(E),b=Promise.all([b,y()]).then(()=>{})),u()}),t.handle("diagnostics:uploadNow",async v=>t.isTrustedSender(v)?(u().enabled&&await m(),u()):_);let h=setTimeout(()=>void y(),im),T=setInterval(()=>void y(),sm);return h.unref?.(),T.unref?.(),t.log(`[forsion-extend] diagnostics registered${ju(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(h),clearInterval(T)},{tick:y,settled:()=>b})}import{randomUUID as dd}from"node:crypto";import{appendFileSync as Zm,existsSync as Qm,mkdirSync as Vo,readFileSync as fd,renameSync as pd,rmSync as Yo,statSync as ey,writeFileSync as hd}from"node:fs";import{lstat as bd}from"node:fs/promises";import{homedir as ty,release as ny}from"node:os";import{join as Un}from"node:path";var Dr={$comment:"\u5E2E\u52A9\u6539\u8FDB Forsion(\u533F\u540D\u9065\u6D4B)\u4E8B\u4EF6\u767D\u540D\u5355 v3(v1\u3001v2 \u539F\u6837\u4FDD\u7559,\u6BCF\u7248\u53EA\u52A0\u4E8B\u4EF6\u3001\u5B57\u6BB5\u4E0E\u679A\u4E3E\u503C;\u5951\u7EA6\u89C1\u540C\u76EE\u5F55 contract.md \xA76\u2013\xA715\u3001v3 \u89C1 \xA716\u2013\xA724)\u3002\u6B63\u5178\u5728\u4ED3\u6839 docs/ToBeImproved/\u9ED8\u8BA4\u6570\u636E\u91C7\u96C6\u65B9\u6848_2026-10-28/telemetry-schema.json;server(src/config/telemetry-schema.json)\u4E0E Forsion-Extend(src/core/telemetry-schema.json)\u5404\u5B58\u4E00\u4EFD\u539F\u6837\u526F\u672C,\u6539\u4E00\u5904\u4E09\u5904\u540C\u6539,\u5E76\u540C\u6B65\u9690\u79C1\u653F\u7B56\u300C\u6539\u8FDB\u6570\u636E\u300D\u4E00\u8282\u3002\u7C7B\u578B:int = 0..2147483647 \u7684\u6574\u6570;bool;enum = \u53EA\u80FD\u53D6\u5217\u51FA\u7684\u503C;id = \u5339\u914D ^[A-Za-z0-9._:/@+-]{1,max}$ \u7684\u77ED\u4E32;text = \u81EA\u7531\u6587\u672C,\u5FC5\u987B\u5148\u8FC7 sanitize \u518D\u622A\u5230 max\u3002\u4E0D\u5728\u8868\u91CC\u7684\u4E8B\u4EF6\u4E0E\u5B57\u6BB5\u4E00\u5F8B\u4E22\u3002",version:3,limits:{maxBatchBytes:65536,maxEvents:200},envelope:{installId:{type:"uuid"},app:{type:"enum",values:["desktop","web","mobile"]},appVersion:{type:"id",max:40},coreVersion:{type:"id",max:40},channel:{type:"enum",values:["stable","beta"]},os:{type:"enum",values:["darwin","win32","linux","android","ios","other"]},osVersion:{type:"id",max:40},arch:{type:"enum",values:["arm64","x64","ia32","other"]},locale:{type:"enum",values:["zh","en"]},region:{type:"enum",values:["CN","other"]}},eventFields:{event:{type:"enum",values:["crash","agent_run","tool_call","perf","feature","approval","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","sync_health","daily_muse","daily_muse_card","daily_memory","daily_judge","daily_human","quota_prompt","plugin_inventory","model_feedback","first_run"]},ts:{type:"iso-time"},sessionId:{type:"uuid"}},events:{crash:{process:{type:"enum",values:["main","renderer","engine","plugin-host","extend","other"]},errorName:{type:"id",max:60},stack:{type:"stack",max:4e3},uptimeS:{type:"int"},exitCode:{type:"int"},reason:{type:"enum",values:["exception","rejection","crashed","oom","killed","abnormal-exit","launch-failed","integrity-failure","other"]},pluginId:{type:"id",max:64}},agent_run:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},mode:{type:"enum",values:["chat","agent","muse","historian","team","task","other"]},steps:{type:"int"},llmCalls:{type:"int"},tokensIn:{type:"int"},tokensOut:{type:"int"},tokensCached:{type:"int"},retries:{type:"int"},durationMs:{type:"int"},outcome:{type:"enum",values:["done","error","aborted","other"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},recallEntries:{type:"int"},recallHistory:{type:"int"},recallTruncated:{type:"bool"},memoryTokens:{type:"int"},humanTokens:{type:"int"},profileTokens:{type:"int"},projectTokens:{type:"int"}},tool_call:{tool:{type:"id",max:80},calls:{type:"int"},failures:{type:"int"},totalMs:{type:"int"},maxMs:{type:"int"},runOutcome:{type:"enum",values:["done","error","aborted","other"]},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},pluginId:{type:"id",max:80}},perf:{kind:{type:"enum",values:["startup","hourly"]},startupMs:{type:"int"},engineReadyMs:{type:"int"},rssMb:{type:"int"},heapMb:{type:"int"},longTasks:{type:"int"}},feature:{name:{type:"enum",values:["space_open","view_open","plugin_open","setting_change"]},kind:{type:"id",max:60},id:{type:"id",max:80},key:{type:"id",max:80},value:{type:"id",max:40}},approval:{tool:{type:"id",max:80},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},reasonKind:{type:"enum",values:["custom-ask","escalate","mode","protected","control","always","other"]},mode:{type:"enum",values:["readonly","auto-edit","full-auto","custom","other"]},asked:{type:"int"},approved:{type:"int"},rejected:{type:"int"},expired:{type:"int"},decideSecTotal:{type:"int"},remoteAnswers:{type:"int"}},plugin_install:{id:{type:"id",max:80},entry:{type:"enum",values:["store","chat-card","muse-card","plugin-onboarding","deps","other"]},kind:{type:"enum",values:["plugin","skill","agent","space","theme","amadeus-plugin","other"]},source:{type:"enum",values:["github","npm","zip","other"]},stage:{type:"enum",values:["resolve","download","install","activate","done"]},outcome:{type:"enum",values:["done","error","canceled"]},errorClass:{type:"enum",values:["timeout","network","http","too-large","not-zip","integrity","identity","version","min-app","platform","deps","builtin","activate","disk","other"]},durationMs:{type:"int"},sizeKb:{type:"int"},restart:{type:"bool"}},plugin_deps:{total:{type:"int"},installed:{type:"int"},failedAt:{type:"int"},outcome:{type:"enum",values:["ready","not-ready","not-running","failed"]}},plugin_lifecycle:{id:{type:"id",max:80},action:{type:"enum",values:["uninstall","enable","disable","blocked"]},blockedReason:{type:"enum",values:["min-app","api","invalid","dev-fileext","deps","other"]},daysSinceInstall:{type:"int"},reason:{type:"enum",values:["unused","broken","slow","mistake"]}},plugin_load:{id:{type:"id",max:80},outcome:{type:"enum",values:["ok","error"]},activateMs:{type:"int"}},update:{target:{type:"enum",values:["app","engine","ui","builtin-plugin","store-plugin","first-boot-prefetch"]},id:{type:"id",max:80},outcome:{type:"enum",values:["available","not-available","staged","applied","current","error","incompatible","rolled-back","timeout","skipped"]},errorClass:{type:"enum",values:["network","http","integrity","signature","version","identity","incompatible","disk","other"]}},onboarding:{mode:{type:"enum",values:["full","returning","brief","update"]},outcome:{type:"enum",values:["finish","skip","error-skip"]},screens:{type:"int"},backJumps:{type:"int"},msStart:{type:"int"},msTheme:{type:"int"},msYou:{type:"int"},msTeam:{type:"int"},msWelcome:{type:"int"},signedIn:{type:"bool"},syncNotes:{type:"bool"},syncAgents:{type:"bool"},syncPlugins:{type:"bool"},addedAgent:{type:"bool"},museOn:{type:"bool"},computerHistoryOn:{type:"bool"},youWritten:{type:"bool"}},guide_tip:{pluginId:{type:"id",max:80},tipId:{type:"id",max:60},result:{type:"enum",values:["ok","learned","mute","gone","missing","replaced","closed"]}},command_use:{id:{type:"id",max:80},source:{type:"enum",values:["palette","hotkey","ribbon","agent","other"]},n:{type:"int"}},app_counts:{achChatSend:{type:"int"},achChatGroup:{type:"int"},achNoteCreate:{type:"int"},achNoteWikilink:{type:"int"},achNoteCanvas:{type:"int"},achBaseCreate:{type:"int"},achSpaceSave:{type:"int"},achSpaceSwitch:{type:"int"},achAgentCreate:{type:"int"},achAutomationCreate:{type:"int"},achMuseOpen:{type:"int"},achComputerUse:{type:"int"},achMarketInstall:{type:"int"},achThemeChange:{type:"int"},achTodoDone:{type:"int"},achCalendarEvent:{type:"int"},achAccountLogin:{type:"int"},achImageGenerate:{type:"int"},achDrawingCreate:{type:"int"},achMiniOpen:{type:"int"},achSpecialEnable:{type:"int"},chatStop:{type:"int"},chatRegenerate:{type:"int"},chatEditResend:{type:"int"},chatTruncateResend:{type:"int"},chatRetry:{type:"int"},chatRewind:{type:"int"},chatBranch:{type:"int"},chatSteer:{type:"int"},chatSteerWithdraw:{type:"int"},chatCompact:{type:"int"},chatRetryFailed:{type:"int"},searchOpen:{type:"int"},searchPick:{type:"int"},searchCloseEmpty:{type:"int"},providerLoginOk:{type:"int"},providerLoginFail:{type:"int"},byokSave:{type:"int"},byokImport:{type:"int"},byokImportStale:{type:"int"},byokDelete:{type:"int"},connTestOk:{type:"int"},connTestFail:{type:"int"},connTestAuthRejected:{type:"int"},modelSwitchUser:{type:"int"},modelSwitchRemember:{type:"int"},engineDefaultModelSet:{type:"int"},homeWidgetAdd:{type:"int"},homeWidgetRemove:{type:"int"},homeWidgetMove:{type:"int"},openNote:{type:"int"},openDatabase:{type:"int"},openDashboard:{type:"int"},openPdf:{type:"int"},openBoard:{type:"int"},openPluginFile:{type:"int"},openOther:{type:"int"}},sync_health:{system:{type:"enum",values:["vault","content","remote"]},day:{type:"id",max:10},cycles:{type:"int"},cycleMsTotal:{type:"int"},errAuth:{type:"int"},errOffline:{type:"int"},errVaultMissing:{type:"int"},errScan:{type:"int"},errMirrorMissing:{type:"int"},errHttp:{type:"int"},errTimeout:{type:"int"},errBlocked:{type:"int"},errOther:{type:"int"},conflicts:{type:"int"},skippedTooLarge:{type:"int"},skippedNotFound:{type:"int"},skippedExists:{type:"int"},skippedOther:{type:"int"},massDeleteGuard:{type:"int"},uploads:{type:"int"},downloads:{type:"int"}},daily_muse:{day:{type:"id",max:10},cyclesRule:{type:"int"},cyclesSchedule:{type:"int"},cyclesHeartbeat:{type:"int"},cyclesRunEnd:{type:"int"},cyclesModeAsk:{type:"int"},cyclesModeAgent:{type:"int"},cyclesModeAuto:{type:"int"},cyclesDone:{type:"int"},cyclesError:{type:"int"},cyclesAborted:{type:"int"},cyclesSilent:{type:"int"},cycleTokens:{type:"int"},cycleMs:{type:"int"},producedCards:{type:"int"},producedDms:{type:"int"},producedTodos:{type:"int"},producedStarters:{type:"int"},inboxMarked:{type:"int"},inboxUnmarked:{type:"int"},skipNoModel:{type:"int"},skipOutsideHours:{type:"int"},skipUserActive:{type:"int"},skipNothingDue:{type:"int"},skipAlreadyRunning:{type:"int"},skipBudgetBillable:{type:"int"},skipBudgetGross:{type:"int"},skipRestartCap:{type:"int"},skipRemoteLock:{type:"int"},skipSleepCleared:{type:"int"},dmProactive:{type:"int"},dmTodo:{type:"int"},dmApproval:{type:"int"},dmCard:{type:"int"},dmNotice:{type:"int"},dmRemind:{type:"int"},dmSuppressed:{type:"int"},dmAwaitingUser:{type:"int"},dmReadIn24h:{type:"int"},dmRepliedIn24h:{type:"int"},feedbackUp:{type:"int"},feedbackDown:{type:"int"},feedbackText:{type:"int"},todoCreated:{type:"int"},todoApproved:{type:"int"},todoInjected:{type:"int"},todoDone:{type:"int"},todoDismissed:{type:"int"},starterCreated:{type:"int"},starterUsed:{type:"int"},starterDismissed:{type:"int"},starterMuted:{type:"int"},ruleCreatedMuse:{type:"int"},ruleCreatedUser:{type:"int"},ruleObserveForced:{type:"int"},rulePromoted:{type:"int"},ruleExtended:{type:"int"},rulePaused:{type:"int"},ruleObservedHits:{type:"int"},approvalByAgent:{type:"int"},approvalUserApproved:{type:"int"},approvalUserRejected:{type:"int"},introAnswered:{type:"int"},introSkipped:{type:"int"},introWhenAnytime:{type:"int"},introWhenDaytime:{type:"int"},introWhenOpen:{type:"int"},introPaceAsNeeded:{type:"int"},introPaceDaily:{type:"int"},introPaceFree:{type:"int"},introFocusSchedule:{type:"int"},introFocusStudy:{type:"int"},introFocusProjects:{type:"int"},introFocusInbox:{type:"int"},introFocusCustom:{type:"int"},summarySent:{type:"int"},summaryProposed:{type:"int"},summaryAdopted:{type:"int"},summaryAskUpgrade:{type:"int"},sleepSet:{type:"int"},digestSent:{type:"int"},gEnabled:{type:"int"},gDaysEnabled:{type:"int"},gModeAsk:{type:"int"},gModeAgent:{type:"int"},gModeAuto:{type:"int"},gNotifyDigest:{type:"int"},gHeartbeatMin:{type:"int"},gMaxDmPerDay:{type:"int"},gOnboardingDay:{type:"int"},gRulesObserving:{type:"int"},gRulesEnabled:{type:"int"}},daily_muse_card:{day:{type:"id",max:10},cardKind:{type:"enum",values:["plugin","feature","inbox-ask","inbox-list","channel","settings","intro","summary","rule","rule-observed"]},created:{type:"int"},accept:{type:"int"},observe:{type:"int"},edit:{type:"int"},dismiss:{type:"int"},open:{type:"int"},apply:{type:"int"},yes:{type:"int"},later:{type:"int"},ignore:{type:"int"},ack:{type:"int"},item:{type:"int"},enable:{type:"int"},extend:{type:"int"},pause:{type:"int"},answer:{type:"int"},skip:{type:"int"},ok:{type:"int"},remove:{type:"int"},installed:{type:"int"},gone:{type:"int"},dismissIrrelevant:{type:"int"},dismissTiming:{type:"int"},dismissFrequent:{type:"int"},dismissKnown:{type:"int"},decideSecTotal:{type:"int"},decidedRemote:{type:"int"},gPendingOver3d:{type:"int"}},daily_memory:{day:{type:"id",max:10},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},addAgent:{type:"int"},addProject:{type:"int"},addPerson:{type:"int"},updateAgent:{type:"int"},updateProject:{type:"int"},updatePerson:{type:"int"},forgetAgent:{type:"int"},forgetProject:{type:"int"},forgetPerson:{type:"int"},moveScope:{type:"int"},srcExplicit:{type:"int"},srcHistorian:{type:"int"},srcDream:{type:"int"},srcManual:{type:"int"},srcRestore:{type:"int"},srcExternalEdit:{type:"int"},srcSync:{type:"int"},srcMigration:{type:"int"},errFull:{type:"int"},errVersionConflict:{type:"int"},errPortraitFull:{type:"int"},userEditAgentWritten7d:{type:"int"},userForgetAgentWritten7d:{type:"int"},userRestoreDreamRetired:{type:"int"},userEdit:{type:"int"},userForget:{type:"int"},userAdd:{type:"int"},userForgetWrong:{type:"int"},userForgetStale:{type:"int"},userForgetUnwanted:{type:"int"},userForgetDuplicate:{type:"int"},retellExisting:{type:"int"},retellForgotten:{type:"int"},candidatesAdded:{type:"int"},dreamAuto:{type:"int"},dreamManual:{type:"int"},dreamArchive:{type:"int"},dreamCompleted:{type:"int"},dreamSkipped:{type:"int"},dreamFailed:{type:"int"},dreamCancelled:{type:"int"},dreamCalls:{type:"int"},dreamSources:{type:"int"},dreamGroups:{type:"int"},dreamMerges:{type:"int"},dreamDiscarded:{type:"int"},dreamToPortrait:{type:"int"},dreamPending:{type:"int"},dreamDeferred:{type:"int"},dreamVerifyFail:{type:"int"},dreamRetried:{type:"int"},dreamMs:{type:"int"},harnessUpsertAgent:{type:"int"},harnessUpsertHistorian:{type:"int"},harnessUpsertMuse:{type:"int"},harnessUpsertUser:{type:"int"},harnessDelete:{type:"int"},harnessRollback:{type:"int"},gEntries:{type:"int"},gCharsPct:{type:"int"},gTombstones:{type:"int"},gCandidatesPending:{type:"int"},gCandidatesOldestDays:{type:"int"},gHarnessEntries:{type:"int"}},daily_judge:{day:{type:"id",max:10},rounds:{type:"int"},roundsIndependent:{type:"int"},roundsAssist:{type:"int"},roundsFork:{type:"int"},isolationSkips:{type:"int"},memCandidates:{type:"int"},projCandidatesAuto:{type:"int"},projCandidatesQueued:{type:"int"},projAdopted:{type:"int"},projDismissed:{type:"int"},projForgotten:{type:"int"},projRestored:{type:"int"},projCompacted:{type:"int"},harnessCandidatesAuto:{type:"int"},harnessCandidatesQueued:{type:"int"},signalStop:{type:"int"},signalToolLoop:{type:"int"},signalNudge:{type:"int"},signalCorrectionDecision:{type:"int"},signalCorrectionLexical:{type:"int"},titleUpdated:{type:"int"},summaryUpdated:{type:"int"},iconUpdated:{type:"int"}},daily_human:{day:{type:"id",max:10},wAgentShared:{type:"int"},wAgentAgent:{type:"int"},wAgentProject:{type:"int"},wAgentPortrait:{type:"int"},wAgentAgentMd:{type:"int"},wAgentMemory:{type:"int"},wUserShared:{type:"int"},wUserAgent:{type:"int"},wUserProject:{type:"int"},wUserPortrait:{type:"int"},wUserAgentMd:{type:"int"},wUserMemory:{type:"int"},srcRemember:{type:"int"},srcDream:{type:"int"},srcMove:{type:"int"},srcPromote:{type:"int"},srcUser:{type:"int"},userUndoAgentWrite7d:{type:"int"},moveScan:{type:"int"},moveMoved:{type:"int"},moveKept:{type:"int"},moveUndo:{type:"int"},promoteToAgentMd:{type:"int"},coldstartAgents:{type:"int"},coldstartPersonWrites:{type:"int"},coldstartRelearned:{type:"int"},mirrorConflicts:{type:"int"},syncConflictCopies:{type:"int"},gHumanMdEntries:{type:"int"},gAgentMdEntries:{type:"int"},gPortraitEntries:{type:"int"},gMemoryEntries:{type:"int"},gCalendarRows:{type:"int"},gAgentsWithHumanMd:{type:"int"},gAgentsTotal:{type:"int"}},quota_prompt:{entry:{type:"enum",values:["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","other"]},shown:{type:"int"},dismiss:{type:"int"},card:{type:"int"},points:{type:"int"},upgrade:{type:"int"},topup:{type:"int"},bgConvert:{type:"int"},bgSettings:{type:"int"},more:{type:"int"}},plugin_inventory:{day:{type:"id",max:10},id:{type:"id",max:80},source:{type:"enum",values:["store","builtin","local"]},installed:{type:"int"},enabled:{type:"int"},localCount:{type:"int"}},model_feedback:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},regenerate:{type:"int"},stop:{type:"int"},editResend:{type:"int"}},first_run:{outcome:{type:"enum",values:["done","error","aborted"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},sinceFirstLaunchS:{type:"int"},durationMs:{type:"int"}}}};var zm=Dr.events,Bm=Dr.envelope,Bo=Dr.limits,td=Dr.version,qm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Wm=/^[A-Za-z0-9._:/@+-]+$/,nd=t=>typeof t=="string"&&qm.test(t),Qu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Gm=[[/\/Users\/[^/\s]+\//gi,"~/"],[/\/home\/[^/\s]+\//gi,"~/"],[/[a-z]:\\Users\\[^\\\s]+\\/gi,"~\\"],[/~([/\\])[^\s"'`」:()]+/g,"~$1\u2026"],[/\/Volumes\/[^\s"'`」:()]+/g,"/Volumes/\u2026"],[/\b([d-z]):\\[^\s"'`」:()]+/gi,"$1:\\\u2026"],[/forsion-agent-space\/[^/\s]+\//g,"forsion-agent-space/\u2026/"],[/"[^"]{1,200}"/g,'"\u2026"'],[/'[^']{1,200}'/g,"'\u2026'"],[/`[^`]{1,200}`/g,"`\u2026`"],[/「[^「」]{1,200}」/g,"\u300C\u2026\u300D"],[/(https?:\/\/[^\s?#"'`」]+)[?#][^\s"'`」]*/gi,"$1"],[/sk-[A-Za-z0-9_-]{10,}/g,"[redacted]"],[/Bearer\s+\S+/gi,"[redacted]"],[/[0-9a-f]{32,}/gi,"[redacted]"],[/[A-Za-z0-9+/]{40,}={0,2}/g,"[redacted]"],[/[A-Za-z0-9_-]{40,}/g,"[redacted]"],[/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]"]],rd=t=>Gm.reduce((e,[n,r])=>e.replace(n,r),t);function ed(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(Qu,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=rd(r),(r.length>e?r.slice(0,e):r).replace(Qu,"\uFFFD")}var id=/^pr-[a-f0-9]{48}$/,Vm=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,sd=t=>id.test(t)||Vm.test(t)||rd(t)===t;function Ym(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function zo(t,e,n){switch(t.type){case"enum":return typeof e=="string"&&t.values.includes(e)?e:void 0;case"int":return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.min(Math.round(e),2147483647):void 0;case"bool":return typeof e=="boolean"?e:void 0;case"uuid":return nd(e)?e.toLowerCase():void 0;case"iso-time":return typeof e=="string"&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():void 0;case"id":return typeof e=="string"&&e.length<=t.max&&Wm.test(e)&&sd(e)?e:void 0;case"text":return typeof e=="string"&&e?ed(e,t.max,n):void 0;case"stack":{let r=Ym(e);return r?ed(r,t.max,n):void 0}}}function Qt(t,e){let n=typeof t?.event=="string"?zm[t.event]:void 0;if(!n)return null;let r={},i=t.props&&typeof t.props=="object"?t.props:{};for(let[a,o]of Object.entries(n)){let l=zo(o,i[a],e);l!==void 0&&(r[a]=l)}let s=zo({type:"iso-time"},t.ts);return{event:t.event,ts:s??new Date().toISOString(),...nd(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function od(t){let e={};for(let[n,r]of Object.entries(Bm)){if(n==="installId")continue;let i=zo(r,t[n]);e[n]=typeof i=="string"?i:null}return e}function ad(t,e){if(e==="aborted")return"aborted";if(!t)return;let n=t.toLowerCase();return/abort|cancel/.test(n)?"aborted":/timeout|timed out|etimedout/.test(n)?"timeout":/token_quota_exceeded/.test(n)?"quota":/\b429\b|rate.?limit|too many requests|quota/.test(n)?"rate_limit":/\b40[13]\b|unauthori[sz]ed|forbidden|invalid api key|authentication/.test(n)?"auth":/context.{0,20}(length|window|too long)|maximum context|too many tokens|prompt is too long/.test(n)?"context_length":/econn|enotfound|eai_again|socket|network|fetch failed|getaddrinfo/.test(n)?"network":/\b5\d\d\b|upstream|bad gateway|overloaded|service unavailable/.test(n)?"upstream":/tool/.test(n)?"tool":"other"}function ld(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function Wi(t){return t?/^pr-/.test(t)?"forsion":/^codex\//.test(t)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(t)?"local":"byok":"other"}var Jm=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function qo(t,e){if(typeof t!="string"||!t)return;let n=Wi(t);if((n==="codex"||n==="forsion"&&id.test(t))&&(e===void 0||e===n))return t;let i=t.slice(t.lastIndexOf("/")+1);return Jm.test(i)?i:void 0}function Wo(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function Go(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}var Km=/^market-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i,Xm=/^[a-z0-9][a-z0-9-]{0,79}$/;function cd(t,e){if(typeof t!="string"||!t)return;let n=Km.exec(t);if(n)return n[1].toLowerCase();if((e===!0||e===1)&&t.length<=80&&Xm.test(t)&&sd(t))return t}function ud(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var ry=10*6e4,iy=6e4,sy=50,gd=1024*1024,oy=168*36e5,md=15e3,ay=200,ly=2e3,Jo=7,cy=5e3,yd=864e5,uy=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","quota_prompt","plugin_inventory","model_feedback","first_run"]),dy=new Set(["shown","dismiss","card","points","upgrade","topup","bgConvert","bgSettings","more"]),fy=1e3,wd=36e5,Ko=2,Xo={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},py=new Set(["custom-ask","escalate","mode","protected","control","always"]);function hy(t){let e=t.props&&typeof t.props=="object"?t.props:{};if(t.event==="model_feedback"){let n=typeof e.modelId=="string"?e.modelId:void 0,r=qo(n,typeof e.providerKind=="string"?e.providerKind:"other");return r?{...t,props:{...e,modelId:r,providerKind:typeof e.providerKind=="string"?e.providerKind:Wi(n)}}:null}if(t.event==="plugin_inventory"){if(!In(e.day))return null;if(e.source==="local"||e.id==="local")return{...t,props:{day:e.day,id:"local",source:"local",localCount:e.localCount}};let n=typeof e.id=="string"?e.id:"";return(e.source==="store"?!gy.test(n):e.source!=="builtin"||!(n.length<=80&&my.test(n)))?null:{...t,props:{day:e.day,id:n,source:e.source,installed:e.installed,enabled:e.enabled}}}return t}var gy=/^(?:market-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,my=/^[a-z0-9][a-z0-9-]{0,79}$/,yy={model_feedback:"modelId",plugin_inventory:"id",quota_prompt:"entry"},wy=new Set(["readonly","auto-edit","full-auto","custom"]),Sd=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),Zo=t=>({at:Sd(t),id:"~"}),Fn=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function by(t,e,n,r){let i=Un(t,"tangu","state.db");if(!await bd(i).then(a=>a.isFile(),()=>!1))return{events:[],cursor:e};let s;try{let{DatabaseSync:a}=await import("node:sqlite");s=new a(i,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let o=s.prepare(`SELECT r.id, r.status, r.current_step, r.model_id, substr(r.error, 1, 2000) AS error, r.created_at, r.updated_at, s.kind
|
|
260
|
+
json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${bs}) AS error
|
|
261
|
+
FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),u=m=>typeof m=="number"&&Number.isFinite(m)&&m>0?m:0,d=m=>m||void 0,g=[],f=0,p=l.length>t.runs;for(let m of l.slice(0,t.runs)){let y={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},b=new Map,h=[],E=0,v=c.all(m.id,t.events+1),k=v.length>t.events;for(let _ of v.slice(0,t.events))if(_.type==="usage")y.llmCalls++,y.prompt+=u(_.prompt),y.completion+=u(_.completion),y.cached+=u(_.cached),y.reasoning+=u(_.reasoning),y.llmMs+=u(_.llm_ms),y.ttftMaxMs=Math.max(y.ttftMaxMs,u(_.ttft_ms)),y.requestMaxBytes=Math.max(y.requestMaxBytes,u(_.request_bytes));else if(_.type==="tool_result"){let R=be(_.name,80)??"?",N=b.get(R)??(b.size<t.tools?{name:R,n:0,ms:0,maxMs:0}:void 0);if(!N){k=!0;continue}b.set(R,N),N.n++,_.failed&&(N.errors=(N.errors??0)+1),N.ms+=u(_.ms),N.maxMs=Math.max(N.maxMs,u(_.ms))}else if(_.type==="error"){let R=Wl(_.error,t.errorChars);R&&!h.includes(R)&&h.length<3&&h.push(R)}else _.phase==="llm_retry"&&E++;let C={id:be(m.id,64)??null,session:be(m.session_id,64)??null,kind:be(m.kind,16),app:be(m.app_id,50),model:be(m.model_id,128),status:be(m.status,16)??null,error:Wl(m.error,t.errorChars),createdAt:be(m.created_at,40)??null,updatedAt:be(m.updated_at,40)??null,steps:d(u(m.current_step)),tokens:d(u(m.tokens_total)),retries:d(E),...Object.fromEntries(Object.entries(y).map(([_,R])=>[_,d(R)])),errors:h.length?h:void 0,tools:b.size?[...b.values()]:void 0,partial:k||void 0},S=Buffer.byteLength(JSON.stringify(C));if(f+S>t.totalBytes){p=!0;break}f+=S,g.push(C)}return{runs:g,...p?{runsTruncated:!0}:{}}}catch(a){return{runs:[],runsError:Qr(a)}}finally{try{o?.close()}catch{}}}async function oI(n){let e=i=>Math.round(i/1048576),t=i=>ur(i).then(o=>o.isFile()?o.size:0,()=>0),r=ve(n,"tangu","state.db");return{cpus:DC().length,memTotalMB:e(MC()),memFreeMB:e(PC()),diskFreeMB:await TC(n).then(i=>e(i.bavail*i.bsize),()=>null),stateDbMB:e(await t(r)+await t(`${r}-wal`)),uptimeMin:Math.round(process.uptime()/60)}}var cb=n=>typeof n.diagnosticLogs=="function";function sI(n,e=VC){let t=n?.engine;if(!t||typeof t!="object")return null;let r=(Array.isArray(t.lines)?t.lines:[]).filter(l=>typeof l=="string"&&!!l),i=r.map(l=>Wl(l,uf)??""),o=i.some((l,c)=>l.length>uf||r[c].length>bs),a=i.length,s=e;for(;a>0&&Buffer.byteLength(i[a-1])+1<=s;)s-=Buffer.byteLength(i[--a])+1;return a>0&&(o=!0),{state:be(t.state,32)??null,lastError:Wl(t.lastError,uf)??null,log:i.slice(a).join(`
|
|
262
|
+
`),...o?{logTruncated:!0}:{}}}var pf={errors:20,errorChars:300,agents:100},aI=n=>bb(wb(n,!1).replace(/[^\s"'`<>()[\]{},;]*\/[^\s"'`<>()[\]{},;]*/g,e=>ff.test(e)?e:"[path]")),lI=(n,e=[],t=pf.errorChars)=>Vn(aI(Xh(zn(n),e.map(r=>zn(r)))),t)??"",kt=n=>typeof n=="number"&&Number.isFinite(n)&&n>0?Math.round(n):0,ql=n=>typeof n=="number"&&Number.isFinite(n)&&n>0?new Date(n).toISOString():null,Sb=n=>{let e=n&&typeof n=="object"?n:{};return Object.fromEntries(Yh.flatMap(t=>kt(e[t])?[[t,kt(e[t])]]:[]))},db=n=>{let e=n;return e&&typeof e=="object"?{at:ql(e.at),ms:kt(e.ms),completed:e.completed===!0,...Sb(e.counts)}:null},cI=Object.fromEntries(on.map(n=>[n.path,n.id])),dI=new Set(["idle","scanning","syncing","paused"]),uI=new Set(["queued","active","done","failed","paused","conflict"]);function fI(n,e){let t=(Array.isArray(n)?n:[]).filter(s=>!!s&&typeof s.source=="string"&&typeof s.target=="string"),r=s=>s===void 0?null:s==="default"?"shared":s==="off"?"off":e&&s===`device-${e}`?"device":/^device-/.test(s)?"other-device":"unknown",i={other:r(t.find(s=>s.source==="")?.target)};for(let s of on)i[s.id]=r(Hn(s.path,t)?.target);let o={},a={};for(let s of t){if(s.source===""||cI[s.source])continue;let l=Mo(s.source);if(l&&Object.keys(o).length<pf.agents)o[l]=r(s.target);else if(!l){let c=r(s.target)??"unknown";a[c]=(a[c]??0)+1}}return{...i,agentRules:o,folderRules:a,count:t.length}}function gI(n){let e=n;if(!e||typeof e!="object")return null;let t=typeof e.deviceId=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e.deviceId)?e.deviceId:null,r=e.backlog&&typeof e.backlog=="object"?e.backlog:null,i=r?.jobs&&typeof r.jobs=="object"?Object.fromEntries(Object.entries(r.jobs).filter(([a,s])=>uI.has(a)&&kt(s)).map(([a,s])=>[a,kt(s)])):{},o=e.totals??{};return{deviceId:t,session:e.session===!0,enabled:e.enabled===!0,paused:e.paused===!0,running:e.running===!0,phase:typeof e.phase=="string"&&dI.has(e.phase)?e.phase:null,revision:kt(e.revision),rules:fI(e.rules,t),backlog:r?{jobs:i,blocked:kt(r.blocked),pendingUploads:kt(r.pendingUploads),unconfirmed:kt(r.unconfirmed),trash:kt(r.trash),awaitingBytes:kt(r.awaitingBytes),dirty:kt(r.dirty)}:null,archive:e.archive==="running"||e.archive==="done"?e.archive:null,since:ql(e.since),lastRun:db(e.lastRun),runs:(Array.isArray(e.runs)?e.runs:[]).slice(-20).map(db).filter(Boolean),totals:{runs:kt(o.runs),completedRuns:kt(o.completedRuns),idleRuns:kt(o.idleRuns),...Sb(o)},errors:(Array.isArray(e.errors)?e.errors:[]).slice(-pf.errors).flatMap(a=>{if(!a||typeof a!="object"||typeof a.text!="string"||!a.text)return[];let s=Array.isArray(a.paths)?a.paths.filter(l=>typeof l=="string"):[];return[{first:ql(a.first),at:ql(a.at),n:kt(a.n)||1,kind:Ca(a.text)??"other",text:lI(a.text,s)}]})}}function pI(n){let e=n?.engine?.lines;if(!Array.isArray(e))return null;let t={lines:0,errorRounds:0,tooLarge:0,overwrites:0,pulledNew:0,conflictCopies:0};for(let r of e){if(typeof r!="string"||!r.includes("[agent sync]"))continue;t.lines++;let i=/已从云端拉取(覆盖|新文件)/.exec(r);if(i){i[1]==="\u8986\u76D6"?t.overwrites++:t.pulledNew++,r.includes("\u672C\u5730\u7248\u672C\u5DF2\u5B58\u4E3A")&&t.conflictCopies++;continue}t.errorRounds++,t.tooLarge+=r.match(/exceeds sync limit/g)?.length??0}return t}function hI(n,e=qC){let t;try{t=Vl(n)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof t[r]=="string"&&t[r]?[[r,t[r]]]:[]))}async function kb(n,e=HC){try{if(!(await ur(n)).isFile())return null;let t=await fb(n,Zw.O_RDONLY|(Zw.O_NOFOLLOW??0));try{let r=await t.stat();if(!r.isFile())return null;let i=Buffer.alloc(Math.min(e,r.size)),{bytesRead:o}=await t.read(i,0,i.length,0);return i.subarray(0,o).toString("utf8")}finally{await t.close()}}catch{return null}}var ys=async(n,e)=>{let t=await kb(n);return t?Vn(zn(t),e):void 0};async function mI(n,e){let t=await kb(ve(n,"config.toml")),r=Object.entries(t?hI(t):{}).map(([i,o])=>[i,Vn(zn(o),e)??""]);return r.length?Object.fromEntries(r):void 0}async function ub(n){let e=await Wi(ve(n,".memory-state.json"));if(!e||typeof e!="object")return;let t=r=>Array.isArray(r)?r.length:0;return{entries:t(e.entries),tombstones:t(e.tombstones),revisions:t(e.revisions),processedCandidates:t(e.processedCandidateIds),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:null,projectionPending:e.projectionPending===!0?!0:void 0}}async function yI(n,e,t=zC){let r=ve(n,"tangu"),i=f=>ur(f).then(p=>p.isFile()?p.mtimeMs:0,()=>0),o=dr(new Date(jn(e))),a={agents:[],teams:[],projects:[],activity:[]},s=t.totalBytes,l=(f,p)=>{let m=Buffer.byteLength(JSON.stringify(p))+1;return m>s?(a.truncated=!0,!1):(s-=m,f.push(p),!0)},c=await ys(ve(r,"USER.md"),t.fileChars);c&&l([],c)&&(a.user=c);let u=ve(r,"state.db"),d=await ur(u).then(f=>f.isFile(),f=>f?.code==="ENOENT"?!1:Qr(f));if(typeof d=="string")a.activityError=d;else if(d){let f;try{let{DatabaseSync:p}=await import("node:sqlite");f=new p(u,{readOnly:!0}),f.exec("PRAGMA busy_timeout = 1500");let y=f.prepare(`SELECT agent, action, substr(detail, 1, ${bs}) AS detail, session_ref, created_at FROM special_agent_log
|
|
263
|
+
WHERE created_at >= ? AND created_at < ? AND (${WC.map(b=>`action GLOB '${b}*'`).join(" OR ")})
|
|
264
|
+
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(Gi(jn(e)),Gi(e.getTime()),t.activity+1);y.length>t.activity&&(a.truncated=!0);for(let b of y.slice(0,t.activity))if(!l(a.activity,{at:be(b.created_at,40)??null,agent:be(b.agent,64)??null,action:be(b.action,64)??null,detail:typeof b.detail=="string"&&b.detail?Vn(zn(b.detail),t.detailChars):void 0,session:be(b.session_ref,64)}))break}catch(p){a.activityError=Qr(p)}finally{try{f?.close()}catch{}}}for(let f of await Un(ve(r,"project-memory"),100)){let p=ve(r,"project-memory",f);if(!await ws(p))continue;let m=await ys(ve(p,"MEMORY.md"),t.fileChars),y=await ub(p);if(!m&&!y)continue;let b=(await Wi(ve(p,"PROJECT.json")))?.project;if(!l(a.projects,{id:be(f,64)??null,name:typeof b=="string"?be(hb(b.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:y,memory:m}))break}for(let f of await Un(ve(r,"teams"),100)){if(!await ws(ve(r,"teams",f)))continue;let p=await ys(ve(r,"teams",f,"TEAM.md"),t.fileChars);if(p&&!l(a.teams,{id:f,files:{"TEAM.md":p}}))break}let g=[];for(let f of await Un(ve(r,"agents"),100)){let p=ve(r,"agents",f);await ws(p)&&g.push({id:f,dir:p,at:Math.max(0,...await Promise.all([...nb,".memory-state.json"].map(m=>i(ve(p,m)))))})}for(let{id:f,dir:p,at:m}of g.sort((y,b)=>b.at-y.at||y.id.localeCompare(b.id))){let y={};for(let k of nb){let C=await ys(ve(p,k),t.fileChars);C&&(y[k]=C)}let b=[];if(await ws(ve(p,"LOG")))for(let k of(await Un(ve(p,"LOG"),400)).filter(C=>/^\d{4}-\d{2}-\d{2}\.md$/.test(C)&&C.slice(0,10)>=o&&C.slice(0,10)<=dr(e))){let C=await ys(ve(p,"LOG",k),t.logChars);C&&b.push({date:k.slice(0,10),text:C})}let h=(await Wi(ve(p,".memory-dream.json")))?.last,E=await ub(p),v=await mI(p,t.fileChars);!Object.keys(y).length&&!b.length&&!E&&!v||l(a.agents,{id:f,updatedAt:m?new Date(m).toISOString():null,config:v,state:E,dream:h&&typeof h=="object"?{state:be(h.state,32),startedAt:be(h.startedAt,40),finishedAt:be(h.finishedAt,40),calls:typeof h.calls=="number"?h.calls:void 0,detail:typeof h.detail=="string"?Vn(zn(h.detail),t.detailChars):void 0}:void 0,files:Object.keys(y).length?y:void 0,log:b.length?b:void 0})}return a}async function Eb(n){let e=(await Wi(ve(n,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${_C("sha256").update(pb()).digest("hex").slice(0,8)}`}async function wI(n){let{home:e}=n,t=ve(e,"tangu"),r=n.now??new Date,i=a=>n.since?.[a]??jn(r),o=sI(n.engineLogs);return zn({schema:4,collectedAt:r.toISOString(),app:{version:n.appVersion,platform:process.platform,arch:process.arch,os:OC(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:hb(e),cloudUrl:n.cloudUrl},device:{id:await Eb(e),name:pb()},system:await oI(e),config:eI(await Wi(ve(e,"config.json"))),agents:await sb(ve(t,"agents")),teams:await sb(ve(t,"teams")),plugins:{desktop:await ab(ve(e,"plugins")),engine:await ab(ve(t,"plugins"))},inventory:{skills:await Un(ve(t,"skills")),spaces:await Un(ve(e,"spaces")),themes:await Un(ve(e,"themes"))},...n.activity?{...await nI(ve(e,"activity"),r,i("activity")),activitySince:new Date(i("activity")).toISOString()}:{},...n.sessions?{...await rI(e,r,yb,i("sessions")),sessionsSince:new Date(i("sessions")).toISOString()}:{},...(typeof n.memory=="function"?n.memory():n.memory)===!0?{memory:await yI(e,r)}:{},...await iI(e,r),runsSince:new Date(jn(r)).toISOString(),...o?{engine:o}:{},sync:{content:gI(n.contentSync),legacy:pI(n.engineLogs)}})}function _b(n,e={}){let t=e.now??(()=>new Date),r=e.remoteFor??(v=>Ml({baseUrl:v.cloudUrl,vault:Nl,getToken:()=>v.token})),i=e.policyFor??df,o=()=>ve(n.homeDir(),"extend-diagnostics.json"),a=()=>{let v=k=>k&&typeof k=="object"?k:{};try{let k=JSON.parse(AC(o(),"utf8"));return{accounts:v(k?.accounts),sent:v(k?.sent)}}catch{return{accounts:{},sent:{}}}},s=()=>a().accounts,l=(v,k,C)=>{let S=a();S.accounts[v]={...S.accounts[v],...k},Object.assign(S.sent,C),RC(n.homeDir(),{recursive:!0});let _=`${o()}.${process.pid}.tmp`;IC(_,JSON.stringify(S,null,2),{encoding:"utf8",mode:384}),CC(_,o())},c=()=>{let v=n.readCreds();return v.token&&v.cloudUrl?n.accountId():null},u=()=>{let v=c(),k=v?s()[v]??{}:{},C=ms(k.policy);return{signedIn:!!v,enabled:k.enabled===!0,activity:k.activity!==!1,sessions:k.sessions??k.enabled!==!0,memory:k.memory??k.enabled!==!0,lastUploadAt:k.lastUploadAt??null,lastError:k.lastError??null,retainDays:Hl,mode:C.mode,intervalHours:C.intervalHours}},d=()=>{try{return cb(n)?n.diagnosticLogs():null}catch{return null}},g=null,f=new Map,p=async()=>{let v=c();if(!v)return!1;if(g)return g.id===v?g.done:(await g.done,p());let k={...n.readCreds()},C=t(),S=a(),_=S.accounts[v],R=k.cloudUrl.replace(/\/+$/,""),N=sf(_?.file,S.sent[R]??{},C),D=(async()=>{try{let M=await wI({home:n.homeDir(),appVersion:n.appVersion(),cloudUrl:k.cloudUrl,activity:_?.activity!==!1,sessions:_?.sessions===!0,now:C,since:N,engineLogs:d(),contentSync:em(),memory:()=>{let Y=c()===v?s()[v]:void 0;return Y?.enabled===!0&&Y.memory===!0}}),x=await Eb(n.homeDir()),$=s()[v];if(c()!==v||$?.enabled!==!0)return!1;if($.activity===!1)for(let Y of["activity","activityTruncated","activityError","activitySince"])delete M[Y];if($.sessions!==!0)for(let Y of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete M[Y];$.memory!==!0&&delete M.memory;let O=[],q=NC(M,O);if(!q)throw new Error("snapshot too large");await lf(r(k),x,q,C),f.delete(v);let ie=af(a().sent[R]??{},_?.file,N,C,M,O);return l(v,{lastUploadAt:t().getTime(),lastError:void 0,file:ie.file},{[R]:ie.sent}),n.log(`[forsion-extend] diagnostics uploaded (${q.length} bytes)`),!0}catch(M){f.set(v,t().getTime());let x=String(M?.message||M).slice(0,300);try{l(v,{lastError:x})}catch{}return n.log(`[forsion-extend] diagnostics upload failed: ${x}`),!1}finally{g=null}})();return g={id:v,done:D},D},m=async()=>{try{let v=c();if(!v||s()[v]?.enabled!==!0)return;let k=await i({...n.readCreds()}),C=c()===v?s()[v]:void 0;if(C?.enabled!==!0)return;k&&(k.mode!==C.policy?.mode||k.intervalHours!==C.policy?.intervalHours)&&l(v,{policy:{mode:k.mode,intervalHours:k.intervalHours}}),k&&C.requestSeen===void 0&&l(v,{requestSeen:k.requestedAt});let S=k??{...ms(C.policy),requestedAt:0},_=S.requestedAt>(C.requestSeen??S.requestedAt),R=C.lastUploadAt??0,N=!R||S.mode==="scheduled"&&t().getTime()-R>=S.intervalHours*mb;if(!_&&!N||t().getTime()-(f.get(v)??-eb)<eb)return;await p()&&_&&l(v,{requestSeen:S.requestedAt})}catch(v){n.log(`[forsion-extend] diagnostics tick failed: ${String(v?.message||v)}`)}},y=Promise.resolve(),b={ok:!1,error:"untrusted"};n.handle("diagnostics:get",v=>n.isTrustedSender(v)?u():b),n.handle("diagnostics:set",(v,k)=>{if(!n.isTrustedSender(v))return b;let C=c();if(!C)return u();let S={};typeof k?.enabled=="boolean"&&(S.enabled=k.enabled),S.enabled&&(S.requestSeen=void 0),typeof k?.activity=="boolean"&&(S.activity=k.activity),typeof k?.sessions=="boolean"&&(S.sessions=k.sessions),typeof k?.memory=="boolean"&&(S.memory=k.memory);let _=s()[C];for(let R of["sessions","memory"])S[R]!==void 0||_?.[R]!==void 0||(_?.enabled===!0?S[R]=!1:S.enabled&&(S[R]=!0));return l(C,S),S.enabled&&(f.delete(C),y=Promise.all([y,m()]).then(()=>{})),u()}),n.handle("diagnostics:uploadNow",async v=>n.isTrustedSender(v)?(u().enabled&&await p(),u()):b);let h=setTimeout(()=>void m(),$C),E=setInterval(()=>void m(),LC);return h.unref?.(),E.unref?.(),n.log(`[forsion-extend] diagnostics registered${cb(n)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(h),clearInterval(E)},{tick:m,settled:()=>y})}import{randomUUID as Lb}from"node:crypto";import{appendFileSync as TI,existsSync as DI,mkdirSync as vf,readFileSync as Fb,renameSync as Bb,rmSync as Sf,statSync as PI,writeFileSync as jb}from"node:fs";import{lstat as Hb}from"node:fs/promises";import{homedir as OI,release as MI}from"node:os";import{join as Ki}from"node:path";var vs={$comment:"\u5E2E\u52A9\u6539\u8FDB Forsion(\u533F\u540D\u9065\u6D4B)\u4E8B\u4EF6\u767D\u540D\u5355 v3(v1\u3001v2 \u539F\u6837\u4FDD\u7559,\u6BCF\u7248\u53EA\u52A0\u4E8B\u4EF6\u3001\u5B57\u6BB5\u4E0E\u679A\u4E3E\u503C;\u5951\u7EA6\u89C1\u540C\u76EE\u5F55 contract.md \xA76\u2013\xA715\u3001v3 \u89C1 \xA716\u2013\xA724)\u3002\u6B63\u5178\u5728\u4ED3\u6839 docs/ToBeImproved/\u9ED8\u8BA4\u6570\u636E\u91C7\u96C6\u65B9\u6848_2026-10-28/telemetry-schema.json;server(src/config/telemetry-schema.json)\u4E0E Forsion-Extend(src/core/telemetry-schema.json)\u5404\u5B58\u4E00\u4EFD\u539F\u6837\u526F\u672C,\u6539\u4E00\u5904\u4E09\u5904\u540C\u6539,\u5E76\u540C\u6B65\u9690\u79C1\u653F\u7B56\u300C\u6539\u8FDB\u6570\u636E\u300D\u4E00\u8282\u3002\u7C7B\u578B:int = 0..2147483647 \u7684\u6574\u6570;bool;enum = \u53EA\u80FD\u53D6\u5217\u51FA\u7684\u503C;id = \u5339\u914D ^[A-Za-z0-9._:/@+-]{1,max}$ \u7684\u77ED\u4E32;text = \u81EA\u7531\u6587\u672C,\u5FC5\u987B\u5148\u8FC7 sanitize \u518D\u622A\u5230 max\u3002\u4E0D\u5728\u8868\u91CC\u7684\u4E8B\u4EF6\u4E0E\u5B57\u6BB5\u4E00\u5F8B\u4E22\u3002",version:3,limits:{maxBatchBytes:65536,maxEvents:200},envelope:{installId:{type:"uuid"},app:{type:"enum",values:["desktop","web","mobile"]},appVersion:{type:"id",max:40},coreVersion:{type:"id",max:40},channel:{type:"enum",values:["stable","beta"]},os:{type:"enum",values:["darwin","win32","linux","android","ios","other"]},osVersion:{type:"id",max:40},arch:{type:"enum",values:["arm64","x64","ia32","other"]},locale:{type:"enum",values:["zh","en"]},region:{type:"enum",values:["CN","other"]}},eventFields:{event:{type:"enum",values:["crash","agent_run","tool_call","perf","feature","approval","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","sync_health","daily_muse","daily_muse_card","daily_memory","daily_judge","daily_human","quota_prompt","plugin_inventory","model_feedback","first_run","forced_update"]},ts:{type:"iso-time"},sessionId:{type:"uuid"}},events:{crash:{process:{type:"enum",values:["main","renderer","engine","plugin-host","extend","other"]},errorName:{type:"id",max:60},stack:{type:"stack",max:4e3},uptimeS:{type:"int"},exitCode:{type:"int"},reason:{type:"enum",values:["exception","rejection","crashed","oom","killed","abnormal-exit","launch-failed","integrity-failure","other"]},pluginId:{type:"id",max:64}},agent_run:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},mode:{type:"enum",values:["chat","agent","muse","historian","team","task","other"]},steps:{type:"int"},llmCalls:{type:"int"},tokensIn:{type:"int"},tokensOut:{type:"int"},tokensCached:{type:"int"},retries:{type:"int"},durationMs:{type:"int"},outcome:{type:"enum",values:["done","error","aborted","other"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},recallEntries:{type:"int"},recallHistory:{type:"int"},recallTruncated:{type:"bool"},memoryTokens:{type:"int"},humanTokens:{type:"int"},profileTokens:{type:"int"},projectTokens:{type:"int"}},tool_call:{tool:{type:"id",max:80},calls:{type:"int"},failures:{type:"int"},totalMs:{type:"int"},maxMs:{type:"int"},runOutcome:{type:"enum",values:["done","error","aborted","other"]},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},pluginId:{type:"id",max:80}},perf:{kind:{type:"enum",values:["startup","hourly"]},startupMs:{type:"int"},engineReadyMs:{type:"int"},rssMb:{type:"int"},heapMb:{type:"int"},longTasks:{type:"int"}},feature:{name:{type:"enum",values:["space_open","view_open","plugin_open","setting_change"]},kind:{type:"id",max:60},id:{type:"id",max:80},key:{type:"id",max:80},value:{type:"id",max:40}},approval:{tool:{type:"id",max:80},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},reasonKind:{type:"enum",values:["custom-ask","escalate","mode","protected","control","always","other"]},mode:{type:"enum",values:["readonly","auto-edit","full-auto","custom","other"]},asked:{type:"int"},approved:{type:"int"},rejected:{type:"int"},expired:{type:"int"},decideSecTotal:{type:"int"},remoteAnswers:{type:"int"}},plugin_install:{id:{type:"id",max:80},entry:{type:"enum",values:["store","chat-card","muse-card","plugin-onboarding","deps","other"]},kind:{type:"enum",values:["plugin","skill","agent","space","theme","amadeus-plugin","other"]},source:{type:"enum",values:["github","npm","zip","other"]},stage:{type:"enum",values:["resolve","download","install","activate","done"]},outcome:{type:"enum",values:["done","error","canceled"]},errorClass:{type:"enum",values:["timeout","network","http","too-large","not-zip","integrity","identity","version","min-app","platform","deps","builtin","activate","disk","other"]},durationMs:{type:"int"},sizeKb:{type:"int"},restart:{type:"bool"}},plugin_deps:{total:{type:"int"},installed:{type:"int"},failedAt:{type:"int"},outcome:{type:"enum",values:["ready","not-ready","not-running","failed"]}},plugin_lifecycle:{id:{type:"id",max:80},action:{type:"enum",values:["uninstall","enable","disable","blocked"]},blockedReason:{type:"enum",values:["min-app","api","invalid","dev-fileext","deps","other"]},daysSinceInstall:{type:"int"},reason:{type:"enum",values:["unused","broken","slow","mistake"]}},plugin_load:{id:{type:"id",max:80},outcome:{type:"enum",values:["ok","error"]},activateMs:{type:"int"}},update:{target:{type:"enum",values:["app","engine","ui","builtin-plugin","store-plugin","first-boot-prefetch"]},id:{type:"id",max:80},outcome:{type:"enum",values:["available","not-available","staged","applied","current","error","incompatible","rolled-back","timeout","skipped"]},errorClass:{type:"enum",values:["network","http","integrity","signature","version","identity","incompatible","disk","other"]}},onboarding:{mode:{type:"enum",values:["full","returning","brief","update"]},outcome:{type:"enum",values:["finish","skip","error-skip"]},screens:{type:"int"},backJumps:{type:"int"},msStart:{type:"int"},msTheme:{type:"int"},msYou:{type:"int"},msTeam:{type:"int"},msWelcome:{type:"int"},signedIn:{type:"bool"},syncNotes:{type:"bool"},syncAgents:{type:"bool"},syncPlugins:{type:"bool"},addedAgent:{type:"bool"},museOn:{type:"bool"},computerHistoryOn:{type:"bool"},youWritten:{type:"bool"}},guide_tip:{pluginId:{type:"id",max:80},tipId:{type:"id",max:60},result:{type:"enum",values:["ok","learned","mute","gone","missing","replaced","closed"]}},command_use:{id:{type:"id",max:80},source:{type:"enum",values:["palette","hotkey","ribbon","agent","other"]},n:{type:"int"}},app_counts:{achChatSend:{type:"int"},achChatGroup:{type:"int"},achNoteCreate:{type:"int"},achNoteWikilink:{type:"int"},achNoteCanvas:{type:"int"},achBaseCreate:{type:"int"},achSpaceSave:{type:"int"},achSpaceSwitch:{type:"int"},achAgentCreate:{type:"int"},achAutomationCreate:{type:"int"},achMuseOpen:{type:"int"},achComputerUse:{type:"int"},achMarketInstall:{type:"int"},achThemeChange:{type:"int"},achTodoDone:{type:"int"},achCalendarEvent:{type:"int"},achAccountLogin:{type:"int"},achImageGenerate:{type:"int"},achDrawingCreate:{type:"int"},achMiniOpen:{type:"int"},achSpecialEnable:{type:"int"},chatStop:{type:"int"},chatRegenerate:{type:"int"},chatEditResend:{type:"int"},chatTruncateResend:{type:"int"},chatRetry:{type:"int"},chatRewind:{type:"int"},chatBranch:{type:"int"},chatSteer:{type:"int"},chatSteerWithdraw:{type:"int"},chatCompact:{type:"int"},chatRetryFailed:{type:"int"},searchOpen:{type:"int"},searchPick:{type:"int"},searchCloseEmpty:{type:"int"},providerLoginOk:{type:"int"},providerLoginFail:{type:"int"},byokSave:{type:"int"},byokImport:{type:"int"},byokImportStale:{type:"int"},byokDelete:{type:"int"},connTestOk:{type:"int"},connTestFail:{type:"int"},connTestAuthRejected:{type:"int"},modelSwitchUser:{type:"int"},modelSwitchRemember:{type:"int"},engineDefaultModelSet:{type:"int"},homeWidgetAdd:{type:"int"},homeWidgetRemove:{type:"int"},homeWidgetMove:{type:"int"},openNote:{type:"int"},openDatabase:{type:"int"},openDashboard:{type:"int"},openPdf:{type:"int"},openBoard:{type:"int"},openPluginFile:{type:"int"},openOther:{type:"int"}},sync_health:{system:{type:"enum",values:["vault","content","remote"]},day:{type:"id",max:10},cycles:{type:"int"},cycleMsTotal:{type:"int"},errAuth:{type:"int"},errOffline:{type:"int"},errVaultMissing:{type:"int"},errScan:{type:"int"},errMirrorMissing:{type:"int"},errHttp:{type:"int"},errTimeout:{type:"int"},errBlocked:{type:"int"},errOther:{type:"int"},conflicts:{type:"int"},skippedTooLarge:{type:"int"},skippedNotFound:{type:"int"},skippedExists:{type:"int"},skippedOther:{type:"int"},massDeleteGuard:{type:"int"},uploads:{type:"int"},downloads:{type:"int"}},daily_muse:{day:{type:"id",max:10},cyclesRule:{type:"int"},cyclesSchedule:{type:"int"},cyclesHeartbeat:{type:"int"},cyclesRunEnd:{type:"int"},cyclesModeAsk:{type:"int"},cyclesModeAgent:{type:"int"},cyclesModeAuto:{type:"int"},cyclesDone:{type:"int"},cyclesError:{type:"int"},cyclesAborted:{type:"int"},cyclesSilent:{type:"int"},cycleTokens:{type:"int"},cycleMs:{type:"int"},producedCards:{type:"int"},producedDms:{type:"int"},producedTodos:{type:"int"},producedStarters:{type:"int"},inboxMarked:{type:"int"},inboxUnmarked:{type:"int"},skipNoModel:{type:"int"},skipOutsideHours:{type:"int"},skipUserActive:{type:"int"},skipNothingDue:{type:"int"},skipAlreadyRunning:{type:"int"},skipBudgetBillable:{type:"int"},skipBudgetGross:{type:"int"},skipRestartCap:{type:"int"},skipRemoteLock:{type:"int"},skipSleepCleared:{type:"int"},dmProactive:{type:"int"},dmTodo:{type:"int"},dmApproval:{type:"int"},dmCard:{type:"int"},dmNotice:{type:"int"},dmRemind:{type:"int"},dmSuppressed:{type:"int"},dmAwaitingUser:{type:"int"},dmReadIn24h:{type:"int"},dmRepliedIn24h:{type:"int"},feedbackUp:{type:"int"},feedbackDown:{type:"int"},feedbackText:{type:"int"},todoCreated:{type:"int"},todoApproved:{type:"int"},todoInjected:{type:"int"},todoDone:{type:"int"},todoDismissed:{type:"int"},starterCreated:{type:"int"},starterUsed:{type:"int"},starterDismissed:{type:"int"},starterMuted:{type:"int"},ruleCreatedMuse:{type:"int"},ruleCreatedUser:{type:"int"},ruleObserveForced:{type:"int"},rulePromoted:{type:"int"},ruleExtended:{type:"int"},rulePaused:{type:"int"},ruleObservedHits:{type:"int"},approvalByAgent:{type:"int"},approvalUserApproved:{type:"int"},approvalUserRejected:{type:"int"},introAnswered:{type:"int"},introSkipped:{type:"int"},introWhenAnytime:{type:"int"},introWhenDaytime:{type:"int"},introWhenOpen:{type:"int"},introPaceAsNeeded:{type:"int"},introPaceDaily:{type:"int"},introPaceFree:{type:"int"},introFocusSchedule:{type:"int"},introFocusStudy:{type:"int"},introFocusProjects:{type:"int"},introFocusInbox:{type:"int"},introFocusCustom:{type:"int"},summarySent:{type:"int"},summaryProposed:{type:"int"},summaryAdopted:{type:"int"},summaryAskUpgrade:{type:"int"},sleepSet:{type:"int"},digestSent:{type:"int"},gEnabled:{type:"int"},gDaysEnabled:{type:"int"},gModeAsk:{type:"int"},gModeAgent:{type:"int"},gModeAuto:{type:"int"},gNotifyDigest:{type:"int"},gHeartbeatMin:{type:"int"},gMaxDmPerDay:{type:"int"},gOnboardingDay:{type:"int"},gRulesObserving:{type:"int"},gRulesEnabled:{type:"int"}},daily_muse_card:{day:{type:"id",max:10},cardKind:{type:"enum",values:["plugin","feature","inbox-ask","inbox-list","channel","settings","intro","summary","rule","rule-observed"]},created:{type:"int"},accept:{type:"int"},observe:{type:"int"},edit:{type:"int"},dismiss:{type:"int"},open:{type:"int"},apply:{type:"int"},yes:{type:"int"},later:{type:"int"},ignore:{type:"int"},ack:{type:"int"},item:{type:"int"},enable:{type:"int"},extend:{type:"int"},pause:{type:"int"},answer:{type:"int"},skip:{type:"int"},ok:{type:"int"},remove:{type:"int"},installed:{type:"int"},gone:{type:"int"},dismissIrrelevant:{type:"int"},dismissTiming:{type:"int"},dismissFrequent:{type:"int"},dismissKnown:{type:"int"},decideSecTotal:{type:"int"},decidedRemote:{type:"int"},gPendingOver3d:{type:"int"}},daily_memory:{day:{type:"id",max:10},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},addAgent:{type:"int"},addProject:{type:"int"},addPerson:{type:"int"},updateAgent:{type:"int"},updateProject:{type:"int"},updatePerson:{type:"int"},forgetAgent:{type:"int"},forgetProject:{type:"int"},forgetPerson:{type:"int"},moveScope:{type:"int"},srcExplicit:{type:"int"},srcHistorian:{type:"int"},srcDream:{type:"int"},srcManual:{type:"int"},srcRestore:{type:"int"},srcExternalEdit:{type:"int"},srcSync:{type:"int"},srcMigration:{type:"int"},errFull:{type:"int"},errVersionConflict:{type:"int"},errPortraitFull:{type:"int"},userEditAgentWritten7d:{type:"int"},userForgetAgentWritten7d:{type:"int"},userRestoreDreamRetired:{type:"int"},userEdit:{type:"int"},userForget:{type:"int"},userAdd:{type:"int"},userForgetWrong:{type:"int"},userForgetStale:{type:"int"},userForgetUnwanted:{type:"int"},userForgetDuplicate:{type:"int"},retellExisting:{type:"int"},retellForgotten:{type:"int"},candidatesAdded:{type:"int"},dreamAuto:{type:"int"},dreamManual:{type:"int"},dreamArchive:{type:"int"},dreamCompleted:{type:"int"},dreamSkipped:{type:"int"},dreamFailed:{type:"int"},dreamCancelled:{type:"int"},dreamCalls:{type:"int"},dreamSources:{type:"int"},dreamGroups:{type:"int"},dreamMerges:{type:"int"},dreamDiscarded:{type:"int"},dreamToPortrait:{type:"int"},dreamPending:{type:"int"},dreamDeferred:{type:"int"},dreamVerifyFail:{type:"int"},dreamRetried:{type:"int"},dreamMs:{type:"int"},harnessUpsertAgent:{type:"int"},harnessUpsertHistorian:{type:"int"},harnessUpsertMuse:{type:"int"},harnessUpsertUser:{type:"int"},harnessDelete:{type:"int"},harnessRollback:{type:"int"},gEntries:{type:"int"},gCharsPct:{type:"int"},gTombstones:{type:"int"},gCandidatesPending:{type:"int"},gCandidatesOldestDays:{type:"int"},gHarnessEntries:{type:"int"}},daily_judge:{day:{type:"id",max:10},rounds:{type:"int"},roundsIndependent:{type:"int"},roundsAssist:{type:"int"},roundsFork:{type:"int"},isolationSkips:{type:"int"},memCandidates:{type:"int"},projCandidatesAuto:{type:"int"},projCandidatesQueued:{type:"int"},projAdopted:{type:"int"},projDismissed:{type:"int"},projForgotten:{type:"int"},projRestored:{type:"int"},projCompacted:{type:"int"},harnessCandidatesAuto:{type:"int"},harnessCandidatesQueued:{type:"int"},signalStop:{type:"int"},signalToolLoop:{type:"int"},signalNudge:{type:"int"},signalCorrectionDecision:{type:"int"},signalCorrectionLexical:{type:"int"},titleUpdated:{type:"int"},summaryUpdated:{type:"int"},iconUpdated:{type:"int"}},daily_human:{day:{type:"id",max:10},wAgentShared:{type:"int"},wAgentAgent:{type:"int"},wAgentProject:{type:"int"},wAgentPortrait:{type:"int"},wAgentAgentMd:{type:"int"},wAgentMemory:{type:"int"},wUserShared:{type:"int"},wUserAgent:{type:"int"},wUserProject:{type:"int"},wUserPortrait:{type:"int"},wUserAgentMd:{type:"int"},wUserMemory:{type:"int"},srcRemember:{type:"int"},srcDream:{type:"int"},srcMove:{type:"int"},srcPromote:{type:"int"},srcUser:{type:"int"},userUndoAgentWrite7d:{type:"int"},moveScan:{type:"int"},moveMoved:{type:"int"},moveKept:{type:"int"},moveUndo:{type:"int"},promoteToAgentMd:{type:"int"},coldstartAgents:{type:"int"},coldstartPersonWrites:{type:"int"},coldstartRelearned:{type:"int"},mirrorConflicts:{type:"int"},syncConflictCopies:{type:"int"},gHumanMdEntries:{type:"int"},gAgentMdEntries:{type:"int"},gPortraitEntries:{type:"int"},gMemoryEntries:{type:"int"},gCalendarRows:{type:"int"},gAgentsWithHumanMd:{type:"int"},gAgentsTotal:{type:"int"}},quota_prompt:{entry:{type:"enum",values:["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","other"]},shown:{type:"int"},dismiss:{type:"int"},card:{type:"int"},points:{type:"int"},upgrade:{type:"int"},topup:{type:"int"},bgConvert:{type:"int"},bgSettings:{type:"int"},more:{type:"int"}},plugin_inventory:{day:{type:"id",max:10},id:{type:"id",max:80},source:{type:"enum",values:["store","builtin","local"]},installed:{type:"int"},enabled:{type:"int"},localCount:{type:"int"}},model_feedback:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},regenerate:{type:"int"},stop:{type:"int"},editResend:{type:"int"}},first_run:{outcome:{type:"enum",values:["done","error","aborted"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},sinceFirstLaunchS:{type:"int"},durationMs:{type:"int"}},forced_update:{stage:{type:"enum",values:["matched","downloading","waiting_idle","countdown_shown","postponed","installing","manual_prompt","target_below_threshold","never_idle","install_failed"]},reasons:{type:"id",max:80},target:{type:"id",max:40},policy:{type:"id",max:40}}}};var vI=vs.events,SI=vs.envelope,mf=vs.limits,Cb=vs.version,kI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,EI=/^[A-Za-z0-9._:/@+-]+$/,Ib=n=>typeof n=="string"&&kI.test(n),Rb=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,_I=[[/\/Users\/[^/\s]+\//gi,"~/"],[/\/home\/[^/\s]+\//gi,"~/"],[/[a-z]:\\Users\\[^\\\s]+\\/gi,"~\\"],[/~([/\\])[^\s"'`」:()]+/g,"~$1\u2026"],[/\/Volumes\/[^\s"'`」:()]+/g,"/Volumes/\u2026"],[/\b([d-z]):\\[^\s"'`」:()]+/gi,"$1:\\\u2026"],[/forsion-agent-space\/[^/\s]+\//g,"forsion-agent-space/\u2026/"],[/"[^"]{1,200}"/g,'"\u2026"'],[/'[^']{1,200}'/g,"'\u2026'"],[/`[^`]{1,200}`/g,"`\u2026`"],[/「[^「」]{1,200}」/g,"\u300C\u2026\u300D"],[/(https?:\/\/[^\s?#"'`」]+)[?#][^\s"'`」]*/gi,"$1"],[/sk-[A-Za-z0-9_-]{10,}/g,"[redacted]"],[/Bearer\s+\S+/gi,"[redacted]"],[/[0-9a-f]{32,}/gi,"[redacted]"],[/[A-Za-z0-9+/]{40,}={0,2}/g,"[redacted]"],[/[A-Za-z0-9_-]{40,}/g,"[redacted]"],[/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]"]],xb=n=>_I.reduce((e,[t,r])=>e.replace(t,r),n);function Ab(n,e,t){let r=n.slice(0,2e4).replace(/\u0000/g,"").replace(Rb,"\uFFFD");return t&&t.length>3&&(r=r.split(t).join("~")),r=xb(r),(r.length>e?r.slice(0,e):r).replace(Rb,"\uFFFD")}var Tb=/^pr-[a-f0-9]{48}$/,RI=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Db=n=>Tb.test(n)||RI.test(n)||xb(n)===n;function AI(n){if(typeof n!="string")return"";let e=n.search(/^\s+at /m);return e<0?"":n.slice(e)}function hf(n,e,t){switch(n.type){case"enum":return typeof e=="string"&&n.values.includes(e)?e:void 0;case"int":return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.min(Math.round(e),2147483647):void 0;case"bool":return typeof e=="boolean"?e:void 0;case"uuid":return Ib(e)?e.toLowerCase():void 0;case"iso-time":return typeof e=="string"&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():void 0;case"id":return typeof e=="string"&&e.length<=n.max&&EI.test(e)&&Db(e)?e:void 0;case"text":return typeof e=="string"&&e?Ab(e,n.max,t):void 0;case"stack":{let r=AI(e);return r?Ab(r,n.max,t):void 0}}}function fr(n,e){let t=typeof n?.event=="string"?vI[n.event]:void 0;if(!t)return null;let r={},i=n.props&&typeof n.props=="object"?n.props:{};for(let[a,s]of Object.entries(t)){let l=hf(s,i[a],e);l!==void 0&&(r[a]=l)}let o=hf({type:"iso-time"},n.ts);return{event:n.event,ts:o??new Date().toISOString(),...Ib(n.sessionId)?{sessionId:n.sessionId.toLowerCase()}:{},props:r}}function Pb(n){let e={};for(let[t,r]of Object.entries(SI)){if(t==="installId")continue;let i=hf(r,n[t]);e[t]=typeof i=="string"?i:null}return e}function Ob(n,e){if(e==="aborted")return"aborted";if(!n)return;let t=n.toLowerCase();return/abort|cancel/.test(t)?"aborted":/timeout|timed out|etimedout/.test(t)?"timeout":/token_quota_exceeded/.test(t)?"quota":/\b429\b|rate.?limit|too many requests|quota/.test(t)?"rate_limit":/\b40[13]\b|unauthori[sz]ed|forbidden|invalid api key|authentication/.test(t)?"auth":/context.{0,20}(length|window|too long)|maximum context|too many tokens|prompt is too long/.test(t)?"context_length":/econn|enotfound|eai_again|socket|network|fetch failed|getaddrinfo/.test(t)?"network":/\b5\d\d\b|upstream|bad gateway|overloaded|service unavailable/.test(t)?"upstream":/tool/.test(t)?"tool":"other"}function Mb(n){return n==="done"?"done":n==="failed"?"error":n==="aborted"?"aborted":"other"}function Gl(n){return n?/^pr-/.test(n)?"forsion":/^codex\//.test(n)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(n)?"local":"byok":"other"}var CI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function yf(n,e){if(typeof n!="string"||!n)return;let t=Gl(n);if((t==="codex"||t==="forsion"&&Tb.test(n))&&(e===void 0||e===t))return n;let i=n.slice(n.lastIndexOf("/")+1);return CI.test(i)?i:void 0}function wf(n){return n==="builtin"||n==="mcp"||n==="plugin"?n:"other"}function bf(n,e){return e==="plugin"?"plugin":e==="mcp"||n.startsWith("mcp__")?"mcp":n}var II=/^market-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i,xI=/^[a-z0-9][a-z0-9-]{0,79}$/;function Nb(n,e){if(typeof n!="string"||!n)return;let t=II.exec(n);if(t)return t[1].toLowerCase();if((e===!0||e===1)&&n.length<=80&&xI.test(n)&&Db(n))return n}function $b(n){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[n||"user"]??"other"}var NI=10*6e4,$I=6e4,LI=50,Ub=1024*1024,FI=168*36e5,Vb=15e3,BI=200,jI=2e3,kf=7,UI=5e3,zb=864e5,VI=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","quota_prompt","plugin_inventory","model_feedback","first_run"]),zI=new Set(["shown","dismiss","card","points","upgrade","topup","bgConvert","bgSettings","more"]),HI=1e3,qI=new Set(["matched","downloading","waiting_idle","countdown_shown","postponed","installing","manual_prompt","target_below_threshold","never_idle","install_failed"]),WI=new Set(["engine_busy","engine_error","engine_not_ready","voice","sync","transfers","extend_unknown","input","input_os","os_unknown","offered_below","none","declined","no_restart","still_old","tick_gap","aborted"]),GI=10,JI=80,KI=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/,YI=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,Ef=36e5,_f=2,Rf={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},XI=new Set(["custom-ask","escalate","mode","protected","control","always"]);function ZI(n){let e=n.props&&typeof n.props=="object"?n.props:{};if(n.event==="model_feedback"){let t=typeof e.modelId=="string"?e.modelId:void 0,r=yf(t,typeof e.providerKind=="string"?e.providerKind:"other");return r?{...n,props:{...e,modelId:r,providerKind:typeof e.providerKind=="string"?e.providerKind:Gl(t)}}:null}if(n.event==="plugin_inventory"){if(!bi(e.day))return null;if(e.source==="local"||e.id==="local")return{...n,props:{day:e.day,id:"local",source:"local",localCount:e.localCount}};let t=typeof e.id=="string"?e.id:"";return(e.source==="store"?!QI.test(t):e.source!=="builtin"||!(t.length<=80&&ex.test(t)))?null:{...n,props:{day:e.day,id:t,source:e.source,installed:e.installed,enabled:e.enabled}}}return n}var QI=/^(?:market-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ex=/^[a-z0-9][a-z0-9-]{0,79}$/,tx={model_feedback:"modelId",plugin_inventory:"id",quota_prompt:"entry"},nx=new Set(["readonly","auto-edit","full-auto","custom"]),qb=n=>new Date(n).toISOString().slice(0,19).replace("T"," "),Af=n=>({at:qb(n),id:"~"}),Ji=n=>typeof n=="string"?Date.parse(`${n.replace(" ","T")}Z`):NaN;async function rx(n,e,t,r){let i=Ki(n,"tangu","state.db");if(!await Hb(i).then(a=>a.isFile(),()=>!1))return{events:[],cursor:e};let o;try{let{DatabaseSync:a}=await import("node:sqlite");o=new a(i,{readOnly:!0}),o.exec("PRAGMA busy_timeout = 1500");let s=o.prepare(`SELECT r.id, r.status, r.current_step, r.model_id, substr(r.error, 1, 2000) AS error, r.created_at, r.updated_at, s.kind
|
|
259
265
|
FROM agent_runs r LEFT JOIN chat_sessions s ON s.id = r.session_id
|
|
260
266
|
WHERE r.status IN ('done', 'failed', 'aborted') AND (r.updated_at > ? OR (r.updated_at = ? AND r.id > ?)) AND r.updated_at < ?
|
|
261
|
-
ORDER BY r.updated_at, r.id LIMIT ?`).all(e.at,e.at,e.id,r??"9999-12-31 23:59:59",
|
|
267
|
+
ORDER BY r.updated_at, r.id LIMIT ?`).all(e.at,e.at,e.id,r??"9999-12-31 23:59:59",BI),l=o.prepare(`SELECT e.type, json_extract(e.payload, '$.id') AS id, json_extract(e.payload, '$.name') AS name, json_extract(e.payload, '$.source') AS source,
|
|
262
268
|
json_extract(e.payload, '$.isError') AS failed, json_extract(e.payload, '$.elapsedMs') AS ms,
|
|
263
269
|
json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
|
|
264
270
|
json_extract(e.payload, '$.phase') AS phase,
|
|
@@ -268,23 +274,21 @@ ${s}`,n),this.line=r,this.column=i,this.codeblock=s}};var _g=/^((0x[0-9a-fA-F](_
|
|
|
268
274
|
json_extract(e.payload, '$.pluginId') AS pluginId, json_extract(e.payload, '$.pluginOfficial') AS pluginOfficial, e.created_at AS at
|
|
269
275
|
FROM agent_run_events e
|
|
270
276
|
WHERE e.run_id = ? AND e.type IN ('usage', 'tool_call', 'tool_result', 'status', 'approval_request', 'approval_result') AND json_valid(e.payload)
|
|
271
|
-
ORDER BY e.seq LIMIT ?`),c=
|
|
277
|
+
ORDER BY e.seq LIMIT ?`),c=m=>`(SELECT total(json_extract(s.value, '$.tokens')) FROM json_each(e.payload, '$.sections') s WHERE json_extract(s.value, '$.k') = '${m}')`,u=o.prepare(`SELECT json_extract(e.payload, '$.telemetry.agentRole') AS agentRole, json_extract(e.payload, '$.telemetry.recallEntries') AS recallEntries,
|
|
272
278
|
json_extract(e.payload, '$.telemetry.recallHistory') AS recallHistory, json_extract(e.payload, '$.telemetry.recallTruncated') AS recallTruncated,
|
|
273
279
|
json_type(e.payload, '$.sections') AS sectionsType,
|
|
274
280
|
${c("memory")} AS memoryTokens, ${c("human")} AS humanTokens,
|
|
275
281
|
${c("profile")} AS profileTokens, ${c("project")} AS projectTokens
|
|
276
282
|
FROM agent_run_events e
|
|
277
283
|
WHERE e.run_id = ? AND e.type = 'status' AND json_valid(e.payload) AND json_extract(e.payload, '$.phase') = 'context_info'
|
|
278
|
-
ORDER BY e.seq LIMIT 1`),
|
|
279
|
-
WHERE day > ? AND day < ? AND day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' AND event IN (${
|
|
280
|
-
ORDER BY day LIMIT ?`).all(e,
|
|
281
|
-
`).filter(Boolean)}catch{return[]}},h=()=>
|
|
284
|
+
ORDER BY e.seq LIMIT 1`),d=m=>typeof m=="number"&&Number.isFinite(m)&&m>0?m:0,g=m=>typeof m=="string"&&m?m:void 0,f=[],p=e;for(let m of s){p={at:String(m.updated_at),id:String(m.id)};let y={llmCalls:0,tokensIn:0,tokensOut:0,tokensCached:0,retries:0},b=new Map,h=new Map,E=new Map,v=[],k=new Map;for(let M of l.all(m.id,jI))if(M.type==="usage")y.llmCalls++,y.tokensIn+=d(M.prompt),y.tokensOut+=d(M.completion),y.tokensCached+=d(M.cached);else if(M.type==="tool_call"||M.type==="tool_result"){if(typeof M.id=="string"&&M.source!=null&&h.set(M.id,M.source),typeof M.id=="string"&&M.pluginId!=null&&E.set(M.id,{pluginId:M.pluginId,official:M.pluginOfficial}),M.type!=="tool_result"||typeof M.name!="string")continue;let x=M.source??(typeof M.id=="string"?h.get(M.id):void 0),$=bf(M.name,x),O=wf(x),q=typeof M.id=="string"?E.get(M.id):void 0,ie=x==="plugin"?Nb(M.pluginId??q?.pluginId,M.pluginOfficial??q?.official):void 0,Y=`${$}\0${O}\0${ie??""}`,ne=b.get(Y)??{tool:$,toolSource:O,...ie?{pluginId:ie}:{},calls:0,failures:0,totalMs:0,maxMs:0};b.set(Y,ne),ne.calls++,M.failed&&ne.failures++,ne.totalMs+=d(M.ms),ne.maxMs=Math.max(ne.maxMs,d(M.ms))}else if(M.type==="approval_request")v.push({approvalId:g(M.approvalId),name:g(M.name),toolCallId:g(M.toolCallId),reasonKind:XI.has(M.reasonKind)?M.reasonKind:"other",mode:nx.has(M.reasonMode)?M.reasonMode:"other",at:Ji(M.at)});else if(M.type==="approval_result"){let x=g(M.approvalId);x&&!k.has(x)&&k.set(x,{action:g(M.action),via:g(M.via),at:Ji(M.at)})}else M.phase==="llm_retry"&&y.retries++;let C=u.all(m.id)[0],S=Mb(m.status),_=Ji(m.updated_at)-Ji(m.created_at),R=new Date(Number.isNaN(Ji(m.updated_at))?Date.now():Ji(m.updated_at)).toISOString(),N=fr({event:"agent_run",ts:R,sessionId:t,props:{modelId:yf(m.model_id),providerKind:Gl(m.model_id),mode:$b(m.kind),steps:d(m.current_step),...y,durationMs:Number.isFinite(_)&&_>=0?_:void 0,outcome:S,errorClass:S==="done"?void 0:Ob(m.error,m.status),...C?{agentRole:C.agentRole,recallEntries:C.recallEntries,recallHistory:C.recallHistory,recallTruncated:C.recallTruncated===1?!0:C.recallTruncated===0?!1:void 0,...C.sectionsType==="array"?{memoryTokens:C.memoryTokens,humanTokens:C.humanTokens,profileTokens:C.profileTokens,projectTokens:C.projectTokens}:{}}:{}}});N&&f.push(N);for(let M of b.values()){let x=fr({event:"tool_call",ts:R,sessionId:t,props:{...M,runOutcome:S}});x&&x.props.tool&&f.push(x)}let D=new Map;for(let M of v){if(!M.name)continue;let x=M.toolCallId?h.get(M.toolCallId):void 0,$=x==null?M.name.startsWith("mcp__")?"mcp":void 0:bf(M.name,x),O=wf(x),q=`${$??""}\0${O}\0${M.reasonKind}\0${M.mode}`,ie=D.get(q)??{tool:$,toolSource:O,reasonKind:M.reasonKind,mode:M.mode,asked:0,approved:0,rejected:0,expired:0,decideSecTotal:0,remoteAnswers:0};D.set(q,ie),ie.asked++;let Y=M.approvalId?k.get(M.approvalId):void 0;if(!Y){ie.expired++;continue}Y.action==="approve"||Y.action==="approve_always"?ie.approved++:Y.action==="reject"&&ie.rejected++;let ne=Math.round((Y.at-M.at)/1e3);Number.isFinite(ne)&&ne>0&&(ie.decideSecTotal+=ne),Y.via&&Y.via!=="local"&&ie.remoteAnswers++}for(let M of D.values()){let x=fr({event:"approval",ts:R,sessionId:t,props:M});x&&(x.props.tool||M.tool===void 0)&&f.push(x)}}return{events:f,cursor:p}}catch{return{events:[],cursor:e}}finally{try{o?.close()}catch{}}}async function ix(n,e,t){let r=Ki(n,"tangu","state.db"),i=await Hb(r).then(a=>a.isFile(),a=>a?.code==="ENOENT"||a?.code==="ENOTDIR"?!1:null);if(i===null)return null;if(!i)return{days:[],complete:!0};let o;try{let{DatabaseSync:a}=await import("node:sqlite");if(o=new a(r,{readOnly:!0}),o.exec("PRAGMA busy_timeout = 1500"),!o.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'telemetry_ledger'").all().length)return{days:[],complete:!0};let s=Object.keys(Rf),l=o.prepare(`SELECT DISTINCT day FROM telemetry_ledger
|
|
285
|
+
WHERE day > ? AND day < ? AND day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' AND event IN (${s.map(()=>"?").join(", ")})
|
|
286
|
+
ORDER BY day LIMIT ?`).all(e,t,...s,kf+1),c=o.prepare("SELECT event, dim, field, n FROM telemetry_ledger WHERE day = ? ORDER BY event, dim, field LIMIT ?"),u=[];for(let{day:d}of l.slice(0,kf)){if(!bi(d))continue;let g=new Map;for(let p of c.all(d,UI)){if(typeof p.event!="string"||!Object.hasOwn(Rf,p.event))continue;let m=Rf[p.event],y=typeof p.dim=="string"?p.dim:"";if((m?!y:y!=="")||typeof p.field!="string"||typeof p.n!="number")continue;let b=`${p.event}\0${y}`,h=g.get(b)??{event:p.event,dimKey:m,dim:y,fields:new Map};g.set(b,h),h.fields.set(p.field,(h.fields.get(p.field)??0)+p.n)}let f=[];for(let p of g.values()){let m=fr({event:p.event,ts:`${d}T23:59:59.000Z`,props:{...Object.fromEntries(p.fields),day:d,...p.dimKey?{[p.dimKey]:p.dim}:{}}});!m||m.props.day!==d||p.dimKey&&m.props[p.dimKey]===void 0||Object.keys(m.props).some(y=>y!=="day"&&y!==p.dimKey)&&f.push(m)}u.push({day:d,events:f})}return{days:u,complete:l.length<=kf}}catch{return null}finally{try{o?.close()}catch{}}}var ox=(n,e,t)=>fr({event:"sync_health",ts:`${n}T23:59:59.000Z`,props:{...t,system:e,day:n}}),sx=n=>["darwin","win32","linux"].includes(n)?n:"other",ax=n=>["arm64","x64","ia32"].includes(n)?n:"other",lx=()=>/^zh\b/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en";function Wb(n,e={}){let t=e.now??(()=>new Date),r=e.fetch??fetch,i=()=>n.homeDir(),o=()=>Ki(i(),"extend-telemetry.json"),a=()=>Ki(i(),"telemetry"),s=()=>Ki(a(),"queue.jsonl"),l=()=>Ki(a(),"sent.jsonl"),c=n.telemetry,u=()=>wi(t().getTime()-zb);Kh(()=>t().getTime());let d=()=>g()??{},g=()=>{let te;try{te=Fb(o(),"utf8")}catch(Z){return Z?.code==="ENOENT"?{}:null}try{let Z=JSON.parse(te);return Z&&typeof Z=="object"&&!Array.isArray(Z)?Z:null}catch{return null}},f=(te,Z=d())=>{let P={...Z,...te};vf(i(),{recursive:!0});let F=`${o()}.${process.pid}.tmp`;return jb(F,JSON.stringify(P,null,2),{encoding:"utf8",mode:384}),Bb(F,o()),P},p=()=>d().installId??f({installId:Lb()}).installId,m=()=>{try{return!!n.readCreds().token}catch{return!1}},y=(te=d())=>te.enabled!==!1&&te.noticeSeen===!0&&c?.packaged===!0&&m(),b=te=>{try{return Fb(te,"utf8").split(`
|
|
287
|
+
`).filter(Boolean)}catch{return[]}},h=()=>b(s()).flatMap(te=>{try{return[JSON.parse(te)]}catch{return[]}}),E=(te,Z)=>{if(vf(a(),{recursive:!0}),!Z.length){Sf(te,{force:!0});return}let P=`${te}.${process.pid}.tmp`;jb(P,Z.map(F=>JSON.stringify(F)).join(`
|
|
282
288
|
`)+`
|
|
283
|
-
`,{encoding:"utf8",mode:384}),
|
|
289
|
+
`,{encoding:"utf8",mode:384}),Bb(P,te)},v=0,k=null,C=null,S=()=>{v++,Sf(s(),{force:!0}),Sf(l(),{force:!0}),Jh(),k=null},_=()=>{let te=t().getTime(),Z=b(l()).flatMap(F=>{try{return[JSON.parse(F)]}catch{return[]}}),P=Z.filter(F=>te-F.at<FI);return P.length!==Z.length&&E(l(),P),P},R=0,N=!1,D=0,M=()=>{let te=g();if(!te)return kd(!1),!1;let Z=y(te);return Z&&te.closed?f({closed:void 0,cursor:Af(t().getTime()),ledgerCursor:u()},te):Z&&!bi(te.ledgerCursor)?f({ledgerCursor:u()},te):!Z&&!te.closed&&(R++,f({closed:!0},te)),kd(Z),Z},x=()=>{let te=g();if(!te){n.log("[forsion-extend] telemetry state unreadable; skipping the signed-in migration");return}if(te.signedInGate)return;let Z={signedInGate:1};!m()&&te.enabled===void 0&&te.noticeSeen===!0&&(Z.enabled=!1,Z.syncHealth=void 0,R++,S(),n.log("[forsion-extend] telemetry turned off: not signed in (sending now needs a Forsion account)")),f(Z,te)},$=te=>{if(!(!te.length||!y())){vf(a(),{recursive:!0}),TI(s(),te.map(Z=>JSON.stringify(Z)).join(`
|
|
284
290
|
`)+`
|
|
285
|
-
`,{encoding:"utf8",mode:384});try{if(ey(o()).size>gd){let A=h(),j=A.length,F=0;for(;j>0&&F+Buffer.byteLength(JSON.stringify(A[j-1]))+1<=gd/2;)F+=Buffer.byteLength(JSON.stringify(A[--j]))+1;T(o(),A.slice(j))}}catch{}h().length>=sy&&Q()}},ee=()=>{let C=f();return{available:!!c,enabled:C.enabled!==!1,noticeSeen:C.noticeSeen===!0,signedIn:y(),active:b(C),packaged:c?.packaged===!0,installId:m(),queued:Qm(o())?h().length:0,lastSentAt:C.lastSentAt??null,lastError:C.lastError??null}},J=()=>od({app:"desktop",appVersion:t.appVersion(),coreVersion:c?.coreVersion()??void 0,channel:c?.channel(),os:ky(process.platform),osVersion:ny(),arch:Ey(process.arch),locale:_y()}),se=td,te=async C=>{try{let A=await C.json?.();return!!A&&typeof A=="object"&&A.detail==="unsupported v"}catch{return!1}},ae=null,Q=()=>{if(ae)return ae;if(L||n().getTime()<V)return Promise.resolve();let C=x,A=v,j=(async()=>{try{for(let F=0;F<5;F++){let z=h();if(!z.length)return;let q=m(),ne={v:se,installId:q,...J()},re=[],Z=Buffer.byteLength(JSON.stringify({...ne,events:[]}));for(let X of z){let ve=Buffer.byteLength(JSON.stringify(X))+1;if(re.length>=Bo.maxEvents||Z+ve>Bo.maxBatchBytes)break;re.push(X),Z+=ve}if(!re.length){T(o(),z.slice(1));continue}let{base:ie}=await t.getCloud(),oe={...ne,events:re};if(!H()||C!==x)return;let pe=await r(`${ie.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(oe),signal:AbortSignal.timeout(md)}).catch(X=>({ok:!1,status:0,error:String(X?.message||X)})),le=pe.status;if(le===400&&ne.v>Ko&&await te(pe)){se=Ko,t.log(`[forsion-extend] telemetry server does not accept v${ne.v}; resending as v${Ko}`);continue}if(le>=200&&le<300||le===400||le===413){let X=new Set(re.map(ve=>JSON.stringify(ve)));T(o(),h().filter(ve=>!X.has(JSON.stringify(ve))))}if(le>=200&&le<300){let X=n().getTime();A===v&&T(l(),[...D(),{at:X,body:oe}]),p({lastSentAt:X,lastError:void 0});continue}if(le!==400&&le!==413){let X=Number(pe.headers?.get?.("retry-after"));V=n().getTime()+(Number.isFinite(X)&&X>0?Math.min(X,3600)*1e3:5*6e4)}p({lastError:le?`HTTP ${le}`:String(pe.error??"network error").slice(0,200)});return}}catch(F){try{p({lastError:String(F?.message||F).slice(0,200)})}catch{}}})();return ae=j,j.finally(()=>{ae===j&&(ae=null)}),j},me=C=>{if(!I||!C&&Math.floor(n().getTime()/wd)===I.hour)return;let A=I;if(I=null,A.gen!==x||!H())return;let j=Qt({event:"quota_prompt",ts:n().toISOString(),sessionId:c?.sessionId,props:{...A.counts,entry:"quota-page"}});try{j&&Object.keys(j.props).some(F=>F!=="entry")&&Y([j])}catch(F){throw I=A,F}},ge=async()=>{try{if(D(),me(!1),!H())return;let C=f(),A=x,j=C.cursor??Zo(n().getTime()),F=await by(i(),j,c?.sessionId,Sd(n().getTime()));if(!H()||A!==x)return;Y(F.events),F.cursor!==j&&p({cursor:F.cursor}),await Pe(A),await Q()}catch(C){t.log(`[forsion-extend] telemetry tick failed: ${String(C?.message||C)}`)}},Pe=async C=>{let A=n().getTime(),j=Tn(A),F=Tn(A-yd),z=f().ledgerCursor;if(In(z)||(z=F,p({ledgerCursor:z})),yo(z),z>=F){Ce();return}let q=await Sy(i(),z,j);if(!(!H()||C!==x)){if(q){let ne=q.complete?F:q.days[q.days.length-1]?.day??z;if(ne>z){let re=Vc(z,ne),Z=[...new Set([...q.days.map(oe=>oe.day),...re.map(oe=>oe.day)])].filter(oe=>oe>z&&oe<=ne).sort(),ie=[];for(let oe of Z){ie.push(...q.days.find(pe=>pe.day===oe)?.events??[]);for(let pe of re)if(pe.day===oe){let le=vy(oe,pe.system,pe.counts);le&&ie.push(le)}}Y(ie),p({ledgerCursor:ne}),yo(ne)}}Ce()}},Ce=()=>{if(!Wc())return;let C=g();if(!C)return;let A=qc();p({syncHealth:Object.keys(A).length?A:void 0},C),Gc()},He=c?.subscribe(C=>{try{if(!uy.has(C?.event)||!H())return;let A=hy(C);if(!A)return;let j=Qt({...A,sessionId:c.sessionId},ty()),F=yy[C.event];j&&(!F||j.props[F]!==void 0)&&Y([j])}catch(A){t.log(`[forsion-extend] telemetry event dropped: ${String(A?.message||A)}`)}}),Ae={ok:!1,error:"untrusted"};t.handle("telemetry:get",C=>t.isTrustedSender(C)?(H(),ee()):Ae),t.handle("telemetry:set",(C,A)=>{if(!t.isTrustedSender(C))return Ae;let j=f(),F={};typeof A?.enabled=="boolean"&&(F.enabled=A.enabled),A?.noticeSeen===!0&&(F.noticeSeen=!0);let z={...j,...F};return!b(j)&&b(z)&&(F.cursor=Zo(n().getTime()),F.ledgerCursor=u()),b(j)&&!b(z)&&x++,F.enabled===!1&&(F.syncHealth=void 0),p(F),F.enabled===!1&&E(),H(),ee()}),t.handle("telemetry:quotaPrompt",(C,A)=>{if(!t.isTrustedSender(C))return Ae;let j=A?.action;return A?.entry!=="quota-page"||typeof j!="string"||!dy.has(j)?{ok:!1,error:"invalid"}:(me(!1),H()?((!I||I.gen!==x)&&(I={hour:Math.floor(n().getTime()/wd),gen:x,counts:{}}),I.counts[j]=Math.min((I.counts[j]??0)+1,fy),{ok:!0,counted:!0}):{ok:!0,counted:!1})}),t.handle("telemetry:sent",C=>t.isTrustedSender(C)?{batches:D()}:Ae),t.handle("telemetry:delete",async C=>{if(!t.isTrustedSender(C))return Ae;L=!0,x++;try{await ae?.catch(()=>{});let A=m(),{base:j}=await t.getCloud(),z=(await r(`${j.replace(/\/+$/,"")}/api/telemetry/install/${A}`,{method:"DELETE",signal:AbortSignal.timeout(md)}).catch(q=>({ok:!1,status:0,error:String(q?.message||q)}))).status;return z>=200&&z<300?(E(),p({installId:dd(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),ee()):{ok:!1,error:z?`HTTP ${z}`:"network error"}}finally{L=!1}});try{Bc(f().syncHealth),N(),H()}catch(C){t.log(`[forsion-extend] telemetry startup check failed: ${String(C?.message||C)}`)}let ut=t.addFlushHook?.(C=>{if(C!=="blur"){try{Ce()}catch{}try{me(!0)}catch{}}}),M=setTimeout(()=>void ge(),iy),U=setInterval(()=>void ge(),ry);return M.unref?.(),U.unref?.(),t.log(`[forsion-extend] telemetry registered (${c?c.packaged?"packaged":"dev build: never sends":"host has no telemetry seam: never sends"})`),Object.assign(()=>{clearTimeout(M),clearInterval(U),He?.(),ut?.()},{tick:ge,flush:Q})}import{readFileSync as Gn,lstatSync as Zy,statSync as Qy,renameSync as ew,linkSync as tw,unlinkSync as aa,readdirSync as nw,rmdirSync as rw,writeFileSync as iw,mkdirSync as sw,copyFileSync as ow,constants as aw}from"node:fs";import{readFile as Pr,writeFile as $r,mkdir as la,rename as rs,readdir as jr,lstat as Bt,stat as ca,unlink as Lr}from"node:fs/promises";import{join as Fe,dirname as wn,relative as Fr,sep as Vn}from"node:path";import{hostname as ua}from"node:os";import{createHash as lw,randomUUID as mt}from"node:crypto";import{isUtf8 as da}from"node:buffer";import{Readable as cw}from"node:stream";import{performance as fa}from"node:perf_hooks";import{setImmediate as uw}from"node:timers/promises";var Cy=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],Ay=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],Or=".memory-tombstones.json",Ed=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),kd=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),xy=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)&&Number.isFinite(Date.parse(`${t}T00:00:00Z`))&&new Date(`${t}T00:00:00Z`).toISOString().slice(0,10)===t,Ty=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function Iy(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===Or)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:Cy.includes(t)||Ed(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&xy(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var Ry=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),Dy=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,Oy=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function Gi(t){let e=t.slice(t.lastIndexOf("/")+1);return Dy.test(e)||Oy.test(e)}function _d(t,e,n=1){let r=t.lastIndexOf("/"),i=r<0?"":t.slice(0,r+1),s=r<0?t:t.slice(r+1),a=s.lastIndexOf("."),o=a>0?s.slice(0,a):s,l=a>0?s.slice(a):"",c=f=>String(f).padStart(2,"0"),u=`${e.getFullYear()}-${c(e.getMonth()+1)}-${c(e.getDate())} ${c(e.getHours())}${c(e.getMinutes())}${n>1?` ${n}`:""}`;return`${i}${o} (conflict ${u})${l}`}function Qo(t,e="file"){if(t==="agents"||t==="human")return e==="folder";let n=t.startsWith("human/"),r=t.startsWith("agents/");if(!n&&!r)return null;if(Gi(t))return!1;if(n){let c=t.slice(6);return e==="folder"?kd(c):Ay.includes(c)||Ed(c)}let i=t.slice(7),s=i.indexOf("/"),a=s<0?i:i.slice(0,s),o=s<0?"":i.slice(s+1);if(!Ty(a)||Ry(a))return!1;if(e==="file")return Iy(o);if(o===""||o==="LOG"||kd(o))return!0;let l=o.split("/");return l[0]==="Library"&&l.every(c=>c&&!c.startsWith(".")&&!c.endsWith(".")&&!c.endsWith(" "))}import{isAbsolute as My}from"node:path";var it=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Dt=t=>typeof t=="string",hn=t=>Dt(t)&&t.length>0,Ut=t=>typeof t=="boolean",gn=t=>typeof t=="number"&&Number.isFinite(t),zn=t=>gn(t)&&Number.isSafeInteger(t)&&t>=0,Cd=t=>gn(t)&&Number.isInteger(t)&&t>=0,xd=t=>zn(t)&&t>0,mn=t=>Dt(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),Ji=t=>Dt(t)&&/^[a-f0-9]{64}$/.test(t),ea=t=>Dt(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),Mr=(t,e)=>Dt(t)&&e.includes(t),be=(t,e)=>t===void 0||e(t),Td=(t,e,n)=>e.every(r=>be(t[r],n)),Id=t=>Dt(t)&&!t.includes("\0")&&My(t);function Ht(t,e=!1){try{return Xt(t,e),!0}catch{return!1}}var Rd=t=>Ht(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,Dd=t=>t===""||mn(t);function Yi(t,e){let n=t.indexOf(":");return n>0&&mn(e)&&t.slice(n+1)===e&&ea(t.slice(0,n))}function Ny(t,e){return it(e)&&Yi(t,e.id)&&Ht(e.path)&&hn(e.version)&&Ji(e.hash)&&Td(e,["base","inode","stat"],Dt)&&be(e.statAt,gn)&&be(e.memoryDeleted,Ut)&&be(e.file,hn)}function Py(t,e){return it(e)&&Yi(t,e.localId)&&mn(e.id)&&Ht(e.path)&&xd(e.revision)&&Dd(e.parentId)&&Rd(e.name)}function $y(t){return it(t)&&mn(t.id)&&Ht(t.path)&&ea(t.target)&&Mr(t.direction,["upload","download","merge","rename","delete"])&&Mr(t.state,["queued","active","done","failed","paused","conflict"])&&zn(t.done)&&(t.size===null||zn(t.size))&&gn(t.at)&&be(t.error,Dt)&&be(t.finishedAt,gn)}function jy(t){return it(t)&&Ht(t.path)&&Ji(t.hash)&&Dt(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&be(t.parentId,mn)&&be(t.stageRoot,Id)&&be(t.stageIdentity,Vt)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&Cd(t.stageDev)&&Cd(t.stageIno))}function Ly(t){return it(t)&&Ht(t.prefix,!0)&&Id(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Vt(t))}function Fy(t){return it(t)&&Mr(t.state,["running","done"])&&Ut(t.seen)&&Td(t,["name","folderId","shelfId","shelfName"],Dt)&&be(t.files,zn)&&be(t.at,gn)&&be(t.rewritten,Ut)}function Ad(t){return it(t)&&hn(t.key)&&ea(t.ns)&&mn(t.id)&&Ht(t.path)&&Mr(t.side,["cloud","local"])}function Uy(t){return it(t)&&Ut(t.latched)&&Hn(t.pending,Ad)&&be(t.confirmed,e=>Hn(e,hn))&&be(t.restore,e=>Hn(e,Ad))}var Vi=(t,e)=>it(t)&&Object.entries(t).every(([n,r])=>e(n,r)),Hn=(t,e)=>Array.isArray(t)&&t.every(e);function Od(t){if(!it(t)||!it(t.config)||!zn(t.config.revision)||!Ut(t.owned)||!Ut(t.paused)||!Vi(t.files,Ny)||!Vi(t.folders,Py)||!Hn(t.jobs,$y)||!be(t.accountReview,Ut)||!be(t.deleteGuard,Uy)||!be(t.agentArchive,Fy)||!be(t.roots,e=>Hn(e,Ly))||!be(t.trash,e=>Hn(e,jy))||!be(t.unconfirmed,e=>Vi(e,(n,r)=>Yi(n,n.slice(-36))&&Ji(r)))||!be(t.pendingUploads,e=>Vi(e,(n,r)=>it(r)&&Yi(n,r.id)&&Ht(r.path))))throw Error("Invalid content sync state; original data was retained");Zt(t.config,t.config.revision)}function Md(t){return it(t)&&mn(t.id)&&Dd(t.parentId)&&Rd(t.name)&&Ht(t.path)&&Mr(t.kind,["file","folder"])&&xd(t.revision)&&Ut(t.deleted)&&be(t.busy,Ut)&&be(t.version,hn)&&be(t.hash,Ji)&&be(t.size,zn)&&be(t.mtime,gn)&&be(t.file,hn)&&t.version===void 0==(t.hash===void 0)}function Nd(t){return Md(t)&&t.deleted===!0}function Ki(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!it(t)||t.schemaVersion!==1||t.namespace!==e||!hn(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,i=new Set;for(let s of t.nodes){if(!Md(s)||r.has(s.id)||!s.deleted&&i.has(s.path))throw n();r.set(s.id,s),s.deleted||i.add(s.path)}for(let s of r.values()){let a=s.parentId?r.get(s.parentId):void 0;if(s.parentId&&(!a||a.kind!=="folder"||a.deleted&&!s.deleted)||s.path!==(a?a.path+"/"+s.name:s.name))throw n()}}import{constants as Pd,lstatSync as yn,readdirSync as Hy,readFileSync as zy,renameSync as Xi,unlinkSync as By,linkSync as qy,mkdirSync as es,realpathSync as ta,rmdirSync as Wy}from"node:fs";import{open as Fd,lstat as Zi,readdir as $d,realpath as Ud,readFile as na,writeFile as Gy,mkdir as Hd,unlink as Vy}from"node:fs/promises";import{join as zt,dirname as Qi,relative as ra,sep as ts}from"node:path";import{randomUUID as zd,createHash as Yy}from"node:crypto";var Nr=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,Bn=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),Bd=".forsion-sync-id.json",Jy=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),jd=t=>!Jy.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),Oe=t=>Yy("sha256").update(t).digest("hex");function qd(t){if(process.platform==="win32"&&t.split("/").some(e=>/[:*?"<>|]/.test(e)||/^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\..*)?$/i.test(e)))throw Error("This name is not a safe Windows file destination")}async function ct(t,e,n=!1){if(n){if(e.split("/").some(o=>o===".."||o==="."||!o)||e.startsWith("/")||e.includes("\\"))throw Error("Invalid internal content path")}else Xt(e,!0);qd(e);let r=await Ud(t),i=zt(r,...e.split("/").filter(Boolean)),s=ra(r,i);if(s===".."||s.startsWith(".."+ts))throw Error("Content path escapes root");let a=r;for(let o of s.split(ts).filter(Boolean)){a=zt(a,o);try{if((await Zi(a)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(l){if(l.code!=="ENOENT")throw l}}return i}function vt(t,e,n=!1){if(n||Xt(e,!0),qd(e),e.split("/").some(s=>s===".."||s===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let i=ta(t);for(let s of e.split("/").filter(Boolean)){i=zt(i,s);try{if(yn(i).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(a){if(a.code!=="ENOENT")throw a}}return i}var Ld=t=>t?.code!=="ENOENT";async function ns(t){let e=new Map,n=[],r=[],i=new Set,s=t.filter(u=>u.prefix).map(u=>u.prefix),a=[];for(let u of t)try{a.push({...u,root:await Ud(u.root)})}catch(f){if(f.code!=="ENOENT")throw f}if(new Set(a.map(u=>u.root)).size!==a.length)throw Error("Managed roots refer to the same directory; choose a separate vault folder");let o=u=>{try{return Xt(u),!0}catch{return!1}},l=async u=>{let f;try{f=await $d(u,{withFileTypes:!0})}catch{return}for(let g of f){if(!jd(g.name)||!g.isDirectory()&&!g.isFile())continue;let p=zt(u,g.name);try{let m=await Zi(p);if(m.isSymbolicLink())continue;i.add(Bn(m).inode),m.isDirectory()&&await l(p)}catch{}}};for(let u of a){let f=u.root;if(!(await Zi(f)).isDirectory())throw Error(`Sync root is not a directory: ${u.prefix||"Forsion"}`);let g=async(p,m)=>{let y;try{y=await Zi(p)}catch(h){if(!m||p===f)throw h;Ld(h)&&(n.push({path:m,reason:"unreadable"}),r.push(m));return}if(y.isSymbolicLink()||p!==f&&a.some(h=>h!==u&&h.root===p)||m&&u.prefix===""&&s.some(h=>m===h||m.startsWith(h+"/")))return;if(m&&!o(m)){n.push({path:m,reason:"invalid-name"}),i.add(Bn(y).inode),y.isDirectory()&&await l(p);return}let b,_=null;if(y.isDirectory())try{try{let h=JSON.parse(await na(zt(p,Bd),"utf8"));/^[a-f0-9-]{36}$/i.test(h.id)&&(b=h.id)}catch(h){if(h.code!=="ENOENT"&&!(h instanceof SyntaxError))throw h}_=await $d(p,{withFileTypes:!0})}catch(h){if(!m||p===f)throw h;if(!Ld(h))return;n.push({path:m,reason:"unreadable"}),r.push(m);return}if(m&&e.set(m,{path:m,physical:p,root:f,kind:y.isDirectory()?"folder":"file",localId:b,...Bn(y),size:y.isFile()?y.size:0}),!!_)for(let h of _)!jd(h.name)||!h.isDirectory()&&!h.isFile()||await g(zt(p,h.name),m?`${m}/${h.name}`:h.name)};await g(f,u.prefix)}let c=[...e.values()].sort((u,f)=>u.path.split("/").length-f.path.split("/").length||u.path.localeCompare(f.path));return Ky(c,{skipped:n,unscanned:r,skippedInodes:i})}function Ky(t,e){for(let[n,r]of Object.entries(e))Object.defineProperty(t,n,{value:r,enumerable:!1,configurable:!0});return t}var qn=(t,e)=>t.some(n=>e===n||e.startsWith(n+"/"));async function ia(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await ct(t.root,ra(t.root,zt(t.physical,Bd)).split(ts).join("/"),!0),n=zd();try{let r=await Fd(e,"wx",384);try{await r.writeFile(JSON.stringify({version:1,id:n})+`
|
|
286
|
-
`)}finally{await r.close()}return t.localId=n,n}catch(r){if(r.code!=="EEXIST")throw r;let i=JSON.parse(await na(e,"utf8"));if(!/^[a-f0-9-]{36}$/i.test(i.id))throw Error("Invalid folder sync identity");return t.localId=i.id,i.id}}async function Wn(t){let e=await ct(t.root,ra(t.root,t.physical).split(ts).join("/")),n=await Fd(e,Pd.O_RDONLY|(Pd.O_NOFOLLOW||0));try{if((await n.stat()).size>50*1024*1024)throw Error("File exceeds 50 MB content limit");return await n.readFile()}finally{await n.close()}}function Ke(t,e){Xt(e);let n=[...t].sort((r,i)=>i.prefix.length-r.prefix.length).find(r=>!r.prefix||e===r.prefix||e.startsWith(r.prefix+"/"));if(!n)throw Error("Content root unavailable");return{root:n.root,relative:n.prefix?e.slice(n.prefix.length).replace(/^\//,""):e}}async function sa(t,e,n,r,i=async(s,a)=>a()){let s=Ke(t,e);await Hd(s.root,{recursive:!0});let a=await ct(s.root,s.relative),o=await na(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});if((o?Oe(o):null)!==r)throw Error("Local file changed during download");let l=zt(s.root,`.forsion-sync-${zd()}.tmp`);try{await Gy(l,n,{flag:"wx",mode:384}),await ct(s.root,s.relative),await i(a,()=>{vt(s.root,s.relative),es(Qi(a),{recursive:!0}),vt(s.root,s.relative);let c=null;try{c=zy(a)}catch(u){if(u.code!=="ENOENT")throw u}if((c?Oe(c):null)!==r)throw Error("Local file changed during download");Xi(l,a)})}finally{await Vy(l).catch(()=>{})}}async function Wd(t,e,n=async(r,i)=>i()){let r=Ke(t,e);await Hd(r.root,{recursive:!0});let i=await ct(r.root,r.relative);await n([i],()=>{vt(r.root,r.relative),es(i,{recursive:!0})})}async function oa(t,e,n,r=async(i,s)=>s()){let i=Ke(t,e),s=Ke(t,n);if(i.root!==s.root)throw Error("Folder move crosses a managed source");let a=await ct(i.root,i.relative),o=await ct(s.root,s.relative);await r([a,o],()=>{if(vt(i.root,i.relative),vt(s.root,s.relative),Xy(o)){let c=yn(a),u=yn(o),f=ta(Qi(a));if((c.dev===u.dev&&c.ino===u.ino&&f===ta(Qi(o))?Hy(f).filter(m=>{let y=yn(zt(f,m));return y.dev===c.dev&&y.ino===c.ino}):[]).length!==1)throw Error("Local rename destination exists");Xi(a,o);return}es(Qi(o),{recursive:!0});let l=yn(a);if(l.isDirectory()){if(process.platform==="win32"){Xi(a,o);return}es(o,{mode:448});try{Xi(a,o)}catch(c){try{Wy(o)}catch{}throw c}}else{qy(a,o);let c=yn(a);if(c.ino!==l.ino||c.dev!==l.dev)throw Error("Source changed during rename");By(a)}})}function Xy(t){try{return yn(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Gd=(t,e,n,r,i)=>JSON.stringify([t,e,n,r,i]),Ot=(t,e,n)=>`${t}:${e}:${n}`,Vd=t=>({key:t.key,ns:t.ns,id:t.id,path:t.path,side:t.side}),Yd=t=>lw("sha256").update(t.map(e=>e.key).sort().join(`
|
|
287
|
-
`)).digest("hex").slice(0,24),dw=(t,e)=>t.length===e.length&&t.every(n=>e.some(r=>n.prefix===r.prefix&&n.root===r.root&&(n.dev===void 0||an(n,r)))),fw=()=>({config:structuredClone(du),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),qt=ji,pw=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CLOSED"]),hw=t=>{let e=t;return!!e&&(e.name==="TypeError"&&/fetch failed/i.test(e.message??"")||pw.has(String(e.cause?.code??e.code??"")))},gw=t=>{let e=t;return e&&e.code==="TOO_LARGE"&&Number.isSafeInteger(e.maxBytes)&&e.maxBytes>0?e.maxBytes:null},mw=t=>`l:${t.size}:${t.mtime}`,yw=10*6e4,Jd=1024*1024,Re=(t,e)=>`${t}:${e}`,Wt=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",bn=t=>t.slice(t.lastIndexOf("/")+1),Yn=Oe(""),ww=t=>/\.db$/i.test(t)&&!/^(agents|human)(\/|$)/.test(t),is=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),en=t=>t.split("/").length,Ue=t=>t instanceof Error?t.message:String(t),bw={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},pa=t=>t.file.replace(/\.json$/,".bases"),Qd=5e3,Sw=3e4,Kd=3e4,vw=3e3,ss=10*6e4,kw=60*6e4,Ew=10*6e4,_w=3*6e4,Xd=2e3,Cw=1440*6e4,ha=t=>/^(agents|human)\//.test(t)?Sw:Qd,Aw=t=>Math.max(t.mtime,t.ctime);async function*tn(t){let e=fa.now()+8;for(let n of t)fa.now()>=e&&(await uw(),e=fa.now()+8),yield n}function ef(t){if(!t.contentSync)return;let e=new ga(t);for(let[n,r]of Object.entries({[gt.get]:(i,s)=>e.snapshot(i,s),[gt.preview]:i=>e.preview(i),[gt.apply]:(i,s)=>e.apply(typeof i=="string"?i:"",s),[gt.run]:()=>{e.retrySoon(),e.touch(),e.kick()},[gt.pause]:i=>e.pause(i===!0),[gt.retry]:()=>{e.retryFailed(),e.touch(),e.kick()},[gt.rename]:i=>e.rename(i),[gt.setup]:i=>e.setup(i),[gt.archiveSeen]:()=>e.archiveSeen(),[gt.confirmDeletes]:i=>e.confirmDeletes(typeof i=="string"?i:""),[gt.abandonDeletes]:i=>e.abandonDeletes(typeof i=="string"?i:"")}))t.handle(n,async(i,...s)=>{if(!t.isTrustedSender(i))return{ok:!1,error:"untrusted"};try{return{ok:!0,value:await r(...s)}}catch(a){return{ok:!1,error:Ue(a)}}});t.addQuitGuard?.(n=>e.running&&!e.quitting?{message:n==="zh"?"\u8FD8\u6709\u5185\u5BB9\u6B63\u5728\u540C\u6B65":"Content is still syncing"}:null),t.addFlushHook?.(n=>e.flush(n)),_u(()=>e.stats()),e.start()}var ga=class{session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;activeAt=Date.now();lastRunAt=0;focused=!1;devices=[];others;deviceId="";customName="";serial=Promise.resolve();scheduled=null;tick=null;first=null;blocked=new Map;phase="idle";lastError;get error(){return this.lastError}set error(e){this.lastError=e,e&&this.fault(e)}runLog=new xr;logAccount=null;runAccount=null;blockedError=void 0;live(){let e=this.host.accountId();return!!e&&e===this.logAccount&&(!this.running||!this.runAccount||this.runAccount===e)}tally(e){this.live()&&this.runLog.count(e)}fault(e,n=[]){this.live()&&this.runLog.fault(e,n)}health=Ei((e,n,r)=>lt("content",e,n,r));httpStatus=0;closed=!1;runFinished=Promise.resolve();archiving=null;archiveRetry={account:"",at:0};resolving=!1;awaitingBytes=new Map;scanned={skipped:[],unscanned:[],skippedInodes:new Set};deleteStamps=[];failures=new Map;tooLarge=new Map;tooLargeSeen=null;recordsAccount=null;roundVisited=null;bypassBackoff=!1;bypassThisRound=!1;limitsByNs=new Map;round=null;uiLocale=null;running=!1;quitting=!1;again=!1;flushing=null;flushRequest=0;flushThrough=0;dirty=new Map;flushAt=0;due=null;registered=null;devicesAt=0;changedAt=0;wroteLocal=!1;openJobs=new Set;host;options;accountGeneration=0;stopAccountWatch;constructor(e,n={}){this.host=e,this.options=n,this.stopAccountWatch=Kl(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{this.idleSkip()||this.run()},3e4)).unref?.(),(this.first=setTimeout(()=>{this.run()},5e3)).unref?.()}locale(){if(this.uiLocale)return this.uiLocale;try{return/^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en"}catch{return"zh"}}archiveStep(e){if(e.stored.accountReview||e.stored.agentArchive?.state==="done"||this.archiveRetry.account===e.account&&Date.now()<this.archiveRetry.at)return Promise.resolve();let n=()=>{this.archiveRetry={account:e.account,at:Date.now()+ss}};return this.archiving??=(async()=>{try{let r=this.host.readCreds();if(!r.token)return;let i=await this.gatedFetch(e,r.cloudUrl,"/api/remotesync/agent-archive",{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({locale:this.locale()})},6e4);if(this.guard(e),!i.ok){n();return}let s=await i.json();if(this.guard(e),s.state!=="done"&&s.state!=="running"){n();return}let a=e.stored.agentArchive,o=s.archive;a?.rewritten||this.turnAgentsOff(e);let l={rewritten:!0,seen:a?.seen??!1,state:s.state};s.state==="done"&&(o?.folderId?Object.assign(l,{folderId:o.folderId,name:o.name??void 0,shelfId:o.shelfId??void 0,shelfName:o.shelfName??void 0,files:o.files??0,at:o.at??Date.now()}):l.seen=!0),e.stored.agentArchive=l,await this.persist(e)}catch(r){if(Ue(r)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${Ue(r)}`)}finally{this.archiving=null}})()}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=Su(n);if(!r)return;e.stored.config=Zt(r,n.revision+1);let i=s=>s==="agents"||s.startsWith("agents/");for(let[s,a]of Object.entries(e.stored.files))i(a.path)&&(delete e.stored.files[s],delete e.stored.unconfirmed?.[s]);for(let[s,a]of Object.entries(e.stored.folders))i(a.path)&&delete e.stored.folders[s];for(let[s,a]of Object.entries(e.stored.pendingUploads??{}))i(a.path)&&delete e.stored.pendingUploads[s];this.previewValue=null}async archiveSeen(){let e=await this.getSession();e.stored.agentArchive&&(e.stored.agentArchive.seen=!0,await this.persist(e))}async close(){this.closed=!0,this.stopAccountWatch(),this.tick&&clearInterval(this.tick),this.first&&clearTimeout(this.first),this.scheduled&&clearTimeout(this.scheduled),this.due&&clearTimeout(this.due),this.session?.abort.abort(),await this.watcher?.close(),await this.runFinished}currentBinding(e){if(!e.binding)return!0;let n=dr(e.binding.file);return n!==null&&!n.pending&&n.account===e.binding.account&&n.epoch===e.binding.epoch}guard(e,n=!0){if(this.closed)throw Error("content_sync_closed");if(Zs(this.host),this.host.accountId()!==e.account||this.session!==e||e.generation!==this.accountGeneration)throw Error("account_changed");if(!this.currentBinding(e))throw Error("content_account_changed_preview_required");n&&e.abort.signal.throwIfAborted()}async accountWrite(e,n){let r=async()=>{this.guard(e),await n(e.account),this.guard(e)};this.host.accountTransition?await this.host.accountTransition(r):await r()}async persist(e){let n=e.writes.catch(()=>{}).then(async()=>{this.guard(e,!1);let r=JSON.stringify(e.stored);if(r===e.persisted)return;await la(wn(e.file),{recursive:!0,mode:448});let i=e.file+".tmp-"+mt();try{await $r(i,r,{mode:384,flag:"wx"}),this.guard(e,!1),await rs(i,e.file),e.persisted=r}finally{await Lr(i).catch(()=>{})}});return e.writes=n,n}async getSession(){let e=this.host.accountId();if(!e)throw this.logAccount&&(this.runLog.reset(),this.logAccount=null),this.session?.abort.abort(),this.session=null,Error("not_signed_in");let n=this.accountGeneration;return Zs(this.host),this.initializing?this.initializing.then(r=>(this.guard(r),r)):this.session?.account===e&&this.session.generation===n&&this.currentBinding(this.session)?(this.guard(this.session,!1),this.session):(this.session?.abort.abort(new Error("account_changed")),this.logAccount!==e&&(this.runLog.reset(),this.logAccount=e),this.initializing=(async()=>{await this.watcher?.close(),this.watcher=null,this.previewValue=null,this.sources=[],this.agentNames.clear(),this.cloudAgents=void 0,this.devices=[],this.dirty.clear(),this.registered=null,this.devicesAt=0,this.changedAt=0;let r=Fe(this.host.homeDir(),"content-sync"),i=Fe(r,Oe(e)+".json"),s=fw();try{let f=JSON.parse(await Pr(i,"utf8"));Od(f),s={...s,...f,config:Zt(f.config,f.config.revision)},s.jobs=Array.isArray(f.jobs)?f.jobs.slice(-200):[]}catch(f){if(f.code!=="ENOENT")throw Error("Invalid content sync state; original data was retained")}let a,o=Fe(this.host.homeDir(),"content-sync-device.json"),l=async()=>{let f=JSON.parse(await Pr(o,"utf8"));if(typeof f?.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(f.id))throw Error("Invalid device sync ID");return f};try{a=await l()}catch(f){if(f.code!=="ENOENT")throw f;a={id:mt()},await la(wn(o),{recursive:!0});try{await $r(o,JSON.stringify(a),{flag:"wx",mode:384})}catch(g){if(g.code!=="EEXIST")throw g;a=await l()}}if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=a.id,this.customName=typeof a.name=="string"?a.name:"";let c=await this.host.contentSync.roots();if(this.host.accountId()!==e)throw Error("account_changed");let u={account:e,generation:n,file:i,stored:s,roots:c,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map,tombstones:new Map};return this.session=u,await this.bindAccount(u),await this.recoverTrash(u),this.guard(u),s.owned&&await this.accountWrite(u,f=>this.host.contentSync.claim(!0,f)),this.setSources(await this.scan(u,c).catch(f=>(this.error=Ue(f),[]))),await this.register(u,!0),await this.watchRoots(u),u})().catch(r=>{throw this.session?.account===e&&(this.session.abort.abort(),this.session=null),r}).finally(()=>{this.initializing=null}),this.initializing)}async bindAccount(e){let n=wn(e.file),r=Ks(this.host.homeDir()),i=Oe(e.account),s=dr(r),a=!s?.account&&(await jr(n).catch(l=>{if(l.code==="ENOENT")return[];throw l})).some(l=>/^[a-f0-9]{64}\.json$/.test(l)&&l!==i+".json"),o=s?.pending&&(e.stored.owned||e.stored.config.revision>0);if((s?.account&&s.account!==i||a||o)&&(e.stored.accountReview=!0,e.stored.owned=!0,e.stored.config.enabled&&(e.stored.config={...e.stored.config,enabled:!1,revision:e.stored.config.revision+1}),await this.persist(e)),s?.account!==i||s.pending){this.guard(e,!1);let l=dr(r);if(l?.account!==s?.account||l?.epoch!==s?.epoch||l?.pending!==s?.pending)throw Error("account_changed");Xs(r,{version:1,account:i,...s?.epoch?{epoch:s.epoch}:{}})}e.binding={file:r,account:i,epoch:s?.epoch},this.guard(e,!1)}async rootIdentity(e,n){let r=e.rootIdentities.get(n);if(r){let s=await ca(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!s.isDirectory()||!bt(r,s))throw Error("Sync root changed; preview before rebinding");return r}let i=await ar(n).catch(s=>{throw s.code==="ENOENT"?Error("Sync root unavailable: "+n):s});return this.guard(e),e.rootIdentities.set(n,i),i}async scan(e,n=e.roots){let r=!1;for(let s of e.stored.roots??[]){let a=n.find(l=>l.prefix===s.prefix);if(!a||a.root!==s.root)throw Error("content_roots_changed_preview_required");let o=await this.rootIdentity(e,s.root);if(s.dev!==void 0&&!an(s,o))throw Error("Sync root changed; preview before rebinding");if(s.dev!==void 0&&s.dev!==o.dev){let l=String(s.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(l)&&Ke(n,c.path).root===s.root&&(c.inode=String(o.dev)+":"+c.inode.slice(l.length),delete c.stat,delete c.statAt)}JSON.stringify(s)!==JSON.stringify({...s,...o})&&(Object.assign(s,o),r=!0)}r&&await this.persist(e);let i=await ns(n);return this.scanned={skipped:i.skipped,unscanned:i.unscanned,skippedInodes:i.skippedInodes},i}async write(e,n,r,i){this.guard(e),await sa(e.roots,n,r,i,(s,a)=>this.lock(e,s,a)),await this.recordRoots(e)}async recordRoots(e){this.guard(e);let n=!1;for(let r of e.roots){if(e.stored.roots?.some(s=>s.prefix===r.prefix&&s.root===r.root))continue;await ca(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&((e.stored.roots??=[]).push({...r,...await this.rootIdentity(e,r.root)}),n=!0)}n&&await this.persist(e)}lock(e,n,r,i=!1){let s=()=>{if(this.guard(e),e.stored.paused&&!i)throw Error("paused");for(let[a,o]of e.rootIdentities){let l;try{l=Qy(a)}catch{throw Error("Sync root unavailable: "+a)}if(!l.isDirectory()||!bt(o,l))throw Error("Sync root changed; restart before retrying")}r(),this.wroteLocal=!0};return this.host.contentSync.withWriteLock?.(n,s)??Promise.resolve().then(s)}async previewScan(e,n){for(let r of e.stored.roots??[])n.some(i=>i.prefix===r.prefix&&i.root===r.root)&&await Bt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return ns(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Rs(e.roots.map(n=>n.root),{ignoreInitial:!0,ignored:n=>{let r=n.split(/[\\/]/).at(-1)??"";return r.startsWith(".")&&r!==".memory-tombstones.json"||r==="node_modules"||r==="__pycache__"}}),this.watcher.on("all",(n,r)=>{let i=this.logical(e,r),s=Date.now();if(this.activeAt=s,i){let a=this.dirty.get(i);a?a.last=s:this.dirty.set(i,{first:s,last:s})}this.schedule(i?void 0:s+Qd)}))}logical(e,n){let r=null;for(let a of e.roots)(n===a.root||n.startsWith(a.root+Vn))&&(!r||a.root.length>r.root.length)&&(r=a);if(!r)return null;let i=Fr(r.root,n).split(Vn).join("/");return(r.prefix?i?`${r.prefix}/${i}`:r.prefix:i)||null}dueAt(e,n){return n.last<=this.flushAt?0:Math.min(n.last+ha(e),n.first+Kd)}schedule(e){let n=e??1/0;for(let[r,i]of this.dirty)n=Math.min(n,this.dueAt(r,i));this.due&&clearTimeout(this.due),this.due=null,!(n===1/0||this.closed)&&(this.due=setTimeout(()=>{this.due=null;let r=this.session;r?.stored.config.enabled&&!r.stored.paused&&this.kick()},Math.max(0,n-Date.now())+50),this.due.unref?.())}kick(){if(this.running){this.again=!0;return}this.run()}touch(){this.activeAt=Date.now()}idleSkip(e=Date.now()){return e-this.activeAt>=Ew&&e-this.lastRunAt<_w-5e3}flush(e){let n=this.session;if(!(this.closed||!this.host.accountId()||n&&(!n.stored.config.enabled||n.stored.paused)))return this.flushRequest++,this.flushThrough=Math.max(this.flushThrough,Date.now()),this.bypassBackoff=!0,e==="quit"&&(this.quitting=!0),this.flushAt=this.quitting?1/0:this.flushThrough,this.flushing?this.flushing:this.flushing=(async()=>{try{for(;!this.closed;){let r=this.serial;if(await r,r!==this.serial)continue;if(this.running){await this.runFinished;continue}let i=this.flushRequest;if(await this.run(),i===this.flushRequest)return}}finally{this.flushing=null,this.quitting=!1,this.flushAt=this.flushThrough}})()}async request(e,n,r="",i="GET",s,a,o){for(;;){this.guard(e);let l=this.host.readCreds();if(!l.token)throw Error("not_signed_in");let c=Jt(l.cloudUrl);await c.ready(e.abort.signal),this.guard(e);let u=l.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(n)}${r}`,f={Authorization:`Bearer ${l.token}`,"X-Content-Device":this.deviceId,"X-Content-Caps":No,...o},g;if(s instanceof Buffer){f["Content-Type"]="application/octet-stream",f["Content-Length"]=String(s.length);let y=async function*(){for(let b=0;b<s.length;b+=64*1024)e.abort.signal.throwIfAborted(),yield s.subarray(b,b+64*1024),a?.(Math.min(s.length,b+64*1024))};g=cw.from(y())}else s!==void 0&&(f["Content-Type"]="application/json",g=JSON.stringify(s));let p={method:i,headers:f,body:g,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...s instanceof Buffer?{duplex:"half"}:{}},m=await fetch(u,p);if(this.guard(e),!m.ok&&!(m.status===304&&o?.["If-None-Match"])){let y=await m.json().catch(()=>({}));if(c.observe(m.status,m.headers,y?.code,y?.retryAfterMs))continue;throw this.httpStatus=m.status,Object.assign(new Error(typeof y?.detail=="string"?y.detail:`content_http_${m.status}`),{status:m.status,...typeof y?.code=="string"?{code:y.code}:{},...Number.isSafeInteger(y?.maxBytes)&&y.maxBytes>0?{maxBytes:y.maxBytes}:{}})}return c.observe(m.status,m.headers),i==="DELETE"&&this.tally("deletesSent"),m}}async gatedFetch(e,n,r,i,s){let a=Jt(n);for(;;){await a.ready(e.abort.signal),this.guard(e);let o=await fetch(n.replace(/\/+$/,"")+r,{...i,headers:{...i.headers,"X-Content-Caps":No},signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(s)])});if(o.status===429){let l=await o.clone().json().catch(()=>({}));if(a.observe(o.status,o.headers,l?.code,l?.retryAfterMs))continue}return a.observe(o.status,o.headers),o}}async json(e,n,r="",i="GET",s,a){let o=await(await this.request(e,n,r,i,s,void 0,a)).json();return this.guard(e),o}async manifests(e,n){let r=new Map;for(let s of new Set(n.rules.filter(a=>a.target!=="off").map(a=>a.target))){let a=JSON.parse(await this.manifestText(e,s));Ki(a,s),await this.knownTombstones(e,s,a),r.set(s,a)}let i=[r.get("default"),r.get(`device-${this.deviceId}`)].filter(Boolean);return i.length&&(this.cloudAgents=[...new Set(i.flatMap(s=>s.nodes.filter(a=>!a.deleted&&a.kind==="file").map(a=>/^agents\/([^/]+)\/config\.toml$/.exec(a.path)?.[1]).filter(a=>!!a&&Cr.test(a))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),i=r&&Date.now()-r.at<kw?r:void 0,s=await this.request(e,n,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...i?{"If-None-Match":i.etag}:{}});if(s.status===304)return await s.body?.cancel(),i?i.text:(e.manifests.delete(n),this.manifestText(e,n));let a=await s.text();this.guard(e),Ki(JSON.parse(a),n);let o=s.headers.get("etag");return r?.text!==a&&this.touch(),o?e.manifests.set(n,{etag:o,text:a,at:Date.now()}):e.manifests.delete(n),a}async knownTombstones(e,n,r){if(typeof r.tombstonesSince!="string")return;let i=new Set(r.nodes.map(c=>c.id)),s=new Set;for(let[c,u]of Object.entries(e.stored.files))c.startsWith(n+":")&&s.add(u.id);for(let[c,u]of Object.entries(e.stored.folders))c.startsWith(n+":")&&s.add(u.id);for(let[c,u]of Object.entries(e.stored.pendingUploads??{}))c.startsWith(n+":")&&s.add(u.id);let a=e.tombstones.get(n);a||e.tombstones.set(n,a=new Map);for(let c of[...a.keys()])i.has(c)&&a.delete(c);let o=Date.now(),l=[...s].filter(c=>{if(i.has(c))return!1;let u=a.get(c);return!u||!u.node&&o-u.at>=Cw});for(let c=0;c<l.length;c+=Xd){let u=l.slice(c,c+Xd),f=new Set(u),g=await this.json(e,n,"/tombstones","POST",{ids:u}),p=new Map((Array.isArray(g?.nodes)?g.nodes:[]).filter(m=>Nd(m)&&f.has(m.id)).map(m=>[m.id,m]));for(let m of u)a.set(m,{node:p.get(m)??null,at:o})}for(let c of s)if(!i.has(c)){let u=a.get(c)?.node;u&&r.nodes.push(structuredClone(u))}}route(e,n,r="file"){if(Gi(e)||Qo(e,r)===!1)return null;let i=Mn(e,n.rules);return i&&i.target!=="off"?i.target:null}effective(e,n){let r=new Map(n.filter(i=>i.localId).map(i=>[i.localId,i.path]));return{...e,rules:e.rules.map(i=>i.sourceId&&r.has(i.sourceId)?{...i,source:r.get(i.sourceId)}:i)}}deviceName(){return this.customName||Fi(ua())}setSources(e){let n=new Map,r={files:0,size:0};for(let s of e)s.kind==="folder"&&n.set(s.path,{size:0,files:0});for(let s of e)if(s.kind==="file"){fu.some(a=>s.path.startsWith(a+"/"))||(r.files++,r.size+=s.size);for(let a=Wt(s.path);a;a=Wt(a)){let o=n.get(a);o&&(o.size+=s.size,o.files++)}}let i=new Map(e.filter(s=>s.kind==="file"&&/^agents\/[^/]+\/config\.toml$/.test(s.path)).map(s=>[s.path.slice(0,-12),s]));this.others=r,this.sources=[...n].sort(([s],[a])=>en(s)-en(a)||(s<a?-1:1)).slice(0,2e3).map(([s,a])=>({path:s,kind:"folder",size:a.size,files:a.files,...Ar(s)&&i.has(s)?{agent:!0}:{}})),this.sourcesAt=Date.now(),this.readAgentNames(i)}async readAgentNames(e){for(let n of this.agentNames.keys())e.has(n)||this.agentNames.delete(n);for(let[n,r]of e){let i=`${r.mtime}:${r.size}`;if(!(this.agentNames.get(n)?.key===i||r.size>256*1024))try{this.agentNames.set(n,{key:i,...hu((await Wn(r)).toString("utf8"))})}catch{this.agentNames.set(n,{key:i})}}}async rename(e){let n=typeof e=="string"?e.trim():"";if(n.length>64||/[\u0000-\u001f\u007f]/.test(n))throw Error("Invalid device name");let r=await this.getSession(),i=n||Fi(ua()),s=Mo(i,this.devices,this.deviceId);if(s)throw Error(s==="taken"?"device_name_taken":s==="reserved"?"device_name_reserved":"device_name_invalid");return await this.json(r,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:i,unique:!0}),await this.saveName(n),await this.register(r,!0),this.deviceName()}async saveName(e){let n=Fe(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+mt();try{await $r(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await rs(r,n)}finally{await Lr(r).catch(()=>{})}this.customName=e}async register(e,n=!1){let r=Date.now();if(!n&&this.registered?.name===this.deviceName()&&r-this.registered.at<ss){r-this.devicesAt>=ss&&await this.refreshDevices(e);return}let i=(o,l)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:o,...l?{unique:!0}:{}}),s=async()=>(await this.json(e,"devices")).devices,a=o=>/device_name_(taken|reserved|invalid)/.test(Ue(o));try{await i(this.deviceName(),!0)}catch(o){if(!a(o))throw o;let l=!1;if(!this.customName){let c=Fi(ua());for(let u=0;u<5&&!l;u++){let f=await s(),g=null;for(let p=2;p<100&&!g;p++){let m=`${c} ${p}`;Mo(m,f,this.deviceId)||(g=m)}if(!g)break;try{await i(g,!0),await this.saveName(g),l=!0}catch(p){if(!a(p))throw p}}}l||await i(this.deviceName(),!1)}this.registered={name:this.deviceName(),at:r},await this.refreshDevices(e)}async refreshDevices(e){this.devicesAt=Date.now(),this.devices=(await this.json(e,"devices")).devices,await this.cacheDevices()}cachedDevices="";async cacheDevices(){let e=Fe(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let o=JSON.parse(await Pr(e,"utf8"));Array.isArray(o?.devices)&&(n=o.devices)}catch{}let r=new Map(n.filter(o=>o&&typeof o.id=="string").map(o=>[o.id,o])),i=this.devices.map(o=>{let l=r.get(o.id),c=[...Array.isArray(l?.aliases)?l.aliases:[],...l&&typeof l.name=="string"&&l.name!==o.name?[l.name]:[]],u=c.filter((f,g)=>typeof f=="string"&&f!==o.name&&c.lastIndexOf(f)===g).slice(-5);return{id:o.id,name:o.name,...u.length?{aliases:u}:{}}}),s=JSON.stringify({devices:i});if(s===this.cachedDevices)return;let a=e+".tmp-"+mt();try{await $r(a,s,{mode:384,flag:"wx"}),await rs(a,e),this.cachedDevices=s}catch(o){this.error=Ue(o)}finally{await Lr(a).catch(()=>{})}}async setup(e){let n=await this.getSession(),r=e&&typeof e=="object"?e:{};if(n.stored.config.enabled||n.stored.config.revision>0)return null;let i=Pn(wu(n.stored.config),"","off");for(let o of Lt)o.id!=="agents"&&r[o.id]===!1&&(i=Pn(i,o.path,"off"));let s=new Set(this.sources.filter(o=>o.agent).map(o=>o.path.slice(7))),a=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(o=>typeof o=="string"&&s.has(o)):[];return this.preview(bu(i,a))}retryFailed(){this.failures.clear(),this.tooLarge.clear(),this.bypassBackoff=!0}retrySoon(){this.bypassBackoff=!0}rateLimitedUntil(){let e=this.host.readCreds();return e.cloudUrl?Jt(e.cloudUrl).until():null}capFor(e,n,r){let i=Ui(n,e,r?.limits),s=this.tooLarge.get(e+"\0"+n)?.learned;return s&&s.published===i?Math.min(i,s.maxBytes):i}noteTooLarge(e,n,r,i,s,a){let o=n+"\0"+r,l=this.tooLarge.get(o);this.tooLargeSeen?.add(o),this.failures.delete(o),lt("content","skippedTooLarge",1,r),e.stored.jobs=e.stored.jobs.filter(c=>!(c.path===r&&c.target===n&&(c.state==="failed"||c.state==="paused")&&(c.direction==="upload"||c.direction==="download"))),this.tooLarge.set(o,{ns:n,path:r,size:i,maxBytes:s,...a??l?.learned?{learned:a??l.learned}:{}})}tooLargeList(){return[...this.tooLarge.values()].map(e=>({path:e.path,reason:"too-large",size:e.size,maxBytes:e.maxBytes}))}backingOff(e,n,r){let i=e+"\0"+n,s=this.failures.get(i);return this.roundVisited?.add(i),s?s.fp!==r?(this.failures.delete(i),!1):!this.bypassThisRound&&Date.now()<s.retryAt:!1}succeeded(e,n){this.failures.delete(e+"\0"+n)}fileFailed(e,n,r,i,s,a){if(e.abort.signal.aborted||hw(i))throw i;let o=n+"\0"+r,l=gw(i);if(l!==null){let m=i.size,y=Number.isSafeInteger(m)?m:a??0;this.noteTooLarge(e,n,r,y,l,{maxBytes:l,published:Ui(r,n,this.limitsByNs.get(n))});return}this.error=Ue(i);let c=this.failures.get(o),u=(c&&c.fp===s?c.count:0)+1,f=Date.now()+pu(u),g=i?.code;this.failures.set(o,{ns:n,path:r,reason:Ue(i),...typeof g=="string"?{code:g}:{},count:u,retryAt:f,fp:s});let p=e.stored.jobs.findLast(m=>m.path===r&&m.target===n&&m.state==="failed");p&&(p.retryAt=f)}failureList(){return[...this.failures.values()].sort((e,n)=>e.retryAt-n.retryAt).slice(0,200).map(e=>({path:e.path,target:e.ns,reason:e.reason,...e.code?{code:e.code}:{},count:e.count,retryAt:e.retryAt}))}async snapshot(e,n){(e==="zh"||e==="en")&&(this.uiLocale=e);let r=await this.getSession(),i=n&&typeof n=="object"?n:{};if(i.focused===!0){let s=!this.focused;this.focused=!0,this.touch(),s&&r.stored.config.enabled&&!r.stored.paused&&Date.now()-this.lastRunAt>3e4&&this.kick()}else i.focused===!1&&(this.focused=!1);return!r.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(r).then(s=>{this.session===r&&this.setSources(s)},()=>{})),i.devices===!0&&Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(r).catch(()=>{})),{available:!0,account:Oe(r.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(r.stored.config),running:this.running,paused:r.stored.paused,phase:this.phase,jobs:structuredClone(r.stored.jobs),devices:this.devices,sources:this.sources.map(s=>{let a=s.agent&&this.agentNames.get(s.path);return a?{...s,...a.name?{name:a.name}:{},...a.nameEn?{nameEn:a.nameEn}:{}}:s}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...r.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...r.stored.agentArchive?{agentArchive:(({rewritten:s,...a})=>a)(r.stored.agentArchive)}:{},...(s=>s&&(s.latched||s.pending.length)?{deletes:{latched:s.latched,pending:s.pending.length,token:Yd(s.pending),items:s.pending.slice(0,200).map(a=>({path:a.path,side:a.side}))}}:{})(r.stored.deleteGuard),...(s=>s.length?{skipped:s.slice(0,200),skippedCount:s.length}:{})([...this.scanned.skipped,...this.recordsAccount===r.account?this.tooLargeList():[]]),...(s=>s?{rateLimitedUntil:s}:{})(this.rateLimitedUntil()),...this.failures.size&&this.recordsAccount===r.account?{failures:this.failureList()}:{}}}async confirmDeletes(e){await this.decideDeletes("confirm",e)}async abandonDeletes(e){await this.decideDeletes("restore",e)}deferredDecision=[];async decideDeletes(e,n){let r=await this.getSession(),i=r.stored.deleteGuard?.pending??[],s=i.map(a=>a.key);if(n!==void 0&&n!==Yd(i))throw Error("deletes_changed");if(!(!s.length&&!r.stored.deleteGuard?.latched)){if(this.running){this.deferredDecision.push({kind:e,keys:s}),this.again=!0;return}this.applyDecision(r,e,s),await this.persist(r),this.touch(),this.kick()}}applyDecision(e,n,r){let i=e.stored.deleteGuard;if(!i)return;let s=new Set(r),a=i.pending.filter(f=>!s.has(f.key)),o=i.pending.filter(f=>s.has(f.key)),l=[...new Set([...i.confirmed??[],...o.map(f=>f.key)])],c=[...new Map([...i.restore??[],...o].map(f=>[Ot(f.side,f.ns,f.id),f])).values()],u={latched:a.length>0,pending:a,...n==="confirm"?{confirmed:l}:i.confirmed?.length?{confirmed:i.confirmed}:{},...n==="restore"?{restore:c}:i.restore?.length?{restore:i.restore}:{}};u.latched||u.pending.length||u.confirmed?.length||u.restore?.length?e.stored.deleteGuard=u:delete e.stored.deleteGuard,n==="confirm"&&(this.deleteStamps=[])}stats(){let e=this.host.accountId(),n=e&&this.session?.account===e?this.session:null,r=n?.stored,i={},s=e&&e===this.logAccount?this.runLog.snapshot():new xr().snapshot();for(let a of r?.jobs??[])i[a.state]=(i[a.state]??0)+1;return{deviceId:this.deviceId||null,session:!!n,enabled:!!r?.config.enabled,paused:!!r?.paused,running:!!n&&this.running,phase:n?this.phase:"idle",revision:r?.config.revision??0,rules:(r?.config.rules??[]).map(a=>({source:a.source,target:a.target})),backlog:r?{jobs:i,blocked:[...this.blocked.values()].reduce((a,o)=>a+o.length,0),pendingUploads:Object.keys(r.pendingUploads??{}).length,unconfirmed:Object.keys(r.unconfirmed??{}).length,trash:r.trash?.length??0,awaitingBytes:this.awaitingBytes.size,dirty:this.dirty.size}:null,archive:r?.agentArchive?.state??null,...s}}async preview(e){let n=await this.getSession();if(e?.revision!==n.stored.config.revision)throw Error("config_changed");let i=Zt(e,n.stored.config.revision+1),s=await this.host.contentSync.roots();this.guard(n);let a=await this.previewScan(n,s),o=this.effective(i,a);if(n.stored.agentArchive?.state==="running"&&a.some(N=>N.kind==="file"&&N.path.startsWith("agents/")&&this.route(N.path,o)))throw Error("agent_archive_running");let l=await this.manifests(n,o);this.guard(n),this.setSources(a);let c=0,u=0,f=0,g=0,p=await this.bindingsOf(s),m=new Map,y=new Map;for(let[N,Y]of Object.entries(n.stored.files))this.survives(n.stored,o,p,Y.path)&&(m.set(N,Y),y.set(N.slice(0,N.indexOf(":"))+"\0"+Y.path,Y));let b=n.stored.deleteGuard,_=new Set((b?.restore??[]).map(N=>Ot(N.side,N.ns,N.id))),h=[],T=new Map,v=new Set(a.map(N=>N.path));for await(let N of tn(a.filter(Y=>Y.kind==="file"))){let Y=this.route(N.path,o);if(!Y)continue;let ee=l.get(Y),J=ee?.nodes.find(te=>!te.deleted&&te.kind==="file"&&te.path===N.path);if(N.size>Ui(N.path,Y,ee?.limits))continue;let se=Oe(await Wn(N));if(this.guard(n),T.set(N.path,se),!J){let te=y.get(Y+"\0"+N.path),ae=te&&ee?.nodes.find(Q=>Q.id===te.id&&Q.deleted);if(ae&&te&&is(N.path)&&(te.hash===se||te.memoryDeleted&&se===Yn))continue;if(ae&&te&&te.hash===se&&!_.has(Ot("local",Y,te.id))){h.push({ns:Y,path:N.path});continue}}se!==J?.hash&&(c++,g+=N.size,J?.version&&f++)}let I=i.enabled?this.agentAsks(n,a,o,l,T):[],E=h.length;for(let[N,Y]of l)for await(let ee of tn(Y.nodes)){if(ee.deleted||ee.kind!=="file"||this.route(ee.path,o)!==N||v.has(ee.path))continue;let J=m.get(Re(N,ee.id)),se=qn(a.unscanned,ee.path)||!!J?.inode&&a.skippedInodes.has(J.inode);if(J&&J.path!==ee.path&&v.has(J.path))continue;let te=Do(ee,J,!!n.stored.pendingUploads?.[Re(N,ee.id)],se);te==="download"?u++:te==="delete"&&await this.absent(n,ee.path,s)&&(_.has(Ot("cloud",N,ee.id))?u++:h.push({ns:N,path:ee.path}))}let D=h.length-E,x=[...m].map(([N,Y])=>({ns:N.slice(0,N.indexOf(":")),path:Y.path})),L=Oo(h,x,{latched:!!b?.latched,recent:this.deleteStamps.filter(N=>Date.now()-N<Ro).length}),V=this.signature(a,l,s),H={token:mt(),config:o,upload:i.enabled?c:0,download:i.enabled?u:0,conflicts:i.enabled?f:0,bytes:i.enabled?g:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,deleteCloud:i.enabled?D:0,deleteLocal:i.enabled?E:0,...i.enabled&&L?{deletesHeld:!0}:{},...I.length?{agentAsks:I}:{}};return this.previewValue={value:H,account:n.account,signature:V},H}async bindingsOf(e){let n=[];for(let r of e)await ca(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&n.push({...r,...await ar(r.root)});return n}survives(e,n,r,i,s="file"){return e.config.enabled===n.enabled&&dw(e.roots??r,r)&&this.route(i,e.config,s)===this.route(i,n,s)}signature(e,n,r){return Oe(JSON.stringify([r,e.map(i=>[i.path,i.size,i.mtime,i.inode]),[...n].map(([i,s])=>[i,s.nodes.map(a=>[a.id,a.revision,a.version,a.deleted])])]))}async apply(e,n){let r=this.serial,i;this.serial=new Promise(s=>{i=s}),await r;try{let s=await this.getSession(),a=this.previewValue;if(!a||a.value.token!==e||a.account!==s.account||a.value.expiresAt<Date.now()||a.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let o=a.value.agentAsks??[],l=xw(n);this.resolving=!0;try{let c=await this.host.contentSync.roots(),u=await this.previewScan(s,c),f=await this.manifests(s,a.value.config);if(this.signature(u,f,c)!==a.signature)throw Error("preview_changed");let g=await this.bindingsOf(c),p=structuredClone(a.value.config);for(let b of p.rules){let _=u.find(h=>h.kind==="folder"&&h.path===b.source);_&&(b.sourceId=await ia(_))}let m=o.length?Zt(o.reduce((b,_)=>Pn(b,`agents/${_.slug}`,"off"),p),p.revision):p;if(this.guard(s),this.previewValue!==a||a.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");let y=structuredClone(s.stored);s.stored.config=m,s.stored.owned=!0,s.stored.paused=!1,delete s.stored.unconfirmed;for(let[b,_]of Object.entries(s.stored.files))this.survives(y,s.stored.config,g,_.path)||delete s.stored.files[b];for(let[b,_]of Object.entries(s.stored.folders))this.survives(y,s.stored.config,g,_.path,"folder")||delete s.stored.folders[b];s.stored.roots=g,s.rootIdentities=new Map(g.map(b=>[b.root,b])),await this.persist(s);try{await this.accountWrite(s,b=>this.host.contentSync.claim(!0,b))}catch(b){throw s.stored=y,await this.persist(s),await this.accountWrite(s,_=>this.host.contentSync.claim(y.owned,_)).catch(()=>{}),b}if(this.previewValue=null,s.roots=c,await this.watchRoots(s),o.length)try{await this.resolveAsks(s,o,l,p)}catch(b){throw this.fault(Ue(b)),b}s.stored.accountReview&&(delete s.stored.accountReview,await this.persist(s))}finally{this.resolving=!1}}finally{i()}this.run()}async pause(e){let n=await this.getSession();if(!e&&n.stored.accountReview)throw Error("content_account_changed_preview_required");n.stored.paused=e,e?(n.abort.abort(new Error("paused")),this.phase="paused"):this.running||(n.abort=new AbortController),await this.persist(n),e||this.run()}job(e,n,r,i,s){let a=e.stored.jobs.findLast(l=>l.path===n&&l.target===r&&l.direction===i&&["failed","paused","queued"].includes(l.state));if(a)return Object.assign(a,{state:"active",done:0,size:s,at:Date.now(),error:void 0,finishedAt:void 0}),a;let o={id:mt(),path:n,target:r,direction:i,state:"active",done:0,size:s,at:Date.now()};return e.stored.jobs.push(o),e.stored.jobs=e.stored.jobs.slice(-200),o}done(e){e.state="done",e.done=e.size??e.done,e.finishedAt=Date.now()}async operation(e,n,r,i,s,a){if(this.guard(e),e.stored.paused)throw Error("paused");this.activeAt=Date.now();let o=this.job(e,n,r,i,s);try{let l=await a(o);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(o),i==="upload"?lt("content","uploads"):i==="download"&<("content","downloads");let c=bw[i];return c&&this.tally(c),l}catch(l){throw o.state=e.stored.paused?"paused":"failed",o.error=Ue(l),o.finishedAt=Date.now(),l}}async run(){if(this.running||this.closed||this.resolving)return;this.running=!0;let e;this.runFinished=new Promise(o=>{e=o});let n=Date.now();this.lastRunAt=n,this.wroteLocal=!1;let r=new Set,i,s=!1,a=!1;try{if(i=await this.getSession(),this.runAccount=i.account,i.stored.accountReview){this.error="content_account_changed_preview_required";return}if(await this.archiveStep(i),!i.stored.config.enabled||i.stored.paused)return;i.abort.signal.aborted&&(i.abort=new AbortController),this.blocked.clear(),this.phase="scanning",this.error=void 0,s=!0,this.httpStatus=0,this.live()&&this.runLog.begin(n);let o=await this.host.contentSync.roots();this.guard(i),i.roots=o,this.tooLargeSeen=new Set,this.roundVisited=new Set,this.recordsAccount!==i.account&&(this.failures.clear(),this.tooLarge.clear(),this.recordsAccount=i.account),this.bypassThisRound=this.bypassBackoff,this.bypassBackoff=!1,await this.host.contentSync.agentFiles?.prepare().catch(T=>{this.error=Ue(T)}),this.guard(i);let l=await this.scan(i,o);await this.recordRoots(i);let c=this.effective(i.stored.config,l),u=await this.manifests(i,c);this.guard(i),this.limitsByNs=new Map([...u].map(([T,v])=>[T,v.limits]));let f=new Map;for(let[T,v]of u)for(let I of v.nodes)I.kind==="file"&&!I.deleted&&f.set(T+"\0"+I.path,I.version??"");let g=(T,v)=>`${mw(v)}|c:${f.get(T+"\0"+v.path)??""}`;await this.register(i),this.openJobs=new Set(i.stored.jobs.filter(T=>["failed","paused","active"].includes(T.state)&&["upload","download","merge"].includes(T.direction)).map(T=>T.target+"\0"+T.path)),await this.folders(i,c,l,u),await this.recordRoots(i),await this.fileRenames(i,c,l,u),l=await this.scan(i,o),c=this.effective(c,l),i.stored.config=c,this.setSources(l),this.phase="syncing",this.round={plan:[],restore:new Map((i.stored.deleteGuard?.restore??[]).map(T=>[Ot(T.side,T.ns,T.id),T])),restoreHit:new Set,restoreDone:new Set,tracked:Object.entries(i.stored.files).map(([T,v])=>({ns:T.slice(0,T.indexOf(":")),path:v.path})),undecided:new Set};let p=(T,v)=>this.round.undecided.add(T+"\0"+v),m=T=>T.endsWith("/"+Or),y=new Set,b=new Set,_=T=>T.startsWith("agents/")?T.slice(0,T.lastIndexOf("/")+1):null,h=T=>T.endsWith("/MEMORY.md")&&b.has(_(T)??"");for(let[T,v]of u)for await(let I of tn(v.nodes.filter(E=>E.kind==="file"&&!E.busy&&m(E.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(I.path,c)!==T||l.some(E=>E.path===I.path))){if(this.isBlocked(T,I.path)){b.add(_(I.path)??""),p(T,I.path);continue}if(this.backingOff(T,I.path,`c:${I.version??""}`)){b.add(_(I.path)??""),p(T,I.path);continue}y.add(I.id);try{await this.missing(i,I,T,l,c)==="unknown"?b.add(_(I.path)??""):this.succeeded(T,I.path)}catch(E){this.fileFailed(i,T,I.path,E,`c:${I.version??""}`,I.size),b.add(_(I.path)??""),p(T,I.path)}}}for await(let T of tn(l.filter(v=>v.kind==="file").sort((v,I)=>+!m(v.path)-+!m(I.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");let v=this.route(T.path,c);if(v){if(h(T.path)){p(v,T.path);continue}if(this.isBlocked(v,T.path)){m(T.path)&&b.add(_(T.path)??""),p(v,T.path);continue}if(this.backingOff(v,T.path,g(v,T))){p(v,T.path),m(T.path)&&b.add(_(T.path)??"");continue}try{let I=await this.file(i,c,T,v,u.get(v));I==="held"?(r.add(T.path),p(v,T.path)):I==="too-large"?(p(v,T.path),m(T.path)&&b.add(_(T.path)??"")):this.succeeded(v,T.path)}catch(I){this.fileFailed(i,v,T.path,I,g(v,T),T.size),p(v,T.path),m(T.path)&&b.add(_(T.path)??"")}}}for(let[T,v]of u)for await(let I of tn(v.nodes.filter(E=>E.kind==="file"&&!E.busy&&!y.has(E.id)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(I.path,c)!==T||l.some(E=>E.path===I.path))){if(this.isBlocked(T,I.path)||h(I.path)){p(T,I.path);continue}if(this.holdGone(I.path)){r.add(I.path),p(T,I.path);continue}if(this.backingOff(T,I.path,`c:${I.version??""}`)){p(T,I.path);continue}try{await this.missing(i,I,T,l,c),this.succeeded(T,I.path)}catch(E){this.fileFailed(i,T,I.path,E,`c:${I.version??""}`,I.size),p(T,I.path)}}}await this.executeDeletes(i,this.round),await this.cleanupFolders(i,c,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(i).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=ss)&&(await this.accountWrite(i,T=>this.host.contentSync.changed(T)),this.changedAt=Date.now()),this.guard(i),await this.persist(i),await this.pruneBases(i),a=!0;for(let T of[...this.tooLarge.keys()])this.tooLargeSeen?.has(T)||this.tooLarge.delete(T);for(let T of[...this.failures.keys()])this.roundVisited?.has(T)||this.failures.delete(T);!this.error&&this.failures.size&&(this.error=[...this.failures.values()].reduce((T,v)=>T.retryAt>v.retryAt?T:v).reason)}catch(o){this.error=Ue(o)}finally{if(this.round=null,this.phase=i?.stored.paused?"paused":"idle",i&&this.host.accountId()===i.account)for(let o of this.deferredDecision.splice(0))this.applyDecision(i,o.kind,o.keys);s&&(this.noteHealth(n,a),this.live()&&this.runLog.end(a));for(let[o,l]of this.dirty)!r.has(o)&&l.last<n&&this.dirty.delete(o);i&&this.host.accountId()===i.account&&(await this.persist(i).catch(()=>{}),!this.closed&&i.abort.signal.aborted&&!i.stored.paused&&i.stored.config.enabled&&(i.abort=new AbortController,this.again=!0)),this.running=!1,this.runAccount=null,this.again&&!this.closed?(this.again=!1,queueMicrotask(()=>void this.run())):this.schedule(),e()}}noteHealth(e,n){n&&(lt("content","cycles"),lt("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?ki(this.error,this.httpStatus):null;r?this.health.error(r):this.error||this.health.ok()}holdGone(e){let n=this.dirty.get(e);if(!n)return!1;let r=Date.now();return n.last>this.flushAt&&r-n.last<ha(e)&&r-n.first<Kd}isBlocked(e,n){return(this.blocked.get(e)??[]).some(r=>n===r||n.startsWith(r+"/"))}block(e,n,r){if(this.blocked.set(e,[...this.blocked.get(e)??[],n]),this.lastError=Ue(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(Ue(r),[n])}async folders(e,n,r,i){let s=r.filter(o=>o.kind==="folder"),a=new Map;for(let o of s)if(o.localId){if(a.has(o.localId))throw Error(`Duplicate folder sync identity: ${o.path}`);a.set(o.localId,o.path)}for(let[o,l]of i){for await(let c of tn(l.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,f)=>en(u.path)-en(f.path))))if(!(this.isBlocked(o,c.path)||qn(this.scanned.unscanned,c.path)))try{let u=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(o+":")&&p.id===c.id)?.[1],f=(u?s.find(g=>g.localId===u.localId):null)??s.find(g=>g.path===c.path);if(u&&f&&c.path!==u.path&&f.path!==u.path&&c.path!==f.path)throw Error(`Concurrent folder rename: ${f.path}`);if(u&&f&&c.path!==u.path&&f.path===u.path){if(this.route(f.path,n,"folder")!==o)continue;if(this.route(c.path,n,"folder")!==o)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,f.path,o,"rename",null,()=>oa(e.roots,f.path,c.path,(p,m)=>this.lock(e,p,m)));let g=f.path;for(let p of r)if(p.path===g||p.path.startsWith(g+"/")){let m=p.path;p.path=c.path+m.slice(g.length);let y=Ke(e.roots,p.path);p.physical=Fe(y.root,y.relative)}for(let[p,m]of Object.entries(e.stored.files))p.startsWith(o+":")&&m.path.startsWith(u.path+"/")&&(m.path=c.path+m.path.slice(u.path.length));for(let p of n.rules)(p.source===u.path||p.source.startsWith(u.path+"/"))&&(p.source=c.path+p.source.slice(u.path.length))}if(!f&&this.route(c.path,n,"folder")===o&&!u){await Wd(e.roots,c.path,(p,m)=>this.lock(e,p,m));let g=(await this.scan(e)).find(p=>p.path===c.path);g&&(r.push(g),s.push(g))}}catch(u){this.block(o,c.path,u),this.tally("folderConflicts");let f=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(o+":")&&p.id===c.id)?.[1];f&&this.block(o,f.path,u)}for await(let c of tn(s.sort((u,f)=>en(u.path)-en(f.path))))if(!this.isBlocked(o,c.path))try{let u=this.route(c.path,n,"folder"),f=n.rules.some(_=>_.target===o&&_.source.startsWith(c.path+"/"));if(u!==o&&!f||Qo(c.path,"folder")===!1)continue;let g=await ia(c),p=e.stored.folders[Re(o,g)],m=p?l.nodes.find(_=>_.id===p.id):l.nodes.find(_=>_.path===c.path&&!_.deleted);if(m?.deleted){let _=(e.stored.deleteGuard?.restore??[]).some(h=>h.side==="local"&&h.ns===o&&h.path.startsWith(c.path+"/"));if(p&&!_){let h=!1;for(let T of r.filter(v=>v.kind==="file"&&v.path.startsWith(c.path+"/")&&this.route(v.path,n)===o)){let v=Object.entries(e.stored.files).find(([I,E])=>I.startsWith(o+":")&&E.path===T.path)?.[1];if(!v){h=!0;break}if(!this.sameAsShadow(v,T)){let I=Oe(await Wn(T));if(I!==v.hash&&!(v.memoryDeleted&&is(T.path)&&I===Yn)){h=!0;break}}}if(!h)continue}m=void 0}let y=Wt(c.path),b=y?l.nodes.find(_=>_.path===y&&_.kind==="folder"&&!_.deleted)?.id:"";if(y&&!b)throw Error("Cloud parent is unavailable");if(!m)m=await this.json(e,o,"/nodes","POST",{id:p?mt():g,parentId:b,name:bn(c.path),kind:"folder"}),e.tombstones.get(o)?.delete(m.id),l.nodes.push(m);else if(p&&m.path!==c.path){if(m.revision!==p.revision)throw Error(`Concurrent folder rename: ${c.path}`);let _=m.path,h=await this.operation(e,c.path,o,"rename",null,()=>this.json(e,o,`/nodes/${m.id}`,"PATCH",{parentId:b,name:bn(c.path),revision:m.revision}));for(let T of l.nodes)T.path.startsWith(_+"/")&&(T.path=c.path+T.path.slice(_.length));Object.assign(m,h);for(let[T,v]of Object.entries(e.stored.files))T.startsWith(o+":")&&v.path.startsWith(_+"/")&&(v.path=c.path+v.path.slice(_.length))}e.stored.folders[Re(o,g)]={id:m.id,localId:g,path:c.path,revision:m.revision,parentId:m.parentId,name:m.name}}catch(u){this.block(o,c.path,u);let f=c.localId?e.stored.folders[Re(o,c.localId)]:void 0;f&&this.block(o,f.path,u),lt("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,c.path,o,"rename",null);g.state="conflict",g.error=Ue(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let i=await this.scan(e);for(let[s,a]of r)for await(let o of tn(a.nodes.filter(l=>l.kind==="folder"&&!l.busy).sort((l,c)=>en(c.path)-en(l.path)))){if(this.isBlocked(s,o.path)||this.route(o.path,n,"folder")!==s||qn(this.scanned.unscanned,o.path))continue;let l=Object.entries(e.stored.folders).find(([u,f])=>u.startsWith(s+":")&&f.id===o.id);if(!l)continue;let c=i.find(u=>u.path===o.path&&u.kind==="folder");if(o.deleted&&c){if(i.some(f=>f.path.startsWith(o.path+"/"))||(await jr(c.physical)).some(f=>f!==".forsion-sync-id.json"))continue;await this.operation(e,o.path,s,"delete",null,()=>this.lock(e,c.physical,()=>{vt(c.root,Fr(c.root,c.physical).split(Vn).join("/"));let f=nw(c.physical);if(f.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let g=Fe(c.physical,".forsion-sync-id.json"),p=f.length?Gn(g):null;p&&aa(g);try{rw(c.physical)}catch(m){if(p)try{iw(g,p,{flag:"wx",mode:384})}catch{}throw m}})),this.tally("deletesLocal"),delete e.stored.folders[l[0]]}else if(!o.deleted&&!c){if(e.stored.deleteGuard?.latched||e.stored.deleteGuard?.pending.length||e.stored.deleteGuard?.restore?.length||!await this.absent(e,o.path)||a.nodes.some(u=>u.parentId===o.id&&!u.deleted))continue;await this.operation(e,o.path,s,"delete",null,()=>this.json(e,s,`/nodes/${o.id}`,"DELETE",{revision:o.revision,version:null})),o.deleted=!0,delete e.stored.folders[l[0]]}}}async download(e,n,r,i){if(n.size!==void 0&&n.size>qt)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:qt});let s=await this.request(e,r,`/nodes/${n.id}/content`),a=[],o=0;if(s.body){let c=s.body.getReader();for(;;){let u=await c.read();if(u.done)break;if(this.guard(e),o+=u.value.length,o>qt)throw await c.cancel(),Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:qt});a.push(u.value),i.done=o}}let l=Buffer.concat(a);if(n.hash&&Oe(l)!==n.hash)throw Error("Cloud file changed during download");return l}async fileRenames(e,n,r,i){for(let[s,a]of i)for(let o of a.nodes.filter(l=>l.kind==="file"&&!l.deleted&&!l.busy)){let l=e.stored.files[Re(s,o.id)];if(!l||l.path===o.path)continue;let c=r.find(u=>u.kind==="file"&&u.path===l.path);if(!(!c||this.route(c.path,n)!==s))try{if(this.route(o.path,n)!==s)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,c.path,s,"rename",null,()=>oa(e.roots,c.path,o.path,(u,f)=>this.lock(e,u,f))),l.path=o.path}catch(u){this.block(s,c.path,u),this.block(s,o.path,u)}}}async upload(e,n,r,i,s){let a=this.capFor(r,n.path,{limits:this.limitsByNs.get(r)});if(i.length>a)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:a,size:i.length});let o=await this.request(e,r,`/nodes/${n.id}/content`,"PUT",i,u=>{s.done=u},{"X-Content-Version":n.version??"create",...n.version&&n.file?{"X-Content-File":n.file}:{}}),l=await o.json(),c=o.headers.get("x-content-file");return c&&/^[A-Za-z0-9_-]{1,64}$/.test(c)&&(l.file=c),l}async shadow(e,n,r,i,s,a){let o=Re(n,r.id),l=Oe(i),c=da(i);c&&i.length>=Jd&&await this.keepBase(e,l,i);for(let u of e.stored.jobs)u.path===r.path&&u.target===n&&["failed","paused","active"].includes(u.state)&&["upload","download","merge"].includes(u.direction)&&this.done(u);e.stored.pendingUploads&&delete e.stored.pendingUploads[o],delete e.stored.unconfirmed?.[o],e.stored.files[o]={id:r.id,path:r.path,version:r.version,hash:l,...r.file?{file:r.file}:{},...c&&i.length<Jd?{base:i.toString("utf8")}:{},...a?{inode:a.inode,stat:a.key,statAt:a.at}:s?{inode:s.inode}:{}}}async seen(e,n,r){let i=Ke(e.roots,n),s=await Bt(Fe(i.root,...i.relative.split("/"))).catch(()=>null);if(!s?.isFile())return;let a=Bn(s);return{key:Nr(a),at:r,inode:a.inode}}sameAsShadow(e,n){return!this.dirty.has(n.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===Nr(n)&&Aw(n)<=e.statAt-vw}unchanged(e,n,r,i,s){let a=Re(n,r.id),o=this.sameAsShadow(i,s)&&i.id===r.id&&i.path===s.path&&!r.busy&&!r.deleted&&r.version===i.version&&r.hash===i.hash&&Li(i.file,r.file)&&!e.stored.unconfirmed?.[a]&&!e.stored.pendingUploads?.[a]&&!this.openJobs.has(n+"\0"+s.path);return o&&i.file===void 0&&r.file&&(i.file=r.file),o}hold(e,n){if(e.path.endsWith("/"+Or)||n?.stat===Nr(e))return!1;let r=e.mtime,i=Date.now(),s=this.dirty.get(e.path);if(Math.floor(r)<=this.flushAt)return!1;if(s)s.last=Math.max(s.last,r);else{if(i-r>=ha(e.path))return!1;s={first:Math.min(i,r),last:r},this.dirty.set(e.path,s)}return this.dueAt(e.path,s)>i}settled(e,n){let r=this.dirty.get(e);r&&(r.last<n?this.dirty.delete(e):r.first=n)}async keepBase(e,n,r){let i=pa(e),s=Fe(i,n);if(await Bt(s).then(()=>!0,()=>!1))return;await la(i,{recursive:!0,mode:448});let a=s+".tmp-"+mt();try{await $r(a,r,{mode:384,flag:"wx"}),await rs(a,s)}finally{await Lr(a).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await Pr(Fe(pa(e),n.hash)).catch(i=>{if(i.code==="ENOENT")return null;throw i});return r&&Oe(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(i=>i.hash)),r=pa(e);for(let i of await jr(r).catch(()=>[]))n.has(i)||await Lr(Fe(r,i)).catch(()=>{})}async file(e,n,r,i,s){if(r.size>qt)return this.noteTooLarge(e,i,r.path,r.size,qt),"too-large";let a=v=>{let I=this.capFor(i,r.path,s);return v.length<=I?!1:(this.noteTooLarge(e,i,r.path,v.length,I),!0)},o=s.nodes.find(v=>v.kind==="file"&&!v.deleted&&v.path===r.path);if(!o){let v=Object.entries(e.stored.files).find(([I,E])=>I.startsWith(i+":")&&E.inode===r.inode&&E.path!==r.path)?.[1];if(v){let I=Ke(e.roots,v.path),E=await Bt(Fe(I.root,I.relative)).then(async x=>Bn(x).inode!==r.inode||Wt(v.path)!==Wt(r.path)?!0:(await jr(wn(r.physical))).includes(bn(v.path)),x=>x.code==="ENOENT"?!1:Promise.reject(x)),D=s.nodes.find(x=>x.id===v.id&&!x.deleted);if(!E&&D)try{if(D.path!==v.path)throw Error(`Concurrent file rename: ${r.path}`);let x=Wt(r.path),L=x?s.nodes.find(H=>H.path===x&&H.kind==="folder"&&!H.deleted)?.id:"";if(x&&!L)throw Error("Rename parent unavailable");let V=await this.operation(e,r.path,i,"rename",null,()=>this.json(e,i,`/nodes/${D.id}`,"PATCH",{name:bn(r.path),parentId:L,revision:D.revision}));Object.assign(D,V),v.path=r.path,o=D}catch(x){for(let L of new Set([v.path,D.path,r.path]))this.block(i,L,x);throw x}}}let l=o?e.stored.files[Re(i,o.id)]:Object.entries(e.stored.files).find(([v,I])=>v.startsWith(i+":")&&I.path===r.path)?.[1];if(!l&&o?.version&&i==="default"&&(l=await this.legacyBaseline(r.path,o)),o&&l&&this.unchanged(e,i,o,l,r))return;if(!o&&!l&&r.size>this.capFor(i,r.path,s))return this.noteTooLarge(e,i,r.path,r.size,this.capFor(i,r.path,s)),"too-large";if(this.hold(r,l))return"held";let c=Date.now(),u=await Wn(r),f=Oe(u),g={key:Nr(r),at:c,inode:r.inode};this.guard(e),this.settled(r.path,c);let p,m;if(!o){if((l?s.nodes.find(V=>V.id===l.id&&V.deleted):null)&&l&&(l.hash===f||l.memoryDeleted&&is(r.path)&&f===Yn)){if(is(r.path)){await this.clearDeletedMemory(e,i,r,l,u,f);return}let V=Ot("local",i,l.id),H=this.round;if(!H.restore.has(V)){H.plan.push({key:Gd("local",i,l.id,f,r.path),ns:i,id:l.id,path:r.path,side:"local",e:r,hash:f});return}H.restoreHit.add(V),p=V,m=Re(i,l.id)}if(a(u))return"too-large";let I=Wt(r.path),E=I?s.nodes.find(V=>V.path===I&&!V.deleted&&V.kind==="folder")?.id:"";if(I&&!E)throw Error("Parent folder is unavailable");let D=Object.entries(e.stored.pendingUploads??{}).find(([V,H])=>V.startsWith(i+":")&&H.path===r.path&&!s.nodes.some(N=>N.id===H.id))?.[1];for(let[V,H]of Object.entries(e.stored.pendingUploads??{}))V.startsWith(i+":")&&H.path===r.path&&s.nodes.some(N=>N.id===H.id&&N.deleted)&&delete e.stored.pendingUploads[V];let x=D?.id??mt(),L=Re(i,x);(e.stored.pendingUploads??={})[L]={id:x,path:r.path},await this.persist(e),o=await this.json(e,i,"/nodes","POST",{id:x,parentId:E,name:bn(r.path),kind:"file"}),e.tombstones.get(i)?.delete(o.id),o.id!==x&&delete e.stored.pendingUploads[L],s.nodes.push(o),l=void 0}if(o.busy)return;let y=Re(i,o.id);if(o.version&&this.awaitingBytes.delete(y),o.hash===f){await this.shadow(e,i,o,u,r,g);return}if(o.hash&&e.stored.unconfirmed?.[y]===o.hash&&(await this.shadow(e,i,o,await this.operation(e,r.path,i,"download",o.size??null,v=>this.download(e,o,i,v)),r),l=e.stored.files[y]),!o.version&&l&&l.hash===f&&!e.stored.pendingUploads?.[y]){let v=this.awaitingBytes.get(y)??Date.now();if(this.awaitingBytes.set(y,v),Date.now()-v<yw)return}if(this.awaitingBytes.delete(y),!o.version||l&&o.version===l.version&&Li(l.file,o.file)){if(a(u))return"too-large";(e.stored.unconfirmed??={})[y]=f,await this.persist(e);let v=await this.operation(e,r.path,i,"upload",u.length,I=>this.upload(e,o,i,u,I));Object.assign(o,v),await this.shadow(e,i,o,u,r,g),p&&(this.round.restoreDone.add(p),m&&m!==y&&delete e.stored.files[m]);return}let b=await this.operation(e,r.path,i,"download",o.size??null,v=>this.download(e,o,i,v)),_=b,h=!1;if(!l||l.hash!==f){let v=u.toString("utf8"),I=b.toString("utf8"),E=l?await this.readBase(e,l):null,D=Buffer.from(v).equals(u)&&Buffer.from(I).equals(b)?this.host.contentSync.merge(r.path,v,E,I):null;if(D&&!D.conflict&&E!==null&&ww(r.path)&&!So(E,v,D.content)&&(D=null),D?(_=Buffer.from(D.content),h=D.conflict):h=!0,h){await this.preserveConflict(e,r.path,u)&&(lt("content","conflicts"),this.tally("conflictCopies"));let x=this.job(e,r.path,i,"merge",u.length);x.state="conflict",x.error="Both versions preserved",x.finishedAt=Date.now()}if(!_.equals(b)){let x=await this.operation(e,r.path,i,"merge",_.length,L=>this.upload(e,o,i,_,L));Object.assign(o,x)}}let T=Date.now();await this.write(e,r.path,_,f),await this.shadow(e,i,o,_,r,await this.seen(e,r.path,T))}async preserveConflict(e,n,r){let i=Ke(e.roots,n),s=await ct(i.root,i.relative),a=bn(n),o=Oe(r);for(let l of await jr(wn(s))){if(l.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==a||!Gi(l))continue;let c=Wt(n)?Wt(n)+"/"+l:l,u=Ke(e.roots,c),f=await ct(u.root,u.relative),g=await Bt(f);if(g.isFile()&&g.size===r.length&&Oe(await Pr(f))===o)return!1}return await this.write(e,await this.copyName(e,n),r,null),!0}async copyName(e,n){let r=new Date;for(let i=1;;i++){let s=_d(n,r,i),a=Ke(e.roots,s);if(!await Bt(Fe(a.root,...a.relative.split("/"))).then(()=>!0,o=>o.code==="ENOENT"?!1:Promise.reject(o)))return s}}async legacyBaseline(e,n){let r=await this.host.contentSync.agentFiles?.baseline(e).catch(()=>null);if(!(!r||!n.version)&&!(r.pending&&Number(n.version.split(":")[0])!==r.seq))return{id:n.id,path:e,version:`${r.seq}:${r.hash}`,hash:r.hash,...r.base!==void 0?{base:r.base}:{}}}agentAsks(e,n,r,i,s){let a=[],o=l=>l.length?Math.max(...l):null;for(let l of n){let c=l.kind==="folder"?Ar(l.path):null;if(!c||Hi.has(c))continue;let u=`agents/${c}/`,f=this.route(u+"config.toml",r);if(!f||Object.entries(e.stored.files).some(([b,_])=>b.startsWith(f+":")&&_.path.startsWith(u)))continue;let g=(i.get(f)?.nodes??[]).filter(b=>!b.deleted&&b.kind==="file"&&b.version&&b.path.startsWith(u)&&this.route(b.path,r)===f),p=n.filter(b=>b.kind==="file"&&b.path.startsWith(u)&&this.route(b.path,r)===f);if(!g.length||!p.length)continue;let m=new Map(g.map(b=>[b.path,b])),y=p.filter(b=>{let _=m.get(b.path);return!!_&&s.get(b.path)!==_.hash}).length;!y&&p.length===g.length&&p.every(b=>m.has(b.path))||a.push({slug:c,namespace:f,cloudFiles:g.length,localFiles:p.length,differ:y,cloudMtime:o(g.map(b=>b.mtime??0)),localMtime:o(p.map(b=>b.mtime))})}return a}async resolveAsks(e,n,r,i){for(let s of n){try{await this.resolveAsk(e,s,r[s.slug]??"merge",i)}catch(c){throw this.dropShadows(e,s.namespace,`agents/${s.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Ue(c)}`)}let a=`agents/${s.slug}`,o=i.rules.find(c=>c.source===a),l=Pn(e.stored.config,a,gu(i,a));o&&(l={...l,rules:l.rules.map(c=>c.source===a?{...o,target:c.target}:c)}),e.stored.config=Zt(l,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,i){let s=n.namespace,a=`agents/${n.slug}/`;if(this.dropShadows(e,s,a),r==="local"){await this.archiveAgent(e,s,n.slug),await this.persist(e);return}let o=await this.json(e,s);this.guard(e),Ki(o,s);let l=new Map(o.nodes.filter(p=>!p.deleted&&!p.busy&&p.kind==="file"&&p.version&&p.path.startsWith(a)&&this.route(p.path,i)===s).map(p=>[p.path,p])),c=p=>p.endsWith("/"+Or),u=async(p,m,y)=>{let b=Date.now();return await this.write(e,p,m,y),this.seen(e,p,b)};for(let[p,m]of l){if(!c(p))continue;let y=Ke(e.roots,p);if(Zd(Fe(y.root,y.relative)))continue;let b=await this.operation(e,p,s,"download",m.size??null,_=>this.download(e,m,s,_));await this.shadow(e,s,m,b,void 0,await u(p,b,null))}let f=(await this.scan(e)).filter(p=>p.kind==="file"&&p.path.startsWith(a)&&this.route(p.path,i)===s&&p.size<=qt).sort((p,m)=>+!c(p.path)-+!c(m.path)),g=await this.removedDir(e,n.slug);for(let p of f){this.guard(e);let m=await Wn(p),y=Oe(m),b=l.get(p.path),_=p.path.slice(a.length);if(b&&b.hash===y){await this.shadow(e,s,b,m,p);continue}if(r==="cloud"){if(await this.keep(e,`${g}/${_}`,m),b){let E=await this.operation(e,p.path,s,"download",b.size??null,D=>this.download(e,b,s,D));await this.shadow(e,s,b,E,p,await u(p.path,E,y))}else _==="MEMORY.md"?await this.write(e,p.path,Buffer.alloc(0),y):await this.removeLocal(e,p,y);continue}if(!b)continue;let h=await this.operation(e,p.path,s,"download",b.size??null,E=>this.download(e,b,s,E)),T=s==="default"?await this.legacyBaseline(p.path,b):void 0;if(T?.hash===y){await this.shadow(e,s,b,h,p,await u(p.path,h,y));continue}let v=T?await this.readBase(e,T):null,I=da(m)&&da(h)?this.host.contentSync.merge(p.path,m.toString("utf8"),v,h.toString("utf8")):null;if(I&&!I.conflict){let E=Buffer.from(I.content);E.equals(m)||await this.write(e,p.path,E,y),await this.shadow(e,s,b,h)}else(b.mtime??0)>p.mtime?(await this.keep(e,`${g}/${_}`,m),await this.shadow(e,s,b,h,p,await u(p.path,h,y))):(await this.keep(e,`${g}/${_}`,h),await this.shadow(e,s,b,h))}await this.persist(e)}dropShadows(e,n,r){for(let[i,s]of Object.entries(e.stored.files))i.startsWith(n+":")&&s.path.startsWith(r)&&(delete e.stored.files[i],delete e.stored.unconfirmed?.[i])}async removedDir(e,n,r="agents"){let i=new Date,s=o=>String(o).padStart(2,"0"),a=`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())} ${s(i.getHours())}${s(i.getMinutes())}`;for(let o=1;;o++){let l=`${r}/.removed/${n} ${a}${o>1?` ${o}`:""}`,c=Ke(e.roots,l);if(!await Bt(Fe(c.root,...c.relative.split("/"))).then(()=>!0,u=>u.code==="ENOENT"?!1:Promise.reject(u)))return l}}async keep(e,n,r){this.guard(e),await sa(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(vt(n.root,Fr(n.root,n.physical).split(Vn).join("/")),Oe(Gn(n.physical))!==r)throw Error("Local file changed before replacing");aa(n.physical)})}async archiveAgent(e,n,r){let i=this.host.readCreds();if(!i.token)throw Error("not_signed_in");let s=await this.gatedFetch(e,i.cloudUrl,"/api/remotesync/agent-archive/agent",{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({namespace:n,slug:r,opId:mt(),locale:this.locale()})},12e4);this.guard(e);let a=await s.json().catch(()=>({}));if(this.guard(e),!s.ok||a?.state!=="done")throw Error(typeof a?.detail=="string"?a.detail:`agent_archive_http_${s.status}`)}async absent(e,n,r=e.roots){this.guard(e);let i=Ke(r,n),s=await ct(i.root,i.relative);try{return await Bt(s),!1}catch(a){if(a.code==="ENOENT")return!0;throw a}}async missing(e,n,r,i,s){let a=e.stored.files[Re(r,n.id)],o=e.stored.pendingUploads?.[Re(r,n.id)];if(!n.deleted&&a?.inode&&this.blocked.has(r)&&i.some(y=>y.kind==="file"&&y.inode===a.inode&&this.isBlocked(r,y.path)&&this.route(y.path,s)===r)){this.round?.undecided.add(r+"\0"+n.path);return}let l=qn(this.scanned.unscanned,n.path)||!!a?.inode&&this.scanned.skippedInodes.has(a.inode),c=Do(n,a,!!o,l),u=this.round,f=()=>u.plan.some(y=>y.side==="local"&&y.ns===r&&y.id===n.id)||u.restore.has(Ot("local",r,n.id))||!!e.stored.deleteGuard?.pending.some(y=>y.side==="local"&&y.ns===r&&y.id===n.id);if(c==="forget"){a&&!f()&&delete e.stored.files[Re(r,n.id)],o&&delete e.stored.pendingUploads[Re(r,n.id)];return}if(c==="skip")return u.undecided.add(r+"\0"+n.path),a&&u.undecided.add(r+"\0"+a.path),l?"unknown":void 0;if(c==="cancel"){await this.absent(e,n.path)&&(await this.operation(e,n.path,r,"delete",null,()=>this.json(e,r,`/nodes/${n.id}`,"DELETE",{revision:n.revision,version:null})),delete e.stored.pendingUploads[Re(r,n.id)],n.deleted=!0);return}let g;if(c==="delete"){if(!await this.absent(e,n.path))return;let y=Ot("cloud",r,n.id);if(!u.restore.has(y)){u.plan.push({key:Gd("cloud",r,n.id,n.version,n.path),ns:r,id:n.id,path:n.path,side:"cloud",node:n});return}u.restoreHit.add(y),g=y}if(n.size!==void 0&&n.size>qt){this.noteTooLarge(e,r,n.path,n.size,qt),u.undecided.add(r+"\0"+n.path);return}let p=await this.operation(e,n.path,r,"download",n.size??null,y=>this.download(e,n,r,y)),m=Date.now();await this.write(e,n.path,p,null),await this.shadow(e,r,n,p,void 0,await this.seen(e,n.path,m)),g&&u.restoreDone.add(g)}async executeDeletes(e,n){let r=e.stored.deleteGuard,i=n.plan,s=new Set(i.map(_=>_.key)),a=new Set(i.map(_=>Ot(_.side,_.ns,_.id))),o=new Set((r?.confirmed??[]).filter(_=>s.has(_))),l=Date.now();this.deleteStamps=this.deleteStamps.filter(_=>l-_<Ro);let c=i.filter(_=>!o.has(_.key)),u=Oo(c,n.tracked,{latched:!!r?.latched,recent:this.deleteStamps.length});u&&!r?.latched&<("content","massDeleteGuard");let f=_=>{let h=e.stored.files[Re(_.ns,_.id)];return[_.path,...h?[h.path]:[]].some(v=>n.undecided.has(_.ns+"\0"+v)||qn(this.scanned.unscanned,v))||!!h?.inode&&this.scanned.skippedInodes.has(h.inode)},g=(r?.pending??[]).filter(_=>!a.has(Ot(_.side,_.ns,_.id))&&f(_)),p=[...n.restore].filter(([_,h])=>!n.restoreDone.has(_)&&(n.restoreHit.has(_)||f(h))).map(([,_])=>_),m={latched:u||g.length>0,pending:[...u?c.map(Vd):[],...g],...o.size?{confirmed:[...o]}:{},...p.length?{restore:p}:{}},y=()=>{m.latched||m.pending.length||m.confirmed?.length||m.restore?.length?e.stored.deleteGuard=m:delete e.stored.deleteGuard};y(),await this.persist(e);let b=[...i.filter(_=>o.has(_.key)),...u?[]:c];for(let _=0;_<b.length;_++){let h=b[_],T=o.has(h.key);try{if(h.side==="cloud"){if(!await this.absent(e,h.path))continue;let v=h.node;await this.operation(e,h.path,h.ns,"delete",v.size??null,()=>this.json(e,h.ns,`/nodes/${v.id}`,"DELETE",{revision:v.revision,version:v.version,...v.file?{file:v.file}:{}},T?{"X-Content-Delete-Confirmed":"1"}:void 0)),delete e.stored.files[Re(h.ns,v.id)],v.deleted=!0}else await this.operation(e,h.path,h.ns,"delete",h.e.size,()=>this.trashFile(e,h.e,h.hash)),this.tally("deletesLocal"),delete e.stored.files[Re(h.ns,h.id)];T?m.confirmed=m.confirmed?.filter(v=>v!==h.key):this.deleteStamps.push(Date.now())}catch(v){if(v?.code!=="MASS_DELETE_BLOCKED"){this.error=Ue(v);continue}m.latched||lt("content","massDeleteGuard"),m.latched=!0,m.pending=[...m.pending,...b.slice(_).filter(I=>I.side==="cloud").map(Vd)];for(let I of b.slice(_+1))if(I.side==="local")try{await this.operation(e,I.path,I.ns,"delete",I.e.size,()=>this.trashFile(e,I.e,I.hash)),this.tally("deletesLocal"),delete e.stored.files[Re(I.ns,I.id)]}catch(E){this.error=Ue(E)}break}}y(),await this.persist(e)}async recoverTrash(e){for(let n of[...e.stored.trash??[]]){if(n.parentId){let c=(await ns(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);c&&(n.path=c.path+"/"+bn(n.path))}let r=Ke(e.roots,n.path),i=await ct(r.root,r.relative);if(!/^\.forsion-sync-trash-[a-f0-9-]+$/.test(n.stage))throw Error("Invalid sync recovery journal");let s=n.stageRoot??r.root,a=await this.rootIdentity(e,s),o=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(o&&!an(o,a))throw Error("Sync recovery root changed; journal retained");let l=Fe(s,n.stage);await Bt(l).then(()=>!0,c=>c.code==="ENOENT"?!1:Promise.reject(c))&&await this.lock(e,i,()=>{if(vt(s,n.stage,!0),Oe(Gn(l))!==n.hash)throw Error("Sync recovery content changed");vt(r.root,r.relative),sw(wn(i),{recursive:!0});let c=Zd(i)?i+` (sync recovery ${mt().slice(0,8)})`:i;try{tw(l,c)}catch(u){if(u.code!=="EXDEV")throw u;if(ow(l,c,aw.COPYFILE_EXCL),Oe(Gn(c))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}aa(l)},!0),e.stored.trash=e.stored.trash.filter(c=>c!==n)}}async clearDeletedMemory(e,n,r,i,s,a){i.memoryDeleted&&i.hash===Yn&&a===Yn||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!i.memoryDeleted&&s.length){let c=r.path==="human/MEMORY.md",u=await this.removedDir(e,c?"memory":r.path.split("/")[1],c?"human":"agents");await this.keep(e,`${u}/MEMORY.md`,s)}i.memoryDeleted=!0,await this.persist(e);let o=Date.now();s.length&&await this.write(e,r.path,Buffer.alloc(0),a);let l=await this.seen(e,r.path,o);e.stored.files[Re(n,i.id)]={...i,hash:Yn,base:"",stat:void 0,statAt:void 0,...l?{inode:l.inode,stat:l.key,statAt:l.at}:{}}}),this.tally("deletesLocal"))}async trashFile(e,n,r){this.guard(e);let i=await ct(n.root,Fr(n.root,n.physical).split(Vn).join("/")),s={path:n.path,stage:".forsion-sync-trash-"+mt(),hash:r},a=Fe(n.root,s.stage),o=await this.rootIdentity(e,n.root);s.stageRoot=n.root,s.stageDev=o.dev,s.stageIno=o.ino,s.stageIdentity=o;try{let l=JSON.parse(Gn(Fe(wn(i),".forsion-sync-id.json"),"utf8")).id;/^[a-f0-9-]{36}$/i.test(l)&&(s.parentId=l)}catch{}(e.stored.trash??=[]).push(s),await this.persist(e);try{await this.lock(e,i,()=>{if(vt(n.root,Fr(n.root,i).split(Vn).join("/")),Oe(Gn(i))!==r)throw Error("Local file changed before deletion");ew(i,a)}),await this.host.contentSync.trash(a),e.stored.trash=e.stored.trash.filter(l=>l!==s)}catch(l){throw this.host.accountId()===e.account&&!e.abort.signal.aborted&&await this.recoverTrash(e),l}}};function xw(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))Cr.test(n)&&uu.includes(r)&&(e[n]=r);return e}function Zd(t){try{return Zy(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}Ha(El);function Rk(t){kl(t.contentSync?.withWriteLock?.bind(t.contentSync)),Xa(t),Gs(t),ef(t),t.log("[forsion-extend] cloud account handlers registered"),js(t)?Ls(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Us(t)?Hs(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),Qs(t)?eo(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),wo(t)?bo(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),ko(t)?Eo(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Uo(t)?Zu(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),Uo(t)&&vd(t)}export{Ql as ACCOUNT_SEAM,Kc as AMADEUS_SEAM,$s as CONNECT_MAX_FILES,Al as CONNECT_MAX_FILE_BYTES,xl as CONNECT_MAX_TOTAL_BYTES,mi as DIAGNOSTICS_VAULT,$l as FORSION_CONNECT_LOCAL_SDK,Ja as PAY_PERIODS,Ya as PAY_TABS,Fl as PENZOR_MAX_FILE,Ne as SYNC_IPC,Qc as UNIT_SEAM,cr as UPLOAD_MAX_FILE,vr as UnitCapsReporter,Sr as UnitHost,Ze as cloudJson,Il as collectProjectFiles,Si as conflictCopyPath,Dh as conflictCopyVariant,Nl as connectMetaOf,Zl as createAccountCloud,Xc as createAmadeusCloud,gi as createPenzorRemote,eu as createUnitHub,hi as deviceHeader,Fs as expectedPartsOf,Ve as forsionAccountId,ri as forsionRefreshToken,lr as forsionWhoami,Qs as hasAccountHost,wo as hasAmadeusHost,js as hasConnectHost,Us as hasRemoteSyncHost,ko as hasUnitHost,Pl as makePreviewProxy,Yl as multipartFrame,Dl as readConnectMeta,eo as registerAccount,bo as registerAmadeus,Rk as registerCloud,Ls as registerConnect,Hs as registerPenzor,Gs as registerPenzorTransfers,Eo as registerUnit,yi as safeDownloadName,Ml as scanSdkUsage,ni as shouldRefreshToken,zs as speedOf,Zc as streamWorthy,Pc as stripConflictSuffix,Oh as textFingerprint,ws as tokenAgeMs,Wa as tokenRemainingMs,Bs as uploadError,Ol as writeConnectMeta};
|
|
291
|
+
`,{encoding:"utf8",mode:384});try{if(PI(s()).size>Ub){let Z=h(),P=Z.length,F=0;for(;P>0&&F+Buffer.byteLength(JSON.stringify(Z[P-1]))+1<=Ub/2;)F+=Buffer.byteLength(JSON.stringify(Z[--P]))+1;E(s(),Z.slice(P))}}catch{}h().length>=LI&&ce()}},O=()=>{let te=d();return{available:!!c,enabled:te.enabled!==!1,noticeSeen:te.noticeSeen===!0,signedIn:m(),active:y(te),packaged:c?.packaged===!0,installId:p(),queued:DI(s())?h().length:0,lastSentAt:te.lastSentAt??null,lastError:te.lastError??null}},q=()=>Pb({app:"desktop",appVersion:n.appVersion(),coreVersion:c?.coreVersion()??void 0,channel:c?.channel(),os:sx(process.platform),osVersion:MI(),arch:ax(process.arch),locale:lx()}),ie=Cb,Y=async te=>{try{let Z=await te.json?.();return!!Z&&typeof Z=="object"&&Z.detail==="unsupported v"}catch{return!1}},ne=null,ce=()=>{if(ne)return ne;if(N||t().getTime()<D)return Promise.resolve();let te=R,Z=v,P=(async()=>{try{for(let F=0;F<5;F++){let L=h();if(!L.length)return;let j=p(),z={v:ie,installId:j,...q()},W=[],ee=Buffer.byteLength(JSON.stringify({...z,events:[]}));for(let ue of L){let X=Buffer.byteLength(JSON.stringify(ue))+1;if(W.length>=mf.maxEvents||ee+X>mf.maxBatchBytes)break;W.push(ue),ee+=X}if(!W.length){E(s(),L.slice(1));continue}let{base:K}=await n.getCloud(),H={...z,events:W};if(!M()||te!==R)return;let oe=await r(`${K.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(H),signal:AbortSignal.timeout(Vb)}).catch(ue=>({ok:!1,status:0,error:String(ue?.message||ue)})),se=oe.status;if(se===400&&z.v>_f&&await Y(oe)){ie=_f,n.log(`[forsion-extend] telemetry server does not accept v${z.v}; resending as v${_f}`);continue}if(se>=200&&se<300||se===400||se===413){let ue=new Set(W.map(X=>JSON.stringify(X)));E(s(),h().filter(X=>!ue.has(JSON.stringify(X))))}if(se>=200&&se<300){let ue=t().getTime();Z===v&&E(l(),[..._(),{at:ue,body:H}]),f({lastSentAt:ue,lastError:void 0});continue}if(se!==400&&se!==413){let ue=Number(oe.headers?.get?.("retry-after"));D=t().getTime()+(Number.isFinite(ue)&&ue>0?Math.min(ue,3600)*1e3:5*6e4)}f({lastError:se?`HTTP ${se}`:String(oe.error??"network error").slice(0,200)});return}}catch(F){try{f({lastError:String(F?.message||F).slice(0,200)})}catch{}}})();return ne=P,P.finally(()=>{ne===P&&(ne=null)}),P},Re=te=>{if(!k||!te&&Math.floor(t().getTime()/Ef)===k.hour)return;let Z=k;if(k=null,Z.gen!==R||!M())return;let P=fr({event:"quota_prompt",ts:t().toISOString(),sessionId:c?.sessionId,props:{...Z.counts,entry:"quota-page"}});try{P&&Object.keys(P.props).some(F=>F!=="entry")&&$([P])}catch(F){throw k=Z,F}},Ee=async()=>{try{if(_(),Re(!1),!M())return;let te=d(),Z=R,P=te.cursor??Af(t().getTime()),F=await rx(i(),P,c?.sessionId,qb(t().getTime()));if(!M()||Z!==R)return;$(F.events),F.cursor!==P&&f({cursor:F.cursor}),await me(Z),await ce()}catch(te){n.log(`[forsion-extend] telemetry tick failed: ${String(te?.message||te)}`)}},me=async te=>{let Z=t().getTime(),P=wi(Z),F=wi(Z-zb),L=d().ledgerCursor;if(bi(L)||(L=F,f({ledgerCursor:L})),Ed(L),L>=F){Ce();return}let j=await ix(i(),L,P);if(!(!M()||te!==R)){if(j){let z=j.complete?F:j.days[j.days.length-1]?.day??L;if(z>L){let W=Gh(L,z),ee=[...new Set([...j.days.map(H=>H.day),...W.map(H=>H.day)])].filter(H=>H>L&&H<=z).sort(),K=[];for(let H of ee){K.push(...j.days.find(oe=>oe.day===H)?.events??[]);for(let oe of W)if(oe.day===H){let se=ox(H,oe.system,oe.counts);se&&K.push(se)}}$(K),f({ledgerCursor:z}),Ed(z)}}Ce()}},Ce=()=>{if(!qh())return;let te=g();if(!te)return;let Z=Hh();f({syncHealth:Object.keys(Z).length?Z:void 0},te),Wh()},Be=c?.subscribe(te=>{try{if(!VI.has(te?.event)||!M())return;let Z=ZI(te);if(!Z)return;let P=fr({...Z,sessionId:c.sessionId},OI()),F=tx[te.event];P&&(!F||P.props[F]!==void 0)&&$([P])}catch(Z){n.log(`[forsion-extend] telemetry event dropped: ${String(Z?.message||Z)}`)}}),_e={ok:!1,error:"untrusted"};n.handle("telemetry:get",te=>n.isTrustedSender(te)?(M(),O()):_e),n.handle("telemetry:set",(te,Z)=>{if(!n.isTrustedSender(te))return _e;let P=d(),F={};typeof Z?.enabled=="boolean"&&(F.enabled=Z.enabled),Z?.noticeSeen===!0&&(F.noticeSeen=!0);let L={...P,...F};return!y(P)&&y(L)&&(F.cursor=Af(t().getTime()),F.ledgerCursor=u()),y(P)&&!y(L)&&R++,F.enabled===!1&&(F.syncHealth=void 0),f(F),F.enabled===!1&&S(),M(),O()}),n.handle("telemetry:quotaPrompt",(te,Z)=>{if(!n.isTrustedSender(te))return _e;let P=Z?.action;return Z?.entry!=="quota-page"||typeof P!="string"||!zI.has(P)?{ok:!1,error:"invalid"}:(Re(!1),M()?((!k||k.gen!==R)&&(k={hour:Math.floor(t().getTime()/Ef),gen:R,counts:{}}),k.counts[P]=Math.min((k.counts[P]??0)+1,HI),{ok:!0,counted:!0}):{ok:!0,counted:!1})}),n.handle("telemetry:forcedUpdate",(te,Z)=>{if(!n.isTrustedSender(te))return _e;let P=Z?.stage;if(typeof P!="string"||!qI.has(P))return{ok:!1,error:"invalid"};let F=Array.isArray(Z?.reasons)?[...new Set(Z.reasons.filter(K=>typeof K=="string"&&WI.has(K)))].sort():[],L="";for(let K of F){let H=L?`${L}+${K}`:K;H.length<=JI&&(L=H)}let j=typeof Z?.target=="string"&&Z.target.length<=40&&YI.test(Z.target)?Z.target:void 0,z=typeof Z?.policy=="string"&&KI.test(Z.policy)?Z.policy:void 0;if(!M())return{ok:!0,counted:!1};let W=Math.floor(t().getTime()/Ef);if((!C||C.hour!==W)&&(C={hour:W,counts:{}}),(C.counts[P]=(C.counts[P]??0)+1)>GI)return{ok:!0,counted:!1};let ee=fr({event:"forced_update",ts:t().toISOString(),sessionId:c?.sessionId,props:{stage:P,...L?{reasons:L}:{},...j?{target:j}:{},...z?{policy:z}:{}}});return ee&&$([ee]),{ok:!0,counted:!!ee}}),n.handle("telemetry:sent",te=>n.isTrustedSender(te)?{batches:_()}:_e),n.handle("telemetry:delete",async te=>{if(!n.isTrustedSender(te))return _e;N=!0,R++;try{await ne?.catch(()=>{});let Z=p(),{base:P}=await n.getCloud(),L=(await r(`${P.replace(/\/+$/,"")}/api/telemetry/install/${Z}`,{method:"DELETE",signal:AbortSignal.timeout(Vb)}).catch(j=>({ok:!1,status:0,error:String(j?.message||j)}))).status;return L>=200&&L<300?(S(),f({installId:Lb(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),O()):{ok:!1,error:L?`HTTP ${L}`:"network error"}}finally{N=!1}});try{zh(d().syncHealth),x(),M()}catch(te){n.log(`[forsion-extend] telemetry startup check failed: ${String(te?.message||te)}`)}let ft=n.addFlushHook?.(te=>{if(te!=="blur"){try{Ce()}catch{}try{Re(!0)}catch{}}}),at=setTimeout(()=>void Ee(),$I),Ir=setInterval(()=>void Ee(),NI);return at.unref?.(),Ir.unref?.(),n.log(`[forsion-extend] telemetry registered (${c?c.packaged?"packaged":"dev build: never sends":"host has no telemetry seam: never sends"})`),Object.assign(()=>{clearTimeout(at),clearInterval(Ir),Be?.(),ft?.()},{tick:Ee,flush:ce})}import{writeFile as hx,mkdir as mx,lstat as yx}from"node:fs/promises";import{basename as Yb,dirname as wx,extname as bx}from"node:path";import{isDeepStrictEqual as vx}from"node:util";import{stat as cx}from"node:fs/promises";import{isAbsolute as dx}from"node:path";import{basename as ux}from"node:path";var fx=new Set(["root_nested","primary_exists","mirror_root","folder_target_nested","entry_sync_active","already_local","legacy_remote_same_root"]),gx=new Set(["reserved","invalid_name","server_unsupported","not_signed_in"]);async function px(n,e){let t=Le(e);return(await n.libraries?.().catch(()=>null))?.find(i=>!i.deleted&&i.nameKey===t)?.id}async function Gb(n,e,t){let{root:r,expectedAccountId:i}=t&&typeof t=="object"?t:{},o=n.host.accountId(),a=i!==void 0;if(a&&(typeof i!="string"||!i||i!==o))return{ok:!1,error:"account_changed"};if(!o)return{ok:!1,error:"not_signed_in"};if(typeof r!="string"||!dx(r))return{ok:!1,error:"root_missing"};let s=await cx(r).catch(()=>null);if(!s)return{ok:!1,error:"root_missing"};if(!s.isDirectory())return{ok:!1,error:"not_a_directory"};let l=await pe(r),c=(await n.bindings()).find(d=>d.b.root===l&&d.b.role==="primary");if(c)return{ok:!1,error:"already_bound",bindingId:c.b.id};let u={root:l,target:{kind:"penzor",candidate:{kind:"new"}},scope:{mode:"all"}};for(let d=0;d<2;d++){let g=e;try{if(n.host.accountId()!==o)throw Error("stale");if(a){let m=e.snapshot?.();if(!m||m.account!==i)return{ok:!1,error:"account_changed"};g=m.api}let f=await ji(n,g,u),p=await Ui(n,g,{token:f.token,generation:f.generation,onDiffer:"hold"},{account:o,expectedAccountId:i});if("bindingId"in p)return{ok:!0,bindingId:p.bindingId}}catch(f){let p=String(f?.message??"");if(a&&(p==="account_changed"||n.host.accountId()!==o))return{ok:!1,error:"account_changed"};if(p==="name_exists"){let m=await px(g,ux(l));return{ok:!1,error:"name_exists",...m?{libraryId:m}:{}}}if(gx.has(p))return{ok:!1,error:p};if(fx.has(p))return{ok:!1,error:p};if(f instanceof ze&&f.status===404)return{ok:!1,error:"server_unsupported"};if(f instanceof ze&&f.code==="not_signed_in")return{ok:!1,error:"not_signed_in"};if($u(f))return{ok:!1,error:"offline"};throw f}}throw Error("stale")}var Jb=[he.download,he.create,he.unbind];function Kb(n,e,t){let r=async()=>{if(t(),n.stateUnreadable()&&await n.refresh().catch(()=>{}),n.stateUnreadable())throw Error("state_unreadable");let i=n.host.accountId();try{await n.v3.read("device"),i&&(await n.v3.read(ae(i)),await n.store.readAccount(i))}catch(o){throw o instanceof Xe?Error("state_unreadable"):o}};return{[he.downloadCheck]:async i=>(await r(),gw(n,e,i)),[he.download]:async i=>(await r(),pw(n,e,i)),[he.create]:async i=>{await r();let o=await Gb(n,e,i);return o.ok&&n.librariesChanged(),o},[he.unbind]:async i=>(await r(),Wy(n,i))}}var Sx=new Set([he.apply,he.setEnabled,he.setScope,he.setTarget,he.resolve,he.resolveAll,he.deletesConfirm,he.deletesAbandon,he.renameAnswer,he.choose,he.setCadence,he.recoveryRestore,he.takeoverRevert,...Jb]);function kx(n,e,t,r=1){let i=bx(n),o=i?n.slice(0,-i.length):n,a=e.toISOString().slice(0,10),s=t==="zh"?`\uFF08\u627E\u56DE ${a}${r>1?` ${r}`:""}\uFF09`:` (recovered ${a}${r>1?` ${r}`:""})`;return`${o}${s}${i}`}var mt=n=>n&&typeof n=="object"?n:{},Xb=new Set(["invalid_ref","account_changed","no_main_window","renderer_unsupported","switch_failed","switch_timeout"]),Cf=async n=>{try{return await n()}catch(e){if(e instanceof go||e instanceof $r)return e.failure;throw e}};function Zb(n,e={}){if(!n.contentSync)return;let t=new Pl(n,e),r=_o(n,()=>t.deviceId()),i="zh",o=0,a=0;t.isMutating=()=>o>0;let s=()=>{if(!t.full())throw Error("compat_mode")},l=async y=>{let b=(await t.bindings()).find(h=>h.b.id===y);if(!b)throw Error("binding_not_found");return b},c=async y=>{if(typeof y=="string"&&await ar(t,y))throw Error("move_in_progress")},u=async(y,b,h)=>{let E=!1,v=k=>{let C=k.bindings.find(N=>N.id===y);if(!C)throw Error("binding_not_found");let{enabled:S,paused:_,scope:R}=C;return h(C),E=C.enabled!==S||C.paused!==_||!vx(C.scope,R),k};return b?await t.store.updateAccount(b,v):await t.store.updateDevice(v),E?b:null},d=(y,b)=>Ae(async()=>{await c(y);let{b:h,account:E}=await l(y);return b(h,E)}),g=y=>y.mode==="full"?{...y,onlineCapable:Gr(n)}:y,f=async y=>{let b="not_fetched";for(let h of[!1,!0]){let E=await t.libraries(h);if("list"in E){let v=E.list.libraries.find(k=>k.id===y);if(v)return v;b=h&&E.stale?"not_fetched":"library_not_found"}else b=E.error}if(b==="library_not_found")return null;throw Error(b)},p=async(y,b)=>{let h;try{h=r.snapshot?.()}catch{throw Error("not_fetched")}if(!h?.account||!h.api.sharedWithMe)throw Error("not_fetched");if(h.account!==b)throw Error("account_changed");let v=(await h.api.sharedWithMe().catch(k=>{throw Error(k instanceof ze&&k.status===404?"server_unsupported":"not_fetched")})).find(k=>k.vaultId===y);if(!v)throw Error("library_not_found");return{id:v.vaultId,vaultId:v.vaultId,prefix:"Amadeus/",name:v.title}},m={[he.get]:async y=>((y==="zh"||y==="en")&&(i=y),g(await t.get())),[he.status]:async()=>g(await t.status()),[he.openOnline]:async y=>{if(typeof n.openLibrary!="function"||!Fd())throw Error("unsupported");if(!Bd(n))throw Error("renderer_unsupported");s();let b=n.accountId();if(!b)throw Error("not_signed_in");let h=mt(y).libraryId;if(typeof h!="string"||!h||h.length>4096)throw Error("library_not_found");let E=++a,v=await f(h);if(n.accountId()!==b)throw Error("account_changed");let k=v??await p(h,b).finally(()=>{if(n.accountId()!==b)throw Error("account_changed");if(E!==a)throw Error("switch_failed")}),C=Fa(k,Sr(b));if(!C)throw Error("invalid_ref");try{await n.openLibrary(C)}catch(S){if(!v&&n.accountId()!==b)throw Error("account_changed");let _=String(S?.message??S);throw Xb.has(_)||n.log?.(`[vault-sync] openLibrary: ${_}`),Error(Xb.has(_)?_:"switch_failed")}if(n.accountId()!==b)throw Error("account_changed")},[he.libraries]:y=>(s(),t.libraries(mt(y).refresh===!0)),[he.resolveName]:async y=>{s();let b=String(mt(y).root??""),h=b.split(/[\\/]/).filter(Boolean).pop()??"";if(qn(h))return{candidates:[],error:"invalid_name"};if(uo(h))return{candidates:[],error:"reserved"};let E=n.readCreds(),v=await fetch(E.cloudUrl.replace(/\/+$/,"")+"/api/amadeus/vaults/resolve",{method:"POST",headers:{Authorization:`Bearer ${E.token}`,"Content-Type":"application/json","X-Content-Caps":rd},body:JSON.stringify({name:h}),signal:AbortSignal.timeout(3e4)});if(v.status===404)return{candidates:[],error:"server_unsupported"};if(!v.ok)throw new ze(v.status,void 0,`http_${v.status}`);let k=await v.json();return{candidates:Array.isArray(k?.candidates)?k.candidates:[]}},[he.preview]:y=>(s(),Cf(()=>ji(t,r,y))),[he.apply]:async y=>{s();let b=await Cf(()=>Ui(t,r,y));return"error"in b?b:(t.librariesChanged(),(await t.get({waitCloud:!1})).bindings.find(E=>E.id===b.bindingId)??b)},[he.setEnabled]:y=>Cf(async()=>{s();let{bindingId:b,enabled:h}=mt(y);if(await c(b),h!==!0){let k=await d(b,(C,S)=>u(C.id,S,_=>{_.enabled=!1}));await t.refreshAfterBindingChange(k);return}let E=yn.of(n);if(E){let{b:k}=await l(b);if(k.target.kind==="remote"){let C=await t.legacyAdmission();await Yn({root:k.root,id:k.id,target:k.target},t.occupied((await t.bindings()).map(S=>S.b)),{released:await t.manager.releasedBindings(),legacy:C.occupant,identities:E})}}let v=await Ae(async()=>{let{b:k,account:C}=await l(b),S=(await t.v3.read(k.target.kind==="remote"?"device":ae(C??""))).marks[k.id];if(t.unbinding.has(k.id)||S?.unbinding)throw Error("unbinding_in_progress");if(t.retargeting.has(k.id)||S?.retarget)throw Error("retarget_in_progress");if(k.state==="takeover")throw Error("takeover_in_progress");await c(k.id);let _=C??n.accountId();if(k.target.kind==="penzor"&&_&&jt(await t.entrySyncRoots(_),await pe(k.root)))throw Error("entry_sync_active");let R=t.occupied((await t.bindings()).map(x=>x.b)),N=Ke({root:k.root,id:k.id,role:k.role},R);if(N)throw Error(N);let D=await t.legacyAdmission();k.target.kind==="remote"&&Xn({root:k.root,id:k.id,target:k.target},R,{released:await t.manager.releasedBindings(),legacy:D.occupant,identities:E}),nn(await pe(k.root),k.scope,D.running),k.target.kind==="remote"&&(await $i(t,_,k.root,k.target,R),await Li(t,_,await pe(k.root)));let M=await u(k.id,C,x=>{x.enabled=!0,x.paused=!1});return S?.cloudDeleted&&await t.v3.update(ae(C??""),x=>{let $=x.marks[k.id];if($?.cloudDeleted)return delete $.cloudDeleted,Object.keys($).length||delete x.marks[k.id],x}),M??(S?.cloudDeleted?C:null)});await t.refreshAfterBindingChange(v)}),[he.setScope]:async y=>{s();let{bindingId:b,scope:h}=mt(y),E,v=await d(b,async(k,C)=>{if(!h||h.mode!=="all"&&h.mode!=="some")throw Error("invalid_scope");if(k.state==="takeover"||k.firstRound==="takeover")throw Error("takeover_in_progress");let S=Cp(k.scope,h);return S?u(k.id,C,_=>{if(_.generation!==k.generation)throw Error("stale");if(_.state==="takeover"||_.firstRound==="takeover")throw Error("takeover_in_progress");_.scope=S,_.generation+=1}):(E={error:"preview_required"},null)});if(E)return E;await t.refreshAfterBindingChange(v)},[he.setTarget]:()=>({error:"preview_required"}),[he.run]:y=>{s();let b=mt(y);if(b.reason==="focus"){t.scheduler.focus(),t.librariesFocus();return}t.runNow(typeof b.bindingId=="string"?b.bindingId:void 0)},[he.resolve]:async y=>{s();let{ref:b,action:h}=mt(y);if(!b||typeof h!="string"||!["local","cloud","both","newer"].includes(h))return{ok:!1,error:"invalid"};await c(b.bindingId);let{b:E}=await l(b.bindingId).catch(()=>({b:null}));if(!E)return{ok:!1,error:"not_found"};let v=Sy(E,b),k=t.engineOf(E.id);if(!v||!k)return{ok:!1,error:"stale"};let C=await k.engine.resolveHeld(b.path,v,h);return!C.ok&&C.error==="vault_moving"&&t.takeMoved(k),!C.ok&&C.error==="vault_deleted"&&t.takeDeleted(k),C},[he.resolveAll]:async y=>{s();let{bindingId:b,action:h,token:E}=mt(y);if(typeof h!="string"||!["local","cloud","both","newer"].includes(h))return{error:"invalid"};await c(b);let{b:v}=await l(b),k=t.engineOf(v.id);if(!k)throw Error("binding_not_running");let C=await k.engine.heldList();if(nl(tl(v,C))!==String(E??""))return{error:"stale"};let S={resolved:0,cannotDecide:0,stale:0,failed:0,recoveryEventIds:[]};for(let _ of C){let R=await k.engine.resolveHeld(_.path,_.generation,h).catch(()=>({ok:!1,error:"failed"}));if(R.ok)S.resolved++,R.recoveryEventId&&S.recoveryEventIds.push(R.recoveryEventId);else if(R.error==="cannot_decide"||R.error==="direction_forbids")S.cannotDecide++;else if(R.error==="stale"||R.error==="not_found")S.stale++;else if(R.error==="vault_moving"){S.stale+=C.length-S.resolved-S.cannotDecide-S.stale-S.failed,t.takeMoved(k);break}else if(R.error==="vault_deleted"){S.stale+=C.length-S.resolved-S.cannotDecide-S.stale-S.failed,t.takeDeleted(k);break}else S.failed++}return S},[he.deletesConfirm]:async y=>{s();let{bindingId:b,token:h}=mt(y);await c(b);let E=t.engineOf(String(b));if(!E)throw Error("binding_not_running");await E.engine.confirmDeletes(String(h??""))},[he.deletesAbandon]:async y=>{s();let{bindingId:b,token:h}=mt(y);await c(b);let E=t.engineOf(String(b));if(!E)throw Error("binding_not_running");await E.engine.abandonDeletes(String(h??""))},[he.renameAnswer]:async y=>{s();let{bindingId:b,choice:h}=mt(y);await c(b);let{b:E,account:v}=await l(b);if(E.state!=="needs-rename-answer")throw Error("not_needs_rename_answer");let k=_=>{_.state="active",_.nameKey=Le(Yb(_.root)),delete _.renamedFrom};if(h==="pause"){let _=await d(E.id,async(R,N)=>{if(R.state!=="needs-rename-answer")throw Error("stale");let D=await u(R.id,N,M=>{k(M),M.paused=!0});return N&&await t.v3.update(ae(N),M=>{let x=M.marks[R.id]?.cloudDeleted;if(!(!x||x.wasPaused))return x.wasPaused=!0,M}),D});return t.refreshAfterBindingChange(_)}if(h==="newVault")return{next:"preview"};if(h!=="renameCloud")throw Error("invalid_choice");if(E.target.kind!=="penzor"||E.target.placement!=="own")return{error:"legacy_rename_unavailable"};let C=Yb(E.root);if(qn(C))return{error:"invalid_name"};if(uo(C))return{error:"reserved"};try{await r.renameVault(E.target.vaultId,C)}catch(_){if(_ instanceof ze&&_.status===409&&(_.code==="EXISTS"||_.code==="LEGACY_PLACEMENT"))return{error:"name_exists"};if(_ instanceof ze&&(_.code==="RESERVED"||_.code==="DEFAULT_VAULT"))return{error:"reserved"};throw _}t.librariesChanged();let S=await Ae(async()=>{await c(E.id);let _=Ke({root:E.root,id:E.id,role:E.role},(await t.bindings()).map(R=>R.b).filter(R=>R.id!==E.id));if(_)throw Error(_);return u(E.id,v,R=>{if(R.state!=="needs-rename-answer")throw Error("stale");k(R),R.paused=!1})});await t.refreshAfterBindingChange(S)},[he.choose]:async y=>{s();let{bindingId:b,choice:h}=mt(y);await c(b);let{b:E}=await l(b);if(E.state!=="needs-choice")throw Error("not_needs_choice");if(h!=="off"&&h!=="backup"&&h!=="primary")throw Error("invalid_choice");let v=await d(E.id,async(k,C)=>{if(k.state!=="needs-choice")throw Error("stale");if(h==="off")return u(k.id,C,_=>{_.enabled=!1,_.state="active"});if(h==="backup")return u(k.id,C,_=>{_.role="backup",_.state="active",_.paused=!1,_.target.kind==="remote"&&(_.target.direction="push")});if((await t.bindings()).filter(_=>_.b.id!==k.id&&_.b.root===k.root&&_.b.role==="primary"&&_.b.enabled).length)throw Error("primary_exists");return u(k.id,C,_=>{_.role="primary",_.state="active",_.paused=!1})});await t.refreshAfterBindingChange(v)},[he.setCadence]:async y=>{s();let b=mt(y);if(!(b.kind==="manual"||b.kind==="interval"&&[5,10,30].includes(b.minutes)))throw Error("invalid_cadence");await t.store.updateDevice(h=>(h.cadence=b.kind==="manual"?{kind:"manual"}:{kind:"interval",minutes:b.minutes},h)),await t.refresh()},[he.recoveryList]:async y=>{s();let b=Number(mt(y).since??0)||0,h=n.accountId();return(await Promise.all([Oi(()=>n.homeDir(),"device").list(b),h?Oi(()=>n.homeDir(),ae(h)).list(b):Promise.resolve([])])).flat().sort((v,k)=>k.at-v.at).map(({ns:v,...k})=>k)},[he.recoveryRestore]:async y=>{s();let b=String(mt(y).eventId??""),h=n.accountId();for(let E of["device",...h?[ae(h)]:[]]){let v=Oi(()=>n.homeDir(),E),k=await v.get(b);if(!k)continue;let S=(await t.bindings()).find(x=>x.b.id===k.bindingId)?.b?.root??null;for(let x of[E,...["device",...h?[ae(h)]:[]].filter($=>$!==E)]){if(S)break;S=await Jy(t,x,k.bindingId)}if(!S)throw Error("binding_not_found");let _={root:S},R=await v.bytes(k),N=k.path,D=N,M=1;for(;;){let x=await wt(_.root,D);try{await yx(x)}catch($){if($.code==="ENOENT")return await mx(wx(x),{recursive:!0}),await hx(x,R,{flag:"wx"}),{path:D};throw $}if(D=kx(N,new Date,i,M++),M>50)throw Error("restore_name_exhausted")}}throw Error("not_found")},[he.takeoverRevert]:async y=>{s();let{root:b}=mt(y);await t.manager.revert(n.accountId(),String(b??"")),await t.refresh()},[he.dismissCard]:async y=>{s();let b=String(mt(y).bindingId??"");if(!b)throw Error("binding_not_found");await t.dismissTakeoverCard(b)},[he.quitCheck]:async()=>{if(!t.full())return{state:"synced",pending:[],failed:[]};let y=await t.quitCheck();return{state:y.state,pending:Array.from({length:y.pending},()=>""),failed:y.failed}}};Object.assign(m,Kb(t,r,s));for(let[y,b]of Object.entries(m))n.handle(y,async(h,...E)=>{if(!n.isTrustedSender(h))return{ok:!1,error:"untrusted"};let v=Sx.has(y);v&&o++;try{return{ok:!0,value:await b(...E)}}catch(k){return{ok:!1,error:String(k?.message??k)}}finally{v&&o--}});return t.started=t.start().catch(y=>n.log?.(`[vault-sync] start: ${String(y?.message??y)}`)),t}Qf(Ng);function OB(n){Mg(n.contentSync?.withWriteLock?.bind(n.contentSync)),cg(n),Zu(n),Mm(n),Zb(n),yy(n),sy(n),n.log("[forsion-extend] cloud account handlers registered"),Rc(n)?Ac(n):n.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Wu(n)?Gu(n):n.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),Qu(n)?ef(n):n.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),Wd(n)?Gd(n):n.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),nf(n)?rf(n):n.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),gf(n)?_b(n):n.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),gf(n)&&Wb(n)}export{Uw as ACCOUNT_SEAM,Jm as AMADEUS_SEAM,_c as CONNECT_MAX_FILES,Fg as CONNECT_MAX_FILE_BYTES,Bg as CONNECT_MAX_TOTAL_BYTES,Nl as DIAGNOSTICS_VAULT,Jg as FORSION_CONNECT_LOCAL_SDK,ag as PAY_PERIODS,sg as PAY_TABS,xw as PENZOR_MAX_FILE,et as SYNC_IPC,zw as UNIT_SEAM,ds as UPLOAD_MAX_FILE,gs as UnitCapsReporter,fs as UnitHost,Rt as cloudJson,Ug as collectProjectFiles,Ys as conflictCopyPath,ek as conflictCopyVariant,Wg as connectMetaOf,jw as createAccountCloud,Km as createAmadeusCloud,Ml as createPenzorRemote,Hw as createUnitHub,Ol as deviceHeader,qu as expectedPartsOf,rt as forsionAccountId,Ls as forsionRefreshToken,cs as forsionWhoami,Qu as hasAccountHost,Wd as hasAmadeusHost,Rc as hasConnectHost,Wu as hasRemoteSyncHost,nf as hasUnitHost,Gg as makePreviewProxy,Fw as multipartFrame,zg as readConnectMeta,ef as registerAccount,Gd as registerAmadeus,OB as registerCloud,Ac as registerConnect,Gu as registerPenzor,Zu as registerPenzorTransfers,rf as registerUnit,$l as safeDownloadName,qg as scanSdkUsage,$s as shouldRefreshToken,Ju as speedOf,Vw as streamWorthy,th as stripConflictSuffix,tk as textFingerprint,sc as tokenAgeMs,rg as tokenRemainingMs,Ku as uploadError,Hg as writeConnectMeta};
|
|
288
292
|
/*! Bundled license information:
|
|
289
293
|
|
|
290
294
|
chokidar/index.js:
|