@forsion/extend 0.10.14 → 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/dist/desktop.mjs CHANGED
@@ -1,8 +1,8 @@
1
- var vs=null;function Ka(t){vs=t}function Ae(){if(!vs)throw new Error("core host not set (call setCoreHost first)");return vs}var Xa=new TextEncoder,Ff=new TextDecoder("utf-8",{ignoreBOM:!0}),rr=t=>Xa.encode(t),At=t=>Ff.decode(t),no=t=>typeof t=="string"?Xa.encode(t).length:t.length;function Za(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function ro(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 Je(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 o=r.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(o),l=>l.charCodeAt(0)),a=JSON.parse(new TextDecoder().decode(s)),i=a.userId??a.sub;return typeof i!="string"&&typeof i!="number"||!String(i).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(i)}`}catch{return null}}function ks(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(At(ro(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Es(t,e=Date.now()){let n=ks(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function el(t,e=Date.now()){let n=ks(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var jf=36e5;function oo(t,e=Date.now()){return!!t&&Es(t,e)>=jf}async function so(t,e,n=8e3,r){if(!t||!e)return null;let o=t.replace(/\/+$/,"");try{let s=await fetch(`${o}/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),i=typeof a?.token=="string"?a.token:"";return i&&i!==e?i:null}catch{return null}}var or=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,Lf=(t,e)=>new Promise((n,r)=>{let o=()=>{clearTimeout(s),r(new Error("Sign-in cancelled."))},s=setTimeout(()=>{e.removeEventListener("abort",o),n()},t);e.aborted?o():e.addEventListener("abort",o,{once:!0})});function tl(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===Je(p.cloudUrl,p.token)):null}catch{return null}},o=(f,g)=>{let p=Je(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=ks(f.token),E={...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(E)&&n({version:1,accounts:[...m.filter(h=>h.id!==p),E]})},s=()=>{let f=t.readCreds();o(f);let g=Je(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}},i=f=>{let g=Je(f.cloudUrl||"",f.token||""),p=r();g&&p&&n({version:1,accounts:p.filter(m=>m.id!==g)})},l=null;return{rememberForsionAccount:o,forsionAccounts:s,savedForsionAccount:a,forgetForsionAccount:i,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(/\/+$/,""),E;try{E=await fetch(`${b}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(C=>C.json())}catch(C){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${b}:${C?.message||C}`)}if(y(),!E?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let h=E.verification_uri_complete||`${E.verification_uri}?code=${E.user_code}`,x=new URL(`${b}/auth`);x.searchParams.set("logout","1"),x.searchParams.set("app","forsion-desktop"),x.searchParams.set("redirect",h);let v=x.toString();g?.({url:v,userCode:String(E.user_code||"")}),t.openExternal(v);let T=Date.now()+(E.expires_in||600)*1e3,z=(E.interval||2)*1e3;for(;Date.now()<T;){await Lf(z,m.signal),y();let C=null;try{C=await fetch(`${b}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:E.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),C.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let O=await C.json().catch(()=>({status:"pending"}));if(y(),O.status==="approved"&&O.token){let $={cloudUrl:b,token:O.token};return await p($,y),y(),{token:O.token,cloudUrl:b}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===m&&(l=null)}},readAccounts:()=>r()??[]}}function Pt(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,o;try{r=new URL(n),o=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||o.origin!==r.origin||!o.pathname.startsWith("/api/")?null:o.toString()}function sr(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function et(t,e,n,r,o=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(o)}),a=await s.json().catch(()=>({}));return{status:s.status,json:a}}var Uf=50*1024*1024,Hf=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function zf(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[o,s]of Object.entries(e.fields)){if(!Hf.has(o)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(o))return null;n.append(o,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>Uf)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 nl(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=zf(n);if(!r)return{status:400,json:{error:"invalid_request"}};let o=await t.getCloud();if(!o.token)return{status:401,error:"not_signed_in"};let s=Pt(o.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let a=await sr(o,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 _s(t){if(!t.token)return"";try{let e=await et(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 rl=["membership","credits","storefront"],ol=["monthly","quarterly","yearly","autorenew","autorenew-quarterly"],Bf=t=>t==="autorenew-quarterly"?"autorenew&cycle=quarterly":t,qf=/^[A-Za-z0-9_-]{1,64}$/,Wf=["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","agent-tool","backpack","other"],sl=t=>Wf.includes(t)?t:void 0,io=(t,e)=>{let n=sl(e);return n?{...t,entry:n}:t};function il(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(o,s)=>{if(!t.isTrustedSender(o))return n;let a=await t.getCloud(),i=a.base;if(!i)return{ok:!1};let l=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",c=await _s(a),u=`${i}/account${c?`?${c}`:""}${l}`;return a.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(o,...s)=>{if(!t.isTrustedSender(o))return n;let a=s.length>=4,[i,l,c]=s.slice(0,3).map(b=>a&&b===null?void 0:b),u=sl(s[3]);if(i!==void 0&&!rl.includes(i))return{ok:!1,error:"invalid_tab"};if(l!==void 0&&(typeof l!="string"||!qf.test(l)))return{ok:!1,error:"invalid_plan"};if(c!==void 0&&!ol.includes(c))return{ok:!1,error:"invalid_period"};let f=(i??"membership")==="membership"&&l?`&plan=${encodeURIComponent(l)}${c?`&period=${Bf(c)}`:""}`:"",g=await t.getCloud(),p=g.base;if(!p)return{ok:!1};let m=await _s(g),y=`${p}/pay?tab=${i??"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 o=>{if(!t.isTrustedSender(o))return n;let s=await t.getCloud(),a=s.base;if(!a)return{ok:!1};let i=await _s(s);if(!i.startsWith("code="))return{ok:!1,error:"handoff_unavailable"};let l=`${a}/pay?tab=membership&action=resume_autorenew&${i}&redirect=${encodeURIComponent(`${a}/account`)}`;return s.signal?.throwIfAborted(),await t.openExternal(l),{ok:!0}}),t.handle("profile:publicOrigin",async o=>{if(!t.isTrustedSender(o))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 i=a.status>=300&&a.status<400?a.headers.get("location"):null;return i&&/^https?:\/\//i.test(i)?{ok:!0,origin:new URL(i).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async o=>{if(!t.isTrustedSender(o))return e;let s=await r();if(!s.token)return{status:401,json:null};try{return await et(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(o,...s)=>{if(!t.isTrustedSender(o))return e;let a=await r();if(!a.token)return{status:401,json:null};let i=s[0];if(i!==void 0&&i!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${String(i)}`}};let l=i??"both";try{return await et(a,"POST","/api/token-quota/reset-card/use",io({type:l},s[1]),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(o,s,a)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(!Number.isInteger(s)||s<1||s>100)return{status:400,json:{error:"invalid_percent"}};try{return await et(i,"POST","/api/token-quota/background/convert",io({percent:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:pointsAutoDeduct",async(o,s,a)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await et(i,"POST","/api/token-quota/auto-deduct",io({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgAutoMain",async(o,s,a)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await et(i,"POST","/api/token-quota/background/auto-main",io({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("feedback:submit",async(o,s)=>{if(!t.isTrustedSender(o))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||Je(a.base,a.token)!==u)return{ok:!1,error:"account-changed"}}let i=(s?.description||"").trim();if(!i)return{ok:!1,error:"empty"};if(i.length>1e4)return{ok:!1,error:"description-too-long"};let l=[],c=!1;if(s?.sessionLogJson){let u=rr(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:Za(u)})}try{let u=await sr(a,`${a.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:i,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(o,s)=>{if(!t.isTrustedSender(o))return{status:0,error:"untrusted"};let a=s??{},i=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(!i.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=Pt(f.base,i);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 sr(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)}}),nl(t)}import{createHash as Rl}from"node:crypto";import{existsSync as zp,promises as Bp,readFileSync as qp,renameSync as Wp,statSync as Gp}from"node:fs";import Vp from"node:path";import{setTimeout as Yp}from"node:timers/promises";import{EventEmitter as Sp}from"node:events";import{stat as vp}from"node:fs";import{readdir as kp,stat as Ep}from"node:fs/promises";import*as ge from"node:path";import{lstat as al,readdir as Gf,realpath as Vf,stat as Yf}from"node:fs/promises";import{join as Jf,resolve as Kf,sep as ll}from"node:path";import{Readable as Xf}from"node:stream";var lt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},vn={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:lt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(vn);var fl="READDIRP_RECURSIVE_ERROR",Zf=new Set(["ENOENT","EPERM","EACCES","ELOOP",fl]),cl=[lt.DIR_TYPE,lt.EVERYTHING_TYPE,lt.FILE_DIR_TYPE,lt.FILE_TYPE],Qf=new Set([lt.DIR_TYPE,lt.EVERYTHING_TYPE,lt.FILE_DIR_TYPE]),ep=new Set([lt.EVERYTHING_TYPE,lt.FILE_DIR_TYPE,lt.FILE_TYPE]),tp=t=>Zf.has(t.code),np=process.platform==="win32",ul=t=>!0,dl=t=>{if(t===void 0)return ul;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 ul},Cs=class extends Xf{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,o=n.type??vn.type;this._fileFilter=dl(n.fileFilter),this._directoryFilter=dl(n.directoryFilter);let s=n.lstat?al:Yf;np?this._stat=i=>s(i,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:vn.depth,this._wantsDir=Qf.has(o),this._wantsFile=ep.has(o),this._wantsEverything=o===lt.EVERYTHING_TYPE,this._root=Kf(r),this._relStart=this._root.endsWith(ll)?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:o,depth:s}=n,a=r.splice(0,e).map(l=>this._formatEntry(l,o)),i=this._isDirent?a:await Promise.all(a);for(let l of i){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 o=this.parents.pop();if(!o){this.push(null);break}let s=o.pending??this._exploreDir(o.path,o.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 Gf(e,this._rdOptions)}catch(o){this._onError(o)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,o=Jf(n,r),s={path:o.slice(this._relStart),fullPath:o,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(o).then(a=>(s.stats=a,s),a=>{this._onError(a)})}_onError(e){tp(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 Vf(n),o=await al(r);if(o.isFile())return"file";if(o.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===ll){let a=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return a.code=fl,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 pl(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=lt.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!cl.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${cl.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 Cs(r)}import{watch as rp,unwatchFile as hl,watchFile as op}from"node:fs";import{realpath as As,lstat as sp,open as ip,stat as ml}from"node:fs/promises";import{type as ap}from"node:os";import*as xe from"node:path";var lp="data",Is="end",yl="close",fo=()=>{};var po=process.platform,Rs=po==="win32",cp=po==="darwin",up=po==="linux",dp=po==="freebsd",wl=ap()==="OS400",Ie={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},bt=Ie,fp="watch",pp={lstat:sp,stat:ml},sn="listeners",ao="errHandlers",kn="rawEmitters",hp=[sn,ao,kn],gp=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"]),mp=t=>gp.has(xe.extname(t).slice(1).toLowerCase()),Ts=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},ir=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},yp=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},ar=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},bl=t=>t instanceof Set?t.size===0:!t,lo=new Map;function gl(t,e,n,r,o){let s=(a,i)=>{n(t),o(a,i,{watchedPath:t}),i&&t!==i&&co(xe.resolve(t,i),sn,xe.join(t,i))};try{return rp(t,{persistent:e.persistent},s)}catch(a){r(a);return}}var co=(t,e,n,r,o)=>{let s=lo.get(t);s&&Ts(s[e],a=>{a(n,r,o)})},wp=(t,e,n,r)=>{let{listener:o,errHandler:s,rawEmitter:a}=r,i=lo.get(e),l;if(!n.persistent)return l=gl(t,n,o,s,a),l?l.close.bind(l):void 0;if(i)ir(i,sn,o),ir(i,ao,s),ir(i,kn,a);else{if(l=gl(t,n,co.bind(null,e,sn),s,co.bind(null,e,kn)),!l)return;l.on(bt.ERROR,async c=>{let u=co.bind(null,e,ao);if(i&&(i.watcherUnusable=!0),Rs&&c.code==="EPERM")try{await(await ip(t,"r")).close(),u(c)}catch{}else u(c)}),i={listeners:o,errHandlers:s,rawEmitters:a,watcher:l},lo.set(e,i)}return()=>{ar(i,sn,o),ar(i,ao,s),ar(i,kn,a),bl(i.listeners)&&(i.watcher.close(),lo.delete(e),hp.forEach(yp(i)),i.watcher=void 0,Object.freeze(i))}},xs=new Map,bp=(t,e,n,r)=>{let{listener:o,rawEmitter:s}=r,a=xs.get(e),i=a&&a.options;return i&&(i.persistent<n.persistent||i.interval>n.interval)&&(hl(e),a=void 0),a?(ir(a,sn,o),ir(a,kn,s)):(a={listeners:o,rawEmitters:s,options:n,watcher:op(e,n,(l,c)=>{Ts(a.rawEmitters,f=>{f(bt.CHANGE,e,{curr:l,prev:c})});let u=l.mtimeMs;(l.size!==c.size||u>c.mtimeMs||u===0)&&Ts(a.listeners,f=>f(t,l))})},xs.set(e,a)),()=>{ar(a,sn,o),ar(a,kn,s),bl(a.listeners)&&(xs.delete(e),hl(e),a.options=a.watcher=void 0,Object.freeze(a))}},uo=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,o=xe.dirname(e),s=xe.basename(e);this.fsw._getWatchedDir(o).add(s);let i=xe.resolve(e),l={persistent:r.persistent};n||(n=fo);let c;if(r.usePolling){let u=r.interval!==r.binaryInterval;l.interval=u&&mp(s)?r.binaryInterval:r.interval,c=bp(e,i,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else c=wp(e,i,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(e,n,r){if(this.fsw.closed)return;let o=xe.dirname(e),s=xe.basename(e),a=this.fsw._getWatchedDir(o),i=n;if(a.has(s))return;let l=async(u,f)=>{if(this.fsw._throttle(fp,e,5)){if(!f||f.mtimeMs===0)try{let g=await ml(e);if(this.fsw.closed)return;let p=g.atimeMs,m=g.mtimeMs;if((!p||p<=m||m!==i.mtimeMs)&&this.fsw._emit(bt.CHANGE,e,g),(cp||up||dp)&&i.ino!==g.ino){this.fsw._closeFile(u),i=g;let y=this._watchWithNodeFs(e,l);y&&this.fsw._addPathCloser(u,y)}else i=g}catch{this.fsw._remove(o,s)}else if(a.has(s)){let g=f.atimeMs,p=f.mtimeMs;(!g||g<=p||p!==i.mtimeMs)&&this.fsw._emit(bt.CHANGE,e,f),i=f}}},c=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(bt.ADD,e,0))return;this.fsw._emit(bt.ADD,e,n)}return c}async _handleSymlink(e,n,r,o){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let i;try{i=await As(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(o)?this.fsw._symlinkPaths.get(s)!==i&&(this.fsw._symlinkPaths.set(s,i),this.fsw._emit(bt.CHANGE,r,e.stats)):(a.add(o),this.fsw._symlinkPaths.set(s,i),this.fsw._emit(bt.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,o,s,a,i){e=xe.join(e,"");let l=o?`${e}:${o}`:e;if(i=this.fsw._throttle("readdir",l,1e3),!i)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(lp,async g=>{if(this.fsw.closed){f=void 0;return}let p=g.path,m=xe.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===o||!o&&!c.has(p))&&(this.fsw._incrReadyCount(),m=xe.join(s,xe.relative(s,m)),this._addToNodeFs(m,n,r,a+1))}}).on(bt.ERROR,this._boundHandleError),new Promise((g,p)=>{if(!f)return p();f.once(Is,()=>{if(this.fsw.closed){f=void 0;return}let m=i?i.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,o,s,a,i)})})}async _handleDir(e,n,r,o,s,a,i){let l=this.fsw._getWatchedDir(xe.dirname(e)),c=l.has(xe.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!c&&this.fsw._emit(bt.ADD_DIR,e,n),l.add(xe.basename(e)),this.fsw._getWatchedDir(e);let u,f,g=this.fsw.options.depth;if((g==null||o<=g)&&!this.fsw._symlinkPaths.has(i)){if(!s&&(await this._handleRead(e,r,a,s,e,o,u),this.fsw.closed))return;f=this._watchWithNodeFs(e,(p,m)=>{m&&m.mtimeMs===0||this._handleRead(p,!1,a,s,e,o,u)})}return f}async _addToNodeFs(e,n,r,o,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let i=this.fsw._getWatchHelpers(e);r&&(i.filterPath=l=>r.filterPath(l),i.filterDir=l=>r.filterDir(l));try{let l=await pp[i.statMethod](i.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(i.watchPath,l))return a(),!1;let c=this.fsw.options.followSymlinks,u;if(l.isDirectory()){let f=xe.resolve(e),g=c?await As(e):e;if(this.fsw.closed||(u=await this._handleDir(i.watchPath,l,n,o,s,i,g),this.fsw.closed))return;f!==g&&g!==void 0&&this.fsw._symlinkPaths.set(f,g)}else if(l.isSymbolicLink()){let f=c?await As(e):e;if(this.fsw.closed)return;let g=xe.dirname(i.watchPath);if(this.fsw._getWatchedDir(g).add(i.watchPath),this.fsw._emit(bt.ADD,i.watchPath,l),u=await this._handleDir(g,l,n,o,e,i,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(xe.resolve(e),f)}else u=this._handleFile(i.watchPath,l,n);return a(),u&&this.fsw._addPathCloser(e,u),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var Ds="/",_p="//",_l=".",Cp="..",Ap="string",xp=/\\/g,Cl=/\/\//g,Tp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ip=/^\.[/\\]/;function ho(t){return Array.isArray(t)?t:[t]}var Os=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Rp(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=ge.relative(t.path,e);return n?!n.startsWith("..")&&!ge.isAbsolute(n):!1}return!1}:()=>!1}function Dp(t){if(typeof t!="string")throw new Error("string expected");t=ge.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(Cl,"/"),e&&(t="/"+t),t}function Sl(t,e,n){let r=Dp(e);for(let o=0;o<t.length;o++){let s=t[o];if(s(r,n))return!0}return!1}function Op(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=ho(t).map(o=>Rp(o));return e==null?(o,s)=>Sl(r,o,s):Sl(r,e)}var vl=t=>{let e=ho(t).flat();if(!e.every(n=>typeof n===Ap))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Al)},kl=t=>{let e=t.replace(xp,Ds),n=!1;return e.startsWith(_p)&&(n=!0),e=e.replace(Cl,Ds),n&&(e=Ds+e),e},Al=t=>kl(ge.normalize(kl(t))),El=(t="")=>e=>typeof e=="string"?Al(ge.isAbsolute(e)?e:ge.join(t,e)):e,Mp=(t,e)=>ge.isAbsolute(t)?t:ge.join(e,t),Np=Object.freeze(new Set),Ms=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!==_l&&e!==Cp&&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 kp(r)}catch{this._removeWatcher&&this._removeWatcher(ge.dirname(r),ge.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=fo,this.items=Np,Object.freeze(this)}},Pp="stat",$p="lstat",Ns=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let o=e;this.path=e=e.replace(Ip,""),this.watchPath=o,this.fullWatchPath=ge.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?Pp:$p}entryPath(e){return ge.join(this.watchPath,ge.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)}},go=class extends Sp{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},o={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?ho(e.ignored):ho([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};wl&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let l=s.toLowerCase();l==="false"||l==="0"?o.usePolling=!1:l==="true"||l==="1"?o.usePolling=!0:o.usePolling=!!l}let a=process.env.CHOKIDAR_INTERVAL;a&&(o.interval=Number.parseInt(a,10));let i=0;this._emitReady=()=>{i++,i>=this._readyCount&&(this._emitReady=fo,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ie.READY)))},this._emitRaw=(...l)=>this.emit(Ie.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new uo(this),Object.freeze(o)}_addIgnoredPath(e){if(Os(e)){for(let n of this._ignoredPaths)if(Os(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)Os(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:o}=this.options;this.closed=!1,this._closePromise=void 0;let s=vl(e);return o&&(s=s.map(a=>Mp(a,o))),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 i=await this._nodeFsHandler._addToNodeFs(a,!r,void 0,0,n);return i&&this._emitReady(),i})).then(a=>{this.closed||a.forEach(i=>{i&&this.add(ge.dirname(i),ge.basename(n||i))})}),this}unwatch(e){if(this.closed)return this;let n=vl(e),{cwd:r}=this.options;return n.forEach(o=>{!ge.isAbsolute(o)&&!this._closers.has(o)&&(r&&(o=ge.join(r,o)),o=ge.resolve(o)),this._closePath(o),this._addIgnoredPath(o),this._watched.has(o)&&this._addIgnoredPath({path:o,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 o=r();o instanceof Promise&&e.push(o)})),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?ge.relative(this.options.cwd,r):r)||_l;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==Ie.ERROR&&this.emit(Ie.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let o=this.options;Rs&&(n=ge.normalize(n)),o.cwd&&(n=ge.relative(o.cwd,n));let s=[n];r!=null&&s.push(r);let a=o.awaitWriteFinish,i;if(a&&(i=this._pendingWrites.get(n)))return i.lastChange=new Date,this;if(o.atomic){if(e===Ie.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((l,c)=>{this.emit(...l),this.emit(Ie.ALL,...l),this._pendingUnlinks.delete(c)})},typeof o.atomic=="number"?o.atomic:100),this;e===Ie.ADD&&this._pendingUnlinks.has(n)&&(e=Ie.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(e===Ie.ADD||e===Ie.CHANGE)&&this._readyEmitted){let l=(c,u)=>{c?(e=Ie.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===Ie.CHANGE&&!this._throttle(Ie.CHANGE,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===Ie.ADD||e===Ie.ADD_DIR||e===Ie.CHANGE)){let l=o.cwd?ge.join(o.cwd,n):n,c;try{c=await Ep(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(Ie.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let o=this._throttled.get(e);if(!o)throw new Error("invalid throttle");let s=o.get(n);if(s)return s.count++,!1;let a,i=()=>{let c=o.get(n),u=c?c.count:0;return o.delete(n),clearTimeout(a),c&&clearTimeout(c.timeoutObject),u};a=setTimeout(i,r);let l={timeoutObject:a,clear:i,count:0};return o.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,o){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,i,l=e;this.options.cwd&&!ge.isAbsolute(e)&&(l=ge.join(this.options.cwd,e));let c=new Date,u=this._pendingWrites;function f(g){vp(l,(p,m)=>{if(p||!u.has(e)){p&&p.code!=="ENOENT"&&o(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),o(void 0,m)):i=setTimeout(f,a,m)})}u.has(e)||(u.set(e,{lastChange:c,cancelWait:()=>(u.delete(e),clearTimeout(i),r)}),i=setTimeout(f,a))}_isIgnored(e,n){if(this.options.atomic&&Tp.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(El(r)),i=[...[...this._ignoredPaths].map(El(r)),...s];this._userIgnored=Op(i,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Ns(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=ge.resolve(e);return this._watched.has(n)||this._watched.set(n,new Ms(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let o=ge.join(e,n),s=ge.resolve(o);if(r=r??(this._watched.has(o)||this._watched.has(s)),!this._throttle("remove",o,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(o).getChildren().forEach(g=>this._remove(o,g));let l=this._getWatchedDir(e),c=l.has(n);l.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=o;if(this.options.cwd&&(u=ge.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Ie.ADD)return;this._watched.delete(o),this._watched.delete(s);let f=r?Ie.UNLINK_DIR:Ie.UNLINK;c&&!this._isIgnored(o)&&this._emit(f,o),this._closePath(o)}_closePath(e){this._closeFile(e);let n=ge.dirname(e);this._getWatchedDir(n).remove(ge.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:Ie.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=pl(e,r);return this._streams.add(o),o.once(yl,()=>{o=void 0}),o.once(Is,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function Ps(t,e={}){let n=new go(e);return n.add(t),n}var xl={watch:Ps,FSWatcher:go};import{execFile as Fp}from"node:child_process";import{stat as Tl}from"node:fs/promises";import{resolve as jp}from"node:path";import{promisify as Lp}from"node:util";function Jt(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 St(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Il=Lp(Fp);function Up(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 Hp(t){if(process.platform!=="darwin")return;let{stdout:e}=await Il("/bin/df",["-P",jp(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
2
- `).slice(1).map(o=>o.trim().split(/\s+/)[0]).find(o=>/^\/dev\/disk\d+(?:s\d+)*$/.test(o));if(!n)return;let{stdout:r}=await Il("/usr/sbin/diskutil",["info","-plist",n],{timeout:5e3,maxBuffer:256*1024});return Up(r)}async function lr(t,e=Hp,n=process.platform){let r=await Tl(t);if(!r.isDirectory())throw Error("Sync root is not a directory");let o={dev:r.dev,ino:r.ino,...(n==="darwin"||n==="win32")&&r.birthtimeMs>0?{birthtimeMs:r.birthtimeMs}:{}},s=await e(t),a=await Tl(t);if(!a.isDirectory()||!St(o,a))throw Error("Sync root changed while reading its identity");return{...o,...s?{volumeId:s}:{}}}var $s;function Dl(t){$s=t}var Ol={fs:Bp,path:Vp,directoryIdentity:lr,sha256Hex:t=>Rl("sha256").update(t).digest("hex"),tmpTag:()=>process.pid,existsSync:zp,async compareAndReplace(t,e,n,r,o){if(!$s)throw new Error("This host needs the shared content write lock for safe cloud downloads");let s=!1,a=$s,i=()=>{if(!r())return;if(o){let c;try{c=Gp(o.path)}catch(u){if(u.code==="ENOENT")return;throw u}if(!c.isDirectory()||!St(o.identity,c))return}let l=null;try{l=Rl("sha256").update(qp(e)).digest("hex")}catch(c){if(c.code!=="ENOENT")throw c}l===n&&(Wp(t,e),s=!0)};for(let l=0;;l++)try{return await a(e,i),s}catch(c){let u=c.code;if(s||process.platform!=="win32"||l>=4||u!=="EPERM"&&u!=="EBUSY")throw c;await Yp(20*2**l)}},watch(t,e,n){let r=xl.watch(t,{ignoreInitial:!0,depth:e.depth,ignored:e.ignored});return r.on("change",n.change),r.on("add",n.add),r.on("unlink",n.unlink),r.on("unlinkDir",n.unlinkDir),r}};import{readdirSync as Jp,lstatSync as Ls,readFileSync as Us,writeFileSync as Kp,realpathSync as Ml,opendirSync as Xp,openSync as Zp,fstatSync as Qp,readSync as eh,closeSync as th,constants as Fs}from"node:fs";import{join as mo,extname as Nl,sep as nh}from"node:path";var Hs=300,Pl=5*1024*1024,$l=20*1024*1024,rh=50*1024*1024,Fl=new Set(["node_modules"]),oh=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function jl(t,e){let n=[],r=0,o=(s,a)=>{for(let i of Jp(s)){if(i.startsWith("."))continue;let l=mo(s,i),c;try{c=Ls(l)}catch{continue}if(c.isSymbolicLink())continue;let u=a?`${a}/${i}`:i;if(c.isDirectory()){Fl.has(i)||o(l,u);continue}if(!c.isFile()||i.endsWith(".d.ts"))continue;if(n.length>=Hs)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Hs}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let f=Nl(i).toLowerCase(),g,p=e.mimeOf(f)??"application/octet-stream";if(oh.has(f)){let m=e.transpile(Us(l,"utf8"),f,u);g=Buffer.from(m??"","utf8"),p="text/javascript"}else g=Us(l);if(g.length>Pl)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${u}`);if(r+=g.length,r>$l)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:u,content_b64:g.toString("base64"),content_type:p,size:g.length})}};if(o(t,""),!n.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:n,totalBytes:r}}var Ll=".forsion-connect.json";function Ul(t){try{return JSON.parse(Us(mo(t,Ll),"utf8"))}catch{return{}}}function Hl(t,e){try{Kp(mo(t,Ll),JSON.stringify(e,null,2)+`
3
- `,"utf8")}catch{}}var sh=new Set([".html",".htm",".js",".mjs",".cjs",".ts",".tsx",".jsx",".mts",".cts",".vue",".svelte"]),ih=400,ah=5e3,js=2*1024*1024,lh=12,ch=/\bforsion\.ai\.(chat|generateImage|agent|status)\b/g;function zl(t){try{if(!Ls(t).isDirectory())return null}catch{return null}let e=!1,n=new Set,r=0,o=0,s=null,a=l=>{let c;try{c=Zp(l,Fs.O_RDONLY|(Fs.O_NOFOLLOW||0)|(Fs.O_NONBLOCK||0))}catch{return null}try{if(!Qp(c).isFile())return null;s??=Buffer.allocUnsafe(js+1);let u=0;for(;u<s.length;){let f=eh(c,s,u,s.length-u,null);if(f<=0)break;u+=f}return u>js?null:s.toString("utf8",0,u)}catch{return null}finally{try{th(c)}catch{}}},i=(l,c)=>{let u;try{u=Xp(l)}catch{return}try{for(;;){if(r>=ih||o>=ah)return;let f;try{f=u.readSync()}catch{return}if(!f)return;o++;let g=f.name;if(g.startsWith(".")||Fl.has(g))continue;let p=mo(l,g),m;try{m=Ls(p)}catch{continue}if(m.isSymbolicLink())continue;if(m.isDirectory()){c<lh&&i(p,c+1);continue}if(!m.isFile()||m.size>js||!sh.has(Nl(g).toLowerCase()))continue;r++;let y=a(p);if(y!==null){!e&&y.includes("forsion-connect.js")&&(e=!0);for(let b of y.matchAll(ch))n.add(`forsion.ai.${b[1]}`)}}}finally{try{u.closeSync()}catch{}}};return i(t,0),{usesSdk:e,sdkMethods:[...n].sort()}}function Bl(t){let e=Ul(t),n=zl(t);return n?{...e,...n}:e}function ql(t){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 n(r){if(e[r])return e[r];let o="/__forsion/agent-events/";if(r.startsWith(o)){let s=r.slice(o.length);if(/^[A-Za-z0-9-]{1,64}$/.test(s))return{method:"GET",path:`/api/agent/runs/${s}/events`,auth:!0,timeoutMs:9e5}}}return async(r,o)=>{let[s,a]=(r.url||"").split("?"),i=(m,y)=>{o.headersSent||(o.statusCode=m,o.setHeader("Content-Type","application/json")),o.end(JSON.stringify({detail:y}))},l=n(s);if(!l)return i(404,"unknown connect endpoint");if((r.method||"GET")!==l.method)return i(405,"method not allowed");let c="",u="";try{({base:c,token:u}=await t())}catch{}if(!c)return i(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(l.auth&&!u)return i(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let f;if(l.method==="POST"){let m=[],y=0;try{for await(let b of r){if(y+=b.length,y>rh)return r.destroy(),i(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");m.push(b)}}catch(b){return i(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${b?.message||String(b)}`)}f=Buffer.concat(m)}if(l.agentRun){let m;try{m=JSON.parse((f||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return i(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}f=Buffer.from(JSON.stringify({session_id:typeof m.session_id=="string"?m.session_id:"",message:typeof m.message=="string"?m.message:"",app_id:"connect",agent_config:{}}))}let g=new AbortController,p=setTimeout(()=>g.abort(new Error("proxy timeout")),l.timeoutMs??3e5);r.on("close",()=>g.abort());try{let m=await fetch(c+l.path+(a?`?${a}`:""),{method:l.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...u?{Authorization:`Bearer ${u}`}:{}},body:f&&f.length?new Uint8Array(f):void 0,signal:g.signal});if(o.statusCode=m.status,o.setHeader("Content-Type",m.headers.get("content-type")||"application/json"),o.setHeader("Cache-Control","no-store"),m.body)for await(let y of m.body)o.write(y);o.end()}catch(m){let y=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${m?.message||String(m)}`;if(o.headersSent){try{o.write(`data: ${JSON.stringify({error:y})}
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{}o.end()}else i(502,y)}finally{clearTimeout(p)}}}var Wl=`
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 vs=null;function Ka(t){vs=t}function Ae(){if(!vs)throw new Error("core host
196
196
  ai: { chat: chat, agent: agentRun, generateImage: generateImage, status: aiStatus }
197
197
  };
198
198
  })();
199
- `,uh=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function dh(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function zs(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Bs(t){t.setPreviewHooks({sdkJs:Wl,proxy:ql(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Bl(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 et(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=Ml(n.dir);let s=null;try{s=Ml(t.projectsRoot())}catch{}if(!(!!s&&(r===s||r.startsWith(s+nh)))&&!dh(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 o=await t.getCloud();if(!o.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:s,totalBytes:a}=jl(r,uh(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:i,json:l}=await et(o,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:s},3e5);if(i===401)return{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"};if(i!==200)return{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${i}`,used:l?.used,limit:l?.limit};Hl(r,{slug:String(l.slug)});let c=typeof l.publicUrl=="string"&&/^https?:\/\//i.test(l.publicUrl)?l.publicUrl:`${o.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:o,json:s}=await et(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return o===401||o===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:o!==200&&o!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${o}`}:{ok:!0}}catch(o){return{ok:!1,code:"error",detail:o?.message||String(o)}}}),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:o,json:s}=await et(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return o===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:o!==200?{ok:!1,code:s?.code||"error",detail:s?.detail||`HTTP ${o}`}:{ok:!0,status:s.status}}catch(o){return{ok:!1,code:"error",detail:o?.message||String(o)}}}),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:o,json:s}=await et(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return o===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:o!==200&&o!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${o}`}:{ok:!0}}catch(o){return{ok:!1,code:"error",detail:o?.message||String(o)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await et(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 fh}from"node:crypto";import{hostname as ph}from"node:os";async function cr(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 o=await r.json();if(!o)return{status:"offline"};let s=o.avatar||o.avatarUrl||o.avatar_url||void 0;return s&&/^\/(?!\/)/.test(s)&&(s=n+s),{status:"ok",user:{username:o.username||o.nickname||void 0,nickname:o.nickname||void 0,avatar:s,membershipTier:o.membershipTier||o.membership_tier||void 0}}}catch{return{status:"offline"}}}var Gl=t=>`${t.seq}:${t.hash}`,yo=(t=ph())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},hh=t=>fh("sha256").update(t).digest("hex");function qs(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 wo(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=yo(),o=async(s,a)=>{let i=t.getToken();if(!i)throw new Error("penzor-not-logged-in");let l=await fetch(s,{...a,headers:{...a.headers,Authorization:`Bearer ${i}`}});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 o(n("/manifest"),{method:"GET",signal:s}),{files:i}=await a.json();return i.map(l=>({key:l.path,size:l.size,mtimeMs:l.mtimeMs,id:Gl(l),hash:l.hash}))},async readFile(s,a){let l=await(await o(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(hh(u)!==l.hash)throw new Error(`penzor hash mismatch: ${s}`);return u},async writeFile(s,a,i,l,c){let u=qs(c),f=new URLSearchParams({path:s,mtimeMs:String(Math.floor(i)||0)});u&&(f.set("baseSeq",String(u.baseSeq)),u.baseHash&&f.set("baseHash",u.baseHash));let p=await(await o(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:Gl(p)}},async rm(s,a,i){let l=qs(i),c=new URLSearchParams({path:s});l&&l.baseSeq>0&&(c.set("baseSeq",String(l.baseSeq)),l.baseHash&&c.set("baseHash",l.baseHash)),await o(n(`/file?${c.toString()}`),{method:"DELETE",signal:a})},async check(){try{return await o(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var bo="forsion-diagnostics",Yl=50*1024*1024,Vl=new Map;async function gh(t,e){let n=Vl.get(e);if(n)return{id:n};let r=await cr(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let o=r.user?.username?.trim();return o?(Vl.set(e,o),{id:o}):{error:"penzor-auth-unverified"}}var Ws=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function Gs(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,o=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(o)||o===bo)return{error:"penzor-bad-vault"};let s=await gh(n.cloudUrl,n.token);if("error"in s)return s;let a=n.token;return{remote:wo({baseUrl:n.cloudUrl,vault:o,getToken:()=>a}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${s.id}|${o}`,maxFileBytes:Yl}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as $h}from"node:fs";import{access as Fh,link as jh,lstat as Lh,mkdir as Uh,open as Hh,readdir as zh,rename as Bh,stat as fc,unlink as Qs}from"node:fs/promises";import{request as qh}from"node:http";import{request as Wh}from"node:https";import{homedir as Gh}from"node:os";import{basename as pc,extname as Vh,isAbsolute as Yh,join as fr}from"node:path";import{randomUUID as Eo}from"node:crypto";import{randomUUID as nc}from"node:crypto";import*as Js from"node:fs";import{basename as mh,dirname as yh,join as rc}from"node:path";var wh="extend-forced-update.json",oc="https://api.forsion.net",Jl=`${oc}/api/website/update-policy`,bh=24*36e5,Sh=1e3,vh=3e3,kh=12e4,Eh=3e4,_h=["suspend","resume","lock-screen"],Ch=1e4,Ah=16*1024,xh=168*36e5,ur=/^[0-9A-Za-z.+-]{1,40}$/,Th=/^[0-9a-f]{32}$/,En=nc(),Ys=new WeakMap;function vo(t,e,n){let r=Ys.get(t);r||Ys.set(t,r=new Map);let o=r.get(e);return o||r.set(e,o=new Set),o.add(n),()=>{o.delete(n)}}function Kl(t){let e={sync:!1,transfers:!1};for(let[n,r]of Ys.get(t)??[])for(let o of r){let s=!0;try{s=o()===!0}catch{s=!0}if(s){e[n]=!0;break}}return e}var Ih=t=>{if(!t||typeof t!="object")return!1;let e=t;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 So(t,e=Js){let n;try{n=e.readFileSync(t,"utf8")}catch(r){return r?.code==="ENOENT"?{}:null}try{let r=JSON.parse(n);if(!r||typeof r!="object"||r.v!==1||!r.attempts||typeof r.attempts!="object"||Array.isArray(r.attempts))return null;let o={};for(let[s,a]of Object.entries(r.attempts)){if(!ur.test(s)||!Ih(a))return null;o[s]={at:a.at,policy:a.policy,from:a.from,launch:a.launch,...a.failedAt!==void 0?{failedAt:a.failedAt}:{}}}return o}catch{return null}}function Xl(t,e,n=Js,r=process.platform){let o=Buffer.from(JSON.stringify({v:1,attempts:e}),"utf8"),s=yh(t),a=rc(s,`.${mh(t)}.${nc()}.tmp`),i=null,l=!1;try{n.mkdirSync(s,{recursive:!0}),i=n.openSync(a,"wx",384),l=!0;for(let f=0;f<o.length;){let g=n.writeSync(i,o,f,o.length-f);if(!(g>0))throw new Error("short write");f+=g}n.fsyncSync(i),n.closeSync(i),i=null;let u=n.readFileSync(a);if(!Buffer.isBuffer(u)||!u.equals(o))throw new Error("temp file does not read back");n.renameSync(a,t),l=!1}catch{if(i!==null)try{n.closeSync(i)}catch{}if(l)try{n.rmSync(a,{force:!0})}catch{}return!1}if(!Dh(s,n,r))return!1;let c=So(t,n);return!!c&&JSON.stringify(c)===JSON.stringify(e)}var Rh=new Set(["EISDIR","EINVAL","ENOTSUP","EBADF"]);function Dh(t,e,n){let r=null;try{return r=e.openSync(t,"r"),e.fsyncSync(r),!0}catch(o){let s=typeof o?.code=="string"?o.code:"";return Rh.has(s)||s==="EPERM"&&n==="win32"}finally{if(r!==null)try{e.closeSync(r)}catch{}}}var Zl=null;function Ks(){return Zl??=import("electron").then(e=>e?.app?e:e?.default??null,()=>null),Zl}async function Oh(){return(await Ks())?.app?.isPackaged===!0}async function Mh(){let e=(await Ks())?.powerMonitor;if(typeof e?.getSystemIdleTime!="function")throw new Error("powerMonitor unavailable");return e.getSystemIdleTime()}async function Nh(t){let e=(await Ks())?.powerMonitor;if(typeof e?.on=="function")for(let n of _h)try{e.on(n,()=>t(n))}catch{}}var Ql=["did-navigate","render-process-gone","destroyed"];function ec(t,e){let n=t;if(typeof n?.on!="function")return()=>{};try{for(let r of Ql)n.on(r,e)}catch{}return()=>{try{for(let r of Ql)n.removeListener?.(r,e)}catch{}}}var Vs=t=>{try{let e=t;return typeof e?.isDestroyed=="function"&&e.isDestroyed()===!0}catch{return!0}},tc=t=>{let e=t?.owner;return typeof e=="string"&&Th.test(e)?e:null};function sc(t,e={}){let n=e.fetch??((...A)=>fetch(...A)),r=e.now??Date.now,o=e.fs??Js,s={ok:!1,error:"untrusted"},a={ok:!1,error:"unsupported"},i=()=>{try{return typeof t.homeDir=="function"&&t.homeDir()?rc(t.homeDir(),wh):null}catch{return null}},l=null,c=()=>l??=(async()=>{try{return(e.sandbox??(()=>process.env.FORSION_SANDBOX==="1"))()?!1:await(e.packaged??Oh)()===!0}catch{return!1}})(),u=async()=>{try{let A=await(e.systemIdle??Mh)();return typeof A=="number"&&Number.isFinite(A)&&A>=0?A:null}catch{return null}},f=(A,U)=>{t.handle(A,async(M,X)=>{if(!t.isTrustedSender(M))return s;if(!await c())return a;try{return await U(M,X)}catch{return{ok:!1,error:"failed"}}})},g=null,p=(A,U)=>!!g&&g.sender===A.sender&&g.token===tc(U),m=(A,U)=>{g===A&&(g=null,A.unwatch(),y&&y.owner===A.token&&!E(y)&&v(y,"aborted",U))};f("forcedUpdate:claim",(A,U)=>{let M=tc(U);if(!M)return{ok:!1,error:"invalid"};if(g&&g.sender!==A.sender&&!Vs(g.sender))return{ok:!1,error:"other_owner"};y&&y.owner!==M&&v(y,"aborted","owner_changed"),g?.unwatch();let X={token:M,sender:A.sender,unwatch:()=>{}};return g=X,X.unwatch=ec(A.sender,()=>m(X,"owner_gone")),{ok:!0,launch:En}}),f("forcedUpdate:release",(A,U)=>p(A,U)?(m(g,"released"),{ok:!0}):{ok:!1,error:"not_owner"});let y=null,b=0,E=A=>A.state==="done"||A.state==="aborted",h=A=>({ok:!0,id:A.id,seq:A.seq,state:A.state,remaining:Math.max(0,A.total-A.ticks),...A.reason?{reason:A.reason}:{}}),x=A=>{A.seq++;let U=h(A),M=[...A.waiters];A.waiters.clear();for(let X of M)X(U)};function v(A,U,M){E(A)||(A.state=U,M&&(A.reason=M),U==="done"&&(A.doneAt=r()),A.timer&&clearInterval(A.timer),A.timer=null,A.unwatch(),x(A))}let T=A=>ec(A.sender,()=>v(A,"aborted","owner_gone")),z=!1,C=()=>{if(z)return;z=!0;let A=()=>{let U=y;U&&(U.state==="done"?U.spent=!0:v(U,"aborted","power"))};try{Promise.resolve((e.powerEvents??Nh)(A)).catch(()=>{})}catch{}},O=(A,U,M,X)=>{let Q=U?.countdownId,ee=y;if(!ee||typeof Q!="number"||ee.id!==Q||ee.state!=="done"||ee.spent||ee.doneAt===null||!p(A,U)||ee.owner!==g.token||ee.sender!==A.sender||ee.target!==M||ee.policyId!==X)return null;let re=r()-ee.doneAt;return re>=0&&re<=Eh?ee:null},$=async A=>{if(y!==A||E(A))return;let U=r(),M=U-A.last;if(A.last=U,M>vh||M<0)return v(A,"aborted","tick_gap");if(Vs(A.sender)||g?.token!==A.owner)return v(A,"aborted","owner_gone");if(A.heldAt!==null)return U-A.heldAt>kh?v(A,"aborted","hold_timeout"):x(A);if(A.checking)return;A.checking=!0;let X=await u();if(A.checking=!1,!(y!==A||E(A)||A.heldAt!==null)){if(X===null)return v(A,"aborted","os_unknown");if(X<A.idleSeconds)return v(A,"aborted","input_os");if(A.ticks++,A.ticks>=A.total)return v(A,"done");x(A)}},q=(A,U)=>{let M=U?.id;return p(A,U)&&y&&y.owner===g.token&&y.id===M?y:null};f("forcedUpdate:countdown:start",(A,U)=>{if(!p(A,U))return{ok:!1,error:"not_owner"};let M=U??{},X=typeof M.target=="string"&&ur.test(M.target)?M.target:null,Q=typeof M.policyId=="string"&&M.policyId.length>0&&M.policyId.length<=100?M.policyId:null,ee=typeof M.total=="number"&&Number.isFinite(M.total)?Math.min(600,Math.max(15,Math.round(M.total))):null,re=typeof M.idleSeconds=="number"&&Number.isFinite(M.idleSeconds)?Math.max(120,M.idleSeconds):null;if(!X||!Q||ee===null||re===null)return{ok:!1,error:"invalid"};y&&v(y,"aborted","replaced");let ie={id:++b,owner:g.token,sender:A.sender,target:X,policyId:Q,total:ee,idleSeconds:re,ticks:0,last:r(),heldAt:null,state:"running",seq:0,checking:!1,doneAt:null,spent:!1,timer:null,waiters:new Set,unwatch:()=>{}};return C(),y=ie,ie.unwatch=T(ie),ie.timer=setInterval(()=>{$(ie).catch(()=>v(ie,"aborted","failed"))},Sh),ie.timer.unref?.(),h(ie)}),f("forcedUpdate:countdown:next",(A,U)=>{if(!p(A,U))return{ok:!1,error:"not_owner"};let M=q(A,U);if(!M)return{ok:!0,id:U?.id??null,seq:Number.MAX_SAFE_INTEGER,state:"aborted",remaining:0,reason:"gone"};let X=Number(U?.after);return E(M)||!(Number.isFinite(X)&&X>=M.seq)?h(M):new Promise(Q=>{M.waiters.add(Q)})}),f("forcedUpdate:countdown:hold",(A,U)=>{let M=q(A,U);return!M||E(M)?{ok:!1,error:"not_running"}:(M.heldAt===null&&(M.heldAt=r(),M.state="held",x(M)),{ok:!0})}),f("forcedUpdate:countdown:cancel",(A,U)=>{let M=q(A,U);if(!M)return{ok:!1,error:"not_running"};let X=U?.reason;return v(M,"aborted",typeof X=="string"&&/^[a-z_]{1,32}$/.test(X)?X:"cancelled"),{ok:!0}}),f("forcedUpdate:policy",async(A,U)=>{let M=U?.fresh===!0,X=!1;try{X=new URL(String((await t.getCloud()).base)).origin===oc}catch{X=!1}if(!X)return{ok:!1,error:"unofficial_cloud"};let Q=M?`${Jl}?t=${r()}`:Jl;try{let re={headers:M?{Accept:"application/json","Cache-Control":"no-cache",Pragma:"no-cache"}:{Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(Ch),...M?{cache:"no-store"}:{}},ie=await n(Q,re);if(ie.status!==200)return{ok:!1,status:ie.status,error:"http"};let fe=await ie.text();return fe.length>Ah?{ok:!1,status:ie.status,error:"too_large"}:{ok:!0,status:ie.status,json:JSON.parse(fe)}}catch(ee){return{ok:!1,error:ee?.name==="SyntaxError"?"bad_json":"network"}}}),f("forcedUpdate:busy",()=>({ok:!0,...Kl(t)})),f("forcedUpdate:systemIdle",async()=>{let A=await u();return A===null?{ok:!1,error:"unavailable"}:{ok:!0,seconds:A}}),f("forcedUpdate:attempts",()=>{let A=i();if(!A)return{ok:!1,error:"no_home"};let U=So(A,o);return U?{ok:!0,attempts:U,launch:En}:{ok:!1,error:"unreadable"}});let G=Promise.resolve(),I=A=>{let U=G.then(A,A);return G=U.catch(()=>{}),U};f("forcedUpdate:reserve",(A,U)=>I(async()=>{if(!p(A,U))return{ok:!1,reason:"not_owner"};let M=U??{},X=typeof M.target=="string"&&ur.test(M.target)?M.target:null,Q=typeof M.policyId=="string"&&M.policyId.length>0&&M.policyId.length<=100?M.policyId:null,ee=typeof M.from=="string"&&ur.test(M.from)?M.from:null,re=M.idleSeconds===void 0?null:typeof M.idleSeconds=="number"&&Number.isFinite(M.idleSeconds)&&M.idleSeconds>0?M.idleSeconds:NaN;if(!X||!Q||!ee||Number.isNaN(re))return{ok:!1,reason:"invalid"};if(M.launchId!==En)return{ok:!1,reason:"stale_launch"};if(re!==null){if(!O(A,U,X,Q))return{ok:!1,reason:"countdown"};let N=await u();if(N===null)return{ok:!1,reason:"os_unknown"};if(N<re)return{ok:!1,reason:"input_os"}}let ie=Kl(t);if(ie.sync||ie.transfers)return{ok:!1,reason:"busy"};if(!p(A,U)||Vs(A.sender))return{ok:!1,reason:"not_owner"};if(M.launchId!==En)return{ok:!1,reason:"stale_launch"};let fe=re===null?null:O(A,U,X,Q);if(re!==null&&!fe)return{ok:!1,reason:"countdown"};let we=i();if(!we)return{ok:!1,reason:"no_home"};let ve=So(we,o);if(!ve)return{ok:!1,reason:"unreadable"};let Ge=r(),Ne=ve[X];if(Ne&&Ge-Math.max(Ne.at,Ne.failedAt??0)<bh)return{ok:!1,reason:"cooldown"};let be={};for(let[N,W]of Object.entries(ve))Ge-Math.max(W.at,W.failedAt??0)<xh&&(be[N]=W);return be[X]={at:Ge,policy:Q,from:ee,launch:En},Xl(we,be,o)?(fe&&(fe.spent=!0),{ok:!0,at:Ge,launch:En}):{ok:!1,reason:"write_failed"}})),f("forcedUpdate:attemptFailed",(A,U)=>I(async()=>{if(!p(A,U))return{ok:!1,error:"not_owner"};let M=typeof U?.target=="string"?U.target:"";if(!ur.test(M))return{ok:!1,error:"invalid"};let X=i();if(!X)return{ok:!1,error:"no_home"};let Q=So(X,o);if(!Q)return{ok:!1,error:"unreadable"};let ee=Q[M];if(!ee)return{ok:!1,error:"not_found"};if(ee.failedAt!==void 0)return{ok:!0,failedAt:ee.failedAt};let re=r();return Xl(X,{...Q,[M]:{...ee,failedAt:re}},o)?{ok:!0,failedAt:re}:{ok:!1,error:"write_failed"}}))}var dr=52428800;var ic=["bytes","signed","text"],ac=/^[A-Za-z0-9_-]{1,64}$/,lc=/^[a-z0-9][a-z0-9-]{0,63}$/;function ko(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 Ph={".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 cc(t){let e=t.lastIndexOf(".");return Ph[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function uc(t,e,n,r){let o=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",s=encodeURIComponent(n).replace(/['()*]/g,i=>`%${i.charCodeAt(0).toString(16).toUpperCase()}`),a="";for(let[i,l]of Object.entries(e))a+=`--${t}\r
200
- Content-Disposition: form-data; name="${i}"\r
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&&gt(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+=`--${t}\r
204
- Content-Disposition: form-data; name="file"; filename="${o}"; filename*=UTF-8''${s}\r
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
- --${t}--\r
209
- `}}function Xs(t,e){let n=t.filter(([i])=>e-i<=3e3);if(n.length<2)return 0;let[r,o]=n[0],[s,a]=n[n.length-1];return s>r?Math.max(0,(a-o)/(s-r)*1e3):0}function Zs(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 Jh=3,ei=6e4,Kh=200,Xh=ic;function hc(t,e,n,r){let{head:o,tail:s}=uc(t,e,n,r);return{head:Buffer.from(o,"utf8"),tail:Buffer.from(s,"utf8")}}function Zh(t,e,n,r,o,s,a,i){return new Promise((l,c)=>{let u=new URL(t),f=(u.protocol==="https:"?Wh:qh)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+o+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(i.aborted)return g();i.addEventListener("abort",g,{once:!0}),f.setTimeout(ei,()=>f.destroy(new Error("timeout"))),f.on("error",p=>{i.removeEventListener("abort",g),c(p)}),(async()=>{try{f.write(n);let p=0;for await(let m of $h(r)){let y=m;if(p+=y.length,p>o)throw new Error("changed");f.write(y)||await new Promise(b=>f.once("drain",b)),a(p)}if(p!==o)throw new Error("changed");f.end(s)}catch(p){f.destroy(p)}})()})}function ti(t,e={}){let n=e.downloadsDir??(()=>fr(Gh(),"Downloads")),r=e.post??Zh,o=e.now??Date.now,s=[],a=new Map,i=Promise.resolve(),l=async()=>{let C=await t.getCloud(),O=typeof t.accountId=="function"?t.accountId():null;return{...C,account:O||`${C.base}|${C.token}`}},c=C=>{let{account:O,attempt:$,relDir:q,abort:G,samples:I,dl:A,...U}=C;return{...U,speed:C.state==="active"?Xs(I,o()):0}},u=(C,O,$=null)=>{C.state=O,C.error=$,C.abort=null,C.finishedAt=o(),C.samples=[];let q=s.filter(G=>G.state==="done"||G.state==="canceled");for(let G of q.slice(0,Math.max(0,q.length-Kh)))s.splice(s.indexOf(G),1);f()};function f(){for(let C of["up","down"]){let O=s.filter($=>$.kind===C&&$.state==="active").length;for(let $ of s){if(O>=Jh)break;if($.kind!==C||$.state!=="queued")continue;O++,$.state="active",$.startedAt=o(),$.done=0,$.samples=[[o(),0]],$.abort=new AbortController;let q=++$.attempt,G=()=>$.attempt===q&&$.state==="active";(C==="up"?E($,G):x($,G)).catch(I=>{G()&&u($,"failed",g(I))})}}}let g=C=>{let O=String(C?.message||C);return O==="changed"||O==="too_large"||O==="quota"||O==="account_changed"||O==="not_signed_in"||O.startsWith("http_")||O==="bad_response"||O==="gone"?O:"network"},p=(C,O)=>{C.done=O;let $=o(),q=C.samples[C.samples.length-1];for((!q||$-q[0]>=200)&&C.samples.push([$,O]);C.samples.length>2&&$-C.samples[0][0]>3500;)C.samples.shift()};async function m(C){let O=await l();if(O.account!==C.account)throw new Error("account_changed");if(!O.token)throw new Error("not_signed_in");return O}async function y(C,O,$,q){let G=Pt(C,$);if(!G)throw new Error("bad_path");let I=await fetch(G,{method:q.method??"GET",headers:{Authorization:`Bearer ${O}`,...q.body!==void 0?{"Content-Type":"application/json"}:{},...q.projectSource?{"X-Project-Source":q.projectSource}:{}},body:q.body!==void 0?JSON.stringify(q.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:I.status,json:await I.json().catch(()=>null)}}function b(C,O,$){if(!C.relDir.length)return Promise.resolve(C.targetId);let q=a.get(C.batch);q||a.set(C.batch,q=new Map);let G=q,I=A=>{if(A===0)return Promise.resolve(C.targetId);let U=C.relDir.slice(0,A).join("/"),M=G.get(U);return M||(M=I(A-1).then(async X=>{let Q=C.relDir[A-1],ee=await y(O,$,"/files",{method:"POST",body:{type:"directory",parentId:X,name:Q},projectSource:C.projectSource});if(ee.status===201&&typeof ee.json?.id=="string")return ee.json.id;if(ee.status===409){let re=await y(O,$,`/files${X==="ROOT"?"":`?parentId=${encodeURIComponent(X)}`}`,{projectSource:C.projectSource}),ie=Array.isArray(re.json)?re.json.find(fe=>fe?.fileType==="directory"&&fe?.name===Q):null;if(ie?.id)return String(ie.id)}throw new Error(ee.status===401?"not_signed_in":`http_${ee.status}`)}),M.catch(()=>G.delete(U)),G.set(U,M)),M};return I(C.relDir.length)}async function E(C,O){let{base:$,token:q}=await m(C),G=await fc(C.localPath).catch(()=>null);if(!G?.isFile())throw new Error("gone");if(G.size>52428800)throw new Error("too_large");C.size=G.size;let I=await b(C,$,q);if(!O())return;C.parentId=I;let A=Pt($,"/files/upload");if(!A)throw new Error("bad_path");let U=`----penzor${Eo().replace(/-/g,"")}`,{head:M,tail:X}=hc(U,{parentId:I,autoRename:"true"},C.name,cc(C.name)),Q=await r(A,{Authorization:`Bearer ${q}`,"Content-Type":`multipart/form-data; boundary=${U}`,...C.projectSource?{"X-Project-Source":C.projectSource}:{}},M,C.localPath,G.size,X,ee=>{O()&&p(C,ee)},C.abort.signal);O()&&(Q.status===201||Q.status===200?(C.fileId=typeof Q.body?.id=="string"?Q.body.id:null,p(C,C.size),u(C,"done")):u(C,"failed",Zs(Q.status,Q.body)))}function h(C,O,$,q){let G=async()=>{let A=Vh($),U=A?$.slice(0,-A.length):$;for(let M=0;M<1e3;M++){if(!q())throw new Error("aborted");let X=fr(O,M===0?$:`${U} (${M})${A}`);try{await jh(C,X)}catch(Q){let ee=Q.code;if(ee==="EEXIST")continue;if(ee!=="EPERM"&&ee!=="ENOTSUP"&&ee!=="EOPNOTSUPP"&&ee!=="ENOSYS"&&ee!=="EXDEV")throw Q;if(await Fh(X).then(()=>!0,()=>!1))continue;await Bh(C,X)}if(!q())throw await Qs(X).catch(()=>{}),new Error("aborted");return await Qs(C).catch(()=>{}),X}throw new Error("too many duplicates")},I=i.then(G,G);return i=I.catch(()=>{}),I}async function x(C,O){let $=C.dl,{base:q,token:G}=await m(C);if(!O())return;let I=Pt(q,$.path);if(!I)throw new Error("bad_path");let A=C.abort.signal,U=$.subdir?fr(n(),$.subdir):n();await Uh(U,{recursive:!0});let M=fr(U,`.${C.id}-${C.attempt}.penzor-part`),X=await Hh(M,"wx"),Q=!1;try{let ee=new AbortController,re=setTimeout(()=>ee.abort(),ei),ie=()=>{clearTimeout(re),re=setTimeout(()=>ee.abort(),ei)},fe=AbortSignal.any([A,ee.signal]);try{let we=await fetch(I,{headers:{Authorization:`Bearer ${G}`},signal:fe});if(!we.ok)throw new Error(we.status===401?"not_signed_in":`http_${we.status}`);let ve=we.body,Ge=Number(we.headers.get("content-length"))||C.size;if($.mode!=="bytes"){let Ne=await we.json().catch(()=>null);if($.mode==="text"){if(typeof Ne?.content!="string")throw new Error("bad_response");let be=Buffer.from(Ne.content,"utf8");await X.writeFile(be),C.size=be.length,p(C,be.length),ve=null}else{if(typeof Ne?.url!="string"||!/^https?:\/\//i.test(Ne.url))throw new Error("bad_response");let be=await fetch(Ne.url,{signal:fe});if(!be.ok)throw new Error(`http_${be.status}`);ve=be.body,Ge=Number(be.headers.get("content-length"))||C.size}}if(ve){C.size=Ge;let Ne=0;for await(let be of ve){ie();for(let N=0;N<be.length;){let{bytesWritten:W}=await X.write(be,N,be.length-N);if(W<=0)throw new Error("short_write");N+=W}if(Ne+=be.length,!O())throw new Error("aborted");p(C,Ne)}Ne>C.size&&(C.size=Ne)}}finally{clearTimeout(re)}if(await X.close(),!O()||(C.localPath=await h(M,U,$.name,O),Q=!0,!O()))return;u(C,"done")}finally{Q||(await X.close().catch(()=>{}),await Qs(M).catch(()=>{}))}}let v=(C,O)=>{let $={...C,id:Eo(),attempt:0,done:0,state:O?"failed":"queued",error:O??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:O?o():null};return s.push($),$};async function T(C){let O=[],$=async(q,G)=>{if(G.length>32)return!0;let I=await(G.length?Lh(q):fc(q)).catch(()=>null);if(!I)return!0;if(I.isFile())return O.push({path:q,size:I.size,relDir:G}),O.length<=2e3;if(!I.isDirectory())return!0;let A=(await zh(q).catch(()=>[])).filter(U=>!U.startsWith(".")).sort();for(let U of A)if(!await $(fr(q,U),[...G,pc(q)]))return!1;return!0};for(let q of C)if(!await $(q,[]))return"too_many";return O}t.handle("penzor:device",C=>{if(!t.isTrustedSender(C))return{ok:!1,error:"untrusted"};let O=yo();return{ok:!0,name:O?decodeURIComponent(O):null}}),t.handle("penzor:upload",async(C,O)=>{if(!t.isTrustedSender(C))return{ok:!1,error:"untrusted"};let $=O??{},q=Array.isArray($.paths)?$.paths.filter(ie=>typeof ie=="string"&&Yh(ie)):[],G=typeof $.parentId=="string"&&ac.test($.parentId)?$.parentId:null,I=typeof $.projectSource=="string"&&lc.test($.projectSource)?$.projectSource:null;if(!q.length)return{ok:!1,error:"no_files"};if(!G||!I)return{ok:!1,error:"bad_target"};let{base:A,token:U,account:M}=await l();if(!U)return{ok:!1,error:"not_signed_in"};let X=await T(q);if(X==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!X.length)return{ok:!1,error:"no_files"};let Q=X.filter(ie=>ie.size<=52428800).reduce((ie,fe)=>ie+fe.size,0);try{let ie=await y(A,U,"/storage/quota",{}),fe=Number(ie.json?.used),we=Number(ie.json?.quota);if(ie.status===200&&we>0&&fe+Q>we)return{ok:!1,error:"quota",short:fe+Q-we}}catch{}if((await l()).account!==M)return{ok:!1,error:"account_changed"};let ee=Eo(),re=X.map(ie=>v({kind:"up",name:pc(ie.path),size:ie.size,projectSource:I,parentId:ie.relDir.length?null:G,targetId:G,fileId:null,localPath:ie.path,batch:ee,account:M,relDir:ie.relDir},ie.size>52428800?"too_large":void 0).id);return f(),{ok:!0,ids:re,batch:ee}}),t.handle("penzor:download",async(C,O)=>{if(!t.isTrustedSender(C))return{ok:!1,error:"untrusted"};let $=O??{},q=Xh.includes($.mode)?$.mode:null,G=ko($.name);if(!q)return{ok:!1,error:"bad_mode"};if(!G)return{ok:!1,error:"bad_name"};let{base:I,token:A,account:U}=await l();if(typeof $.path!="string"||!Pt(I,$.path))return{ok:!1,error:"bad_path"};if(!A)return{ok:!1,error:"not_signed_in"};let M=$.subdir==null?null:ko($.subdir),X=v({kind:"down",name:G,size:Math.max(0,Number($.size)||0),localPath:null,batch:typeof $.batch=="string"&&$.batch.length<=64?$.batch:Eo(),account:U,relDir:[],dl:{path:$.path,mode:q,name:G,subdir:M}});return f(),{ok:!0,id:X.id}}),t.handle("penzor:transfers",C=>t.isTrustedSender(C)?{ok:!0,items:s.map(c)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(C,O)=>{if(!t.isTrustedSender(C))return{ok:!1,error:"untrusted"};let $=O??{},q=s.find(I=>I.id===$.id);if(!q)return{ok:!1,error:"not_found"};let G=()=>{q.abort?.abort(),q.abort=null,q.done=0,q.samples=[]};switch($.op){case"pause":(q.state==="active"||q.state==="queued")&&(G(),q.state="paused",f());break;case"resume":q.state==="paused"&&(q.state="queued",f());break;case"cancel":(q.state==="active"||q.state==="queued"||q.state==="paused")&&(G(),u(q,"canceled"));break;case"retry":(q.state==="failed"||q.state==="canceled")&&(q.state="queued",q.error=null,q.finishedAt=null,q.done=0,f());break;case"dismiss":q.state!=="active"&&q.state!=="queued"&&s.splice(s.indexOf(q),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(C,O)=>{if(!t.isTrustedSender(C))return{ok:!1,error:"untrusted"};let $=O?.which==="all";for(let q of[...s])(q.state==="done"||q.state==="canceled"||$&&q.state==="failed")&&s.splice(s.indexOf(q),1);return{ok:!0}});let z=()=>s.filter(C=>C.state==="active"||C.state==="queued"||C.state==="paused").length;return vo(t,"transfers",()=>z()>0),t.addQuitGuard?.(C=>{let O=z();return O?C==="zh"?{message:`\u8FD8\u6709 ${O} \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:O===1?"1 file hasn't finished transferring":`${O} 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 ig,writeFileSync as ag,mkdirSync as lg,chmodSync as cg,renameSync as ug}from"node:fs";import{join as dg}from"node:path";import{mkdirSync as Qh,readFileSync as eg,renameSync as tg,unlinkSync as ng,writeFileSync as rg}from"node:fs";import{dirname as og,join as sg}from"node:path";import{randomUUID as gc}from"node:crypto";var si=t=>sg(t,"content-sync","active-account.json"),ni=()=>Error("Invalid content sync account binding; original data was retained");function pr(t){try{let e=JSON.parse(eg(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 ni();return e}catch(e){if(e?.code==="ENOENT")return null;throw ni()}}function ii(t,e){Qh(og(t),{recursive:!0,mode:448});let n=t+".tmp-"+gc();try{rg(n,JSON.stringify(e),{flag:"wx",mode:384}),tg(n,t)}finally{try{ng(n)}catch{}}}var ri=new WeakMap,oi=new WeakSet;function mc(t,e){let n=ri.get(t);return n||ri.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function ai(t){if(oi.has(t))throw ni()}function _n(t,e,n){if(!t.contentSync||e===n)return;let r=si(t.homeDir());try{let o=pr(r);ii(r,{version:1,account:o?.account??null,epoch:gc(),pending:!0}),oi.delete(t)}catch(o){throw oi.add(t),o}finally{for(let o of ri.get(t)??[])o()}}function fg(t){let e=()=>dg(t(),"auth-accounts.json");return{read:()=>ig(e(),"utf8"),write:n=>{lg(t(),{recursive:!0});let r=`${e()}.tmp`;ag(r,n,{encoding:"utf8",mode:384}),cg(r,384),ug(r,e())}}}var wc=t=>tl(t,fg(()=>t.homeDir())),bc=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],li=t=>bc.every(e=>typeof t[e]=="function");function ci(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=wc(t),o=0,s=()=>{let l=t.readCreds();return or(l.cloudUrl,l.token)},a=l=>Je(l.cloudUrl??"",l.token??""),i=null;t.handle("auth:status",async l=>{if(!t.isTrustedSender(l))return n;let c=o,u=s(),{base:f}=await t.getCloud(),g=t.readCreds().token,p=g?await cr(f,g):null,m=await t.accountBackendState(),{base:y}=await t.getCloud(),b=t.readCreds(),E=or(y,b.token)!==or(f,g),h=or(f,g);!E&&p?.status==="ok"&&p.user&&(i={key:h,user:p.user},r.rememberForsionAccount({...b,cloudUrl:f},p.user));let x=E?void 0:p?.status==="ok"?p.user:p?.status==="offline"&&i?.key===h?i.user:void 0;if(E)return{loggedIn:!!b.token,tokenValid:null,cloudUrl:y,accountId:Je(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!==o||s()!==u)return;let T=()=>{if(c!==o||s()!==u)throw yc};try{await t.accountClear(T,()=>{_n(t,t.accountId?.()??null,null),t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++o,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),i=null})}catch(z){if(z!==yc)throw z}});let v=t.readCreds();return{loggedIn:!!v.token,tokenValid:null,cloudUrl:v.cloudUrl||f,accountId:Je(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:Je(f,g),username:x?.username||null,nickname:x?.nickname||null,avatar:x?.avatar||null,membershipTier:x?.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=++o;return r.cancelForsionLogin(),t.accountTransition(async()=>{let f=r.savedForsionAccount(c);return await t.accountCommit(f,()=>{if(u!==o)throw new Error("Account switch cancelled.")},()=>{_n(t,t.accountId?.()??null,a(f)),r.rememberForsionAccount(f),i=null}),{ok:!0,cloudUrl:f.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(l,c)=>{if(!t.isTrustedSender(l))return e;let u=++o;r.cancelForsionLogin();let{base:f}=await t.getCloud();if(u!==o)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!==o)throw new Error("Sign-in cancelled.")},()=>{_n(t,t.accountId?.()??null,a(m)),r.rememberForsionAccount(m),i=null})))).cloudUrl}}),t.handle("auth:logout",async l=>t.isTrustedSender(l)?(++o,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:c}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{_n(t,t.accountId?.()??null,null),r.forgetForsionAccount(u),i=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{_n(t,a(l),a(c))}catch{t.log("[content-sync] account transition could not be recorded; sync is stopped")}++o,r.cancelForsionLogin(),l.token&&!c.token&&r.forgetForsionAccount(l),i=null,r.rememberForsionAccount(c)}),t.setTokenRefresher(async l=>{let c=o,u=s(),f=t.readCreds().token;if(!oo(f))return;let{base:g}=await t.getCloud(),p=await so(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!==o||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 yc=Symbol("stale-auth-intent");import{promises as On}from"node:fs";import dn from"node:path";import{execFile as Jg}from"node:child_process";import Kg from"node:os";var ui=null;function Sc(t){ui=t}var vc=null;function kc(t){vc=t}var Ec=()=>vc;function Le(){if(!ui)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return ui}var qe=()=>Le().accountId();function Cn(t=qe()){return t?Ae().sha256Hex(t):"signed-out"}var ct=(t=qe())=>Le().readConfig(t),$t=(t,e=qe())=>Le().writeConfig(t,e),An=(t,e=qe())=>Le().updateConfig(t,e),Ft=(t=qe())=>Le().cloudVaultDir(t),_o=t=>Le().isManagedCloudVault(t);function pg(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 o=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let s=0;s<t.length;s++){let a=t[s],i=n[a]||[],l=0,c=o[0];for(let u of i){let f;for(f=l;f<o.length&&!(o[f].buffer2index<u&&(f===o.length-1||o[f+1].buffer2index>u));f++);if(f<o.length){let g={buffer1index:s,buffer2index:u,chain:o[f]};if(l===o.length?o.push(c):o[l]=c,l=f+1,c=g,l===o.length)break}}o[l]=c}return o[o.length-1]}function _c(t,e){let n=pg(t,e),r=[],o=t.length,s=e.length;for(let a=n;a!==null;a=a.chain){let i=o-a.buffer1index-1,l=s-a.buffer2index-1;o=a.buffer1index,s=a.buffer2index,(i||l)&&r.push({buffer1:[o+1,i],buffer1Content:t.slice(o+1,o+1+i),buffer2:[s+1,l],buffer2Content:e.slice(s+1,s+1+l)})}return r.reverse(),r}function hg(t,e,n){let r=[];function o(l,c){r.push({ab:c,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}_c(e,t).forEach(l=>o(l,"a")),_c(e,n).forEach(l=>o(l,"b")),r.sort((l,c)=>l.oStart-c.oStart);let s=[],a=0;function i(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(i(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,x=h+l.oLength,v=l.abStart,T=v+l.abLength,z=g[l.ab];z[0]=Math.min(v,z[0]),z[1]=Math.max(T,z[1]),z[2]=Math.min(h,z[2]),z[3]=Math.max(x,z[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]),E={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(E)}a=u}return i(e.length),s}function Cc(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=hg(t,e,n),i=[];function l(){i.length&&s.push({ok:i}),i=[]}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?i.push(...u.bufferContent):r.excludeFalseConflicts&&c(u.aContent,u.bContent)?i.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 Co(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),o=n<0?t:t.slice(n+1),s=o.lastIndexOf("."),a=s>0?o.slice(0,s):o,i=s>0?o.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})${i}`}function gg(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),o=r?t.slice(0,n):t,s=r?t.slice(n):"";return`${o}-${e}${s}`}function mg(t){let e=3735928559,n=1103547991;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);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 xn=(t,e)=>e.seq===t.seq&&e.hash!==null&&e.hash!==t.hash,Ac=(t,e)=>e.seq!==t.seq||xn(t,e);function Ao(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?Ac(e,n)?{kind:"pull"}:{kind:"pushDelete"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"hold"};if(xn(e,n))return t===n.hash?{kind:"adopt"}:t===e.hash?{kind:"pull"}:{kind:"hold"};let r=t!==e.hash,o=Ac(e,n);return!r&&!o?{kind:"none"}:r?o?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function xc(t,e,n){let r=Cc(t.split(`
210
- `),e.split(`
211
- `),n.split(`
212
- `),{excludeFalseConflicts:!0}),o=[];for(let s of r){if(s.conflict)return null;s.ok&&o.push(...s.ok)}return o.join(`
213
- `)}function hr(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var Tc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function Ic(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function di(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 Rc(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 di(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 xo(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 To(t){let e=null;return{error(n){n!==e&&(e=n,t?.(n))},ok(){e=null}}}var yg=/[\u0000-\u001f\u007f]/;function Kt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||yg.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function fi(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Kt(n):n.startsWith(`${e}/`)?Kt(n.slice(e.length+1)):null}function Oc(t,e){return e===""?t:`${e}/${t}`}function gr(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Oe(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var We=t=>t==="page"||t==="db";var wg=t=>Math.max(3,Math.ceil(t*.1)),bg=(t,e)=>t===429&&e!=="MASS_DELETE_BLOCKED";function Sg(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 vg(t){let e=t.get("ratelimit"),n,r,o;if(e){let s=a=>Number(new RegExp(`(?:^|[;,\\s])${a}=(\\d+)`).exec(e)?.[1]??NaN);n=s("limit"),r=s("remaining"),o=s("reset")}else n=Number(t.get("ratelimit-limit")??NaN),r=Number(t.get("ratelimit-remaining")??NaN),o=Number(t.get("ratelimit-reset")??NaN);return![n,r,o].every(s=>Number.isFinite(s)&&s>=0)||n<=0?null:{limit:n,remaining:r,resetMs:o*1e3}}function kg(t={}){let e=t.now??Date.now,n=0,r=null,o=new Set,s=()=>{for(let i of[...o])try{i()}catch{}},a=i=>{let l=e()+Math.min(Math.max(i,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(i){for(;n>e();)i?.throwIfAborted(),await new Promise((l,c)=>{let u=setTimeout(f,n-e());function f(){i?.removeEventListener("abort",g),l()}function g(){clearTimeout(u),c(i.reason??new DOMException("Aborted","AbortError"))}i?.addEventListener("abort",g,{once:!0})});i?.throwIfAborted()},observe(i,l,c,u){let f=vg(l);if(bg(i,c)){let g=Sg(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<=wg(f.limit)&&f.resetMs>0&&a(f.resetMs),!1},subscribe(i){return o.add(i),()=>{o.delete(i)}}}}var Mc=new Map;function Xt(t){let e;try{e=new URL(t).origin}catch{e=t.replace(/\/+$/,"")}let n=Mc.get(e);return n||(n=kg(),Mc.set(e,n)),n}var Eg=1024,Se=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},Nc=t=>12e4+Math.ceil(t/256);function _g(t,e){let n=AbortSignal.timeout(t);if(!e)return n;let r=new AbortController;for(let o of[n,e])o.addEventListener("abort",()=>r.abort(o.reason),{once:!0});return r.signal}function Pc(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 $c(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=t.gate??Xt(t.baseUrl),r=()=>t.getToken?.()??t.token,o=async(i,l)=>{let c=r();for(let u=0;;u++){let f={...l.headers,Authorization:`Bearer ${c}`},g=await fetch(i,{...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(i,l,c)=>{let u={Authorization:`Bearer ${t.token}`,...c?.headers};i!=="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>=Eg&&(u["Content-Encoding"]="gzip",f=await Qa(f))):c?.form&&(f=c.form);;){n.until()!==null&&await n.ready(Pc(c?.signal,t.signal));let g=await o(l,{method:i,headers:u,body:f,signal:_g(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 Se(g.status,m,l)}n.observe(g.status,g.headers);let p=await g.json();return r(),p}},a=i=>new URLSearchParams(i).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(i){let l=await s("GET",`${e}/vaults/${i}/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(i,l){let c=await s("GET",`${e}/vaults/${i}/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(i,l,c,u,f=!1,g){return s("PUT",`${e}/vaults/${i}/file`,{json:{path:l,content:c,baseSeq:u,...f?{force:!0}:{},...g?{expectedHash:g}:{}}})},async deleteFile(i,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/${i}/file?${a(f)}`,u?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(i,l,c){return s("POST",`${e}/vaults/${i}/move`,{json:{from:l,to:c}})},renameFolder(i,l,c){return s("POST",`${e}/vaults/${i}/folders/rename`,{json:{path:l,newName:c}})},moveFolder(i,l,c){return s("POST",`${e}/vaults/${i}/folders/move`,{json:{path:l,dest:c}})},async deleteFolder(i,l){await s("DELETE",`${e}/vaults/${i}/folders?${a({path:l})}`)},putBinary(i,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/${i}/binary`,{form:f,timeoutMs:Nc(c.length),signal:u?.signal})},async listVersions(i,l){return((await s("GET",`${e}/vaults/${i}/file/versions?${a({path:l})}`)).versions??[]).map(u=>({id:String(u.id),seq:Number(u.seq??0)}))},async getVersion(i,l){let c=await s("GET",`${e}/vaults/${i}/file/versions/${l}`);return String(c.content??"")},async getAsset(i,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(Pc(c,t.signal)),g=setTimeout(f,12e4),p=await o(`${e}/vaults/${i}/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 Se(p.redirected&&(p.status===401||p.status===403)?502:p.status,null,"asset:"+l);clearTimeout(g),g=setTimeout(f,Nc(Number(p.headers.get("content-length"))||0));let m=new Uint8Array(await p.arrayBuffer());return r(),m}finally{clearTimeout(g)}},async changes(i,l){let c=await s("GET",`${e}/vaults/${i}/changes?${a({since:String(l)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function Fc(t,e){let n=!1,r=0,o=null,s=null,a=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,i=(c,u=!1)=>{if(n)return;o?.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;o=new AbortController;try{await t.gate?.ready(o.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:o.signal}),n){await c.body?.cancel();return}t.getToken?.()}catch(E){i(E);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){i(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 E=y.join(`
214
- `),h=m||"message";m="",y=[];let x=null;try{x=E?JSON.parse(E):null}catch{return}h==="hello"?e.onHello(Number(x?.seq??0)):h==="change"?e.onChange(x):h==="reset"?e.onReset():h==="presence"?e.onPresence?.(x):h==="presence-roster"&&e.onPresenceRoster?.(x)};try{for(;;){let{done:E,value:h}=await f.read();if(E)break;for(p+=g.decode(h,{stream:!0});;){let x=p.indexOf(`
215
- `);if(x<0)break;let v=p.slice(0,x).replace(/\r$/,"");if(p=p.slice(x+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(E){n||i(E,Date.now()-u>=1e4);return}i(new Error("sse stream ended"),Date.now()-u>=1e4)};return l(),{stop:()=>{n=!0,s&&clearTimeout(s),o?.abort()}}}var un=t=>Ae().path.join(Le().userDataDir(),Le().isDevMode()?`${t}.dev.json`:`${t}.json`),pi=un,vt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,ln=t=>typeof t=="string"&&Kt(t)===t,mr=t=>typeof t=="string"&&t.length>0,jc=t=>vt(t)&&cn(t.seq)&&mr(t.hash)&&cn(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),Lc=t=>typeof t=="number"&&Number.isFinite(t),Cg=t=>vt(t)&&mr(t.localHash)&&cn(t.localSize)&&Lc(t.localMtimeMs)&&cn(t.remoteSeq)&&(t.remoteHash===null||mr(t.remoteHash))&&(t.remoteUpdatedAt===null||typeof t.remoteUpdatedAt=="string")&&Lc(t.since),Ag=t=>vt(t)&&ln(t.from)&&ln(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||vt(t.hashes)&&Object.values(t.hashes).every(mr));async function hi(t){let e;try{e=await Ae().fs.readFile(pi(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(!vt(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Jt(n.rootIdentity)||n.mirrorMissing!==void 0&&n.mirrorMissing!==!0||n.mirrorRestore!==void 0&&n.mirrorRestore!=="list"&&(!vt(n.mirrorRestore)||!Object.entries(n.mirrorRestore).every(([r,o])=>ln(r)&&vt(o)&&cn(o.seq)&&(o.hash===null||mr(o.hash))))||!vt(n.files)||!Object.entries(n.files).every(([r,o])=>ln(r)&&jc(o))||n.cursor!==void 0&&!cn(n.cursor)||n.lastSyncAt!=null&&!cn(n.lastSyncAt)||n.pending!==void 0&&(!vt(n.pending)||!Object.entries(n.pending).every(([r,o])=>ln(r)&&(o==="local"||o==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(Ag))||n.held!==void 0&&(!vt(n.held)||!Object.entries(n.held).every(([r,o])=>ln(r)&&Cg(o)))||n.dormant!==void 0&&(!vt(n.dormant)||!Object.entries(n.dormant).every(([r,o])=>ln(r)&&jc(o)))||n.dormantRoot!==void 0&&!Jt(n.dormantRoot))throw Error("Invalid cloud vault sync state; original data was retained");return{...n,cursor:n.cursor??0,lastSyncAt:n.lastSyncAt??null}}function Uc(t){let e=null,n=null,r=Promise.resolve(),o=null,s=()=>{if(!e)return r;let a=e,i=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let l=pi(t),c=`${l}.tmp-${Ae().tmpTag()}-${Date.now()}-0`;await Ae().fs.writeFile(c,i,"utf8"),await Ae().fs.rename(c,l),o=null}catch(l){e??=a,o=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&&o)throw o}}}async function Hc(t){try{await Ae().fs.unlink(pi(t))}catch{}}var yr=/^[0-9a-f]{64}$/;function zc(t){let e=Ae(),n=()=>un(t).replace(/\.json$/,".bases"),r=i=>e.path.join(n(),i),o=i=>e.fs.access(r(i)).then(()=>!0,()=>!1),s=new Map,a=(i,l)=>{let c=(s.get(i)??Promise.resolve()).then(l,l);return s.set(i,c),c.finally(()=>{s.get(i)===c&&s.delete(i)}),c};return{put(i,l){return yr.test(i)?a(i,async()=>{try{if(await o(i))return;await e.fs.mkdir(n(),{recursive:!0});let c=`${r(i)}.tmp-${e.tmpTag()}-${Date.now()}`;await e.fs.writeFile(c,l,"utf8"),await e.fs.rename(c,r(i))}catch{}}):Promise.resolve()},async get(i){if(!yr.test(i))return null;try{let l=await e.fs.readFile(r(i),"utf8");return e.sha256Hex(l)===i?l:null}catch{return null}},drop(i,l){return yr.test(i)?a(i,async()=>{if(!(l&&!l()))try{await e.fs.rm(r(i),{force:!0})}catch{}}):Promise.resolve()},async has(i){return yr.test(i)&&o(i)},async prune(i){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(!i.has(c)&&!(!yr.test(c)&&!/^[0-9a-f]{64}\.tmp-/.test(c)))try{await e.fs.rm(e.path.join(n(),c),{force:!0})}catch{}}}}var xg=720*60*60*1e3,Tg=/^[0-9a-f]{64}$/,Io=new Map,Bc=(t,e)=>{let n=(Io.get(t)??Promise.resolve()).then(e,e),r=n.catch(()=>{});return Io.set(t,r),r.then(()=>{Io.get(t)===r&&Io.delete(t)}),n},gi=class extends Error{constructor(e){super(`sync recovery save failed: ${e?.message??String(e)}`),this.name="RecoveryError"}};function qc(t){let e=Ae(),n=()=>e.path.join(Le().homeDir(),"sync-recovery",t),r=i=>e.fs.access(i).then(()=>!0,()=>!1),o=async(i,l)=>{let c=`${i}.tmp-${e.tmpTag()}-${Date.now()}`;try{await e.fs.writeFile(c,l),await e.fs.rename(c,i)}catch(u){throw await e.fs.rm(c,{force:!0}).catch(()=>{}),u}},s={async save(i,l){let c=n(),u=await Bc(c,async()=>{try{let f=e.path.join(c,e.sha256Hex(i));await e.fs.mkdir(c,{recursive:!0}),await r(f)||await o(f,i);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 o(g,JSON.stringify(p)),f}catch(f){throw new gi(f)}});return s.prune(),u},prune(i=Date.now()){let l=n();return Bc(l,()=>a(l,i))}},a=async(i,l)=>{let c;try{c=(await e.fs.readdir(i,{withFileTypes:!0})).filter(u=>u.isFile()).map(u=>u.name)}catch{return}for(let u of c){if(!Tg.test(u))continue;let f=e.path.join(i,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<=xg))try{await e.fs.rm(f,{force:!0}),await e.fs.rm(`${f}.json`,{force:!0})}catch{}}};return s}var Ig=5*1024*1024,Rg=5*1024*1024,Dg=3e4,Og=5e3,Mg=5*6e4,Ng=2500,Pg=3e3,$g=5,Fg=256*1024,jg=5,Ro=1024*1024,Wc=200,Lg=6e4,Ug=50,Hg=".sync-trash",Ke=t=>Ae().sha256Hex(t);function wr(t,e){let n=e??{localRoot:Ft(),shadowName:`amadeus-sync-${Cn()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]},r=d=>{let w=fi(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,Oe(S))?null:S},o=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=>gr(S)||!!n.ignoreNames?.includes(S))?null:w},s=(d,w)=>!n.inScope||n.inScope(d,w),a=n.accountId??qe(),{fs:i,path:l,directoryIdentity:c}=Ae(),u=d=>i.access(d).then(()=>!0,()=>!1),f=!1,g=!1,p=0,m=Promise.resolve(),y=new Set,b="disabled",E=null,h=null,x=null,v=null,T=null,z=null,C=null,O=null,$=null,q=()=>{let d=t.loadCreds();if(!z||a!==qe()||!d.token||d.cloudUrl?.replace(/\/+$/,"")!==z.cloudUrl.replace(/\/+$/,""))throw new Se(401,{code:"ACCOUNT_CHANGED"},"sync-session");return d.token},G=null,I=0,A=new Map,U=null,M=Uc(n.shadowName),X=zc(n.shadowName),Q=qc(Cn(a)),ee=!1,re=new Map,ie=!1,fe=!1,we=[],ve=(d,w,S)=>{try{t.onHealth?.(d,w,S)}catch{}},Ge=To(ve),Ne=0,be=()=>{fe||ve("massDeleteGuard"),fe=!0},N=()=>{h&&(h.pending=re.size?Object.fromEntries(re):void 0,M.save(h))},W=()=>{fe=!1,we.length=0},H=()=>{if(fe)return!0;let d=Date.now();for(;we.length&&d-we[0]>Lg;)we.shift();return we.length>=Ug?(be(),!0):!1},_=[],R=new Set,B=!1,L=null,V=null,se=null,oe=null,Z=()=>{!f||oe||(oe=setTimeout(()=>{oe=null,t.onStatus(Ct())},200))},ae=(d,w,S)=>{let k=b;b=d,w!==void 0&&(E=w),pe(k,d,S),Z()},le=!1,pe=(d,w,S)=>{if(w==="syncing"&&d!=="syncing"&&(Ne=Date.now()),w==="idle"&&d==="syncing"&&(ve("cycles"),ve("cycleMsTotal",Math.max(0,Date.now()-Ne))),w==="idle"||w==="disabled"){le=!1,Ge.ok();return}if(S===null)return;let k=S??Dc(w,E);k&&Ge.error(k)},he=(d,w)=>{A.set(d,w),ve(Ic(w),1,d)},ne=(d,w=!1)=>{if(!(!f||!g)){if(d.key){if(R.has(d.key))return;R.add(d.key)}w?_.unshift(d):_.push(d),Ef()}},me=new Map,tt=d=>{if(!f)return;let w=(h?.files[d]?.size??0)>Fg,S=(n.pushQuietMs??Pg)*(w?jg:1),k=Date.now(),D=me.get(d);D&&clearTimeout(D.timer);let F=D?.since??k,J=Math.max(0,Math.min(S,F+S*$g-k)),P=setTimeout(()=>{me.delete(d),ne({key:d,run:()=>Te(d,!0)})},J);me.set(d,{timer:P,since:F}),Z()},Kn=()=>{for(let{timer:d}of me.values())clearTimeout(d);me.clear()},wt=new Set(["EACCES","EPERM","EISDIR","ENOTDIR","ENAMETOOLONG","EILSEQ","EINVAL","ELOOP","EBUSY","EFBIG","EIO"]),ds=d=>!(d instanceof Se)&&typeof d?.code=="string"&&wt.has(d.code),zr=d=>!(d instanceof Se)||d.status>=500||d.status===0,vf=d=>!!d&&!d.startsWith("\0"),kf=d=>d instanceof Se?d.body?.code||`http ${d.status}`:d?.code??"error",Xn=d=>d instanceof Se&&(d.status===401||d.status===403),Br=(d,w)=>{he(d,kf(w)),Z()},Ef=async()=>{if(!B){B=!0;try{for(;_.length;){(b==="idle"||b==="starting")&&ae("syncing");let d=_.shift();d.key&&R.delete(d.key);try{await d.run()}catch(w){if(!f)return;if(Xn(w)){_.length=0,R.clear(),tr(),ae("auth-required","login-expired");return}if(zr(w)&&!(ds(w)&&vf(d.key))){ne(d,!0),tr(),ae("offline",w?.message||"network error"),Zn();return}Br(d.key??"(op)",w)}}f&&b==="syncing"&&(h&&(h.lastSyncAt=Date.now(),M.save(h)),ae("idle",null))}finally{B=!1;for(let d of y)d();y.clear()}}},Zn=()=>{!f||L||(L=setTimeout(()=>{L=null,nr()},Dg))},ke=new Map,rn=0,Pe=null,qr=()=>!!V||!!Pe||!f,fs=d=>d instanceof Se&&d.status>=500||d?.name==="TimeoutError",Ca=n.pushRetryMs??Og,Aa=d=>{ke.get(d)&&(ke.delete(d),A.delete(d))},Qn=(d,w)=>{(w||!ke.has(d))&&ke.set(d,w)},xa=(d,w,S)=>{he(d,w instanceof Se?`http ${w.status}`:"timeout"),Qn(d,S),rn=Math.min(rn*2||Ca,Mg),V=setTimeout(Wr,rn),Z()},Ta=(d,w,S)=>{let k=new AbortController,D=w(k.signal).then(J=>()=>J,J=>()=>{throw J}),F={path:d,abort:k,after:[],settle:async()=>{let J=await D;if(Pe===F){Pe=null;try{await S(J)}catch(P){if(Xn(P)||zr(P))throw P;Br(d,P)}finally{for(let P of F.after)ne(P);Ia(d)}}}};Pe=F,D.then(()=>ne({run:F.settle}))},Sn=(d,w)=>{for(let[S,k]of[...ke])!k||!Ve(S,d)||(ke.delete(S),A.delete(S),w!==null&&ke.set(w+S.slice(d.length),k));Z()},Wr=()=>{V=null;let[d]=ke;if(d===void 0)return;let[w]=d;R.delete(w),ne({key:w,run:async()=>{if(Pe?.path===w)return;let S=ke.get(w),k=!S&&ke.delete(w);(S||k)&&A.delete(w);try{S?await Qe(w,S.seq):k&&await Te(w,!0)}finally{k&&je(w)&&Qn(w),Ia(w)}}})},Ia=d=>{if(!qr())if(ke.has(d)){let w=ke.get(d);ke.delete(d),ke.set(d,w),V=setTimeout(Wr,rn||Ca)}else Wr()},Fe=d=>{if(!G||!h)throw new Error("engine not bound");let w=o(d);if(w===null)throw new Error("path outside binding: "+d);let S=l.resolve(G,Oc(w,h.folder)),k=l.relative(G,S);if(k.startsWith("..")||l.isAbsolute(k))throw new Error("path escapes vault: "+d);return S},Gr=d=>({size:d,mtimeMs:-1}),Ra=async d=>{try{let w=await i.stat(d);return w.isFile()?{size:w.size,mtimeMs:Math.floor(w.mtimeMs)}:null}catch{return null}},Da=async d=>{if(!i.lstat||!G)return Ra(d);let w=l.relative(G,d).split(l.sep),S=G;for(let[k,D]of w.entries()){S=l.join(S,D);let F=await i.lstat(S).catch(J=>{if(J?.code==="ENOENT")return null;throw J});if(!F)return null;if(F.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(k===w.length-1&&F.isFile())return{size:F.size,mtimeMs:Math.floor(F.mtimeMs)};if(k===w.length-1||!F.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},_f=0,ps=async(d,w,S,k)=>{if(!await rt())throw Error("Cloud vault sync root is unavailable or changed");let D=G&&x?{path:G,identity:x}:void 0;await i.mkdir(l.dirname(d),{recursive:!0});let F=`${d}.tmp-${Ae().tmpTag()}-${Date.now()}-${_f++}`;await i.writeFile(F,w);let J=await Ra(F)??Gr(no(w));try{if(!k())return null;let P=Ae().compareAndReplace;if(!P)throw new Error("Host does not support safe cloud download commits");let Y=await P(F,d,S,k,D);if(!Y&&!await rt())throw Error("Cloud vault sync root is unavailable or changed");return Y?J:null}finally{await rt()&&await i.rm(F,{force:!0})}},Oa=async d=>{let w;try{w=await i.readdir(d,{withFileTypes:!0})}catch{return}for(let S of w)S.isDirectory()&&await Oa(l.join(d,S.name));try{await i.rmdir(d)}catch{}},pt=async d=>{let w=Fe(d),S=await Da(w);if(!await rt())throw Error("Cloud vault sync root is unavailable or changed");if(i.lstat&&!S)return null;let k;try{k=await i.readFile(w)}catch(F){if(F?.code!=="ENOENT")throw F;if(!await rt())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:We(Oe(d))?Ke(At(k)):Ke(k),size:S?.size??k.length,mtimeMs:S?.mtimeMs??-1,buf:k}},nt=async(d,w,S,k,D)=>{if(!h)return;let F=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],M.save(h),D!==void 0&&await Ma(d,S,D),F&&F!==S&&await hs(F)},Ma=async(d,w,S)=>{if(!We(Oe(d))||no(S)>Ro)return;let k=typeof S=="string"?S:At(S);Ke(k)===w&&await X.put(w,k)},hs=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 X.drop(d,w)},ht=d=>{if(h&&d in h.files){let w=h.files[d].hash;delete h.files[d],M.save(h),hs(w)}},gt=(d,w,S)=>{if(!h)return;let k=h.held?.[d];ht(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()}},M.save(h),Z()},_e=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,M.save(h),Z()},Nt=d=>h?.held&&Object.hasOwn(h.held,d)?h.held[d]:void 0,Et=d=>o(d)!==null&&s(d,Oe(d)),gs=d=>{!h||!Object.hasOwn(h.files,d)||(h.dormant={...h.dormant,[d]:h.files[d]},x&&(h.dormantRoot??=x),delete h.files[d],M.save(h))},Vr=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,M.save(h),hs(w)},Na=d=>!!h?.dormant&&Object.hasOwn(h.dormant,d)&&!Object.hasOwn(h.files,d)&&Et(d),Pa=()=>ne({key:"\0full",run:on}),$a=()=>{if(h){for(let d of Object.keys(h.files))!Et(d)&&!je(d)&&gs(d);for(let d of Object.keys(h.held??{}))!Et(d)&&!je(d)&&_e(d)}},Qe=async(d,w)=>{if(!v||!h||je(d))return;if(Na(d)){Pa();return}let S=Ce,k=Oe(d),D=Nt(d);if(D&&!We(k)){Aa(d),w!==null&&w!==D.remoteSeq&&gt(d,{hash:D.localHash,size:D.localSize,mtimeMs:D.localMtimeMs},{seq:w,hash:null,updatedAt:null});return}if(We(k)){let Y;try{Y=await v.getFile(h.vaultId,d),ve("downloads")}catch(te){if(te instanceof Se&&te.status===404){await ms(d);return}throw te}await Fa(d,k,Y.content,Y.seq,Y.hash??Ke(Y.content),S);return}if(qr()){Qn(d,{seq:w}),Z();return}let{vaultId:F}=h,J=v,P={seq:w};ke.set(d,P),Ta(d,Y=>J.getAsset(F,d,Y),async Y=>{let te=ke.get(d)===P,j;try{j=Y(),rn=0,ve("downloads")}catch(K){if(!te)return;if(ke.delete(d),K instanceof Se&&K.status===404){he(d,"ASSET_404"),Z();return}if(fs(K)){xa(d,K,{seq:w});return}throw K}te&&await Fa(d,k,j,w??0,Ke(j),S)}),Z()},Fa=async(d,w,S,k,D,F)=>{if(!h)return;let J=async Re=>{await nt(d,k,D,Re,S),ke.get(d)&&(ke.delete(d),A.delete(d))},P=await pt(d);if(F!==Ce||je(d))return;let Y=h.mirrorRestore,te=Y&&Y!=="list"&&Object.hasOwn(Y,d)?Y[d]:void 0;if(te&&(te.hash!==D||te.seq!==k)){let Re={...te};Object.assign(te,{hash:D,seq:k}),M.save(h);try{await M.flush(!0)}catch(st){throw Object.assign(te,Re),M.save(h),st}if(!f||F!==Ce||je(d))return}if(P&&P.hash===D){await J(P),_e(d);return}let j=h.files[d];if(P&&(!j||Nt(d)||xn(j,{seq:k,hash:D})&&P.hash!==j.hash)){Aa(d),gt(d,P,{seq:k,hash:D});return}if(_e(d),P&&j&&D===j.hash&&P.hash!==j.hash){await J(Gr(j.size)),ne({key:d,run:()=>Te(d)});return}let K=P?Ke(P.buf):null;if(P&&(!j||P.hash!==j.hash)){if(j&&We(w)&&typeof S=="string"&&await Cf(d,j,P,S,k,D,()=>F===Ce&&!je(d))||F!==Ce||je(d)||!await ja(d,()=>F===Ce&&!je(d)))return;K=null}let ye=await ps(Fe(d),S,K,()=>f&&F===Ce&&!je(d));if(!ye){ne({key:d,run:()=>Te(d)});return}await J(ye)},Cf=async(d,w,S,k,D,F,J)=>{try{if(!v||!h||S.buf.length>Ro||k.length>Ro)return!1;let P=await X.get(w.hash);if(P===null){let K=(await v.listVersions(h.vaultId,d)).find(Re=>Re.seq===w.seq);if(!K)return!1;let ye=await v.getVersion(h.vaultId,K.id);if(Ke(ye)!==w.hash)return!1;P=ye}let Y=At(S.buf),te;if(Oe(d)==="db"){let j=Ec(),K=j?j(d,Y,P,k):null;te=K&&!K.conflict?K.content:null}else te=xc(Y,P,k);return te===null?!1:await ps(Fe(d),te,Ke(S.buf),()=>f&&J())?(await nt(d,D,F,Gr(no(te)),k),ne({key:d,run:()=>Te(d)}),!0):(ne({key:d,run:()=>Te(d)}),!0)}catch{return!1}},ja=async(d,w)=>{let S=Kt(Co(d,new Date));if(!S)return!0;let k=S.lastIndexOf("."),D=k>S.lastIndexOf("/"),F=D?S.slice(0,k):S,J=D?S.slice(k):"",P=S,Y=Ae().existsSync;if(Y)for(let te=2;Y(Fe(P));te++)P=`${F}-${te}${J}`;else for(let te=2;await u(Fe(P));te++)P=`${F}-${te}${J}`;if(!w())return!1;try{await i.rename(Fe(d),Fe(P))}catch(te){if(te?.code==="ENOENT")return!0;throw te}return I++,ve("conflicts"),ne({key:P,run:()=>Te(P)}),Z(),!0},La=async d=>{if(!G)return;let w=Fe(d),S=o(d)??d,k=l.join(G,Hg,new Date().toISOString().slice(0,10),...S.split("/")),D=await u(k)?`${k}.${Date.now()}`:k;try{await i.mkdir(l.dirname(D),{recursive:!0}),await i.rename(w,D)}catch(F){if(F?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${w}: ${F?.message??String(F)}`)}},ms=async d=>{if(!h)return;Sn(d,null),_e(d),Vr(d);let w=await pt(d);if(je(d))return;let S=h.files[d]??null,k=Ao(w?.hash??null,S,null);if(k.kind==="deleteLocal"){if(!ie&&H()){re.set(d,"local"),N(),Z();return}we.push(Date.now()),await La(d),ht(d)}else k.kind==="pushCreate"?(ht(d),ne({key:d,run:()=>Te(d)})):ht(d)},Ua=(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]);M.save(h),Z()}},Ha=async d=>{if(!v||!h||d.seq<=h.cursor||!await rt())return;if(d.origin.client&&v.clientId===d.origin.client){h.cursor=d.seq,M.save(h);return}let w=d.type==="structure"?"folder":d.type,S=D=>o(D)!==null&&s(D,w);if(!S(d.path)&&!(d.newPath&&S(d.newPath))){h.cursor=d.seq,M.save(h);return}let k=d.path;if(d.op!=="write"&&d.op!=="mkdir"){for(;Pe&&(Ve(Pe.path,k)||d.newPath&&Ve(Pe.path,d.newPath));)await Pe.settle();if(!f)return}switch(d.op){case"write":await Qe(k,d.fileSeq);break;case"delete":await ms(k);break;case"move":{let D=d.newPath;if(!D)break;let F=h.files[k],J=await pt(k),P=!!ke.get(k);Sn(k,D),Vr(k),Nt(k)&&(_e(k),ne({key:k,run:()=>Te(k)})),P&&Qn(D,{seq:d.fileSeq});let Y=D!==k&&await Da(Fe(D)).then(te=>te!==null,()=>!0);if(J&&F&&Y)await Qe(D,d.fileSeq);else if(J&&F)try{await i.mkdir(l.dirname(Fe(D)),{recursive:!0}),await i.rename(Fe(k),Fe(D)),h.files[D]={...F,seq:P?F.seq:d.fileSeq??F.seq},delete h.files[k],M.save(h)}catch{await Qe(D,d.fileSeq)}else ht(k),await Qe(D,d.fileSeq);break}case"mkdir":await i.mkdir(Fe(k),{recursive:!0});break;case"rename-folder":case"move-folder":{let D=d.newPath;if(!D)break;try{await i.mkdir(l.dirname(Fe(D)),{recursive:!0}),await i.rename(Fe(k),Fe(D))}catch{}Ua(k,D);break}case"delete-folder":{let D=`${k}/`;for(let F of[...Object.keys(h.files),...Object.keys(h.held??{}),...Object.keys(h.dormant??{})])(F===k||F.startsWith(D))&&await ms(F);Sn(k,null),await Oa(Fe(k));break}}if(h.cursor=d.seq,M.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),D=w?.content??null,F;if(w?.seq===void 0&&v&&h)try{let Y=await v.getFile(h.vaultId,d);k=Y.seq,D=Y.content,F=Y.updatedAt}catch(Y){if(!(Y instanceof Se)||Y.status!==404)throw Y;k=0,D=null}if(D!==null&&Ke(D)===S.hash){await nt(d,k,S.hash,S,D),_e(d);return}if(D===null&&k===0){if(!h?.files[d]){he(d,w?.code||"EXISTS"),Z();return}ht(d),ne({key:d,run:()=>Te(d)});return}let J=h?.files[d],P=D===null?null:Ke(D);if(!J||xn(J,{seq:k,hash:P})){gt(d,S,{seq:k,hash:P,updatedAt:F});return}await Qe(d,k)},Yr=async(d,w)=>{if(!v||!h)return;let S=await pt(d);if(!S){ne({key:d,run:()=>Te(d)});return}if(S.size>Ig){he(d,"TOO_LARGE"),Z();return}let k=At(S.buf),D=w>0?h.files[d]?.hash:void 0;try{let F=await v.putFile(h.vaultId,d,k,w,!1,D);ve("uploads"),A.delete(d),await nt(d,F.seq,F.hash??S.hash,S,S.buf),_e(d)}catch(F){if(F instanceof Se&&F.status===409){await Af(d,F.body,S);return}throw F}},Jr=async(d,w)=>{if(!v||!h)return;let S=await pt(d);if(!S){ne({key:d,run:()=>Te(d)});return}if(S.size>(U??Rg)){he(d,"TOO_LARGE"),Z();return}if(Qn(d),Z(),qr())return;let{vaultId:k}=h,D=v,F=w>0?h.files[d]?.hash:void 0;Ta(d,J=>D.putBinary(k,d,S.buf,{baseSeq:w,signal:J,expectedHash:F}),async J=>{if(h){ke.get(d)||ke.delete(d);try{let P=J();rn=0,ve("uploads"),A.delete(d),await nt(d,P.seq,S.hash,S),_e(d)}catch(P){if(fs(P)){xa(d,P);return}if(!(P instanceof Se)||P.status!==409)throw P;let Y=Number(P.body?.seq??0),te=P.body?.hash??null;if(te!==null&&te===S.hash){await nt(d,Y,S.hash,S),_e(d);return}if(Y===0){if(!h.files[d]){he(d,P.body?.code||"EXISTS"),Z();return}ht(d),ne({key:d,run:()=>Te(d)});return}let j=h.files[d];if(!j||xn(j,{seq:Y,hash:te})){gt(d,S,{seq:Y,hash:te});return}await Qe(d,Y)}}})},za=async d=>{if(!v||!h||je(d))return;let w=Ce,S=h.files[d];if(S){if(We(Oe(d)))try{let k=await v.getFile(h.vaultId,d);if(k.seq!==S.seq||k.hash!==null&&k.hash!==S.hash){await Qe(d,k.seq);return}}catch(k){if(k instanceof Se&&k.status===404){ht(d);return}throw k}if(!(!await rt()||w!==Ce||je(d))){try{await v.deleteFile(h.vaultId,d,S.seq,{confirmed:ie,expectedHash:S.hash})}catch(k){if(k instanceof Se&&k.status===409){await Qe(d,Number(k.body?.seq??0)||null);return}if(k instanceof Se&&k.status===429&&k.body?.code==="MASS_DELETE_BLOCKED"){re.set(d,"remote"),be(),N(),Z();return}throw k}ht(d)}}},Kr=d=>i.stat(d).catch(w=>{if(w?.code==="ENOENT")return null;throw w}),ys=async d=>{let w=Le();if(e||!a||a!==qe()||d!==Ft(a)||!w.isManagedCloudVault(d)||!i.lstat)return!1;let S=w.homeDir(),k=l.relative(S,d);if(!k||k.startsWith("..")||l.isAbsolute(k))return!1;let D=S;for(let F of k.split(l.sep)){D=l.join(D,F);let J=await i.lstat(D).catch(P=>{if(P.code==="ENOENT")return null;throw P});if(J&&(!J.isDirectory()||J.isSymbolicLink()))return!1}return!0},Yt=d=>(g=!1,ie=!1,_.length=0,R.clear(),Ss(),tr(),ae("error",`${d}: ${G}`),Zn(),!1),ws=d=>{let w=x??h?.rootIdentity,S=d!==null&&d.isDirectory();return S&&(!w||St(w,d))?!0:Yt(S?"vault-changed":"vault-missing")},rt=async()=>!!G&&ws(await Kr(G)),Ce=0,Xr=new Set,Zr=new Map,ot=d=>JSON.stringify([d.from,d.to]),Ve=(d,w)=>d===w||d.startsWith(`${w}/`),je=d=>[...h?.moves??[],...Xr].some(w=>Ve(d,w.from)||Ve(d,w.to)),_t=()=>!!(h?.moves?.length||Xr.size),Qr=async d=>{if(!v||!h)return;let{from:w,to:S,kind:k}=d;if(o(w)===null||o(S)===null)throw new Error("Invalid queued cloud move");if(Pe&&(Ve(Pe.path,w)||Ve(Pe.path,S))){Pe.after.push({key:`move:${ot(d)}`,run:()=>Qr(d)});return}if(d.hashes??=Object.fromEntries([...Object.entries(h.held??{}).filter(([P,Y])=>Ve(P,w)&&Y.remoteHash!==null).map(([P,Y])=>[P.slice(w.length),Y.remoteHash]),...Object.entries(h.files).filter(([P])=>Ve(P,w)).map(([P,Y])=>[P.slice(w.length),Y.hash])]),M.save(h),await M.flush(!0),!await rt())return;let D,F=!1;try{if(k==="folder"){let P=l.posix.dirname(w)==="."?"":l.posix.dirname(w),Y=l.posix.dirname(S)==="."?"":l.posix.dirname(S);P===Y?await v.renameFolder(h.vaultId,w,l.posix.basename(S)):await v.moveFolder(h.vaultId,w,Y)}else{let P=await v.move(h.vaultId,w,S);D=Number(P.seq)}}catch(P){if(!(P instanceof Se)||P.status!==404)throw P;let Y=await v.tree(h.vaultId);if(Y.entries.some(K=>Ve(K.path,w))||Y.folders.some(K=>Ve(K,w)))throw P;let j=Y.entries.find(K=>K.path===S);if(D=j?.seq,F=!j&&!Y.entries.some(K=>Ve(K.path,S))&&!Y.folders.some(K=>Ve(K,S)),!F){let K=Object.entries(d.hashes);if(!(K.length>0&&K.every(([Re,st])=>Y.entries.some(Ye=>Ye.path===S+Re&&Ye.hash===st))))throw new Se(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(F){for(let P of Object.keys(h.files))Ve(P,w)&&delete h.files[P];for(let P of Object.keys(h.held??{}))Ve(P,w)&&_e(P);for(let P of Object.keys(h.dormant??{}))Ve(P,w)&&Vr(P);Sn(w,null)}else Ua(w,S),D!==void 0&&h.files[S]&&!ke.get(S)&&(h.files[S].seq=D);h.moves=(h.moves??[]).filter(P=>ot(P)!==ot(d)),M.save(h);try{await M.flush(!0)}catch(P){throw h.moves.unshift(d),M.save(h),P}let J=Zr.get(ot(d));Zr.delete(ot(d)),J?.(),je(S)||(k==="folder"?await bs():await Te(S))},Te=async(d,w=!1)=>{if(!h||je(d))return;if(Pe?.path===d){Pe.after.push({key:d,run:()=>Te(d,w)});return}if(!s(d,Oe(d))){gs(d),_e(d);return}if(!await rt())return;let S=await pt(d);if(je(d))return;let k=h.files[d]??null;if(!k&&Na(d)){Pa();return}let D=Nt(d);if(D){S&&S.hash===D.remoteHash&&We(Oe(d))?await Qe(d,null):S&&S.hash===D.remoteHash?(await nt(d,D.remoteSeq,S.hash,S),_e(d)):S&&S.hash!==D.localHash&&gt(d,S,{seq:D.remoteSeq,hash:D.remoteHash});return}let F=Ao(S?.hash??null,k,k?{seq:k.seq,hash:k.hash}:null);switch(F.kind){case"push":We(Oe(d))?await Yr(d,F.baseSeq):await Jr(d,F.baseSeq);break;case"pushCreate":We(Oe(d))?await Yr(d,0):await Jr(d,0);break;case"pushDelete":if(w){to();break}if(!ie&&(re.has(d)||H())){re.set(d,"remote"),N(),Z();break}we.push(Date.now()),await za(d);break;case"dropShadow":ht(d);break;default:S&&k&&S.hash===k.hash&&S.mtimeMs>=0&&(k.size!==S.size||k.mtimeMs!==S.mtimeMs)&&await nt(d,k.seq,k.hash,S,S.buf);break}},xf=async(d,w)=>{if(!v||!h)return;let S=await v.tree(h.vaultId);if(!h)return;let k=new Map(S.entries.map(D=>[D.path,D]));for(let D of d){if(!f||!h||!Nt(D)||je(D)||Pe?.path===D)continue;if(!Et(D)){_e(D);continue}let F=await pt(D),J=k.get(D)??null;if(!F||!J){_e(D),F?ne({key:D,run:()=>Te(D)}):await Qe(D,J?.seq??null);continue}if(F.hash===J.hash){await nt(D,J.seq,F.hash,F,We(Oe(D))?F.buf:void 0),_e(D);continue}let P;if(w==="newer"){let j=J.updatedAt?Date.parse(J.updatedAt):NaN;if(!Number.isFinite(j)||F.mtimeMs<0)continue;P=F.mtimeMs>j?"local":"cloud"}else P=w;let Y=Ce,te=()=>f&&Y===Ce&&!je(D)&&Et(D);try{if(P==="both"){if(!await ja(D,te))continue;_e(D),await Qe(D,J.seq);continue}let j=We(Oe(D));if(!j&&qr())continue;P==="local"?await Tf(D,F,J,j):await If(D,F,J,j,te)}catch(j){let K=j?.name==="RecoveryError";if(Xn(j)||(j instanceof Se?j.status===0:!K&&!fs(j)&&zr(j)))throw j;he(D,j instanceof Se?j.body?.code||`http ${j.status}`:j?.name==="TimeoutError"?"timeout":K?"RECOVERY_FAILED":"RESOLVE_FAILED"),Z()}}},Tf=async(d,w,S,k)=>{if(!v||!h)return;let{vaultId:D}=h;if(k){let P=await v.getFile(D,d),Y=Ke(P.content);if(P.seq!==S.seq||P.hash!==null&&P.hash!==Y||S.hash!==null&&Y!==S.hash){gt(d,w,{seq:P.seq,hash:P.hash??Y,updatedAt:P.updatedAt});return}if(await Q.save(P.content,{binding:n.shadowName,path:d,side:"cloud"}),!Et(d)){_e(d);return}try{let te=await v.putFile(D,d,At(w.buf),P.seq,!1,Y);ve("uploads"),A.delete(d),await nt(d,te.seq,te.hash??w.hash,w,w.buf),_e(d)}catch(te){if(!(te instanceof Se)||te.status!==409)throw te;await Ba(d,w)}return}let F=await v.getAsset(D,d),J=Ke(F);if(S.hash!==null&&J!==S.hash){gt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}if(await Q.save(F,{binding:n.shadowName,path:d,side:"cloud"}),!Et(d)){_e(d);return}try{let P=await v.putBinary(D,d,w.buf,{baseSeq:S.seq,expectedHash:J});ve("uploads"),A.delete(d),await nt(d,P.seq,w.hash,w),_e(d)}catch(P){if(!(P instanceof Se)||P.status!==409)throw P;gt(d,w,{seq:Number(P.body?.seq??S.seq),hash:P.body?.hash??null,updatedAt:null})}},If=async(d,w,S,k,D)=>{if(!v||!h)return;let{vaultId:F}=h,J,P,Y;if(k){let j=await v.getFile(F,d);J=j.content,P=j.seq,Y=Ke(j.content)}else if(J=await v.getAsset(F,d),P=S.seq,Y=Ke(J),S.hash!==null&&Y!==S.hash){gt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}await Q.save(w.buf,{binding:n.shadowName,path:d,side:"local"});let te=await ps(Fe(d),J,Ke(w.buf),D);if(!te){if(!Et(d)){_e(d);return}await Ba(d,null);return}ve("downloads"),A.delete(d),await nt(d,P,Y,te,J),_e(d)},Ba=async(d,w)=>{if(!v||!h)return;let S=w??await pt(d);if(!S){_e(d),await Qe(d,null);return}if(!We(Oe(d))){let F=Nt(d);gt(d,S,{seq:F?.remoteSeq??0,hash:null});return}let k;try{k=await v.getFile(h.vaultId,d)}catch(F){if(!(F instanceof Se)||F.status!==404)throw F;_e(d),ne({key:d,run:()=>Te(d)});return}let D=Ke(k.content);if(D===S.hash){await nt(d,k.seq,S.hash,S,k.content),_e(d);return}gt(d,S,{seq:k.seq,hash:D,updatedAt:k.updatedAt})},qa=async()=>{let d=new Map;if(!G||!h)return d;let w=G,S=null,k=async D=>{if(S)return;let F;try{F=await i.readdir(D,{withFileTypes:!0})}catch(J){S=`${D}: ${J?.message??String(J)}`;return}for(let J of F){if(gr(J.name)||J.isDirectory()&&n.ignoreNames?.includes(J.name))continue;let P=l.join(D,J.name);if(J.isDirectory())await k(P);else if(J.isFile()){let Y=l.relative(w,P).split(l.sep).join("/"),te=r(Y);if(!te)continue;try{let j=await i.stat(P);if(!j.isFile())continue;d.set(te,{size:j.size,mtimeMs:Math.floor(j.mtimeMs)})}catch(j){if(j?.code==="ENOENT")continue;S=`${P}: ${j?.message??String(j)}`;return}}}};return await k(w),S?(ae("error",`scan-failed: ${S}`),Zn(),null):d},bs=async()=>{let d=Ce;if(_t()||d!==Ce||!h||!await rt())return;let w=await qa();if(!w||_t()||d!==Ce||!await rt())return;let S=!1;for(let[F,J]of[...re])(J==="remote"&&w.has(F)||J==="local"&&!w.has(F))&&(re.delete(F),S=!0);re.size||W();for(let[F,J]of w){let P=h.files[F];if(P&&P.size===J.size&&P.mtimeMs===J.mtimeMs)continue;let Y=Nt(F);Y&&Y.localSize===J.size&&Y.localMtimeMs===J.mtimeMs||ne({key:F,run:()=>Te(F)})}for(let F of Object.keys(h.files))Et(F)||gs(F);let k=Object.keys(h.files),D=k.filter(F=>!w.has(F));if(D.length&&!ie&&(fe||hr(D.length,k.length,Wc))){be();for(let F of D)re.set(F,"remote");N(),Z();return}S&&(N(),Z());for(let F of D)re.has(F)||ne({key:F,run:()=>Te(F)})},Rf=async d=>{if(!h)return;let w=new Set;for(let[S,k]of Object.entries(h.files)){if(!We(Oe(S))||k.size>Ro)continue;w.add(k.hash);let D=d.get(S);if(!(!D||D.size!==k.size||D.mtimeMs!==k.mtimeMs||await X.has(k.hash)))try{let F=await pt(S);F&&F.hash===k.hash&&await Ma(S,k.hash,F.buf)}catch{}}for(let S of Object.values(h.dormant??{}))w.add(S.hash);await X.prune(w)},on=async()=>{if(Pe){Pe.after.push({run:on});return}let d=Ce;if(_t()||d!==Ce||!v||!h||!G||!await rt())return;let w=await v.tree(h.vaultId);if(w.maxFileBytes!==void 0&&w.maxFileBytes!==U&&(U=w.maxFileBytes,Z()),_t()||d!==Ce)return;let S=new Map;for(let j of w.entries)o(j.path)===null||!s(j.path,j.kind)||S.set(j.path,j);for(let[j,K]of[...ke])K&&!S.has(j)&&Sn(j,null);let k=await qa();if(!k||_t()||d!==Ce||!await rt())return;if(h.mirrorRestore==="list"){for(let K of Object.keys(h.files))!k.has(K)&&!re.has(K)&&delete h.files[K];let j=Object.create(null);for(let[K,{seq:ye,hash:Re}]of S)Object.hasOwn(h.files,K)||(j[K]={seq:ye,hash:Re});h.mirrorRestore=j,M.save(h);try{await M.flush(!0)}catch(K){throw h.mirrorRestore="list",M.save(h),K}}let D=h.mirrorRestore;if($a(),h.dormant){let j=!h.dormantRoot||!x||an(h.dormantRoot,x);for(let[K,ye]of Object.entries(h.dormant))Et(K)&&(j&&k.has(K)&&S.has(K)&&!Object.hasOwn(h.files,K)?(h.files[K]=ye,delete h.dormant[K]):Vr(K));h.dormant&&!Object.keys(h.dormant).length&&(delete h.dormant,delete h.dormantRoot),M.save(h)}ee||(ee=!0,await Rf(k));let F=new Set([...S.keys(),...k.keys(),...Object.keys(h.files),...Object.keys(D??{}),...Object.keys(h.held??{})]),J=Object.keys(h.files).length,P=[];for(let j of F){if(_t()||d!==Ce)return;let K=h.files[j]??null,ye=S.get(j)??null,Re=k.get(j)??null,st=null,Ye=Gr(Re?.size??0);if(Re)if(K&&K.size===Re.size&&K.mtimeMs===Re.mtimeMs)st=K.hash,Ye=Re;else{let it;try{it=await pt(j)}catch(Be){if(!ds(Be))throw Be;Br(j,Be);continue}it&&(st=it.hash,Ye=it)}if(D&&Object.hasOwn(D,j)){let it=D[j];!K&&st!==null&&it.hash===st&&(K=h.files[j]={seq:it.seq,hash:st,size:Ye.size,mtimeMs:Ye.mtimeMs}),(K||!ye)&&delete D[j]}P.push({sp:j,d:Ao(st,K,ye?{seq:ye.seq,hash:ye.hash}:null),rSeq:ye?.seq??null,rHash:ye?.hash??null,rUpdatedAt:ye?.updatedAt??null,localHash:st,localStat:Ye})}if(_t()||d!==Ce)return;let Y=P.filter(j=>j.d.kind==="deleteLocal"||j.d.kind==="pushDelete").length,te=!ie&&(fe||hr(Y,J,Wc));te&&Y&&be(),re.clear();for(let{sp:j,d:K,rSeq:ye,rHash:Re,rUpdatedAt:st,localHash:Ye,localStat:it}of P){if(_t()||d!==Ce)return;if(K.kind!=="hold"&&Nt(j)&&_e(j),te&&(K.kind==="deleteLocal"||K.kind==="pushDelete")){re.set(j,K.kind==="deleteLocal"?"local":"remote");continue}try{if((K.kind==="deleteLocal"||K.kind==="pushDelete")&&((await pt(j))?.hash??null)!==Ye){ne({key:j,run:()=>Te(j)});continue}if(_t()||d!==Ce)return;switch(K.kind){case"adopt":{let Be=We(Oe(j))?await pt(j):null;await nt(j,ye,Ye,it,Be&&Be.hash===Ye?Be.buf:void 0);break}case"pull":await Qe(j,ye);break;case"push":We(Oe(j))?await Yr(j,K.baseSeq):await Jr(j,K.baseSeq);break;case"pushCreate":We(Oe(j))?await Yr(j,0):await Jr(j,0);break;case"pushDelete":await za(j);break;case"deleteLocal":await La(j),ht(j);break;case"conflict":await Qe(j,ye);break;case"hold":gt(j,{hash:Ye,size:it.size,mtimeMs:it.mtimeMs},{seq:ye,hash:Re,updatedAt:st});break;case"dropShadow":ht(j);break;case"none":break}}catch(Be){if(!f||Xn(Be)||zr(Be)&&!ds(Be))throw Be;Br(j,Be)}}ie&&(ie=!1,we.length=0),re.size||W(),N(),te&&Z();for(let j of w.folders)if(!(o(j)===null||!s(j,"folder")))try{await i.mkdir(Fe(j),{recursive:!0})}catch{}h.cursor=w.seq,h.lastSyncAt=Date.now(),D&&!Object.keys(D).length&&delete h.mirrorRestore,M.save(h)},Df=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 on();return}for(let k of w.changes)await Ha(k)},er=null,Wa=[],Ss=()=>{er&&Wa.push(er.close()),er=null},Of=()=>{if(!f||er||!G)return;let d=Ae();if(!d.watch)return;let w=S=>{if(!G)return;let k=l.relative(G,S);if(!k||k.startsWith(".."))return;let D=r(k);D&&tt(D)};er=d.watch(G,{depth:12,ignored:S=>{let k=l.basename(S);return gr(k)||!!n.ignoreNames?.includes(k)}},{change:w,add:w,unlink:()=>to(),unlinkDir:()=>to()})},tr=()=>{T?.stop(),T=null},Mf=()=>{if(!f||!v||!h||T)return;let d=z;d&&(T=Fc({baseUrl:d.cloudUrl,vaultId:h.vaultId,token:d.token,getToken:q,gate:C??void 0},{getSince:()=>h?.cursor??0,onHello:w=>{h&&w>h.cursor&&ne({run:Df})},onChange:w=>{ne({run:()=>Ha(w)})},onReset:()=>{ne({run:on})},onOpen:()=>{(b==="offline"||b==="starting")&&ae("idle",null),ne({run:bs})},onDown:(w,S)=>{let k=di(Rc(w));b==="idle"||b==="syncing"?(ae("offline",void 0,S?null:k),le=!!S):b==="offline"&&le&&!S&&(le=!1,Ge.error(k))},onPresence:w=>t.onPresence?.(h?.vaultId??"",w),onPresenceRoster:w=>t.onPresenceRoster?.(h?.vaultId??"",w)}))},Nf=async()=>{let d=await ct(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 $t({cloudSync:{...d.cloudSync??{},deviceId:w}},a),w},Pf=async d=>{tr(),Ss(),x=null,_.length=0,R.clear(),re.clear(),ie=!1,fe=!1,we.length=0;let w=await ct(a);if(d!==p)return;let S=w.cloudSync;if(S?.enabled===!1){G=null,v=null,ae("disabled",null);return}if(!a||a!==qe()){ae("auth-required","not-logged-in");return}if(G=n.localRoot,n.requireRootExists){let J=await i.stat(G).then(P=>P.isDirectory()).catch(()=>!1);if(d!==p)return;if(!J){ae("error",`vault-missing: ${G}`),Zn();return}}if(d!==p)return;let k=t.loadCreds();if(!k.cloudUrl||!k.token){v=null,ae("auth-required","not-logged-in");return}ae("starting",null);let D=S?.deviceId??await Nf();if(d!==p)return;let F=n.clientIdSuffix?`${D}#${n.clientIdSuffix}`:D;z={cloudUrl:k.cloudUrl,token:k.token},C=Xt(k.cloudUrl),O=new AbortController,$?.(),$=C.subscribe(Z),v=$c({baseUrl:k.cloudUrl,token:k.token,clientId:F,gate:C,signal:O.signal,getToken:()=>{if(d!==p)throw new Se(401,{code:"ACCOUNT_CHANGED"},"sync-session");return q()}});try{let J=n.vaultId==="first"?S?.vaultId:n.vaultId;if(!J){let j=await v.listVaults();if(d!==p)return;if(!j.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");J=j[0].id,await $t({cloudSync:{...S??{},vaultId:J}},a)}if(d!==p)return;let P=await hi(n.shadowName);if(d!==p||(h=P&&P.vaultRoot===G&&P.vaultId===J&&P.folder===""?P:{vaultRoot:G,folder:"",vaultId:J,cursor:0,lastSyncAt:null,files:{}},d!==p))return;for(let[j,K]of Object.entries(h.pending??{}))re.set(j,K);re.size&&(fe=!0);let Y=await Kr(G);if(d!==p)return;let te=()=>_t()||!!Object.keys(h?.pending??{}).length;if(!Y&&!n.requireRootExists){if(h.rootIdentity||Object.keys(h.files).length||h.mirrorMissing||te()){let j=await ys(G);if(d!==p)return;if(!j||te()){Yt("vault-missing");return}if(h.mirrorMissing=!0,M.save(h),await M.flush(!0),d!==p)return;let K=await ys(G);if(d!==p)return;if(!K||te()){Yt("vault-missing");return}}if(await i.mkdir(G,{recursive:!0}),Y=await Kr(G),d!==p)return}if(!Y?.isDirectory()){ws(Y);return}if(typeof Y.dev=="number"&&Number.isInteger(Y.dev)&&Y.dev>=0&&typeof Y.ino=="number"&&Number.isInteger(Y.ino)&&Y.ino>0){let j=c?await c(G):{dev:Y.dev,ino:Y.ino,...Y.birthtimeMs&&Y.birthtimeMs>0?{birthtimeMs:Y.birthtimeMs}:{}};if(d!==p)return;if(!Jt(j))throw Error("Invalid sync root identity; original state retained");let K=h.rootIdentity,ye=K&&!an(K,j);if(!St(j,Y)){Yt("vault-changed");return}let Re=!K&&!e&&Le().isManagedCloudVault(G)&&(Object.keys(h.files).length>0||te());if(ye||h.mirrorMissing||Re){let Ye=(!K||(K.volumeId?K.volumeId===j.volumeId:K.dev===j.dev))&&await ys(G),it=Ye&&(await i.readdir(G,{withFileTypes:!0})).every(Ja=>Ja.isDirectory()&&n.excludePrefixes?.includes(Ja.name+"/")),Be=it&&await Kr(G);if(d!==p)return;if(it){if(!Be||!St(j,Be)||te()){Yt("vault-changed");return}h.files={},h.cursor=0,h.lastSyncAt=null,h.mirrorRestore="list"}else if(ye||h.mirrorMissing&&!K){Yt("vault-changed");return}else if(Re){if(!Ye||te()){Yt("vault-changed");return}h.mirrorRestore="list"}}if(x=j,(h.mirrorMissing||JSON.stringify(K)!==JSON.stringify(j))&&(delete h.mirrorMissing,h.rootIdentity=j,M.save(h),await M.flush(!0)),d!==p||!await rt())return}else{if(h.mirrorMissing){Yt("vault-changed");return}if(!ws(Y))return}if(d!==p)return;g=!0,Of();for(let j of h.moves??[])ne({key:`move:${ot(j)}`,run:()=>Qr(j)});ne({run:on}),ne({run:async()=>{Mf()}})}catch(J){if(d!==p)return;Xn(J)?ae("auth-required","login-expired"):(ae("offline",J?.message||String(J)),Zn())}},Ga=()=>{f=!1,g=!1,tr(),Ss(),_.length=0,R.clear(),Kn();for(let d of[L,V,se,oe])d&&clearTimeout(d);L=V=se=oe=null,Pe?.abort.abort(),Pe=null,O?.abort(new DOMException("sync engine stopped","AbortError")),$?.(),$=null},Va=async()=>{B&&await new Promise(d=>y.add(d)),await Promise.all(Wa.splice(0)),await M.flush(),h=null,x=null,v=null,z=null,C=null,O=null,G=null,I=0,A.clear(),ke.clear(),rn=0,U=null,re.clear(),ie=!1,fe=!1,we.length=0,b="disabled",E=null},$f=()=>{Ya()},eo=null,nr=()=>{ee=!1,eo?.(),eo=Le().onBeforeQuit($f);let d=++p;Ga();let w=m.catch(()=>{}).then(async()=>{await Va(),d===p&&(f=!0,await Pf(d))});return m=w,w},Ya=()=>{eo?.(),eo=null,++p,Ga();let d=m.catch(()=>{}).then(Va);return m=d,d},Ct=()=>{let d=Object.entries(h?.held??{}).map(([w,S])=>({...S,path:w,local:o(w)??w}));return{enabled:b!=="disabled",state:b==="idle"&&(me.size||ke.size)?"syncing":b,lastSyncAt:h?.lastSyncAt??null,pending:_.length+me.size+ke.size,conflicts:I,skipped:[...[...A].map(([w,S])=>({path:w,reason:S})),...d.map(w=>({path:w.path,reason:"HELD"}))],error:E,pendingDeletions:re.size,maxFileBytes:U,held:d,heldCount:d.length,rateLimitedUntil:b!=="disabled"?C?.until()??null:null}};return{getStatus:Ct,start(){nr()},notifyLocal(d,w,S){if(!h||b==="disabled"||b==="auth-required")return;let k=r(d),D=S?r(S):null;if(w==="write"&&k){gr(k.split("/").pop()||"")||tt(k);return}if(w==="remove"){if(!k)return;let F=`${k}/`,J=!1;for(let P of Object.keys(h.files))(P===k||P.startsWith(F))&&(J=!0,ne({key:P,run:()=>Te(P)}));!J&&k&&ne({key:k,run:()=>Te(k)})}},holdLocalMove(d,w){let S=D=>n.serverDir?`${n.serverDir}/${D.replace(/\\/g,"/").normalize("NFC")}`:D.replace(/\\/g,"/").normalize("NFC"),k={from:S(d),to:S(w)};return++Ce,Xr.add(k),()=>{Xr.delete(k)}},async notifyLocalMove(d,w,S,k){let D=r(d),F=r(w),J=h??await hi(n.shadowName),P=fi(d,""),Y=P&&(n.serverDir?`${n.serverDir}/${P}`:P);if(!D&&F&&Y&&J&&Object.keys(J.files).some(te=>te===Y||te.startsWith(`${Y}/`))&&(D=Y),!D&&!F){S?.();return}if(D&&F){let te=h??J;if(!te){S?.();return}let j=k??(Object.keys(te.files).some(ye=>ye.startsWith(`${D}/`))?"folder":"file"),K={from:D,to:F,kind:j};te.moves??=[],te.moves.some(ye=>ot(ye)===ot(K))||(te.moves.push(K),++Ce),S&&Zr.set(ot(K),S),M.save(te);try{await M.flush(!0)}catch(ye){throw te.moves=te.moves.filter(Re=>ot(Re)!==ot(K)),Zr.delete(ot(K)),M.save(te),ye}h===te&&f&&b!=="disabled"&&b!=="auth-required"&&ne({key:`move:${ot(K)}`,run:()=>Qr(K)});return}D&&this.notifyLocal(d,"remove"),F&&(ne({key:F,run:()=>Te(F)}),to()),S?.()},async setEnabled(d){let w=await ct(a);return await $t({cloudSync:{...w.cloudSync??{},enabled:d}},a),await nr(),Ct()},async restart(){return await nr(),Ct()},async syncNow(){if(A.clear(),!g){let d=p;if(await m,d!==p)return Ct()}if(b==="disabled"||b==="auth-required"||b==="error"||b==="offline"||!g||!v)await nr();else{V&&(clearTimeout(V),Wr());for(let d of h?.moves??[])ne({key:`move:${ot(d)}`,run:()=>Qr(d)});ne({run:on})}return Ct()},resolveHeld(d,w){if(!g||!h?.held||!["local","cloud","both","newer"].includes(w))return Ct();let S=[...new Set(d)].filter(k=>typeof k=="string"&&!!Nt(k));return S.length&&ne({run:()=>xf(S,w)}),Ct()},rescope(){f&&ne({key:"\0rescope",run:async()=>$a()})},confirmMassDeletions(){return!g||!re.size||(ie=!0,ne({run:on})),Ct()},stop:Ya};function to(){f&&(se&&clearTimeout(se),se=setTimeout(()=>{se=null,ne({run:bs})},Ng))}}function mi(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 yi(t){return/\.md$/i.test(t)?mi(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function Gc(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 zg=t=>Ae().sha256Hex(t).slice(0,8),Bg=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Do="\u4E0E\u6211\u5171\u4EAB";function Vc(t,e){let n=zg(`${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:`${Do}/${Bg(t.title)}-${n}`,serverDir:r,inScope:(o,s)=>e.some(a=>Gc(a,o,s)),scopeKey:e.map(o=>o.root).join("\0")}}function Yc(t){return Vc(t,[mi(t.path),...(t.items??[]).map(yi)])}function Jc(t){let e=t.map(Yc),n=t.flatMap((o,s)=>{let a=e[s].serverDir?`${e[s].serverDir}/`:"";return(o.items??[]).filter(i=>!i.startsWith(a)).map(i=>Vc({vaultId:o.vaultId,path:i,title:(i.split("/").pop()??i).replace(/\.md$/i,"")},[yi(i)]))}),r=new Map;for(let o of[...e,...n])r.has(o.key)||r.set(o.key,o);return[...r.values()]}var qg=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 Kc(t,e){let n=l=>l.normalize("NFC"),r=n(e.replace(/\\/g,"/")),o=t.find(l=>r.startsWith(`${n(l.localRelDir)}/`));if(!o)return null;let s=r.slice(n(o.localRelDir).length+1),a=qg(o.serverDir?`${o.serverDir}/${s}`:s);if(!a||a===".."||a.startsWith("../"))return null;let i=[o,...t].find(l=>l.vaultId===o.vaultId&&(!l.serverDir||a.startsWith(`${l.serverDir}/`))&&l.inScope(a,Oe(a)));return i?`${i.localRelDir}/${i.serverDir?a.slice(i.serverDir.length+1):a}`:null}function wi(){let t=Le().readCreds(),e=Je(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let f=Le().readCreds();if(n.signal.aborted||!e||Je(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},o=()=>{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 E=null;try{E=await y.json()}catch{}throw Object.assign(new Error(E?.detail||`http ${y.status}`),{status:y.status,code:E?.code})}let b=await y.json();return r(),b},a=null,i=async()=>(r(),a||(a=(await s("GET","/vaults")).vaults[0]?.id??"default",a)),l=()=>{try{let f=(r().token??"").split(".")[1],g=JSON.parse(At(ro(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=Yc(g),m=g.path.split("/").pop()??g.path;return{...g,localPath:`${p.localRelDir}/${m}`}}),u=null;return{stop:()=>n.abort(),call:s,ensureOwnVault:i,myUserId:l,sharedWithMe:c,linkBase:async()=>{if(r(),u)return u;try{u=((await s("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||o()}catch{u=o()}return u},async heartbeat(f,g){let p=(f??"").replace(/\\/g,"/"),m,y=null,b=g.find(E=>p.startsWith(`${E.localRelDir}/`));b?(m=b.vaultId,y=b.serverDir?`${b.serverDir}/${p.slice(b.localRelDir.length+1)}`:p.slice(b.localRelDir.length+1)):(m=await i(),y=p||null),await s("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:y})}}}import{promises as Qc}from"node:fs";import Wg from"node:path";var bi=".forsion-vault.md",Xc=t=>`${t}/${bi}`;function Oo(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 Zc=t=>`---
216
- devices: ${JSON.stringify(t.map(e=>({id:e.id,name:e.name,...e.since?{since:e.since}:{}})))}
217
- ---
218
- `;var ut=t=>t.replace(/\\/g,"/").normalize("NFC");function Si(t){let e=ut(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function Tn(t,e,n){let r=ut(n);if(!r)return!1;if(t.some(o=>ut(o.path)===r))return!0;for(let o of e??[]){let s=ut(o);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(o=>{let s=Si(o);return!!s&&r.startsWith(s)})}function vi(t,e,n){let r=ut(t),o=ut(e);return r===o?ut(n):r.startsWith(`${o}/`)?ut(n)+r.slice(o.length):null}function br(t,e,n){let r=!1,o=t.map(s=>{let a=vi(s,e,n);return a===null?s:(r=!0,a)});return{changed:r,next:o}}async function eu(t){let e=await Qc.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let o of e){if(!o.isDirectory()||o.name.startsWith("."))continue;let s=await Qc.readFile(Wg.join(t,o.name,bi),"utf8").catch(()=>null);if(s===null)continue;n.push(o.name);let a=Oo(s);a?.length&&(r[o.name]=a)}return{names:n.sort(),devices:r}}var $e={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 Mo=t=>Ae().sha256Hex(t).slice(0,8);function tu(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Zt(t,e=[]){let n=[],r=[];for(let o of t){let s=ut(o.path);if(!s)continue;r.push(s);let a=Si(o);a&&n.push(a)}return{entries:t,exclude:e,prefixes:n,paths:r}}function nu(t,e){let n=tu(ut(e));if(!n)return!1;if(Tn(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let o of t.paths)if(o.startsWith(r))return!0;for(let o of t.prefixes)if(o.startsWith(r))return!0;return!1}function Sr(t,e,n){let r=!1,o=t.map(s=>{let a=vi(s.path,e,n);return a===null?s:(r=!0,{...s,path:a})});return{changed:r,next:o}}function ru(t,e,n,r){if(e==="delete"||e==="delete-folder"){let o=ut(n),s=t.filter(a=>{let i=ut(a.path);return!(i===o||e==="delete-folder"&&i.startsWith(`${o}/`))});return{changed:s.length!==t.length,next:s}}return r?Sr(t,n,r):{changed:!1,next:t}}function ki(t,e){let n=Kt(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Do?`\u300C${Do}\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 Gg,promises as ou}from"node:fs";async function su(t,e){try{await ou.copyFile(un(t),un(e),Gg.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await ou.unlink(un(t)).catch(()=>{}),!0}var Vg=/^\d{4}-\d{2}-\d{2}$/,iu=["vault","content"],au=new Set(Tc),Yg=40,In=t=>new Date(t).toISOString().slice(0,10),Rn=t=>typeof t=="string"&&Vg.test(t),lu=!1,mt=Object.create(null),Dn=!1,Ei=()=>Date.now(),vr=new Set,No="";function dt(t,e,n=1,r){try{if(!lu||!au.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let o=In(Ei());if(r!==void 0){o!==No&&(vr.clear(),No=o);let i=`${t}\0${e}\0${r}`;if(vr.has(i))return;vr.add(i)}let s=mt[o]??={},a=s[t]??={};a[e]=(a[e]??0)+Math.round(n),Dn=!0}catch{}}function _i(t){lu=t}function cu(t){if(mt=Object.create(null),vr.clear(),No="",Dn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!Rn(e)||!n||typeof n!="object"))for(let r of iu){let o=n[r];if(!o||typeof o!="object")continue;let s={};for(let[a,i]of Object.entries(o))au.has(a)&&typeof i=="number"&&Number.isFinite(i)&&i>0&&(s[a]=Math.round(i));Object.keys(s).length&&((mt[e]??={})[r]=s)}}}function uu(){let t=In(Ei()-Yg*864e5),e={};for(let n of Object.keys(mt).sort()){if(n<t){delete mt[n];continue}e[n]=JSON.parse(JSON.stringify(mt[n]))}return e}var du=()=>Dn,fu=()=>{Dn=!1};function pu(t,e){let n=[];for(let r of Object.keys(mt).sort())if(!(r<=t||r>e))for(let o of iu){let s=mt[r][o];s&&Object.keys(s).length&&n.push({day:r,system:o,counts:{...s}})}return n}function Ci(t){for(let e of Object.keys(mt))e<=t&&(delete mt[e],Dn=!0)}function hu(){Object.keys(mt).length&&(Dn=!0),mt=Object.create(null),vr.clear(),No=""}function gu(t){Ei=t}var mu=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],Ai=t=>mu.every(e=>typeof t[e]=="function"),Xg=()=>({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 xi(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle($e.get,()=>e?e.get():Xg()),t.handle($e.setEnabled,(r,o)=>n().setEnabled(o)),t.handle($e.syncNow,()=>n().syncNow()),t.handle($e.confirmDeletions,()=>n().confirmDeletions()),t.handle($e.resolveHeld,(r,o)=>n().resolveHeld(o)),t.handle($e.entryGet,()=>n().entryGet()),t.handle($e.otherSideDbs,()=>n().otherSideDbs()),t.handle($e.entryEnable,(r,o)=>n().entryEnable(o)),t.handle($e.entryDisable,(r,o)=>n().entryDisable(o)),t.handle($e.entryMark,(r,o,s)=>n().entryMark(o,s)),t.handle($e.entryClosure,(r,o,s)=>n().entryClosure(o,s)),t.handle($e.collabCall,(r,o,s)=>n().collabCall(o,s)),t.handle($e.switchSide,(r,o)=>n().switchSide(r.sender.id,o)),t.setAmadeusSyncFactory(r=>{Sc(r),kc(Zg(t));let o=yu(r);return e=o.handlers,o.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function Zg(t){let e=t.contentSync?.merge;return e?(n,r,o,s)=>{if(!/\.db$/i.test(n)||/^(agents|human)(\/|$)/.test(n))return null;let a;try{a=e(n,r,o,s)}catch{return null}return a&&!a.conflict&&!Ti(o,r,a.content)?null:a}:null}function Ti(t,e,n){let r,o,s;try{[r,o,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,i=(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(o)){let u=a(o[c]),f=a(r?.[c]);if(!u||!f||l(i(f,u),i(u,f)))continue;let g=a(s?.[c]);if(!g||!l(i(u,g),i(g,u)))return!1}return!0}function yu(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,o=!1,s=wi(),a=new Map,i=()=>{let N=Date.now();for(let[W,H]of a)N-H.at>7e4&&a.delete(W);e($e.presence,[...a.values()])},c={loadCreds:()=>t.readCreds(),onHealth:(N,W,H)=>dt("vault",N,W,H),onStatus:N=>e($e.status,{...N,pendingDeletions:ie(),side:b()?"cloud":"local"}),onPresence:(N,W)=>{let H=W;H?.userId&&(a.set(H.userId,{userId:H.userId,username:String(H.username??"user"),page:H.page??null,at:Number(H.at)||Date.now()}),i())},onPresenceRoster:(N,W)=>{if(Array.isArray(W)){for(let H of W){let _=H;_?.userId&&a.set(_.userId,{userId:_.userId,username:String(_.username??"user"),page:_.page??null,at:Number(_.at)||Date.now()})}i()}}},u=()=>{let N=r;return{...c,onStatus:W=>{N===r&&c.onStatus(W)},onPresence:(W,H)=>{N===r&&c.onPresence(W,H)},onPresenceRoster:(W,H)=>{N===r&&c.onPresenceRoster(W,H)}}},f=wr(u()),g=new Map,p=[],m=0,y=async()=>{if(!o||!qe())return;let N=r,W=++m,H=s,_;try{_=await H.sharedWithMe()}catch{return}if(N!==r||!o||W!==m)return;let R=Jc(_);p=R;let B=new Map(R.map(L=>[L.key,L.scopeKey]));for(let[L,V]of g)if(B.get(L)!==V.plan.scopeKey){if(await V.engine.stop(),N!==r)return;g.delete(L)}for(let L of R){if(g.has(L.key))continue;let V=u(),se=wr({...V,onStatus:oe=>V.onStatus({...oe,shareKey:L.key})},{localRoot:dn.join(Ft(),...L.localRelDir.split("/")),shadowName:`amadeus-sync-${Cn()}-share-${L.key}`,vaultId:L.vaultId,serverDir:L.serverDir,inScope:L.inScope});g.set(L.key,{engine:se,plan:L}),se.start()}},b=()=>n()===Ft(),E=(N,W=N.base)=>{N.base=W;let H=[W,...N.pendingMoves];N.scope.current=Zt(H.flatMap(_=>_.entries),H.flatMap(_=>_.exclude)),N.engine.rescope()},h=new Map,x=new Set,v=new Set,T=null,z=()=>T??=new Promise(N=>{let W=()=>Kg.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return N(W());Jg("scutil",["--get","ComputerName"],{timeout:1500},(H,_)=>N(!H&&String(_).trim()||W()))}),C=async()=>{let N=(await ct()).cloudSync?.deviceId;return N?{id:N,name:await z()}:null},O=new Map,$=(N,W,H)=>{let _=r,R=(O.get(N)??Promise.resolve()).catch(()=>{}).then(async()=>{_!==r||H&&!await H()||_!==r||await q(N,W,_)});return O.set(N,R),R.finally(()=>{O.get(N)===R&&O.delete(N)}).catch(()=>{}),R},q=async(N,W,H)=>{let _=s,R=encodeURIComponent(await _.ensureOwnVault()),B=Xc(N);for(let L=0;L<3;L++){let V=null;try{V=await _.call("GET",`/vaults/${R}/file?path=${encodeURIComponent(B)}`)}catch(oe){if(oe?.status!==404)throw oe}let se=W(!!V,V?Oo(V.content):null);if(se===void 0||H!==r)return;try{if(se===null){V&&await _.call("DELETE",`/vaults/${R}/file?path=${encodeURIComponent(B)}&baseSeq=${V.seq}`);return}await _.call("PUT",`/vaults/${R}/file`,{path:B,content:Zc(se),baseSeq:V?.seq??0});return}catch(oe){if(oe?.status!==409)throw oe}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},G=async N=>!!(await ct()).entrySync?.some(W=>W.cloudName===N&&W.entries.length>0),I=(N,W)=>$(N,(H,_)=>{let R=_?.find(L=>L.id===W.id);if(R&&R.name===W.name)return;let B=R?.since??new Date().toISOString().slice(0,10);return[...(_??[]).filter(L=>L.id!==W.id),{...W,since:B}]},()=>G(N)),A=(N,W)=>$(N,(H,_)=>{if(!H||!_?.some(B=>B.id===W))return;let R=_.filter(B=>B.id!==W);return R.length?R:null},async()=>!await G(N)),U=()=>{e($e.entryChange)},M=async(N,W)=>{let H=h.get(N);if(!H)return;let _=L=>L&&L.startsWith(`${H.cloudName}/`)?L.slice(H.cloudName.length+1):null,R=_(W.path);if(!R)return;let B=!1;await An(L=>{if(h.get(N)!==H)return!1;let V=(L.entrySync??[]).find(le=>le.vaultRoot===N);if(!V)return!1;let se=W.op,oe=_(W.newPath),Z=ru(V.entries,se,R,oe),ae=oe?br(V.exclude??[],R,oe):{changed:!1,next:V.exclude??[]};if(!Z.changed&&!ae.changed)return!1;B=!0,V.entries=Z.next,ae.changed&&(V.exclude=ae.next),E(H,Zt(V.entries,V.exclude??[]))}),B&&h.get(N)===H&&U()},X=N=>{let W=r;return{...u(),onStatus:H=>{W===r&&e($e.status,{...H,pendingDeletions:ie(),side:"local",binding:N})},onRemoteApplied:async H=>{W===r&&await M(N,H)}}},Q=async()=>{let N=qe();if(!o||!N)return;let W=r,H=s,_=Cn(N);await t.adoptLegacyCloudState(N,su);let R=await ct(N),B=R.entrySync??[];if(W!==r||!o||N!==qe())return;let L=new Map(B.map(V=>[V.vaultRoot,V]));for(let[V,se]of h){let oe=L.get(V);if(!(oe&&oe.cloudName===se.cloudName)&&(await se.engine.stop(),W!==r||(h.delete(V),oe&&await Hc(`amadeus-sync-${_}-entry-${Mo(V)}`),W!==r)))return}for(let V of B){let se=h.get(V.vaultRoot);if(se){E(se,Zt(V.entries,V.exclude??[]));continue}let oe={current:Zt(V.entries,V.exclude??[])},Z=V.cloudName,ae=wr(X(V.vaultRoot),{accountId:N,localRoot:V.vaultRoot,shadowName:`amadeus-sync-${_}-entry-${Mo(V.vaultRoot)}`,vaultId:"first",serverDir:Z,clientIdSuffix:`entry-${Mo(V.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:le=>le===Z?!0:le.startsWith(`${Z}/`)?nu(oe.current,le.slice(Z.length+1)):!1});h.set(V.vaultRoot,{engine:ae,scope:oe,cloudName:Z,base:oe.current,pendingMoves:new Set}),ae.start()}if(R.cloudSync?.enabled!==!1)for(let V of B){let se=V.entries.length>0,oe=se?x:v;oe.has(V.cloudName)||((se?v:x).delete(V.cloudName),(async()=>{try{let Z=await C();if(!Z||W!==r||(await(se?I(V.cloudName,Z):A(V.cloudName,Z.id)),W!==r))return;oe.add(V.cloudName),(se?v:x).delete(V.cloudName)}catch{}})())}},ee=async(N,W,H,_,R)=>{let B=W.replace(/\\/g,"/").normalize("NFC"),L=H.replace(/\\/g,"/").normalize("NFC"),V=!1,se,oe,Z,ae=R??"file";try{await An(async le=>{if(h.get(N)!==_)return!1;let pe=(le.entrySync??[]).find(wt=>wt.vaultRoot===N);if(!pe)return!1;let he=Sr(pe.entries,B,L),ne=br(pe.exclude??[],B,L),me=Tn(pe.entries,pe.exclude,B);!R&&await On.stat(dn.join(N,...L.split("/"))).then(wt=>wt.isDirectory(),()=>!1)&&(ae="folder");let tt=ae==="folder"?"folder":/\.md$/i.test(L)?"page":"asset";me&&!Tn(he.next,ne.next,L)&&(he.next.push({path:L,kind:tt}),he.changed=!0),V=he.changed||ne.changed;let Kn=pe.entries.filter(wt=>Sr([wt],B,L).changed);return me&&!Kn.some(wt=>wt.path===B)&&Kn.push({path:B,kind:tt}),se=Zt(Kn,(pe.exclude??[]).filter(wt=>br([wt],B,L).changed)),oe=_.base,_.pendingMoves.add(se),pe.entries=he.next,pe.exclude=ne.next,Z=Zt(pe.entries,pe.exclude),E(_,Z),V})}catch(le){throw se&&_.pendingMoves.delete(se),E(_,_.base===Z&&oe?oe:_.base),le}try{se&&await _.engine.notifyLocalMove(B,L,()=>{_.pendingMoves.delete(se),E(_)},ae)}catch(le){throw se&&_.pendingMoves.delete(se),await An(pe=>{let he=pe.entrySync?.find(ne=>ne.vaultRoot===N);if(!he)return!1;he.entries=Sr(he.entries,L,B).next,he.exclude=br(he.exclude??[],L,B).next,E(_,Zt(he.entries,he.exclude))}),le}V&&h.get(N)===_&&U()},re=N=>{let W=N.replace(/\\/g,"/");for(let{engine:H,plan:_}of g.values())if(W.startsWith(`${_.localRelDir}/`))return{engine:H,rel:W.slice(_.localRelDir.length+1)};return{engine:f,rel:W}};t.setMutationHooks((N,W)=>{if(b()){let H=re(N);H.engine.notifyLocal(H.rel,W);return}h.get(n()??"")?.engine.notifyLocal(N,W)},(N,W,H)=>{if(b()){let B=re(N),L=re(W);if(B.engine===L.engine)return B.engine.notifyLocalMove(B.rel,L.rel,void 0,H);B.engine.notifyLocal(B.rel,"remove"),L.engine.notifyLocal(L.rel,"write");return}let _=n()??"",R=h.get(_);if(R)return ee(_,N,W,R,H)},(N,W)=>{if(b()){let H=re(N),_=re(W),R=[H.engine.holdLocalMove(H.rel,_.rel)];return H.engine!==_.engine&&R.push(_.engine.holdLocalMove(H.rel,_.rel)),()=>{for(let B of R)B()}}return h.get(n()??"")?.engine.holdLocalMove(N,W)});let ie=()=>{let N=f.getStatus().pendingDeletions;for(let{engine:W}of g.values())N+=W.getStatus().pendingDeletions;for(let{engine:W}of h.values())N+=W.getStatus().pendingDeletions;return N},fe=N=>({...N,pendingDeletions:ie(),side:b()?"cloud":"local"}),we=()=>{if(!o)return Promise.resolve(f.getStatus());y();for(let{engine:N}of g.values())N.syncNow();for(let{engine:N}of h.values())N.syncNow();return f.syncNow()},ve=async()=>{let N=++r;o=!1,s.stop();let W=[f.stop(),...[...g.values()].map(({engine:_})=>_.stop()),...[...h.values()].map(({engine:_})=>_.stop())];if(g.clear(),h.clear(),p=[],x.clear(),v.clear(),a.clear(),i(),await Promise.all(W),await t.awaitPendingVaultWrites(),N!==r)return;let H=n();if(H&&_o(H)){let _=await ct();if(N!==r)return;let R=_.localVault&&!_o(_.localVault)?_.localVault:dn.join(t.workspaceDir(),"Amadeus");if(await On.mkdir(R,{recursive:!0}),N!==r||(await $t({lastVault:R,localVault:R,lastPage:void 0}),N!==r))return;await t.activateRoot(R,!1)}N===r&&U()};return{handlers:{get:()=>fe(f.getStatus()),setEnabled:async N=>{if(!o)throw new Error("Cloud account is changing");let W=r;return await f.setEnabled(N),W!==r?f.getStatus():(await Promise.all([...g.values(),...h.values()].map(({engine:H})=>H.restart())),fe(f.getStatus()))},syncNow:()=>we(),resolveHeld:N=>{let W=Array.isArray(N?.paths)?N.paths.filter(L=>typeof L=="string"):[],H=typeof N?.binding=="string"?N.binding:null,_=!H&&typeof N?.shareKey=="string"?N.shareKey:null,R=H?h.get(H)?.engine:_?g.get(_)?.engine:f;if(!R)return{error:"binding-not-found"};let B=R.resolveHeld(W,N.choice);return H?{...B,binding:H}:_?{...fe(B),shareKey:_}:fe(B)},confirmDeletions:()=>{for(let{engine:N}of g.values())N.confirmMassDeletions();for(let{engine:N}of h.values())N.confirmMassDeletions();return fe(f.confirmMassDeletions())},entryGet:async()=>{let N=await ct(),W=Ft(),H=await eu(W);return{vaults:N.entrySync??[],activeRoot:n(),cloudRoot:W,mirrorVaults:H.names,mirrorVaultDevices:H.devices,deviceId:N.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let N=n();if(!N)return null;let W=Ft(),H=await ct(),_=N===W?H.localVault&&H.localVault!==W?H.localVault:null:W;if(!_)return null;let R=[],B=500,L=async(V,se)=>{if(R.length>=B)return;let oe;try{oe=await On.readdir(V,{withFileTypes:!0})}catch{return}for(let Z of oe){if(R.length>=B)break;if(Z.name.startsWith(".")||Z.isSymbolicLink())continue;let ae=se?`${se}/${Z.name}`:Z.name;if(Z.isDirectory())await L(dn.join(V,Z.name),ae);else if(Z.isFile()&&/\.db$/i.test(Z.name))try{R.push({rel:ae,source:await On.readFile(dn.join(V,Z.name),"utf8")})}catch{}}};return await L(_,""),{root:_,vaultName:_===W?"\u4E91\u7AEF":dn.basename(_),dbs:R}},entryEnable:async N=>{let W=r,H=s;if(!o||!qe())return{error:"Sign in to enable cloud sync"};let _=n();if(!_||b())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let R=await ct(),B=R.entrySync??[],L=B.find(V=>V.vaultRoot===_);if(!L){let V=(N.cloudName??dn.basename(_)).normalize("NFC").trim(),se=ki(V,B.map(oe=>oe.cloudName));if(se)return{error:se};if(!N.merge)try{let oe=await H.ensureOwnVault(),Z=await H.call("GET",`/vaults/${encodeURIComponent(oe)}/tree`);if((Z.folders??[]).some(le=>le===V||le.startsWith(`${V}/`))||(Z.entries??[]).some(le=>le.path===V||le.path.startsWith(`${V}/`)))return{conflict:V}}catch(oe){return{error:oe?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}L={vaultRoot:_,cloudName:V,entries:[]},B.push(L)}return W!==r||!o?{error:"Cloud account changed; retry from the current account"}:(await An(V=>{if(W!==r||!o)return!1;let se=V.entrySync??[],oe=se.find(ne=>ne.vaultRoot===_);if(!oe){let ne=ki(L.cloudName,se.map(me=>me.cloudName));if(ne)throw new Error(ne);oe={vaultRoot:_,cloudName:L.cloudName,entries:[]},se.push(oe)}let Z=ne=>String(ne??"").replace(/\\/g,"/").normalize("NFC"),ae=new Set;for(let ne of N.entries??[]){let me=Z(ne.path);me&&(ae.add(me),!oe.entries.some(tt=>tt.path===me)&&oe.entries.push({path:me,kind:ne.kind==="folder"||ne.kind==="asset"?ne.kind:"page"}))}let le=(N.exclude??[]).map(Z).filter(Boolean),pe=new Set([...ae,...(N.include??[]).map(Z).filter(Boolean)]);oe.exclude=[...new Set([...(oe.exclude??[]).filter(ne=>!pe.has(ne)),...le])];let he=new Set(le);oe.entries=oe.entries.filter(ne=>!he.has(ne.path)),V.entrySync=se,L=oe},R.cloudAccountId),W!==r?{error:"Cloud account changed; retry from the current account"}:(await Q(),h.get(_)?.engine.syncNow(),U(),{ok:!0,cloudName:L.cloudName}))},entryDisable:async N=>{let W=n(),H=!1,_=r;return await An(R=>{if(_!==r||!o)return!1;let B=(R.entrySync??[]).find(se=>se.vaultRoot===W);if(!W||!B)return!1;let L=String(N??"").replace(/\\/g,"/").normalize("NFC"),V=B.entries.length;if(B.entries=B.entries.filter(se=>se.path!==L),Tn(B.entries,B.exclude,L))B.exclude=[...new Set([...B.exclude??[],L])];else if(B.entries.length===V)return!1;H=!0}),!H||_!==r?{ok:!1}:(await Q(),U(),{ok:!0})},entryMark:async(N,W)=>{let H=String(N??"").normalize("NFC");if(!H||H.includes("/")||H.startsWith("."))return{error:"invalid name"};if(!o||!qe())return{error:"Sign in first"};try{await $(H,_=>W?_?void 0:[]:_?null:void 0)}catch(_){return{error:_?.message||String(_)}}return f.syncNow(),{ok:!0}},entryClosure:(N,W)=>t.relatedClosure(String(N??""),W==="folder"?"folder":"page"),collabCall:async(N,W)=>{let H=s,_=async()=>H.ensureOwnVault(),R=L=>String((W??[])[L]??""),B=L=>(W??[])[L]??{};switch(N){case"listVaults":return(await H.call("GET","/vaults")).vaults;case"activeVaultId":return _();case"pageShare":return H.call("GET",`/vaults/${encodeURIComponent(await _())}/page-shares?path=${encodeURIComponent(R(0))}`);case"relatedItems":return H.call("GET",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(R(0))}/related`);case"setShareItem":return H.call("POST",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(R(0))}/items`,{path:R(1),included:(W??[])[2]===!0});case"createPageShare":return H.call("POST",`/vaults/${encodeURIComponent(await _())}/page-shares`,{path:R(0),...B(1)});case"updatePageShare":return H.call("PATCH",`/vaults/${encodeURIComponent(R(2)||await _())}/page-shares/${encodeURIComponent(R(0))}`,B(1));case"revokePageShare":return H.call("DELETE",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(R(0))}`);case"setParticipantRole":return H.call("PATCH",`/vaults/${encodeURIComponent(R(3)||await _())}/page-shares/${encodeURIComponent(R(0))}/members/${encodeURIComponent(R(1))}`,{role:R(2)});case"removeParticipant":return H.call("DELETE",`/vaults/${encodeURIComponent(R(2)||await _())}/page-shares/${encodeURIComponent(R(0))}/members/${encodeURIComponent(R(1))}`);case"sharedWithMe":{let L=await H.sharedWithMe();return y(),L}case"leaveShare":{let L=H.myUserId();if(!L)throw new Error("\u672A\u767B\u5F55");let V=await H.call("DELETE",`/vaults/${encodeURIComponent(R(1)||await _())}/page-shares/${encodeURIComponent(R(0))}/members/${encodeURIComponent(L)}`);return y(),V}case"publishes":return H.call("GET",`/vaults/${encodeURIComponent(await _())}/shares`);case"listAllShares":{let L=(await H.call("GET","/vaults")).vaults||[],V=H.myUserId(),se=[],oe=[];for(let Z of L){try{let ae=await H.call("GET",`/vaults/${encodeURIComponent(Z.id)}/shares`);for(let le of ae.shares||[])se.push({...le,vaultId:Z.id,vaultName:Z.name||""})}catch(ae){t.log(`[connect] listAllShares publishes vault ${Z.id} failed: ${ae?.message}`)}try{let ae=await H.call("GET",`/vaults/${encodeURIComponent(Z.id)}/page-shares?expired=1`),le=ae?.shares||ae?.pageShares||(Array.isArray(ae)?ae:[]);for(let pe of le){let he=pe.created_by??pe.createdBy;(!V||!he||he===V)&&oe.push({...pe,vaultId:Z.id,vaultName:Z.name||""})}}catch(ae){t.log(`[connect] listAllShares pageShares vault ${Z.id} failed: ${ae?.message}`)}}return{publishes:se,pageShares:oe,linkBase:await H.linkBase()}}case"createPublish":{let L=await H.call("POST",`/vaults/${encodeURIComponent(await _())}/shares`,{mode:R(0),path:R(1)});return{...L,url:`${await H.linkBase()}/share/${L.token}`}}case"revokePublish":return H.call("DELETE",`/vaults/${encodeURIComponent(await _())}/shares/${encodeURIComponent(R(0))}`);case"revokePublishIn":return H.call("DELETE",`/vaults/${encodeURIComponent(R(0))}/shares/${encodeURIComponent(R(1))}`);case"revokePageShareIn":return H.call("DELETE",`/vaults/${encodeURIComponent(R(0))}/page-shares/${encodeURIComponent(R(1))}`);case"myUserId":return H.myUserId();case"linkBase":return H.linkBase();case"heartbeat":return H.heartbeat((W??[])[0]??null,p);default:throw new Error(`unknown collab fn: ${N}`)}},switchSide:async(N,W)=>{let H=await ct();if(W==="cloud"){if(!o||!qe())throw new Error("Sign in to open cloud notes");let B=Ft();await On.mkdir(B,{recursive:!0}),H.lastVault&&!_o(H.lastVault)&&await $t({localVault:H.lastVault}),await $t({lastVault:B});let L=await t.activateRoot(B,!1);return t.bindRenderer(N,B),{...L,side:"cloud"}}let _=H.localVault&&await On.stat(H.localVault).then(B=>B.isDirectory()).catch(()=>!1)?H.localVault:null;if(!_){let B=await t.ensureDefaultVault();return t.bindRenderer(N,B.root),{...B,side:"local"}}await $t({lastVault:_});let R=await t.activateRoot(_,!1);return t.bindRenderer(N,_),{...R,side:"local"}}},instance:{start:()=>{o=!0,f.start(),y(),Q()},stopAllSync:ve,restartAllSync:async()=>{let N=ve(),W=r;await N,W===r&&(s=wi(),f=wr(u()),o=!0,await Promise.all([f.restart(),y(),Q()]),W===r&&(U(),e($e.status,fe(f.getStatus()))))},resolveSharedAsset:N=>Kc(p,N)}}}import{hostname as Qg}from"node:os";var em=256*1024;function wu(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>em}var Ii=45e3,tm=3e3,nm=16*1024,rm=6e4,Po=t=>`${t.replace(/\/+$/,"")}/api`,kr=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??rm}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(o,e);function o(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,o()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,o=()=>r.abort();e.signal.addEventListener("abort",o,{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 i=this.deps.getPairing();if(!i){if(i=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(i),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${i.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let c=this.deps.readIdleMs??Ii,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(`${Po(s)}/units/${i.unitId}/channel`,{headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":i.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"))>nm,p=setTimeout(()=>r.abort(),g?0:tm),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",o),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 o=this.deps.readIdleMs??Ii,s=o?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(o/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},o):null;try{let a=await this.hubFetch(`${Po(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Qg(),platform:process.platform}),signal:r.signal});if(!a.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${a.status}`);let i=await a.json();if(!i.unitId||!i.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:i.unitId,secret:i.secret}}finally{s&&clearTimeout(s)}}async consume(e,n){let r=e.getReader(),o=new TextDecoder,s="",a=this.deps.readIdleMs??Ii,i=null,l=()=>{a&&(i&&clearTimeout(i),i=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+o.decode(u,{stream:!0}),n)}}finally{i&&clearTimeout(i)}}parseFrames(e,n){let r=e,o;for(;(o=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 s=r.slice(0,o);if(r=r.slice(o+2),s.includes("event: ready")){let i=s.split(`
221
- `).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(i||"{}").caps;this.hubCaps=new Set(Array.isArray(l)?l.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!s.includes("event: dispatch"))continue;let a=s.split(`
222
- `).find(i=>i.startsWith("data: "))?.slice(6);if(a)try{let i=JSON.parse(a);this.dispatch(i,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 o={ctrl:r,conn:n};this.inflight.set(e.id,o);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===o&&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 o={"x-unit-internal":r.internalSecret};e.ct&&(o["Content-Type"]=e.ct),e.accept&&(o.Accept=e.accept);let s;try{let u=new URL(`${r.url}${e.path}`);Object.assign(o,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:o,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")||"",i={};for(let u of["content-security-policy","x-content-type-options"]){let f=s.headers.get(u);f&&(i[u]=f)}let l=a||"application/octet-stream";s.body&&wu(a,s.headers.get("content-length"),{hasSecHeaders:Object.keys(i).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,s,n,l,i):await this.respond(e.id,s.status,l,Buffer.from(await s.arrayBuffer()),i,n.signal)}async respond(e,n,r,o,s,a){if(a?.aborted)return;let{cloudUrl:i,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(`${Po(i)}/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:o.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,o,s){let{cloudUrl:a,token:i}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let c=s?.["content-security-policy"],u=s?.["x-content-type-options"],f=`${Po(a)}/units/${l.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(o)}`+(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,E=new ReadableStream({async pull(h){++m===2&&b&&clearTimeout(b);let{done:x,value:v}=await p.read();x?h.close():h.enqueue(v)},cancel(h){return p.cancel(h)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:E,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 om(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 Er=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=om(c)}let r=JSON.stringify(n);if(r===this.lastSent)return;let o=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!o||!s.token||!s.cloudUrl)return;let a=this.gen;this.inflight=!0;let i=new AbortController,l=setTimeout(()=>i.abort(),this.d.timeoutMs??1e4);try{let c=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(o.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(c,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":o.secret,"Content-Type":"application/json"},body:r,signal:i.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:${i.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 bu=["setUnitHubFactory"],Ri=t=>bu.every(e=>typeof t[e]=="function");function Su(t){let e=new Er({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),...typeof t.capsFeatures=="function"?{features:()=>t.capsFeatures()}:{},log:r=>t.log(r)}),n=new kr({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 Di(t){let e=async(n,r,o)=>{let{base:s,token:a}=await t.getCloud();if(!a)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let i=await fetch(`${s}/api${r}`,{method:n,headers:{Authorization:`Bearer ${a}`,...o!==void 0?{"Content-Type":"application/json"}:{}},body:o!==void 0?JSON.stringify(o):void 0});return{status:i.status,json:await i.json().catch(()=>null)}}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}};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,o)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:o?.name,icon:o?.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:o,token:s}=await t.getCloud();await t.openExternal(`${o}/api/units/${r}/open${s?`#token=${encodeURIComponent(s)}`:""}`)}),t.setUnitHubFactory(Su),t.log("[forsion-extend] unit hub registered")}import{createHash as Rm}from"node:crypto";import{constants as Gu,mkdirSync as Dm,readFileSync as Om,renameSync as Mm,writeFileSync as Nm}from"node:fs";import{lstat as Ut,open as id,readFile as Pm,readdir as ad,statfs as $m}from"node:fs/promises";import{cpus as Fm,freemem as jm,homedir as Vu,hostname as ld,release as Lm,totalmem as Um}from"node:os";import{basename as cd,join as de}from"node:path";var sm=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,_r=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,o="Z";if(typeof e=="string"){let s=e.match(sm);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="":(o=s[3]||null,e=e.toUpperCase(),!o&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=o)}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 im(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function am(t,e,n){let r=t.split(/\r\n|\n|\r/g),o="",s=(Math.log10(e+1)|0)+1;for(let a=e-1;a<=e+1;a++){let i=r[a-1];i&&(o+=a.toString().padEnd(s," "),o+=": ",o+=i,o+=`
223
- `,a===e&&(o+=" ".repeat(s+n+2),o+=`^
224
- `))}return o}var ce=class extends Error{line;column;codeblock;constructor(e,n){let[r,o]=im(n.toml,n.ptr),s=am(n.toml,r,o);super(`Invalid TOML document: ${e}
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
- ${s}`,n),this.line=r,this.column=o,this.codeblock=s}};var lm=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,cm=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,um=/^[+-]?0[0-9_]/;function $o(t,e){let n=t[e++],r=n,o=n==="'",s=n===t[e]&&n===t[e+1];s&&(t[e+=2]===`
227
- `?e++:t[e]==="\r"&&t[e+1]===`
228
- `&&(e+=2));let a="",i=e,l=0;for(let c=e;c<t.length;c++)if(n=t[c],s&&(n===`
229
- `||n==="\r"&&t[c+1]===`
230
- `))l=l&&3;else{if(n<" "&&n!==" "||n==="\x7F")throw new ce("control characters are not allowed in strings",{toml:t,ptr:c});if((!l||l===3)&&n===r&&(!s||t[c+1]===r&&t[c+2]===r))return s&&(t[c+3]===r&&c++,t[c+3]===r&&c++),[l?a:a+t.slice(i,c),c+(s?3:1)];if(!l)!o&&n==="\\"&&(a+=t.slice(i,i=c),l=1);else if(l===1)if(n==="x"||n==="u"||n==="U"){let u=0,f=n==="x"?2:n==="u"?4:8;for(let g=0;g<f;g++,c++){let p=t.charCodeAt(c+1),m=p>=48&&p<=57?p-48:p>=65&&p<=70?p-65+10:p>=97&&p<=102?p-97+10:-1;if(m<0)throw new ce("invalid non-hex character in unicode escape",{toml:t,ptr:c+1});u=u<<4|m}if(u<0||u>1114111||u>=55296&&u<=57343)throw new ce("invalid unicode escape",{toml:t,ptr:c});a+=String.fromCodePoint(u),i=c+1,l=0}else if(n===" "||n===" ")l=2;else{if(n==="b")a+="\b";else if(n==="t")a+=" ";else if(n==="n")a+=`
231
- `;else if(n==="f")a+="\f";else if(n==="r")a+="\r";else if(n==="e")a+="\x1B";else if(n==='"')a+='"';else if(n==="\\")a+="\\";else throw new ce("unrecognized escape sequence",{toml:t,ptr:c});i=c+1,l=0}else if(n!==" "&&n!==" "){if(l===2)throw new ce("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:i});l=!o&&n==="\\"?1:0,i=c}}throw new ce("unfinished string",{toml:t,ptr:e})}function vu(t,e,n,r){if(t==="true")return!0;if(t==="false")return!1;if(t==="-inf")return-1/0;if(t==="inf"||t==="+inf")return 1/0;if(t==="nan"||t==="+nan"||t==="-nan")return NaN;if(t==="-0")return r?0n:0;let o=lm.test(t);if(o||cm.test(t)){if(um.test(t))throw new ce("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let a=+t;if(isNaN(a))throw new ce("invalid number",{toml:e,ptr:n});if(o){if((o=!Number.isSafeInteger(a))&&!r)throw new ce("integer value cannot be represented losslessly",{toml:e,ptr:n});(o||r===!0)&&(a=BigInt(t))}return a}let s=new _r(t);if(!s.isValid())throw new ce("invalid value",{toml:e,ptr:n});return s}function Fo(t,e=0,n=t.length){let r=t.indexOf(`
232
- `,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function Mn(t,e){for(let n=e;n<t.length;n++){let r=t[n];if(r===`
233
- `)return n;if(r==="\r"&&t[n+1]===`
234
- `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new ce("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function xt(t,e,n,r){let o;for(;;){for(;(o=t[e])===" "||o===" "||!n&&(o===`
235
- `||o==="\r"&&t[e+1]===`
236
- `);)e++;if(r||o!=="#")break;e=Mn(t,e)}return e}function ku(t,e,n,r,o=!1){if(!r)return e=Fo(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let a=t[s];if(a==="#")s=Fo(t,s);else{if(a===n)return s+1;if(a===r||o&&(a===`
237
- `||a==="\r"&&t[s+1]===`
238
- `))return s}}throw new ce("cannot find end of structure",{toml:t,ptr:e})}function dm(t,e,n){let r=t.slice(e,n),o=r.indexOf("#");return o>-1&&(Mn(t,o),r=r.slice(0,o)),[r.trimEnd(),o]}function Cr(t,e,n,r,o){if(r===0)throw new ce("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let s=t[e];if(s==="["||s==="{"){let[l,c]=s==="["?_u(t,e,r,o):Eu(t,e,r,o);if(n){if(c=xt(t,c),t[c]===",")c++;else if(t[c]!==n)throw new ce("expected comma or end of structure",{toml:t,ptr:c})}return[l,c]}if(s==='"'||s==="'"){let[l,c]=$o(t,e);if(n){if(c=xt(t,c),t[c]&&t[c]!==","&&t[c]!==n&&t[c]!==`
239
- `&&t[c]!=="\r")throw new ce("unexpected character encountered",{toml:t,ptr:c});t[c]===","&&c++}return[l,c]}let a=ku(t,e,",",n),i=dm(t,e,a-(t[a-1]===","?1:0));if(!i[0])throw new ce("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&i[1]>-1&&(a=xt(t,e+i[1]),t[a]===","&&a++),[vu(i[0],t,e,o),a]}var fm=/^[a-zA-Z0-9-_]+[ \t]*$/;function jo(t,e,n="="){let r=e-1,o=[],s=t.indexOf(n,e);if(s<0)throw new ce("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let a=t[e=++r];if(a!==" "&&a!==" ")if(a==='"'||a==="'"){if(a===t[e+1]&&a===t[e+2])throw new ce("multiline strings are not allowed in keys",{toml:t,ptr:e});let[i,l]=$o(t,e);r=t.indexOf(".",l);let c=t.slice(l,r<0||r>s?s:r),u=Fo(c);if(u>-1)throw new ce("newlines are not allowed in keys",{toml:t,ptr:e+r+u});if(c.trimStart())throw new ce("found extra tokens after the string part",{toml:t,ptr:l});if(s<l&&(s=t.indexOf(n,l),s<0))throw new ce("incomplete key-value: cannot find end of key",{toml:t,ptr:e});o.push(i)}else{r=t.indexOf(".",e);let i=t.slice(e,r<0||r>s?s:r);if(!fm.test(i))throw new ce("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});o.push(i.trimEnd())}}while(r+1&&r<s);return[o,xt(t,s+1,!0,!0)]}function Eu(t,e,n,r){let o={},s=new Set,a;for(e++;(a=t[e++])!=="}"&&a;){if(a===",")throw new ce("expected value, found comma",{toml:t,ptr:e-1});if(a==="#")e=Mn(t,e);else if(a!==" "&&a!==" "&&a!==`
240
- `&&a!=="\r"){let i,l=o,c=!1,[u,f]=jo(t,e-1);for(let m=0;m<u.length;m++){if(m&&(l=c?l[i]:l[i]={}),i=u[m],(c=Object.hasOwn(l,i))&&(typeof l[i]!="object"||s.has(l[i])))throw new ce("trying to redefine an already defined value",{toml:t,ptr:e});!c&&i==="__proto__"&&Object.defineProperty(l,i,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new ce("trying to redefine an already defined value",{toml:t,ptr:e});let[g,p]=Cr(t,f,"}",n-1,r);s.add(g),l[i]=g,e=p}}if(!a)throw new ce("unfinished table encountered",{toml:t,ptr:e});return[o,e]}function _u(t,e,n,r){let o=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new ce("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=Mn(t,e);else if(s!==" "&&s!==" "&&s!==`
241
- `&&s!=="\r"){let a=Cr(t,e-1,"]",n-1,r);o.push(a[0]),e=a[1]}}if(!s)throw new ce("unfinished array encountered",{toml:t,ptr:e});return[o,e]}function Cu(t,e,n,r){let o=e,s=n,a,i=!1,l;for(let c=0;c<t.length;c++){if(c){if(o=i?o[a]:o[a]={},s=(l=s[a]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=o.length-1;o=o[u],s=s[u].c}}if(a=t[c],(i=Object.hasOwn(o,a))&&s[a]?.t===0&&s[a]?.d)return null;i||(a==="__proto__"&&(Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0})),s[a]={t:c<t.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(l=s[a],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,o[a]=[]),o[a].push(o={}),l.c[l.i++]=l={t:1,d:!1,i:0,c:{}}),l.d))return null;if(l.d=!0,r===1)o=i?o[a]:o[a]={};else if(r===0&&i)return null;return[a,o,l.c]}function Lo(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},o={},s=r,a=o;for(let i=xt(t,0);i<t.length;){if(t[i]==="["){let l=t[++i]==="[",c=jo(t,i+=+l,"]");if(l){if(t[c[1]-1]!=="]")throw new ce("expected end of table declaration",{toml:t,ptr:c[1]-1});c[1]++}let u=Cu(c[0],r,o,l?2:1);if(!u)throw new ce("trying to redefine an already defined table or value",{toml:t,ptr:i});a=u[2],s=u[1],i=c[1]}else{let l=jo(t,i),c=Cu(l[0],s,a,0);if(!c)throw new ce("trying to redefine an already defined table or value",{toml:t,ptr:i});let u=Cr(t,l[1],void 0,e,n);c[1][c[0]]=u[0],i=u[1]}if(i=xt(t,i,!0),t[i]&&t[i]!==`
242
- `&&t[i]!=="\r")throw new ce("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:i});i=xt(t,i)}return r}var Ho=14,pm=1440*6e4,hm=12e4,gm=15e3,Oi=1792*1024,mm=7,jt=t=>t.toISOString().slice(0,10),Tt=t=>Date.parse(jt(t))-(mm-1)*pm,Au=["sessions","activity"],Uo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Mi(t,e,n){let r=t?.day===jt(n)?t:void 0;return Object.fromEntries(Au.map(o=>[o,Uo(r?.[o])??Math.min(Math.max(Uo(e[o])??0,Tt(n)),n.getTime())]))}function Ni(t,e,n,r,o,s){let a=e?.day===jt(r)?e:void 0,i={sent:{...t},file:{day:jt(r)}};for(let l of Au){let c=l in o&&!s.includes(l)&&!(`${l}Error`in o),u=Uo(a?.[l]);c?(i.file[l]=n[l],i.sent[l]=r.getTime()):u!==void 0&&(i.sent[l]=Math.min(Uo(t[l])??u,u))}return i}function xu(t,e=[]){let n={...t},r=rr(JSON.stringify(n));for(let o of["activity","sessions","memory","runs","engine"]){if(r.length<=Oi)break;o in n&&(delete n[o],e.push(o),r=rr(JSON.stringify({...n,truncated:e})))}return r.length>Oi?null:r}async function Pi(t,e,n,r=new Date){let o=AbortSignal.timeout(hm);await t.writeFile(`${e}/${jt(r)}.json`,n,r.getTime(),o);try{let s=jt(new Date(r.getTime()-Ho*24*60*6e4));for(let a of await t.walk(o)){let i=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(a.key);i&&i[1]===e&&i[2]<s&&await t.rm(a.key,o)}}catch{}}var $i={mode:"scheduled",intervalHours:24,requestedAt:0};function Ar(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:$i.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Fi(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(gm)});return e.status===404?{...$i}:e.ok?Ar(await e.json()):null}catch{return null}}var Ru=["merge","cloud","local"],Du={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Qt(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 ym(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 en(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,o=new Set,s=n.rules.map(a=>{let i=Qt(a.source,!0),l=ym(a.target);if(typeof a.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(a.id)||o.has(a.id)||r.has(i))throw Error("Duplicate or invalid sync rule");return o.add(a.id),r.add(i),{id:a.id,source:i,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 Nn(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 Ue={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"},Tu=200,ji=6e4,wm=50;function Li(t,e,n,r){return t.deleted?"forget":t.busy||r?"skip":t.version?e&&e.version===t.version&&Bo(e.file,t.file)?"delete":"download":n?"cancel":"skip"}var Bo=(t,e)=>t===void 0||e===void 0||t===e,bm=(t,e)=>{let n=e.indexOf("/");return t+":"+(n<0?"":e.slice(0,n))};function Ui(t,e,n){if(!t.length)return!1;if(n.latched||t.length>=Tu||n.recent+t.length>wm)return!0;let r=a=>{let i=new Map;for(let l of a){let c=bm(l.ns,l.path);i.set(c,(i.get(c)??0)+1)}return i},o=r(t),s=r(e);for(let[a,i]of o)if(hr(i,s.get(a)??0,Tu))return!0;return!1}var qo=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,Iu=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Hi=(t,e,n)=>{let r=Iu(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(o=>o.id!==n&&Iu(o.name)===r)?"taken":null:null},Ou=["Amadeus","agents","human","Plugins"],fn=1024*1024,zo=50*fn,Sm=[{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}],vm=[{prefix:"",maxBytes:50*fn}];function Wo(t,e,n){let r=Array.isArray(n)&&n.length?n:e==="default"?Sm:vm,o=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"&&o.endsWith(a.toLowerCase()))))return Math.min(s.maxBytes,zo);return zo}var km=6e4,Em=10*6e4,Mu=t=>t<=1?0:Math.min(km*2**(t-2),Em),zi="delete-guard";var Lt=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var xr=/^[a-z0-9][a-z0-9-]{0,63}$/,Go=new Set(["muse"]),Tr=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&xr.test(e[1])?e[1]:null},_m=t=>[...Go].some(e=>Bi(t,`agents/${e}`));function Nu(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"),o=n("name_en");return{...r?{name:r}:{},...o?{nameEn:o}:{}}}var Pn=(t,e)=>Nn(e,t)?.target??"off",Bi=(t,e)=>t===e||t.startsWith(e+"/"),Cm=t=>Lt.some(e=>Bi(t,e.path)),qi=t=>t.some(e=>e.id==="default")?Vo():"default",Pu=(t,e)=>t.enabled?Pn(t.rules,e):"off";function $u(t,e,n){n==="off"&&(t=t.filter(s=>e?!s.source.startsWith(e+"/"):!s.source||Cm(s.source)));let r=t.find(s=>s.source===e),o=t.filter(s=>s!==r);return e&&Pn(o,e)===n?o:r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:e?Vo():qi(t),source:e,target:n}]}function $n(t,e,n,r=!1){if(_m(e))return t;let o=t.rules;if(!t.enabled){let s=o.find(i=>!i.source),a=e?o.filter(i=>i.source&&Bi(i.source,e)):[];o=[{id:s?.id??qi(a),source:"",target:"off"},...a],e!=="agents"&&(o=Wi(o,"agents","off"))}if(!e)for(let s of Lt)o.some(a=>a.source===s.path)||(o=[...o,{id:Vo(),source:s.path,target:Pn(o,s.path)}]);return Fu({...t,rules:$u(o,e,n)},r)}function Fu(t,e=!1){let n=r=>Pn(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 ju(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:qi(t.rules),source:"",target:"default"},...t.rules];for(let n of Lt)n.id!=="agents"&&Pn(e,n.path)==="off"&&(e=$u(e,n.path,"default"));return e=Wi(e,"agents","off"),{...t,enabled:!0,rules:e}}function Wi(t,e,n){let r=t.find(o=>o.source===e);return r?t.map(o=>o===r?{...o,target:n}:o):[...t,{id:Vo(),source:e,target:n}]}function Lu(t,e){let n=t;for(let r of new Set(e))xr.test(r)&&!Go.has(r)&&(n=$n(n,`agents/${r}`,"default"));return n}function Uu(t){let e=Pn(t.rules,"agents")!=="off"||t.rules.some(o=>o.source.startsWith("agents/")&&o.target!=="off"),n=t.rules.some(o=>o.source.startsWith("agents/"));if(!e&&!n)return null;let r=Wi(t.rules.filter(o=>!o.source.startsWith("agents/")),"agents","off");return t.enabled?Fu({...t,rules:r},!0):{...t,rules:r}}var Am=0,Vo=()=>`rule-${Date.now().toString(36)}-${(Am++).toString(36)}`;var Hu=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var xm=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function zu(t,e=[]){let n=t;for(let r of[...e].filter(o=>o&&o.length>=2).sort((o,s)=>s.length-o.length))n=n.split(r).join("[path]");return n.replace(/^(Duplicate folder sync identity|Concurrent (?:folder|file) rename): [\s\S]*$/,"$1: [path]")}var Ir=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||xm.test(e))return;this.count("errors"),/^File exceeds \d+ MB/.test(e)&&this.count("tooLarge");let o=this.errors[this.errors.length-1];if(o&&o.text===e){o.n++,o.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(o=>typeof o=="string"&&o);!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 o={at:r.at,ms:Math.max(0,n-r.at),completed:e,counts:r.counts};this.last=o,this.totals.runs++,e&&this.totals.completedRuns++,!e||Object.keys(r.counts).length?(this.runs.push(o),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]}:{}}))}}},Bu=null;function qu(t){Bu=t}function Wu(){try{return Bu?.()??null}catch{return null}}var Hm=(t,e=[])=>{let n=xu(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},ud=60*6e4,zm=2*6e4,Bm=10*6e4,Yu=ud,qm=4*1024*1024,Wm=256*1024,Ju=["user","teamwork","discussion","delegate"],Gm=/^(?:New remarks in the team chat:|You are activated now \()/,dd={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Vi=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,fd=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,o)=>Vi.test(o)||e&&!/\s/.test(o)?n:`${r}[path]${r}`),pd=t=>fd(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>Vi.test(e)?e:"[path]"),Or=4e3,Jo=(t,e)=>typeof t=="string"&&t?Rt(pd(Dt(t.slice(0,Or))),e):void 0,Vm={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},Ym=64*1024,Gi=500,Jm={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},Km=256*1024,Ku=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],Xm=["description","developer_instructions"],Zm=["memory","harness","project_memory","human","dream","log_appended"],Qm=["homeDir","readCreds","accountId","appVersion"],Yi=t=>Qm.every(e=>typeof t[e]=="function"),Xu=Vu().length>3?Vu():null;function Dt(t){return typeof t=="string"?(Xu?t.split(Xu).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(Dt):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]":Dt(n)])):t}var ey=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ue=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,ty=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function Fn(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,[o,s]]of Object.entries(t).slice(0,100).entries())n[ty(o,r)]=ey.test(o)&&ue(s,80)!==void 0?s:Fn(s,e+1);return n}var ny={"":/^(?: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)$/},Zu={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},ry=/^(?:apps|enabled_skill_ids)$/,Qu=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function oy(t){try{let e=Lo(t),n=[],r=[],o=8192,s=(l,c)=>o<=0?!1:(o-=c.length+1,l.push(c),!0),a=(l,c,u)=>{let f=ny[l].test(c)?c:`[key:${c.length}]`,g=Zu[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===""&&ry.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}]"`}`},i=(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(Zu,l);if(u&&Qu(c))i(l,`[${l}]`,c);else if(u&&Array.isArray(c)&&c.length>0&&c.every(Qu))for(let f of c)i(l,`[[${l}]]`,f);else s(n,a("",l,c));if(o<=0)break}return[...n,...r].join(`
243
- `)}catch{return`[unparsed:${t.length}]`}}var hd=async t=>{try{return(await Ut(t)).isFile()?await Pm(t,"utf8"):null}catch{return null}},Dr=t=>Ut(t).then(e=>e.isDirectory(),()=>!1),jn=async t=>{try{return JSON.parse(await hd(t)??"null")}catch{return null}},It=async(t,e=200)=>{try{return(await ad(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function sy(t,e){if(!(await Ut(t)).isFile())return"";let n=await id(t,"r");try{let{size:r}=await n.stat(),o=Math.max(0,r-e),s=Buffer.alloc(r-o);await n.read(s,0,s.length,o);let a=s.toString("utf8");return o>0?a.slice(a.indexOf(`
244
- `)+1):a}finally{await n.close()}}function iy(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:ue(t.cloud?.defaultModel)??null,models:Fn(t.models),tts:Fn(t.tts),asr:Fn(t.asr),specialAgents:Fn(t.specialAgents),pluginSettings:Fn(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:ue(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(r=>ue(r)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,r])=>({name:ue(n,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(t.channels).map(([n,r])=>({name:ue(n,64)??"[name]",enabled:r?.enabled===!0}))}}var ay=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function ed(t){let e=[];for(let n of await It(t,100)){let r=de(t,n);if(!await Dr(r))continue;let o=await hd(de(r,"config.toml"));e.push({id:n,config:o===null?null:oy(o).slice(0,4096),files:(await It(r,400)).filter(s=>ay.has(s))})}return e}async function td(t){let e=[];for(let n of await It(t,300)){let r=await jn(de(t,n,"manifest.json"));r&&e.push({id:ue(r.id)??n,version:ue(r.version,40)??null,name:ue(r.nameEn)??ue(r.name)??null})}return e}var pn=t=>String(t?.code||t?.message||t).slice(0,120);async function ly(t,e,n,r=Wm){let o=g=>String(g).padStart(2,"0"),s=g=>{let p=new Date(g);return`${p.getFullYear()}${o(p.getMonth()+1)}${o(p.getDate())}${o(p.getHours())}${o(p.getMinutes())}`},a=g=>`${g.slice(0,4)}-${g.slice(4,6)}-${g.slice(6,8)}.log`,i=s(n),l=s(e.getTime()),c=[],u=r,f=!1;try{let g=(await ad(t)).filter(p=>/^\d{4}-\d{2}-\d{2}\.log$/.test(p)&&p>=a(i)&&p<=a(l)).sort().reverse();for(let p of g){if(f)break;let y=(await sy(de(t,p),qm).catch(E=>{if(E?.code==="ENOENT")return"";throw E})).split(`
245
- `).filter(E=>/^\d{12} /.test(E)&&E.slice(0,12)>=i&&E.slice(0,12)<l),b=y.length;for(;b>0&&Buffer.byteLength(y[b-1])+1<=u;)u-=Buffer.byteLength(y[--b])+1;b>0&&(f=!0),b<y.length&&c.push({date:p.slice(0,10),log:y.slice(b).join(`
246
- `)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:pn(g)}}return{activity:c.reverse(),...f?{activityTruncated:!0}:{}}}var Rt=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},nd=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},Ln=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function cy(t,e,n=dd,r=Tt(e)){let o=de(t,"tangu","state.db"),s=await Ut(o).then(i=>i.isFile(),i=>i?.code==="ENOENT"?!1:pn(i));if(s!==!0)return s===!1?{sessions:[]}:{sessions:[],sessionsError:s};let a;try{let{DatabaseSync:i}=await import("node:sqlite");a=new i(o,{readOnly:!0}),a.exec("PRAGMA busy_timeout = 1500");let c="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",u=[Ln(r),Ln(e.getTime()),Tt(e)],f=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
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 (${Ju.map(()=>"?").join(", ")}) AND ${c} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...Ju,...u,n.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
249
- FROM chat_messages m WHERE m.session_id = ? AND ${c} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),p=[],m=0,y=f.length>n.sessions;for(let b of f.slice(0,n.sessions)){let E=g.all(b.id,...u,n.messages+1),h=E.length>n.messages,x=[],v=0;for(let C of E.slice(0,n.messages)){let O=nd(C.tool_calls),$=b.kind==="teamwork"&&C.role==="user"&&Gm.test(String(C.content??"")),q={role:ue(C.role,16)??null,at:Number(C.timestamp)||null,agent:ue(C.agent_slug,64),model:ue(C.model_id,128),error:C.is_error?!0:void 0,text:$?void 0:Rt(C.content,n.textChars),relayChars:$?String(C.content??"").length:void 0,reasoning:Rt(C.reasoning,n.textChars),tools:O.length?O.map(I=>ue(I?.function?.name??I?.name,80)??"?"):void 0,toolArgChars:O.length?O.reduce((I,A)=>I+String(A?.function?.arguments??"").length,0):void 0,toolResultChars:Number(C.tool_result_chars)||void 0,attachments:nd(C.attachments).length||void 0},G=Buffer.byteLength(JSON.stringify(q));if(v+G>n.sessionBytes){h=!0;break}v+=G,x.push(q)}let T={id:ue(b.id,64)??null,kind:ue(b.kind,16)??null,parent:ue(b.parent_session_id,64),app:ue(b.app_id,50)??null,title:Rt(b.title,200)??null,model:ue(b.model_id,128)??null,project:Rt(b.project_name,120),archived:b.archived?!0:void 0,createdAt:ue(b.created_at,40)??null,updatedAt:ue(b.updated_at,40)??null,messages:x.reverse(),...h?{olderMessagesDropped:!0}:{}},z=Buffer.byteLength(JSON.stringify(T));if(m+z>n.totalBytes){y=!0;break}m+=z,p.push(T)}return{sessions:p,...y?{sessionsTruncated:!0}:{}}}catch(i){return{sessions:[],sessionsError:pn(i)}}finally{try{a?.close()}catch{}}}async function uy(t,e,n=Vm){let r=de(t,"tangu","state.db"),o=await Ut(r).then(a=>a.isFile(),a=>a?.code==="ENOENT"?!1:pn(a));if(o!==!0)return o===!1?{runs:[]}:{runs:[],runsError:o};let s;try{let{DatabaseSync:a}=await import("node:sqlite");s=new a(r,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let l=s.prepare(`SELECT r.id, r.session_id, r.app_id, r.status, r.current_step, r.model_id, substr(r.error, 1, ${Or}) AS error, r.tokens_total, r.created_at, r.updated_at, s.kind
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(Ln(Tt(e)),Ln(e.getTime()),n.runs+1),c=s.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,
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, ${Or}) AS error
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=y=>typeof y=="number"&&Number.isFinite(y)&&y>0?y:0,f=y=>y||void 0,g=[],p=0,m=l.length>n.runs;for(let y of l.slice(0,n.runs)){let b={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},E=new Map,h=[],x=0,v=c.all(y.id,n.events+1),T=v.length>n.events;for(let O of v.slice(0,n.events))if(O.type==="usage")b.llmCalls++,b.prompt+=u(O.prompt),b.completion+=u(O.completion),b.cached+=u(O.cached),b.reasoning+=u(O.reasoning),b.llmMs+=u(O.llm_ms),b.ttftMaxMs=Math.max(b.ttftMaxMs,u(O.ttft_ms)),b.requestMaxBytes=Math.max(b.requestMaxBytes,u(O.request_bytes));else if(O.type==="tool_result"){let $=ue(O.name,80)??"?",q=E.get($)??(E.size<n.tools?{name:$,n:0,ms:0,maxMs:0}:void 0);if(!q){T=!0;continue}E.set($,q),q.n++,O.failed&&(q.errors=(q.errors??0)+1),q.ms+=u(O.ms),q.maxMs=Math.max(q.maxMs,u(O.ms))}else if(O.type==="error"){let $=Jo(O.error,n.errorChars);$&&!h.includes($)&&h.length<3&&h.push($)}else O.phase==="llm_retry"&&x++;let z={id:ue(y.id,64)??null,session:ue(y.session_id,64)??null,kind:ue(y.kind,16),app:ue(y.app_id,50),model:ue(y.model_id,128),status:ue(y.status,16)??null,error:Jo(y.error,n.errorChars),createdAt:ue(y.created_at,40)??null,updatedAt:ue(y.updated_at,40)??null,steps:f(u(y.current_step)),tokens:f(u(y.tokens_total)),retries:f(x),...Object.fromEntries(Object.entries(b).map(([O,$])=>[O,f($)])),errors:h.length?h:void 0,tools:E.size?[...E.values()]:void 0,partial:T||void 0},C=Buffer.byteLength(JSON.stringify(z));if(p+C>n.totalBytes){m=!0;break}p+=C,g.push(z)}return{runs:g,...m?{runsTruncated:!0}:{}}}catch(a){return{runs:[],runsError:pn(a)}}finally{try{s?.close()}catch{}}}async function dy(t){let e=o=>Math.round(o/1048576),n=o=>Ut(o).then(s=>s.isFile()?s.size:0,()=>0),r=de(t,"tangu","state.db");return{cpus:Fm().length,memTotalMB:e(Um()),memFreeMB:e(jm()),diskFreeMB:await $m(t).then(o=>e(o.bavail*o.bsize),()=>null),stateDbMB:e(await n(r)+await n(`${r}-wal`)),uptimeMin:Math.round(process.uptime()/60)}}var rd=t=>typeof t.diagnosticLogs=="function";function fy(t,e=Ym){let n=t?.engine;if(!n||typeof n!="object")return null;let r=(Array.isArray(n.lines)?n.lines:[]).filter(l=>typeof l=="string"&&!!l),o=r.map(l=>Jo(l,Gi)??""),s=o.some((l,c)=>l.length>Gi||r[c].length>Or),a=o.length,i=e;for(;a>0&&Buffer.byteLength(o[a-1])+1<=i;)i-=Buffer.byteLength(o[--a])+1;return a>0&&(s=!0),{state:ue(n.state,32)??null,lastError:Jo(n.lastError,Gi)??null,log:o.slice(a).join(`
256
- `),...s?{logTruncated:!0}:{}}}var Ji={errors:20,errorChars:300,agents:100},py=t=>pd(fd(t,!1).replace(/[^\s"'`<>()[\]{},;]*\/[^\s"'`<>()[\]{},;]*/g,e=>Vi.test(e)?e:"[path]")),hy=(t,e=[],n=Ji.errorChars)=>Rt(py(zu(Dt(t),e.map(r=>Dt(r)))),n)??"",Xe=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?Math.round(t):0,Yo=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?new Date(t).toISOString():null,gd=t=>{let e=t&&typeof t=="object"?t:{};return Object.fromEntries(Hu.flatMap(n=>Xe(e[n])?[[n,Xe(e[n])]]:[]))},od=t=>{let e=t;return e&&typeof e=="object"?{at:Yo(e.at),ms:Xe(e.ms),completed:e.completed===!0,...gd(e.counts)}:null},gy=Object.fromEntries(Lt.map(t=>[t.path,t.id])),my=new Set(["idle","scanning","syncing","paused"]),yy=new Set(["queued","active","done","failed","paused","conflict"]);function wy(t,e){let n=(Array.isArray(t)?t:[]).filter(i=>!!i&&typeof i.source=="string"&&typeof i.target=="string"),r=i=>i===void 0?null:i==="default"?"shared":i==="off"?"off":e&&i===`device-${e}`?"device":/^device-/.test(i)?"other-device":"unknown",o={other:r(n.find(i=>i.source==="")?.target)};for(let i of Lt)o[i.id]=r(Nn(i.path,n)?.target);let s={},a={};for(let i of n){if(i.source===""||gy[i.source])continue;let l=Tr(i.source);if(l&&Object.keys(s).length<Ji.agents)s[l]=r(i.target);else if(!l){let c=r(i.target)??"unknown";a[c]=(a[c]??0)+1}}return{...o,agentRules:s,folderRules:a,count:n.length}}function by(t){let e=t;if(!e||typeof e!="object")return null;let n=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,o=r?.jobs&&typeof r.jobs=="object"?Object.fromEntries(Object.entries(r.jobs).filter(([a,i])=>yy.has(a)&&Xe(i)).map(([a,i])=>[a,Xe(i)])):{},s=e.totals??{};return{deviceId:n,session:e.session===!0,enabled:e.enabled===!0,paused:e.paused===!0,running:e.running===!0,phase:typeof e.phase=="string"&&my.has(e.phase)?e.phase:null,revision:Xe(e.revision),rules:wy(e.rules,n),backlog:r?{jobs:o,blocked:Xe(r.blocked),pendingUploads:Xe(r.pendingUploads),unconfirmed:Xe(r.unconfirmed),trash:Xe(r.trash),awaitingBytes:Xe(r.awaitingBytes),dirty:Xe(r.dirty)}:null,archive:e.archive==="running"||e.archive==="done"?e.archive:null,since:Yo(e.since),lastRun:od(e.lastRun),runs:(Array.isArray(e.runs)?e.runs:[]).slice(-20).map(od).filter(Boolean),totals:{runs:Xe(s.runs),completedRuns:Xe(s.completedRuns),idleRuns:Xe(s.idleRuns),...gd(s)},errors:(Array.isArray(e.errors)?e.errors:[]).slice(-Ji.errors).flatMap(a=>{if(!a||typeof a!="object"||typeof a.text!="string"||!a.text)return[];let i=Array.isArray(a.paths)?a.paths.filter(l=>typeof l=="string"):[];return[{first:Yo(a.first),at:Yo(a.at),n:Xe(a.n)||1,kind:xo(a.text)??"other",text:hy(a.text,i)}]})}}function Sy(t){let e=t?.engine?.lines;if(!Array.isArray(e))return null;let n={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;n.lines++;let o=/已从云端拉取(覆盖|新文件)/.exec(r);if(o){o[1]==="\u8986\u76D6"?n.overwrites++:n.pulledNew++,r.includes("\u672C\u5730\u7248\u672C\u5DF2\u5B58\u4E3A")&&n.conflictCopies++;continue}n.errorRounds++,n.tooLarge+=r.match(/exceeds sync limit/g)?.length??0}return n}function vy(t,e=Xm){let n;try{n=Lo(t)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof n[r]=="string"&&n[r]?[[r,n[r]]]:[]))}async function md(t,e=Km){try{if(!(await Ut(t)).isFile())return null;let n=await id(t,Gu.O_RDONLY|(Gu.O_NOFOLLOW??0));try{let r=await n.stat();if(!r.isFile())return null;let o=Buffer.alloc(Math.min(e,r.size)),{bytesRead:s}=await n.read(o,0,o.length,0);return o.subarray(0,s).toString("utf8")}finally{await n.close()}}catch{return null}}var Rr=async(t,e)=>{let n=await md(t);return n?Rt(Dt(n),e):void 0};async function ky(t,e){let n=await md(de(t,"config.toml")),r=Object.entries(n?vy(n):{}).map(([o,s])=>[o,Rt(Dt(s),e)??""]);return r.length?Object.fromEntries(r):void 0}async function sd(t){let e=await jn(de(t,".memory-state.json"));if(!e||typeof e!="object")return;let n=r=>Array.isArray(r)?r.length:0;return{entries:n(e.entries),tombstones:n(e.tombstones),revisions:n(e.revisions),processedCandidates:n(e.processedCandidateIds),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:null,projectionPending:e.projectionPending===!0?!0:void 0}}async function Ey(t,e,n=Jm){let r=de(t,"tangu"),o=p=>Ut(p).then(m=>m.isFile()?m.mtimeMs:0,()=>0),s=jt(new Date(Tt(e))),a={agents:[],teams:[],projects:[],activity:[]},i=n.totalBytes,l=(p,m)=>{let y=Buffer.byteLength(JSON.stringify(m))+1;return y>i?(a.truncated=!0,!1):(i-=y,p.push(m),!0)},c=await Rr(de(r,"USER.md"),n.fileChars);c&&l([],c)&&(a.user=c);let u=de(r,"state.db"),f=await Ut(u).then(p=>p.isFile(),p=>p?.code==="ENOENT"?!1:pn(p));if(typeof f=="string")a.activityError=f;else if(f){let p;try{let{DatabaseSync:m}=await import("node:sqlite");p=new m(u,{readOnly:!0}),p.exec("PRAGMA busy_timeout = 1500");let b=p.prepare(`SELECT agent, action, substr(detail, 1, ${Or}) AS detail, session_ref, created_at FROM special_agent_log
257
- WHERE created_at >= ? AND created_at < ? AND (${Zm.map(E=>`action GLOB '${E}*'`).join(" OR ")})
258
- ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(Ln(Tt(e)),Ln(e.getTime()),n.activity+1);b.length>n.activity&&(a.truncated=!0);for(let E of b.slice(0,n.activity))if(!l(a.activity,{at:ue(E.created_at,40)??null,agent:ue(E.agent,64)??null,action:ue(E.action,64)??null,detail:typeof E.detail=="string"&&E.detail?Rt(Dt(E.detail),n.detailChars):void 0,session:ue(E.session_ref,64)}))break}catch(m){a.activityError=pn(m)}finally{try{p?.close()}catch{}}}for(let p of await It(de(r,"project-memory"),100)){let m=de(r,"project-memory",p);if(!await Dr(m))continue;let y=await Rr(de(m,"MEMORY.md"),n.fileChars),b=await sd(m);if(!y&&!b)continue;let E=(await jn(de(m,"PROJECT.json")))?.project;if(!l(a.projects,{id:ue(p,64)??null,name:typeof E=="string"?ue(cd(E.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:b,memory:y}))break}for(let p of await It(de(r,"teams"),100)){if(!await Dr(de(r,"teams",p)))continue;let m=await Rr(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 It(de(r,"agents"),100)){let m=de(r,"agents",p);await Dr(m)&&g.push({id:p,dir:m,at:Math.max(0,...await Promise.all([...Ku,".memory-state.json"].map(y=>o(de(m,y)))))})}for(let{id:p,dir:m,at:y}of g.sort((b,E)=>E.at-b.at||b.id.localeCompare(E.id))){let b={};for(let T of Ku){let z=await Rr(de(m,T),n.fileChars);z&&(b[T]=z)}let E=[];if(await Dr(de(m,"LOG")))for(let T of(await It(de(m,"LOG"),400)).filter(z=>/^\d{4}-\d{2}-\d{2}\.md$/.test(z)&&z.slice(0,10)>=s&&z.slice(0,10)<=jt(e))){let z=await Rr(de(m,"LOG",T),n.logChars);z&&E.push({date:T.slice(0,10),text:z})}let h=(await jn(de(m,".memory-dream.json")))?.last,x=await sd(m),v=await ky(m,n.fileChars);!Object.keys(b).length&&!E.length&&!x&&!v||l(a.agents,{id:p,updatedAt:y?new Date(y).toISOString():null,config:v,state:x,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"?Rt(Dt(h.detail),n.detailChars):void 0}:void 0,files:Object.keys(b).length?b:void 0,log:E.length?E:void 0})}return a}async function yd(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${Rm("sha256").update(ld()).digest("hex").slice(0,8)}`}async function _y(t){let{home:e}=t,n=de(e,"tangu"),r=t.now??new Date,o=a=>t.since?.[a]??Tt(r),s=fy(t.engineLogs);return Dt({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:Lm(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:cd(e),cloudUrl:t.cloudUrl},device:{id:await yd(e),name:ld()},system:await dy(e),config:iy(await jn(de(e,"config.json"))),agents:await ed(de(n,"agents")),teams:await ed(de(n,"teams")),plugins:{desktop:await td(de(e,"plugins")),engine:await td(de(n,"plugins"))},inventory:{skills:await It(de(n,"skills")),spaces:await It(de(e,"spaces")),themes:await It(de(e,"themes"))},...t.activity?{...await ly(de(e,"activity"),r,o("activity")),activitySince:new Date(o("activity")).toISOString()}:{},...t.sessions?{...await cy(e,r,dd,o("sessions")),sessionsSince:new Date(o("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await Ey(e,r)}:{},...await uy(e,r),runsSince:new Date(Tt(r)).toISOString(),...s?{engine:s}:{},sync:{content:by(t.contentSync),legacy:Sy(t.engineLogs)}})}function wd(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(v=>wo({baseUrl:v.cloudUrl,vault:bo,getToken:()=>v.token})),o=e.policyFor??Fi,s=()=>de(t.homeDir(),"extend-diagnostics.json"),a=()=>{let v=T=>T&&typeof T=="object"?T:{};try{let T=JSON.parse(Om(s(),"utf8"));return{accounts:v(T?.accounts),sent:v(T?.sent)}}catch{return{accounts:{},sent:{}}}},i=()=>a().accounts,l=(v,T,z)=>{let C=a();C.accounts[v]={...C.accounts[v],...T},Object.assign(C.sent,z),Dm(t.homeDir(),{recursive:!0});let O=`${s()}.${process.pid}.tmp`;Nm(O,JSON.stringify(C,null,2),{encoding:"utf8",mode:384}),Mm(O,s())},c=()=>{let v=t.readCreds();return v.token&&v.cloudUrl?t.accountId():null},u=()=>{let v=c(),T=v?i()[v]??{}:{},z=Ar(T.policy);return{signedIn:!!v,enabled:T.enabled===!0,activity:T.activity!==!1,sessions:T.sessions??T.enabled!==!0,memory:T.memory??T.enabled!==!0,lastUploadAt:T.lastUploadAt??null,lastError:T.lastError??null,retainDays:Ho,mode:z.mode,intervalHours:z.intervalHours}},f=()=>{try{return rd(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 T={...t.readCreds()},z=n(),C=a(),O=C.accounts[v],$=T.cloudUrl.replace(/\/+$/,""),q=Mi(O?.file,C.sent[$]??{},z),G=(async()=>{try{let I=await _y({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:T.cloudUrl,activity:O?.activity!==!1,sessions:O?.sessions===!0,now:z,since:q,engineLogs:f(),contentSync:Wu(),memory:()=>{let ee=c()===v?i()[v]:void 0;return ee?.enabled===!0&&ee.memory===!0}}),A=await yd(t.homeDir()),U=i()[v];if(c()!==v||U?.enabled!==!0)return!1;if(U.activity===!1)for(let ee of["activity","activityTruncated","activityError","activitySince"])delete I[ee];if(U.sessions!==!0)for(let ee of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete I[ee];U.memory!==!0&&delete I.memory;let M=[],X=Hm(I,M);if(!X)throw new Error("snapshot too large");await Pi(r(T),A,X,z),p.delete(v);let Q=Ni(a().sent[$]??{},O?.file,q,z,I,M);return l(v,{lastUploadAt:n().getTime(),lastError:void 0,file:Q.file},{[$]:Q.sent}),t.log(`[forsion-extend] diagnostics uploaded (${X.length} bytes)`),!0}catch(I){p.set(v,n().getTime());let A=String(I?.message||I).slice(0,300);try{l(v,{lastError:A})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${A}`),!1}finally{g=null}})();return g={id:v,done:G},G},y=async()=>{try{let v=c();if(!v||i()[v]?.enabled!==!0)return;let T=await o({...t.readCreds()}),z=c()===v?i()[v]:void 0;if(z?.enabled!==!0)return;T&&(T.mode!==z.policy?.mode||T.intervalHours!==z.policy?.intervalHours)&&l(v,{policy:{mode:T.mode,intervalHours:T.intervalHours}}),T&&z.requestSeen===void 0&&l(v,{requestSeen:T.requestedAt});let C=T??{...Ar(z.policy),requestedAt:0},O=C.requestedAt>(z.requestSeen??C.requestedAt),$=z.lastUploadAt??0,q=!$||C.mode==="scheduled"&&n().getTime()-$>=C.intervalHours*ud;if(!O&&!q||n().getTime()-(p.get(v)??-Yu)<Yu)return;await m()&&O&&l(v,{requestSeen:C.requestedAt})}catch(v){t.log(`[forsion-extend] diagnostics tick failed: ${String(v?.message||v)}`)}},b=Promise.resolve(),E={ok:!1,error:"untrusted"};t.handle("diagnostics:get",v=>t.isTrustedSender(v)?u():E),t.handle("diagnostics:set",(v,T)=>{if(!t.isTrustedSender(v))return E;let z=c();if(!z)return u();let C={};typeof T?.enabled=="boolean"&&(C.enabled=T.enabled),C.enabled&&(C.requestSeen=void 0),typeof T?.activity=="boolean"&&(C.activity=T.activity),typeof T?.sessions=="boolean"&&(C.sessions=T.sessions),typeof T?.memory=="boolean"&&(C.memory=T.memory);let O=i()[z];for(let $ of["sessions","memory"])C[$]!==void 0||O?.[$]!==void 0||(O?.enabled===!0?C[$]=!1:C.enabled&&(C[$]=!0));return l(z,C),C.enabled&&(p.delete(z),b=Promise.all([b,y()]).then(()=>{})),u()}),t.handle("diagnostics:uploadNow",async v=>t.isTrustedSender(v)?(u().enabled&&await m(),u()):E);let h=setTimeout(()=>void y(),zm),x=setInterval(()=>void y(),Bm);return h.unref?.(),x.unref?.(),t.log(`[forsion-extend] diagnostics registered${rd(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(h),clearInterval(x)},{tick:y,settled:()=>b})}import{randomUUID as Dd}from"node:crypto";import{appendFileSync as $y,existsSync as Fy,mkdirSync as ta,readFileSync as Od,renameSync as Md,rmSync as na,statSync as jy,writeFileSync as Nd}from"node:fs";import{lstat as jd}from"node:fs/promises";import{homedir as Ly,release as Uy}from"node:os";import{join as Hn}from"node:path";var Mr={$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 Ay=Mr.events,xy=Mr.envelope,Xi=Mr.limits,vd=Mr.version,Ty=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Iy=/^[A-Za-z0-9._:/@+-]+$/,kd=t=>typeof t=="string"&&Ty.test(t),bd=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ry=[[/\/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]"]],Ed=t=>Ry.reduce((e,[n,r])=>e.replace(n,r),t);function Sd(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(bd,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=Ed(r),(r.length>e?r.slice(0,e):r).replace(bd,"\uFFFD")}var _d=/^pr-[a-f0-9]{48}$/,Dy=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Cd=t=>_d.test(t)||Dy.test(t)||Ed(t)===t;function Oy(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function Ki(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 kd(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&&Iy.test(e)&&Cd(e)?e:void 0;case"text":return typeof e=="string"&&e?Sd(e,t.max,n):void 0;case"stack":{let r=Oy(e);return r?Sd(r,t.max,n):void 0}}}function Ht(t,e){let n=typeof t?.event=="string"?Ay[t.event]:void 0;if(!n)return null;let r={},o=t.props&&typeof t.props=="object"?t.props:{};for(let[a,i]of Object.entries(n)){let l=Ki(i,o[a],e);l!==void 0&&(r[a]=l)}let s=Ki({type:"iso-time"},t.ts);return{event:t.event,ts:s??new Date().toISOString(),...kd(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function Ad(t){let e={};for(let[n,r]of Object.entries(xy)){if(n==="installId")continue;let o=Ki(r,t[n]);e[n]=typeof o=="string"?o:null}return e}function xd(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 Td(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function Ko(t){return t?/^pr-/.test(t)?"forsion":/^codex\//.test(t)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(t)?"local":"byok":"other"}var My=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function Zi(t,e){if(typeof t!="string"||!t)return;let n=Ko(t);if((n==="codex"||n==="forsion"&&_d.test(t))&&(e===void 0||e===n))return t;let o=t.slice(t.lastIndexOf("/")+1);return My.test(o)?o:void 0}function Qi(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function ea(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}var Ny=/^market-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i,Py=/^[a-z0-9][a-z0-9-]{0,79}$/;function Id(t,e){if(typeof t!="string"||!t)return;let n=Ny.exec(t);if(n)return n[1].toLowerCase();if((e===!0||e===1)&&t.length<=80&&Py.test(t)&&Cd(t))return t}function Rd(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var Hy=10*6e4,zy=6e4,By=50,Pd=1024*1024,qy=168*36e5,$d=15e3,Wy=200,Gy=2e3,ra=7,Vy=5e3,Fd=864e5,Yy=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"]),Jy=new Set(["shown","dismiss","card","points","upgrade","topup","bgConvert","bgSettings","more"]),Ky=1e3,Xy=new Set(["matched","downloading","waiting_idle","countdown_shown","postponed","installing","manual_prompt","target_below_threshold","never_idle","install_failed"]),Zy=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"]),Qy=10,ew=80,tw=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/,nw=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,oa=36e5,sa=2,ia={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},rw=new Set(["custom-ask","escalate","mode","protected","control","always"]);function ow(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=Zi(n,typeof e.providerKind=="string"?e.providerKind:"other");return r?{...t,props:{...e,modelId:r,providerKind:typeof e.providerKind=="string"?e.providerKind:Ko(n)}}:null}if(t.event==="plugin_inventory"){if(!Rn(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"?!sw.test(n):e.source!=="builtin"||!(n.length<=80&&iw.test(n)))?null:{...t,props:{day:e.day,id:n,source:e.source,installed:e.installed,enabled:e.enabled}}}return t}var sw=/^(?:market-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,iw=/^[a-z0-9][a-z0-9-]{0,79}$/,aw={model_feedback:"modelId",plugin_inventory:"id",quota_prompt:"entry"},lw=new Set(["readonly","auto-edit","full-auto","custom"]),Ld=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),aa=t=>({at:Ld(t),id:"~"}),Un=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function cw(t,e,n,r){let o=Hn(t,"tangu","state.db");if(!await jd(o).then(a=>a.isFile(),()=>!1))return{events:[],cursor:e};let s;try{let{DatabaseSync:a}=await import("node:sqlite");s=new a(o,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let i=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",Wy),l=s.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,
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=o,this.codeblock=s}};var lm=/^((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=y=>`(SELECT total(json_extract(s.value, '$.tokens')) FROM json_each(e.payload, '$.sections') s WHERE json_extract(s.value, '$.k') = '${y}')`,u=s.prepare(`SELECT json_extract(e.payload, '$.telemetry.agentRole') AS agentRole, json_extract(e.payload, '$.telemetry.recallEntries') AS recallEntries,
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`),f=y=>typeof y=="number"&&Number.isFinite(y)&&y>0?y:0,g=y=>typeof y=="string"&&y?y:void 0,p=[],m=e;for(let y of i){m={at:String(y.updated_at),id:String(y.id)};let b={llmCalls:0,tokensIn:0,tokensOut:0,tokensCached:0,retries:0},E=new Map,h=new Map,x=new Map,v=[],T=new Map;for(let I of l.all(y.id,Gy))if(I.type==="usage")b.llmCalls++,b.tokensIn+=f(I.prompt),b.tokensOut+=f(I.completion),b.tokensCached+=f(I.cached);else if(I.type==="tool_call"||I.type==="tool_result"){if(typeof I.id=="string"&&I.source!=null&&h.set(I.id,I.source),typeof I.id=="string"&&I.pluginId!=null&&x.set(I.id,{pluginId:I.pluginId,official:I.pluginOfficial}),I.type!=="tool_result"||typeof I.name!="string")continue;let A=I.source??(typeof I.id=="string"?h.get(I.id):void 0),U=ea(I.name,A),M=Qi(A),X=typeof I.id=="string"?x.get(I.id):void 0,Q=A==="plugin"?Id(I.pluginId??X?.pluginId,I.pluginOfficial??X?.official):void 0,ee=`${U}\0${M}\0${Q??""}`,re=E.get(ee)??{tool:U,toolSource:M,...Q?{pluginId:Q}:{},calls:0,failures:0,totalMs:0,maxMs:0};E.set(ee,re),re.calls++,I.failed&&re.failures++,re.totalMs+=f(I.ms),re.maxMs=Math.max(re.maxMs,f(I.ms))}else if(I.type==="approval_request")v.push({approvalId:g(I.approvalId),name:g(I.name),toolCallId:g(I.toolCallId),reasonKind:rw.has(I.reasonKind)?I.reasonKind:"other",mode:lw.has(I.reasonMode)?I.reasonMode:"other",at:Un(I.at)});else if(I.type==="approval_result"){let A=g(I.approvalId);A&&!T.has(A)&&T.set(A,{action:g(I.action),via:g(I.via),at:Un(I.at)})}else I.phase==="llm_retry"&&b.retries++;let z=u.all(y.id)[0],C=Td(y.status),O=Un(y.updated_at)-Un(y.created_at),$=new Date(Number.isNaN(Un(y.updated_at))?Date.now():Un(y.updated_at)).toISOString(),q=Ht({event:"agent_run",ts:$,sessionId:n,props:{modelId:Zi(y.model_id),providerKind:Ko(y.model_id),mode:Rd(y.kind),steps:f(y.current_step),...b,durationMs:Number.isFinite(O)&&O>=0?O:void 0,outcome:C,errorClass:C==="done"?void 0:xd(y.error,y.status),...z?{agentRole:z.agentRole,recallEntries:z.recallEntries,recallHistory:z.recallHistory,recallTruncated:z.recallTruncated===1?!0:z.recallTruncated===0?!1:void 0,...z.sectionsType==="array"?{memoryTokens:z.memoryTokens,humanTokens:z.humanTokens,profileTokens:z.profileTokens,projectTokens:z.projectTokens}:{}}:{}}});q&&p.push(q);for(let I of E.values()){let A=Ht({event:"tool_call",ts:$,sessionId:n,props:{...I,runOutcome:C}});A&&A.props.tool&&p.push(A)}let G=new Map;for(let I of v){if(!I.name)continue;let A=I.toolCallId?h.get(I.toolCallId):void 0,U=A==null?I.name.startsWith("mcp__")?"mcp":void 0:ea(I.name,A),M=Qi(A),X=`${U??""}\0${M}\0${I.reasonKind}\0${I.mode}`,Q=G.get(X)??{tool:U,toolSource:M,reasonKind:I.reasonKind,mode:I.mode,asked:0,approved:0,rejected:0,expired:0,decideSecTotal:0,remoteAnswers:0};G.set(X,Q),Q.asked++;let ee=I.approvalId?T.get(I.approvalId):void 0;if(!ee){Q.expired++;continue}ee.action==="approve"||ee.action==="approve_always"?Q.approved++:ee.action==="reject"&&Q.rejected++;let re=Math.round((ee.at-I.at)/1e3);Number.isFinite(re)&&re>0&&(Q.decideSecTotal+=re),ee.via&&ee.via!=="local"&&Q.remoteAnswers++}for(let I of G.values()){let A=Ht({event:"approval",ts:$,sessionId:n,props:I});A&&(A.props.tool||I.tool===void 0)&&p.push(A)}}return{events:p,cursor:m}}catch{return{events:[],cursor:e}}finally{try{s?.close()}catch{}}}async function uw(t,e,n){let r=Hn(t,"tangu","state.db"),o=await jd(r).then(a=>a.isFile(),a=>a?.code==="ENOENT"||a?.code==="ENOTDIR"?!1:null);if(o===null)return null;if(!o)return{days:[],complete:!0};let s;try{let{DatabaseSync:a}=await import("node:sqlite");if(s=new a(r,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500"),!s.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'telemetry_ledger'").all().length)return{days:[],complete:!0};let i=Object.keys(ia),l=s.prepare(`SELECT DISTINCT day FROM telemetry_ledger
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 (${i.map(()=>"?").join(", ")})
280
- ORDER BY day LIMIT ?`).all(e,n,...i,ra+1),c=s.prepare("SELECT event, dim, field, n FROM telemetry_ledger WHERE day = ? ORDER BY event, dim, field LIMIT ?"),u=[];for(let{day:f}of l.slice(0,ra)){if(!Rn(f))continue;let g=new Map;for(let m of c.all(f,Vy)){if(typeof m.event!="string"||!Object.hasOwn(ia,m.event))continue;let y=ia[m.event],b=typeof m.dim=="string"?m.dim:"";if((y?!b:b!=="")||typeof m.field!="string"||typeof m.n!="number")continue;let E=`${m.event}\0${b}`,h=g.get(E)??{event:m.event,dimKey:y,dim:b,fields:new Map};g.set(E,h),h.fields.set(m.field,(h.fields.get(m.field)??0)+m.n)}let p=[];for(let m of g.values()){let y=Ht({event:m.event,ts:`${f}T23:59:59.000Z`,props:{...Object.fromEntries(m.fields),day:f,...m.dimKey?{[m.dimKey]:m.dim}:{}}});!y||y.props.day!==f||m.dimKey&&y.props[m.dimKey]===void 0||Object.keys(y.props).some(b=>b!=="day"&&b!==m.dimKey)&&p.push(y)}u.push({day:f,events:p})}return{days:u,complete:l.length<=ra}}catch{return null}finally{try{s?.close()}catch{}}}var dw=(t,e,n)=>Ht({event:"sync_health",ts:`${t}T23:59:59.000Z`,props:{...n,system:e,day:t}}),fw=t=>["darwin","win32","linux"].includes(t)?t:"other",pw=t=>["arm64","x64","ia32"].includes(t)?t:"other",hw=()=>/^zh\b/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en";function Ud(t,e={}){let n=e.now??(()=>new Date),r=e.fetch??fetch,o=()=>t.homeDir(),s=()=>Hn(o(),"extend-telemetry.json"),a=()=>Hn(o(),"telemetry"),i=()=>Hn(a(),"queue.jsonl"),l=()=>Hn(a(),"sent.jsonl"),c=t.telemetry,u=()=>In(n().getTime()-Fd);gu(()=>n().getTime());let f=()=>g()??{},g=()=>{let _;try{_=Od(s(),"utf8")}catch(R){return R?.code==="ENOENT"?{}:null}try{let R=JSON.parse(_);return R&&typeof R=="object"&&!Array.isArray(R)?R:null}catch{return null}},p=(_,R=f())=>{let B={...R,..._};ta(o(),{recursive:!0});let L=`${s()}.${process.pid}.tmp`;return Nd(L,JSON.stringify(B,null,2),{encoding:"utf8",mode:384}),Md(L,s()),B},m=()=>f().installId??p({installId:Dd()}).installId,y=()=>{try{return!!t.readCreds().token}catch{return!1}},b=(_=f())=>_.enabled!==!1&&_.noticeSeen===!0&&c?.packaged===!0&&y(),E=_=>{try{return Od(_,"utf8").split(`
281
- `).filter(Boolean)}catch{return[]}},h=()=>E(i()).flatMap(_=>{try{return[JSON.parse(_)]}catch{return[]}}),x=(_,R)=>{if(ta(a(),{recursive:!0}),!R.length){na(_,{force:!0});return}let B=`${_}.${process.pid}.tmp`;Nd(B,R.map(L=>JSON.stringify(L)).join(`
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}),Md(B,_)},v=0,T=null,z=null,C=()=>{v++,na(i(),{force:!0}),na(l(),{force:!0}),hu(),T=null},O=()=>{let _=n().getTime(),R=E(l()).flatMap(L=>{try{return[JSON.parse(L)]}catch{return[]}}),B=R.filter(L=>_-L.at<qy);return B.length!==R.length&&x(l(),B),B},$=0,q=!1,G=0,I=()=>{let _=g();if(!_)return _i(!1),!1;let R=b(_);return R&&_.closed?p({closed:void 0,cursor:aa(n().getTime()),ledgerCursor:u()},_):R&&!Rn(_.ledgerCursor)?p({ledgerCursor:u()},_):!R&&!_.closed&&($++,p({closed:!0},_)),_i(R),R},A=()=>{let _=g();if(!_){t.log("[forsion-extend] telemetry state unreadable; skipping the signed-in migration");return}if(_.signedInGate)return;let R={signedInGate:1};!y()&&_.enabled===void 0&&_.noticeSeen===!0&&(R.enabled=!1,R.syncHealth=void 0,$++,C(),t.log("[forsion-extend] telemetry turned off: not signed in (sending now needs a Forsion account)")),p(R,_)},U=_=>{if(!(!_.length||!b())){ta(a(),{recursive:!0}),$y(i(),_.map(R=>JSON.stringify(R)).join(`
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(jy(i()).size>Pd){let R=h(),B=R.length,L=0;for(;B>0&&L+Buffer.byteLength(JSON.stringify(R[B-1]))+1<=Pd/2;)L+=Buffer.byteLength(JSON.stringify(R[--B]))+1;x(i(),R.slice(B))}}catch{}h().length>=By&&ie()}},M=()=>{let _=f();return{available:!!c,enabled:_.enabled!==!1,noticeSeen:_.noticeSeen===!0,signedIn:y(),active:b(_),packaged:c?.packaged===!0,installId:m(),queued:Fy(i())?h().length:0,lastSentAt:_.lastSentAt??null,lastError:_.lastError??null}},X=()=>Ad({app:"desktop",appVersion:t.appVersion(),coreVersion:c?.coreVersion()??void 0,channel:c?.channel(),os:fw(process.platform),osVersion:Uy(),arch:pw(process.arch),locale:hw()}),Q=vd,ee=async _=>{try{let R=await _.json?.();return!!R&&typeof R=="object"&&R.detail==="unsupported v"}catch{return!1}},re=null,ie=()=>{if(re)return re;if(q||n().getTime()<G)return Promise.resolve();let _=$,R=v,B=(async()=>{try{for(let L=0;L<5;L++){let V=h();if(!V.length)return;let se=m(),oe={v:Q,installId:se,...X()},Z=[],ae=Buffer.byteLength(JSON.stringify({...oe,events:[]}));for(let me of V){let tt=Buffer.byteLength(JSON.stringify(me))+1;if(Z.length>=Xi.maxEvents||ae+tt>Xi.maxBatchBytes)break;Z.push(me),ae+=tt}if(!Z.length){x(i(),V.slice(1));continue}let{base:le}=await t.getCloud(),pe={...oe,events:Z};if(!I()||_!==$)return;let he=await r(`${le.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(pe),signal:AbortSignal.timeout($d)}).catch(me=>({ok:!1,status:0,error:String(me?.message||me)})),ne=he.status;if(ne===400&&oe.v>sa&&await ee(he)){Q=sa,t.log(`[forsion-extend] telemetry server does not accept v${oe.v}; resending as v${sa}`);continue}if(ne>=200&&ne<300||ne===400||ne===413){let me=new Set(Z.map(tt=>JSON.stringify(tt)));x(i(),h().filter(tt=>!me.has(JSON.stringify(tt))))}if(ne>=200&&ne<300){let me=n().getTime();R===v&&x(l(),[...O(),{at:me,body:pe}]),p({lastSentAt:me,lastError:void 0});continue}if(ne!==400&&ne!==413){let me=Number(he.headers?.get?.("retry-after"));G=n().getTime()+(Number.isFinite(me)&&me>0?Math.min(me,3600)*1e3:5*6e4)}p({lastError:ne?`HTTP ${ne}`:String(he.error??"network error").slice(0,200)});return}}catch(L){try{p({lastError:String(L?.message||L).slice(0,200)})}catch{}}})();return re=B,B.finally(()=>{re===B&&(re=null)}),B},fe=_=>{if(!T||!_&&Math.floor(n().getTime()/oa)===T.hour)return;let R=T;if(T=null,R.gen!==$||!I())return;let B=Ht({event:"quota_prompt",ts:n().toISOString(),sessionId:c?.sessionId,props:{...R.counts,entry:"quota-page"}});try{B&&Object.keys(B.props).some(L=>L!=="entry")&&U([B])}catch(L){throw T=R,L}},we=async()=>{try{if(O(),fe(!1),!I())return;let _=f(),R=$,B=_.cursor??aa(n().getTime()),L=await cw(o(),B,c?.sessionId,Ld(n().getTime()));if(!I()||R!==$)return;U(L.events),L.cursor!==B&&p({cursor:L.cursor}),await ve(R),await ie()}catch(_){t.log(`[forsion-extend] telemetry tick failed: ${String(_?.message||_)}`)}},ve=async _=>{let R=n().getTime(),B=In(R),L=In(R-Fd),V=f().ledgerCursor;if(Rn(V)||(V=L,p({ledgerCursor:V})),Ci(V),V>=L){Ge();return}let se=await uw(o(),V,B);if(!(!I()||_!==$)){if(se){let oe=se.complete?L:se.days[se.days.length-1]?.day??V;if(oe>V){let Z=pu(V,oe),ae=[...new Set([...se.days.map(pe=>pe.day),...Z.map(pe=>pe.day)])].filter(pe=>pe>V&&pe<=oe).sort(),le=[];for(let pe of ae){le.push(...se.days.find(he=>he.day===pe)?.events??[]);for(let he of Z)if(he.day===pe){let ne=dw(pe,he.system,he.counts);ne&&le.push(ne)}}U(le),p({ledgerCursor:oe}),Ci(oe)}}Ge()}},Ge=()=>{if(!du())return;let _=g();if(!_)return;let R=uu();p({syncHealth:Object.keys(R).length?R:void 0},_),fu()},Ne=c?.subscribe(_=>{try{if(!Yy.has(_?.event)||!I())return;let R=ow(_);if(!R)return;let B=Ht({...R,sessionId:c.sessionId},Ly()),L=aw[_.event];B&&(!L||B.props[L]!==void 0)&&U([B])}catch(R){t.log(`[forsion-extend] telemetry event dropped: ${String(R?.message||R)}`)}}),be={ok:!1,error:"untrusted"};t.handle("telemetry:get",_=>t.isTrustedSender(_)?(I(),M()):be),t.handle("telemetry:set",(_,R)=>{if(!t.isTrustedSender(_))return be;let B=f(),L={};typeof R?.enabled=="boolean"&&(L.enabled=R.enabled),R?.noticeSeen===!0&&(L.noticeSeen=!0);let V={...B,...L};return!b(B)&&b(V)&&(L.cursor=aa(n().getTime()),L.ledgerCursor=u()),b(B)&&!b(V)&&$++,L.enabled===!1&&(L.syncHealth=void 0),p(L),L.enabled===!1&&C(),I(),M()}),t.handle("telemetry:quotaPrompt",(_,R)=>{if(!t.isTrustedSender(_))return be;let B=R?.action;return R?.entry!=="quota-page"||typeof B!="string"||!Jy.has(B)?{ok:!1,error:"invalid"}:(fe(!1),I()?((!T||T.gen!==$)&&(T={hour:Math.floor(n().getTime()/oa),gen:$,counts:{}}),T.counts[B]=Math.min((T.counts[B]??0)+1,Ky),{ok:!0,counted:!0}):{ok:!0,counted:!1})}),t.handle("telemetry:forcedUpdate",(_,R)=>{if(!t.isTrustedSender(_))return be;let B=R?.stage;if(typeof B!="string"||!Xy.has(B))return{ok:!1,error:"invalid"};let L=Array.isArray(R?.reasons)?[...new Set(R.reasons.filter(le=>typeof le=="string"&&Zy.has(le)))].sort():[],V="";for(let le of L){let pe=V?`${V}+${le}`:le;pe.length<=ew&&(V=pe)}let se=typeof R?.target=="string"&&R.target.length<=40&&nw.test(R.target)?R.target:void 0,oe=typeof R?.policy=="string"&&tw.test(R.policy)?R.policy:void 0;if(!I())return{ok:!0,counted:!1};let Z=Math.floor(n().getTime()/oa);if((!z||z.hour!==Z)&&(z={hour:Z,counts:{}}),(z.counts[B]=(z.counts[B]??0)+1)>Qy)return{ok:!0,counted:!1};let ae=Ht({event:"forced_update",ts:n().toISOString(),sessionId:c?.sessionId,props:{stage:B,...V?{reasons:V}:{},...se?{target:se}:{},...oe?{policy:oe}:{}}});return ae&&U([ae]),{ok:!0,counted:!!ae}}),t.handle("telemetry:sent",_=>t.isTrustedSender(_)?{batches:O()}:be),t.handle("telemetry:delete",async _=>{if(!t.isTrustedSender(_))return be;q=!0,$++;try{await re?.catch(()=>{});let R=m(),{base:B}=await t.getCloud(),V=(await r(`${B.replace(/\/+$/,"")}/api/telemetry/install/${R}`,{method:"DELETE",signal:AbortSignal.timeout($d)}).catch(se=>({ok:!1,status:0,error:String(se?.message||se)}))).status;return V>=200&&V<300?(C(),p({installId:Dd(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),M()):{ok:!1,error:V?`HTTP ${V}`:"network error"}}finally{q=!1}});try{cu(f().syncHealth),A(),I()}catch(_){t.log(`[forsion-extend] telemetry startup check failed: ${String(_?.message||_)}`)}let N=t.addFlushHook?.(_=>{if(_!=="blur"){try{Ge()}catch{}try{fe(!0)}catch{}}}),W=setTimeout(()=>void we(),zy),H=setInterval(()=>void we(),Hy);return W.unref?.(),H.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(W),clearInterval(H),Ne?.(),N?.()},{tick:we,flush:ie})}import{readFileSync as Vn,lstatSync as zw,statSync as Bw,renameSync as qw,linkSync as Ww,unlinkSync as ma,readdirSync as Gw,rmdirSync as Vw,writeFileSync as Yw,mkdirSync as Jw,copyFileSync as Kw,constants as Xw}from"node:fs";import{readFile as Fr,writeFile as jr,mkdir as ya,rename as ls,readdir as Lr,lstat as Wt,stat as wa,unlink as Ur}from"node:fs/promises";import{join as He,dirname as wn,relative as Hr,sep as Yn}from"node:path";import{hostname as ba}from"node:os";import{createHash as Zw,randomUUID as yt}from"node:crypto";import{isUtf8 as Sa}from"node:buffer";import{Readable as Qw}from"node:stream";import{performance as va}from"node:perf_hooks";import{setImmediate as eb}from"node:timers/promises";var gw=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],mw=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],Nr=".memory-tombstones.json",zd=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),Hd=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),yw=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,ww=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function bw(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===Nr)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:gw.includes(t)||zd(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&yw(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var Sw=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),vw=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,kw=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function Xo(t){let e=t.slice(t.lastIndexOf("/")+1);return vw.test(e)||kw.test(e)}function Bd(t,e,n=1){let r=t.lastIndexOf("/"),o=r<0?"":t.slice(0,r+1),s=r<0?t:t.slice(r+1),a=s.lastIndexOf("."),i=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`${o}${i} (conflict ${u})${l}`}function la(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(Xo(t))return!1;if(n){let c=t.slice(6);return e==="folder"?Hd(c):mw.includes(c)||zd(c)}let o=t.slice(7),s=o.indexOf("/"),a=s<0?o:o.slice(0,s),i=s<0?"":o.slice(s+1);if(!ww(a)||Sw(a))return!1;if(e==="file")return bw(i);if(i===""||i==="LOG"||Hd(i))return!0;let l=i.split("/");return l[0]==="Library"&&l.every(c=>c&&!c.startsWith(".")&&!c.endsWith(".")&&!c.endsWith(" "))}import{isAbsolute as Ew}from"node:path";var at=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ot=t=>typeof t=="string",hn=t=>Ot(t)&&t.length>0,zt=t=>typeof t=="boolean",gn=t=>typeof t=="number"&&Number.isFinite(t),Bn=t=>gn(t)&&Number.isSafeInteger(t)&&t>=0,qd=t=>gn(t)&&Number.isInteger(t)&&t>=0,Gd=t=>Bn(t)&&t>0,mn=t=>Ot(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),es=t=>Ot(t)&&/^[a-f0-9]{64}$/.test(t),ca=t=>Ot(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),Pr=(t,e)=>Ot(t)&&e.includes(t),Ee=(t,e)=>t===void 0||e(t),Vd=(t,e,n)=>e.every(r=>Ee(t[r],n)),Yd=t=>Ot(t)&&!t.includes("\0")&&Ew(t);function Bt(t,e=!1){try{return Qt(t,e),!0}catch{return!1}}var Jd=t=>Bt(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,Kd=t=>t===""||mn(t);function Qo(t,e){let n=t.indexOf(":");return n>0&&mn(e)&&t.slice(n+1)===e&&ca(t.slice(0,n))}function _w(t,e){return at(e)&&Qo(t,e.id)&&Bt(e.path)&&hn(e.version)&&es(e.hash)&&Vd(e,["base","inode","stat"],Ot)&&Ee(e.statAt,gn)&&Ee(e.memoryDeleted,zt)&&Ee(e.file,hn)}function Cw(t,e){return at(e)&&Qo(t,e.localId)&&mn(e.id)&&Bt(e.path)&&Gd(e.revision)&&Kd(e.parentId)&&Jd(e.name)}function Aw(t){return at(t)&&mn(t.id)&&Bt(t.path)&&ca(t.target)&&Pr(t.direction,["upload","download","merge","rename","delete"])&&Pr(t.state,["queued","active","done","failed","paused","conflict"])&&Bn(t.done)&&(t.size===null||Bn(t.size))&&gn(t.at)&&Ee(t.error,Ot)&&Ee(t.finishedAt,gn)}function xw(t){return at(t)&&Bt(t.path)&&es(t.hash)&&Ot(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&Ee(t.parentId,mn)&&Ee(t.stageRoot,Yd)&&Ee(t.stageIdentity,Jt)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&qd(t.stageDev)&&qd(t.stageIno))}function Tw(t){return at(t)&&Bt(t.prefix,!0)&&Yd(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Jt(t))}function Iw(t){return at(t)&&Pr(t.state,["running","done"])&&zt(t.seen)&&Vd(t,["name","folderId","shelfId","shelfName"],Ot)&&Ee(t.files,Bn)&&Ee(t.at,gn)&&Ee(t.rewritten,zt)}function Wd(t){return at(t)&&hn(t.key)&&ca(t.ns)&&mn(t.id)&&Bt(t.path)&&Pr(t.side,["cloud","local"])}function Rw(t){return at(t)&&zt(t.latched)&&zn(t.pending,Wd)&&Ee(t.confirmed,e=>zn(e,hn))&&Ee(t.restore,e=>zn(e,Wd))}var Zo=(t,e)=>at(t)&&Object.entries(t).every(([n,r])=>e(n,r)),zn=(t,e)=>Array.isArray(t)&&t.every(e);function Xd(t){if(!at(t)||!at(t.config)||!Bn(t.config.revision)||!zt(t.owned)||!zt(t.paused)||!Zo(t.files,_w)||!Zo(t.folders,Cw)||!zn(t.jobs,Aw)||!Ee(t.accountReview,zt)||!Ee(t.deleteGuard,Rw)||!Ee(t.agentArchive,Iw)||!Ee(t.roots,e=>zn(e,Tw))||!Ee(t.trash,e=>zn(e,xw))||!Ee(t.unconfirmed,e=>Zo(e,(n,r)=>Qo(n,n.slice(-36))&&es(r)))||!Ee(t.pendingUploads,e=>Zo(e,(n,r)=>at(r)&&Qo(n,r.id)&&Bt(r.path))))throw Error("Invalid content sync state; original data was retained");en(t.config,t.config.revision)}function Zd(t){return at(t)&&mn(t.id)&&Kd(t.parentId)&&Jd(t.name)&&Bt(t.path)&&Pr(t.kind,["file","folder"])&&Gd(t.revision)&&zt(t.deleted)&&Ee(t.busy,zt)&&Ee(t.version,hn)&&Ee(t.hash,es)&&Ee(t.size,Bn)&&Ee(t.mtime,gn)&&Ee(t.file,hn)&&t.version===void 0==(t.hash===void 0)}function Qd(t){return Zd(t)&&t.deleted===!0}function ts(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!at(t)||t.schemaVersion!==1||t.namespace!==e||!hn(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,o=new Set;for(let s of t.nodes){if(!Zd(s)||r.has(s.id)||!s.deleted&&o.has(s.path))throw n();r.set(s.id,s),s.deleted||o.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 ef,lstatSync as yn,readdirSync as Dw,readFileSync as Ow,renameSync as ns,unlinkSync as Mw,linkSync as Nw,mkdirSync as ss,realpathSync as ua,rmdirSync as Pw}from"node:fs";import{open as of,lstat as rs,readdir as tf,realpath as sf,readFile as da,writeFile as $w,mkdir as af,unlink as Fw}from"node:fs/promises";import{join as qt,dirname as os,relative as fa,sep as is}from"node:path";import{randomUUID as lf,createHash as jw}from"node:crypto";var $r=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,qn=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),cf=".forsion-sync-id.json",Lw=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),nf=t=>!Lw.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),Me=t=>jw("sha256").update(t).digest("hex");function uf(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 ft(t,e,n=!1){if(n){if(e.split("/").some(i=>i===".."||i==="."||!i)||e.startsWith("/")||e.includes("\\"))throw Error("Invalid internal content path")}else Qt(e,!0);uf(e);let r=await sf(t),o=qt(r,...e.split("/").filter(Boolean)),s=fa(r,o);if(s===".."||s.startsWith(".."+is))throw Error("Content path escapes root");let a=r;for(let i of s.split(is).filter(Boolean)){a=qt(a,i);try{if((await rs(a)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(l){if(l.code!=="ENOENT")throw l}}return o}function kt(t,e,n=!1){if(n||Qt(e,!0),uf(e),e.split("/").some(s=>s===".."||s===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let o=ua(t);for(let s of e.split("/").filter(Boolean)){o=qt(o,s);try{if(yn(o).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(a){if(a.code!=="ENOENT")throw a}}return o}var rf=t=>t?.code!=="ENOENT";async function as(t){let e=new Map,n=[],r=[],o=new Set,s=t.filter(u=>u.prefix).map(u=>u.prefix),a=[];for(let u of t)try{a.push({...u,root:await sf(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 i=u=>{try{return Qt(u),!0}catch{return!1}},l=async u=>{let f;try{f=await tf(u,{withFileTypes:!0})}catch{return}for(let g of f){if(!nf(g.name)||!g.isDirectory()&&!g.isFile())continue;let p=qt(u,g.name);try{let m=await rs(p);if(m.isSymbolicLink())continue;o.add(qn(m).inode),m.isDirectory()&&await l(p)}catch{}}};for(let u of a){let f=u.root;if(!(await rs(f)).isDirectory())throw Error(`Sync root is not a directory: ${u.prefix||"Forsion"}`);let g=async(p,m)=>{let y;try{y=await rs(p)}catch(h){if(!m||p===f)throw h;rf(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&&!i(m)){n.push({path:m,reason:"invalid-name"}),o.add(qn(y).inode),y.isDirectory()&&await l(p);return}let b,E=null;if(y.isDirectory())try{try{let h=JSON.parse(await da(qt(p,cf),"utf8"));/^[a-f0-9-]{36}$/i.test(h.id)&&(b=h.id)}catch(h){if(h.code!=="ENOENT"&&!(h instanceof SyntaxError))throw h}E=await tf(p,{withFileTypes:!0})}catch(h){if(!m||p===f)throw h;if(!rf(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,...qn(y),size:y.isFile()?y.size:0}),!!E)for(let h of E)!nf(h.name)||!h.isDirectory()&&!h.isFile()||await g(qt(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 Uw(c,{skipped:n,unscanned:r,skippedInodes:o})}function Uw(t,e){for(let[n,r]of Object.entries(e))Object.defineProperty(t,n,{value:r,enumerable:!1,configurable:!0});return t}var Wn=(t,e)=>t.some(n=>e===n||e.startsWith(n+"/"));async function pa(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await ft(t.root,fa(t.root,qt(t.physical,cf)).split(is).join("/"),!0),n=lf();try{let r=await of(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 o=JSON.parse(await da(e,"utf8"));if(!/^[a-f0-9-]{36}$/i.test(o.id))throw Error("Invalid folder sync identity");return t.localId=o.id,o.id}}async function Gn(t){let e=await ft(t.root,fa(t.root,t.physical).split(is).join("/")),n=await of(e,ef.O_RDONLY|(ef.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 Ze(t,e){Qt(e);let n=[...t].sort((r,o)=>o.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 ha(t,e,n,r,o=async(s,a)=>a()){let s=Ze(t,e);await af(s.root,{recursive:!0});let a=await ft(s.root,s.relative),i=await da(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});if((i?Me(i):null)!==r)throw Error("Local file changed during download");let l=qt(s.root,`.forsion-sync-${lf()}.tmp`);try{await $w(l,n,{flag:"wx",mode:384}),await ft(s.root,s.relative),await o(a,()=>{kt(s.root,s.relative),ss(os(a),{recursive:!0}),kt(s.root,s.relative);let c=null;try{c=Ow(a)}catch(u){if(u.code!=="ENOENT")throw u}if((c?Me(c):null)!==r)throw Error("Local file changed during download");ns(l,a)})}finally{await Fw(l).catch(()=>{})}}async function df(t,e,n=async(r,o)=>o()){let r=Ze(t,e);await af(r.root,{recursive:!0});let o=await ft(r.root,r.relative);await n([o],()=>{kt(r.root,r.relative),ss(o,{recursive:!0})})}async function ga(t,e,n,r=async(o,s)=>s()){let o=Ze(t,e),s=Ze(t,n);if(o.root!==s.root)throw Error("Folder move crosses a managed source");let a=await ft(o.root,o.relative),i=await ft(s.root,s.relative);await r([a,i],()=>{if(kt(o.root,o.relative),kt(s.root,s.relative),Hw(i)){let c=yn(a),u=yn(i),f=ua(os(a));if((c.dev===u.dev&&c.ino===u.ino&&f===ua(os(i))?Dw(f).filter(m=>{let y=yn(qt(f,m));return y.dev===c.dev&&y.ino===c.ino}):[]).length!==1)throw Error("Local rename destination exists");ns(a,i);return}ss(os(i),{recursive:!0});let l=yn(a);if(l.isDirectory()){if(process.platform==="win32"){ns(a,i);return}ss(i,{mode:448});try{ns(a,i)}catch(c){try{Pw(i)}catch{}throw c}}else{Nw(a,i);let c=yn(a);if(c.ino!==l.ino||c.dev!==l.dev)throw Error("Source changed during rename");Mw(a)}})}function Hw(t){try{return yn(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var ff=(t,e,n,r,o)=>JSON.stringify([t,e,n,r,o]),Mt=(t,e,n)=>`${t}:${e}:${n}`,pf=t=>({key:t.key,ns:t.ns,id:t.id,path:t.path,side:t.side}),hf=t=>Zw("sha256").update(t.map(e=>e.key).sort().join(`
287
- `)).digest("hex").slice(0,24),tb=(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)))),nb=()=>({config:structuredClone(Du),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),Gt=zo,rb=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CLOSED"]),ob=t=>{let e=t;return!!e&&(e.name==="TypeError"&&/fetch failed/i.test(e.message??"")||rb.has(String(e.cause?.code??e.code??"")))},sb=t=>{let e=t;return e&&e.code==="TOO_LARGE"&&Number.isSafeInteger(e.maxBytes)&&e.maxBytes>0?e.maxBytes:null},ib=t=>`l:${t.size}:${t.mtime}`,ab=10*6e4,gf=1024*1024,De=(t,e)=>`${t}:${e}`,Vt=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",bn=t=>t.slice(t.lastIndexOf("/")+1),Jn=Me(""),lb=t=>/\.db$/i.test(t)&&!/^(agents|human)(\/|$)/.test(t),cs=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),tn=t=>t.split("/").length,ze=t=>t instanceof Error?t.message:String(t),cb={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},ka=t=>t.file.replace(/\.json$/,".bases"),bf=5e3,ub=3e4,mf=3e4,db=3e3,us=10*6e4,fb=60*6e4,pb=10*6e4,hb=3*6e4,yf=2e3,gb=1440*6e4,Ea=t=>/^(agents|human)\//.test(t)?ub:bf,mb=t=>Math.max(t.mtime,t.ctime);async function*nn(t){let e=va.now()+8;for(let n of t)va.now()>=e&&(await eb(),e=va.now()+8),yield n}var yb=new Set([Ue.apply,Ue.pause,Ue.rename,Ue.archiveSeen,Ue.confirmDeletes,Ue.abandonDeletes]);function Sf(t,e={}){if(!t.contentSync)return;let n=new _a(t,e);for(let[o,s]of Object.entries({[Ue.get]:(a,i)=>n.snapshot(a,i),[Ue.preview]:a=>n.preview(a),[Ue.apply]:(a,i)=>n.apply(typeof a=="string"?a:"",i),[Ue.run]:()=>{n.retrySoon(),n.touch(),n.kick()},[Ue.pause]:a=>n.pause(a===!0),[Ue.retry]:()=>{n.retryFailed(),n.touch(),n.kick()},[Ue.rename]:a=>n.rename(a),[Ue.setup]:a=>n.setup(a),[Ue.archiveSeen]:()=>n.archiveSeen(),[Ue.confirmDeletes]:a=>n.confirmDeletes(typeof a=="string"?a:""),[Ue.abandonDeletes]:a=>n.abandonDeletes(typeof a=="string"?a:"")}))t.handle(o,async(a,...i)=>{if(!t.isTrustedSender(a))return{ok:!1,error:"untrusted"};let l=yb.has(o);l&&n.mutating++;try{return{ok:!0,value:await s(...i)}}catch(c){return{ok:!1,error:ze(c)}}finally{l&&n.mutating--}});let r=()=>n.busy()&&!n.quitting;return t.addQuitGuard?.(o=>r()?{message:o==="zh"?"\u8FD8\u6709\u5185\u5BB9\u6B63\u5728\u540C\u6B65":"Content is still syncing"}:null),vo(t,"sync",r),t.addFlushHook?.(o=>n.flush(o)),qu(()=>n.stats()),n.start(),n}var _a=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 Ir;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=To((e,n,r)=>dt("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;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;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=mc(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()+us}};if(this.archiving)return this.archiving;let r=this.archiving=(async()=>{try{let s=this.host.readCreds();if(!s.token)return;let a=await this.gatedFetch(e,s.cloudUrl,"/api/remotesync/agent-archive",{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({locale:this.locale()})},6e4);if(this.guard(e),!a.ok){n();return}let i=await a.json();if(this.guard(e),i.state!=="done"&&i.state!=="running"){n();return}let l=e.stored.agentArchive,c=i.archive;l?.rewritten||this.turnAgentsOff(e);let u={rewritten:!0,seen:l?.seen??!1,state:i.state};i.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(s){if(ze(s)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${ze(s)}`)}})(),o=()=>{this.archiving===r&&(this.archiving=null)};return r.then(o,o),r}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=Uu(n);if(!r)return;e.stored.config=en(r,n.revision+1);let o=s=>s==="agents"||s.startsWith("agents/");for(let[s,a]of Object.entries(e.stored.files))o(a.path)&&(delete e.stored.files[s],delete e.stored.unconfirmed?.[s]);for(let[s,a]of Object.entries(e.stored.folders))o(a.path)&&delete e.stored.folders[s];for(let[s,a]of Object.entries(e.stored.pendingUploads??{}))o(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=pr(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(ai(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 ya(wn(e.file),{recursive:!0,mode:448});let o=e.file+".tmp-"+yt();try{await jr(o,r,{mode:384,flag:"wx"}),this.guard(e,!1),await ls(o,e.file),e.persisted=r}finally{await Ur(o).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 ai(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=He(this.host.homeDir(),"content-sync"),o=He(r,Me(e)+".json"),s=nb();try{let f=JSON.parse(await Fr(o,"utf8"));Xd(f),s={...s,...f,config:en(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,i=He(this.host.homeDir(),"content-sync-device.json"),l=async()=>{let f=JSON.parse(await Fr(i,"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:yt()},await ya(wn(i),{recursive:!0});try{await jr(i,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:o,stored:s,roots:c,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map,tombstones:new Map};this.session=u,this.settingUp++;try{await this.bindAccount(u),await this.recoverTrash(u),this.guard(u),s.owned&&await this.accountWrite(u,f=>this.host.contentSync.claim(!0,f))}finally{this.settingUp--}return this.setSources(await this.scan(u,c).catch(f=>(this.error=ze(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=si(this.host.homeDir()),o=Me(e.account),s=pr(r),a=!s?.account&&(await Lr(n).catch(l=>{if(l.code==="ENOENT")return[];throw l})).some(l=>/^[a-f0-9]{64}\.json$/.test(l)&&l!==o+".json"),i=s?.pending&&(e.stored.owned||e.stored.config.revision>0);if((s?.account&&s.account!==o||a||i)&&(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!==o||s.pending){this.guard(e,!1);let l=pr(r);if(l?.account!==s?.account||l?.epoch!==s?.epoch||l?.pending!==s?.pending)throw Error("account_changed");ii(r,{version:1,account:o,...s?.epoch?{epoch:s.epoch}:{}})}e.binding={file:r,account:o,epoch:s?.epoch},this.guard(e,!1)}async rootIdentity(e,n){let r=e.rootIdentities.get(n);if(r){let s=await wa(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!s.isDirectory()||!St(r,s))throw Error("Sync root changed; preview before rebinding");return r}let o=await lr(n).catch(s=>{throw s.code==="ENOENT"?Error("Sync root unavailable: "+n):s});return this.guard(e),e.rootIdentities.set(n,o),o}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 i=await this.rootIdentity(e,s.root);if(s.dev!==void 0&&!an(s,i))throw Error("Sync root changed; preview before rebinding");if(s.dev!==void 0&&s.dev!==i.dev){let l=String(s.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(l)&&Ze(n,c.path).root===s.root&&(c.inode=String(i.dev)+":"+c.inode.slice(l.length),delete c.stat,delete c.statAt)}JSON.stringify(s)!==JSON.stringify({...s,...i})&&(Object.assign(s,i),r=!0)}r&&await this.persist(e);let o=await as(n);return this.scanned={skipped:o.skipped,unscanned:o.unscanned,skippedInodes:o.skippedInodes},o}async write(e,n,r,o){this.guard(e),await ha(e.roots,n,r,o,(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 wa(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,o=!1){let s=()=>{if(this.guard(e),e.stored.paused&&!o)throw Error("paused");for(let[a,i]of e.rootIdentities){let l;try{l=Bw(a)}catch{throw Error("Sync root unavailable: "+a)}if(!l.isDirectory()||!St(i,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(o=>o.prefix===r.prefix&&o.root===r.root)&&await Wt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return as(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Ps(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 o=this.logical(e,r),s=Date.now();if(this.activeAt=s,o){let a=this.dirty.get(o);a?a.last=s:this.dirty.set(o,{first:s,last:s})}this.schedule(o?void 0:s+bf)}))}logical(e,n){let r=null;for(let a of e.roots)(n===a.root||n.startsWith(a.root+Yn))&&(!r||a.root.length>r.root.length)&&(r=a);if(!r)return null;let o=Hr(r.root,n).split(Yn).join("/");return(r.prefix?o?`${r.prefix}/${o}`:r.prefix:o)||null}dueAt(e,n){return n.last<=this.flushAt?0:Math.min(n.last+Ea(e),n.first+mf)}schedule(e){let n=e??1/0;for(let[r,o]of this.dirty)n=Math.min(n,this.dueAt(r,o));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>=pb&&e-this.lastRunAt<hb-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 o=this.flushRequest;if(await this.run(),o===this.flushRequest)return}}finally{this.flushing=null,this.quitting=!1,this.flushAt=this.flushThrough}})()}async request(e,n,r="",o="GET",s,a,i){for(;;){this.guard(e);let l=this.host.readCreds();if(!l.token)throw Error("not_signed_in");let c=Xt(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":zi,...i},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=Qw.from(y())}else s!==void 0&&(f["Content-Type"]="application/json",g=JSON.stringify(s));let p={method:o,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&&i?.["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),o==="DELETE"&&this.tally("deletesSent"),m}}async gatedFetch(e,n,r,o,s){let a=Xt(n);for(;;){await a.ready(e.abort.signal),this.guard(e);let i=await fetch(n.replace(/\/+$/,"")+r,{...o,headers:{...o.headers,"X-Content-Caps":zi},signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(s)])});if(i.status===429){let l=await i.clone().json().catch(()=>({}));if(a.observe(i.status,i.headers,l?.code,l?.retryAfterMs))continue}return a.observe(i.status,i.headers),i}}async json(e,n,r="",o="GET",s,a){let i=await(await this.request(e,n,r,o,s,void 0,a)).json();return this.guard(e),i}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));ts(a,s),await this.knownTombstones(e,s,a),r.set(s,a)}let o=[r.get("default"),r.get(`device-${this.deviceId}`)].filter(Boolean);return o.length&&(this.cloudAgents=[...new Set(o.flatMap(s=>s.nodes.filter(a=>!a.deleted&&a.kind==="file").map(a=>/^agents\/([^/]+)\/config\.toml$/.exec(a.path)?.[1]).filter(a=>!!a&&xr.test(a))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),o=r&&Date.now()-r.at<fb?r:void 0,s=await this.request(e,n,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...o?{"If-None-Match":o.etag}:{}});if(s.status===304)return await s.body?.cancel(),o?o.text:(e.manifests.delete(n),this.manifestText(e,n));let a=await s.text();this.guard(e),ts(JSON.parse(a),n);let i=s.headers.get("etag");return r?.text!==a&&this.touch(),i?e.manifests.set(n,{etag:i,text:a,at:Date.now()}):e.manifests.delete(n),a}async knownTombstones(e,n,r){if(typeof r.tombstonesSince!="string")return;let o=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()])o.has(c)&&a.delete(c);let i=Date.now(),l=[...s].filter(c=>{if(o.has(c))return!1;let u=a.get(c);return!u||!u.node&&i-u.at>=gb});for(let c=0;c<l.length;c+=yf){let u=l.slice(c,c+yf),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=>Qd(m)&&f.has(m.id)).map(m=>[m.id,m]));for(let m of u)a.set(m,{node:p.get(m)??null,at:i})}for(let c of s)if(!o.has(c)){let u=a.get(c)?.node;u&&r.nodes.push(structuredClone(u))}}route(e,n,r="file"){if(Xo(e)||la(e,r)===!1)return null;let o=Nn(e,n.rules);return o&&o.target!=="off"?o.target:null}effective(e,n){let r=new Map(n.filter(o=>o.localId).map(o=>[o.localId,o.path]));return{...e,rules:e.rules.map(o=>o.sourceId&&r.has(o.sourceId)?{...o,source:r.get(o.sourceId)}:o)}}deviceName(){return this.customName||qo(ba())}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"){Ou.some(a=>s.path.startsWith(a+"/"))||(r.files++,r.size+=s.size);for(let a=Vt(s.path);a;a=Vt(a)){let i=n.get(a);i&&(i.size+=s.size,i.files++)}}let o=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])=>tn(s)-tn(a)||(s<a?-1:1)).slice(0,2e3).map(([s,a])=>({path:s,kind:"folder",size:a.size,files:a.files,...Tr(s)&&o.has(s)?{agent:!0}:{}})),this.sourcesAt=Date.now(),this.readAgentNames(o)}async readAgentNames(e){for(let n of this.agentNames.keys())e.has(n)||this.agentNames.delete(n);for(let[n,r]of e){let o=`${r.mtime}:${r.size}`;if(!(this.agentNames.get(n)?.key===o||r.size>256*1024))try{this.agentNames.set(n,{key:o,...Nu((await Gn(r)).toString("utf8"))})}catch{this.agentNames.set(n,{key:o})}}}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(),o=n||qo(ba()),s=Hi(o,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:o,unique:!0}),await this.saveName(n),await this.register(r,!0),this.deviceName()}async saveName(e){let n=He(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+yt();try{await jr(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await ls(r,n)}finally{await Ur(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<us){r-this.devicesAt>=us&&await this.refreshDevices(e);return}let o=(i,l)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:i,...l?{unique:!0}:{}}),s=async()=>(await this.json(e,"devices")).devices,a=i=>/device_name_(taken|reserved|invalid)/.test(ze(i));try{await o(this.deviceName(),!0)}catch(i){if(!a(i))throw i;let l=!1;if(!this.customName){let c=qo(ba());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}`;Hi(m,f,this.deviceId)||(g=m)}if(!g)break;try{await o(g,!0),await this.saveName(g),l=!0}catch(p){if(!a(p))throw p}}}l||await o(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=He(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let i=JSON.parse(await Fr(e,"utf8"));Array.isArray(i?.devices)&&(n=i.devices)}catch{}let r=new Map(n.filter(i=>i&&typeof i.id=="string").map(i=>[i.id,i])),o=this.devices.map(i=>{let l=r.get(i.id),c=[...Array.isArray(l?.aliases)?l.aliases:[],...l&&typeof l.name=="string"&&l.name!==i.name?[l.name]:[]],u=c.filter((f,g)=>typeof f=="string"&&f!==i.name&&c.lastIndexOf(f)===g).slice(-5);return{id:i.id,name:i.name,...u.length?{aliases:u}:{}}}),s=JSON.stringify({devices:o});if(s===this.cachedDevices)return;let a=e+".tmp-"+yt();try{await jr(a,s,{mode:384,flag:"wx"}),await ls(a,e),this.cachedDevices=s}catch(i){this.error=ze(i)}finally{await Ur(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 o=$n(ju(n.stored.config),"","off");for(let i of Lt)i.id!=="agents"&&r[i.id]===!1&&(o=$n(o,i.path,"off"));let s=new Set(this.sources.filter(i=>i.agent).map(i=>i.path.slice(7))),a=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(i=>typeof i=="string"&&s.has(i)):[];return this.preview(Lu(o,a))}retryFailed(){this.failures.clear(),this.tooLarge.clear(),this.bypassBackoff=!0}retrySoon(){this.bypassBackoff=!0}rateLimitedUntil(){let e=this.host.readCreds();return e.cloudUrl?Xt(e.cloudUrl).until():null}capFor(e,n,r){let o=Wo(n,e,r?.limits),s=this.tooLarge.get(e+"\0"+n)?.learned;return s&&s.published===o?Math.min(o,s.maxBytes):o}noteTooLarge(e,n,r,o,s,a){let i=n+"\0"+r,l=this.tooLarge.get(i);this.tooLargeSeen?.add(i),this.failures.delete(i),dt("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(i,{ns:n,path:r,size:o,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 o=e+"\0"+n,s=this.failures.get(o);return this.roundVisited?.add(o),s?s.fp!==r?(this.failures.delete(o),!1):!this.bypassThisRound&&Date.now()<s.retryAt:!1}succeeded(e,n){this.failures.delete(e+"\0"+n)}fileFailed(e,n,r,o,s,a){if(e.abort.signal.aborted||ob(o))throw o;let i=n+"\0"+r,l=sb(o);if(l!==null){let m=o.size,y=Number.isSafeInteger(m)?m:a??0;this.noteTooLarge(e,n,r,y,l,{maxBytes:l,published:Wo(r,n,this.limitsByNs.get(n))});return}this.error=ze(o);let c=this.failures.get(i),u=(c&&c.fp===s?c.count:0)+1,f=Date.now()+Mu(u),g=o?.code;this.failures.set(i,{ns:n,path:r,reason:ze(o),...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(),o=n&&typeof n=="object"?n:{};if(o.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 o.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)},()=>{})),o.devices===!0&&Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(r).catch(()=>{})),{available:!0,account:Me(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:hf(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(),o=r.stored.deleteGuard?.pending??[],s=o.map(a=>a.key);if(n!==void 0&&n!==hf(o))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 o=e.stored.deleteGuard;if(!o)return;let s=new Set(r),a=o.pending.filter(f=>!s.has(f.key)),i=o.pending.filter(f=>s.has(f.key)),l=[...new Set([...o.confirmed??[],...i.map(f=>f.key)])],c=[...new Map([...o.restore??[],...i].map(f=>[Mt(f.side,f.ns,f.id),f])).values()],u={latched:a.length>0,pending:a,...n==="confirm"?{confirmed:l}:o.confirmed?.length?{confirmed:o.confirmed}:{},...n==="restore"?{restore:c}:o.restore?.length?{restore:o.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,o={},s=e&&e===this.logAccount?this.runLog.snapshot():new Ir().snapshot();for(let a of r?.jobs??[])o[a.state]=(o[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:o,blocked:[...this.blocked.values()].reduce((a,i)=>a+i.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 o=en(e,n.stored.config.revision+1),s=await this.host.contentSync.roots();this.guard(n);let a=await this.previewScan(n,s),i=this.effective(o,a);if(n.stored.agentArchive?.state==="running"&&a.some(I=>I.kind==="file"&&I.path.startsWith("agents/")&&this.route(I.path,i)))throw Error("agent_archive_running");let l=await this.manifests(n,i);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[I,A]of Object.entries(n.stored.files))this.survives(n.stored,i,p,A.path)&&(m.set(I,A),y.set(I.slice(0,I.indexOf(":"))+"\0"+A.path,A));let b=n.stored.deleteGuard,E=new Set((b?.restore??[]).map(I=>Mt(I.side,I.ns,I.id))),h=[],x=new Map,v=new Set(a.map(I=>I.path));for await(let I of nn(a.filter(A=>A.kind==="file"))){let A=this.route(I.path,i);if(!A)continue;let U=l.get(A),M=U?.nodes.find(Q=>!Q.deleted&&Q.kind==="file"&&Q.path===I.path);if(I.size>Wo(I.path,A,U?.limits))continue;let X=Me(await Gn(I));if(this.guard(n),x.set(I.path,X),!M){let Q=y.get(A+"\0"+I.path),ee=Q&&U?.nodes.find(re=>re.id===Q.id&&re.deleted);if(ee&&Q&&cs(I.path)&&(Q.hash===X||Q.memoryDeleted&&X===Jn))continue;if(ee&&Q&&Q.hash===X&&!E.has(Mt("local",A,Q.id))){h.push({ns:A,path:I.path});continue}}X!==M?.hash&&(c++,g+=I.size,M?.version&&f++)}let T=o.enabled?this.agentAsks(n,a,i,l,x):[],z=h.length;for(let[I,A]of l)for await(let U of nn(A.nodes)){if(U.deleted||U.kind!=="file"||this.route(U.path,i)!==I||v.has(U.path))continue;let M=m.get(De(I,U.id)),X=Wn(a.unscanned,U.path)||!!M?.inode&&a.skippedInodes.has(M.inode);if(M&&M.path!==U.path&&v.has(M.path))continue;let Q=Li(U,M,!!n.stored.pendingUploads?.[De(I,U.id)],X);Q==="download"?u++:Q==="delete"&&await this.absent(n,U.path,s)&&(E.has(Mt("cloud",I,U.id))?u++:h.push({ns:I,path:U.path}))}let C=h.length-z,O=[...m].map(([I,A])=>({ns:I.slice(0,I.indexOf(":")),path:A.path})),$=Ui(h,O,{latched:!!b?.latched,recent:this.deleteStamps.filter(I=>Date.now()-I<ji).length}),q=this.signature(a,l,s),G={token:yt(),config:i,upload:o.enabled?c:0,download:o.enabled?u:0,conflicts:o.enabled?f:0,bytes:o.enabled?g:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,deleteCloud:o.enabled?C:0,deleteLocal:o.enabled?z:0,...o.enabled&&$?{deletesHeld:!0}:{},...T.length?{agentAsks:T}:{}};return this.previewValue={value:G,account:n.account,signature:q},G}async bindingsOf(e){let n=[];for(let r of e)await wa(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&n.push({...r,...await lr(r.root)});return n}survives(e,n,r,o,s="file"){return e.config.enabled===n.enabled&&tb(e.roots??r,r)&&this.route(o,e.config,s)===this.route(o,n,s)}signature(e,n,r){return Me(JSON.stringify([r,e.map(o=>[o.path,o.size,o.mtime,o.inode]),[...n].map(([o,s])=>[o,s.nodes.map(a=>[a.id,a.revision,a.version,a.deleted])])]))}async apply(e,n){this.applying++;try{await this.applySerial(e,n)}finally{this.applying--}}async applySerial(e,n){let r=this.serial,o;this.serial=new Promise(s=>{o=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 i=a.value.agentAsks??[],l=wb(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 E=u.find(h=>h.kind==="folder"&&h.path===b.source);E&&(b.sourceId=await pa(E))}let m=i.length?en(i.reduce((b,E)=>$n(b,`agents/${E.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,E]of Object.entries(s.stored.files))this.survives(y,s.stored.config,g,E.path)||delete s.stored.files[b];for(let[b,E]of Object.entries(s.stored.folders))this.survives(y,s.stored.config,g,E.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,E=>this.host.contentSync.claim(y.owned,E)).catch(()=>{}),b}if(this.previewValue=null,s.roots=c,await this.watchRoots(s),i.length)try{await this.resolveAsks(s,i,l,p)}catch(b){throw this.fault(ze(b)),b}s.stored.accountReview&&(delete s.stored.accountReview,await this.persist(s))}finally{this.resolving=!1}}finally{o()}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,o,s){let a=e.stored.jobs.findLast(l=>l.path===n&&l.target===r&&l.direction===o&&["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 i={id:yt(),path:n,target:r,direction:o,state:"active",done:0,size:s,at:Date.now()};return e.stored.jobs.push(i),e.stored.jobs=e.stored.jobs.slice(-200),i}done(e){e.state="done",e.done=e.size??e.done,e.finishedAt=Date.now()}async operation(e,n,r,o,s,a){if(this.guard(e),e.stored.paused)throw Error("paused");this.activeAt=Date.now();let i=this.job(e,n,r,o,s);try{let l=await a(i);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(i),o==="upload"?dt("content","uploads"):o==="download"&&dt("content","downloads");let c=cb[o];return c&&this.tally(c),l}catch(l){throw i.state=e.stored.paused?"paused":"failed",i.error=ze(l),i.finishedAt=Date.now(),l}}async run(){if(this.running||this.closed||this.resolving)return;this.running=!0;let e;this.runFinished=new Promise(i=>{e=i});let n=Date.now();this.lastRunAt=n,this.wroteLocal=!1;let r=new Set,o,s=!1,a=!1;try{if(o=await this.getSession(),this.runAccount=o.account,o.stored.accountReview){this.error="content_account_changed_preview_required";return}if(await this.archiveStep(o),!o.stored.config.enabled||o.stored.paused)return;o.abort.signal.aborted&&(o.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 i=await this.host.contentSync.roots();this.guard(o),o.roots=i,this.tooLargeSeen=new Set,this.roundVisited=new Set,this.recordsAccount!==o.account&&(this.failures.clear(),this.tooLarge.clear(),this.recordsAccount=o.account),this.bypassThisRound=this.bypassBackoff,this.bypassBackoff=!1,await this.host.contentSync.agentFiles?.prepare().catch(x=>{this.error=ze(x)}),this.guard(o);let l=await this.scan(o,i);await this.recordRoots(o);let c=this.effective(o.stored.config,l),u=await this.manifests(o,c);this.guard(o),this.limitsByNs=new Map([...u].map(([x,v])=>[x,v.limits]));let f=new Map;for(let[x,v]of u)for(let T of v.nodes)T.kind==="file"&&!T.deleted&&f.set(x+"\0"+T.path,T.version??"");let g=(x,v)=>`${ib(v)}|c:${f.get(x+"\0"+v.path)??""}`;await this.register(o),this.openJobs=new Set(o.stored.jobs.filter(x=>["failed","paused","active"].includes(x.state)&&["upload","download","merge"].includes(x.direction)).map(x=>x.target+"\0"+x.path)),await this.folders(o,c,l,u),await this.recordRoots(o),await this.fileRenames(o,c,l,u),l=await this.scan(o,i),c=this.effective(c,l),o.stored.config=c,this.setSources(l),this.phase="syncing",this.round={plan:[],restore:new Map((o.stored.deleteGuard?.restore??[]).map(x=>[Mt(x.side,x.ns,x.id),x])),restoreHit:new Set,restoreDone:new Set,tracked:Object.entries(o.stored.files).map(([x,v])=>({ns:x.slice(0,x.indexOf(":")),path:v.path})),undecided:new Set};let p=(x,v)=>this.round.undecided.add(x+"\0"+v),m=x=>x.endsWith("/"+Nr),y=new Set,b=new Set,E=x=>x.startsWith("agents/")?x.slice(0,x.lastIndexOf("/")+1):null,h=x=>x.endsWith("/MEMORY.md")&&b.has(E(x)??"");for(let[x,v]of u)for await(let T of nn(v.nodes.filter(z=>z.kind==="file"&&!z.busy&&m(z.path)))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.route(T.path,c)!==x||l.some(z=>z.path===T.path))){if(this.isBlocked(x,T.path)){b.add(E(T.path)??""),p(x,T.path);continue}if(this.backingOff(x,T.path,`c:${T.version??""}`)){b.add(E(T.path)??""),p(x,T.path);continue}y.add(T.id);try{await this.missing(o,T,x,l,c)==="unknown"?b.add(E(T.path)??""):this.succeeded(x,T.path)}catch(z){this.fileFailed(o,x,T.path,z,`c:${T.version??""}`,T.size),b.add(E(T.path)??""),p(x,T.path)}}}for await(let x of nn(l.filter(v=>v.kind==="file").sort((v,T)=>+!m(v.path)-+!m(T.path)))){if(this.guard(o),o.stored.paused)throw Error("paused");let v=this.route(x.path,c);if(v){if(h(x.path)){p(v,x.path);continue}if(this.isBlocked(v,x.path)){m(x.path)&&b.add(E(x.path)??""),p(v,x.path);continue}if(this.backingOff(v,x.path,g(v,x))){p(v,x.path),m(x.path)&&b.add(E(x.path)??"");continue}try{let T=await this.file(o,c,x,v,u.get(v));T==="held"?(r.add(x.path),p(v,x.path)):T==="too-large"?(p(v,x.path),m(x.path)&&b.add(E(x.path)??"")):this.succeeded(v,x.path)}catch(T){this.fileFailed(o,v,x.path,T,g(v,x),x.size),p(v,x.path),m(x.path)&&b.add(E(x.path)??"")}}}for(let[x,v]of u)for await(let T of nn(v.nodes.filter(z=>z.kind==="file"&&!z.busy&&!y.has(z.id)))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.route(T.path,c)!==x||l.some(z=>z.path===T.path))){if(this.isBlocked(x,T.path)||h(T.path)){p(x,T.path);continue}if(this.holdGone(T.path)){r.add(T.path),p(x,T.path);continue}if(this.backingOff(x,T.path,`c:${T.version??""}`)){p(x,T.path);continue}try{await this.missing(o,T,x,l,c),this.succeeded(x,T.path)}catch(z){this.fileFailed(o,x,T.path,z,`c:${T.version??""}`,T.size),p(x,T.path)}}}await this.executeDeletes(o,this.round),await this.cleanupFolders(o,c,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(o).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=us)&&(await this.accountWrite(o,x=>this.host.contentSync.changed(x)),this.changedAt=Date.now()),this.guard(o),await this.persist(o),await this.pruneBases(o),a=!0;for(let x of[...this.tooLarge.keys()])this.tooLargeSeen?.has(x)||this.tooLarge.delete(x);for(let x of[...this.failures.keys()])this.roundVisited?.has(x)||this.failures.delete(x);!this.error&&this.failures.size&&(this.error=[...this.failures.values()].reduce((x,v)=>x.retryAt>v.retryAt?x:v).reason)}catch(i){this.error=ze(i)}finally{if(this.round=null,this.phase=o?.stored.paused?"paused":"idle",o&&this.host.accountId()===o.account)for(let i of this.deferredDecision.splice(0))this.applyDecision(o,i.kind,i.keys);s&&(this.noteHealth(n,a),this.live()&&this.runLog.end(a));for(let[i,l]of this.dirty)!r.has(i)&&l.last<n&&this.dirty.delete(i);o&&this.host.accountId()===o.account&&(await this.persist(o).catch(()=>{}),!this.closed&&o.abort.signal.aborted&&!o.stored.paused&&o.stored.config.enabled&&(o.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&&(dt("content","cycles"),dt("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?xo(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<Ea(e)&&r-n.first<mf}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=ze(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(ze(r),[n])}async folders(e,n,r,o){let s=r.filter(i=>i.kind==="folder"),a=new Map;for(let i of s)if(i.localId){if(a.has(i.localId))throw Error(`Duplicate folder sync identity: ${i.path}`);a.set(i.localId,i.path)}for(let[i,l]of o){for await(let c of nn(l.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,f)=>tn(u.path)-tn(f.path))))if(!(this.isBlocked(i,c.path)||Wn(this.scanned.unscanned,c.path)))try{let u=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(i+":")&&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")!==i)continue;if(this.route(c.path,n,"folder")!==i)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,f.path,i,"rename",null,()=>ga(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=Ze(e.roots,p.path);p.physical=He(y.root,y.relative)}for(let[p,m]of Object.entries(e.stored.files))p.startsWith(i+":")&&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")===i&&!u){await df(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(i,c.path,u),this.tally("folderConflicts");let f=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(i+":")&&p.id===c.id)?.[1];f&&this.block(i,f.path,u)}for await(let c of nn(s.sort((u,f)=>tn(u.path)-tn(f.path))))if(!this.isBlocked(i,c.path))try{let u=this.route(c.path,n,"folder"),f=n.rules.some(E=>E.target===i&&E.source.startsWith(c.path+"/"));if(u!==i&&!f||la(c.path,"folder")===!1)continue;let g=await pa(c),p=e.stored.folders[De(i,g)],m=p?l.nodes.find(E=>E.id===p.id):l.nodes.find(E=>E.path===c.path&&!E.deleted);if(m?.deleted){let E=(e.stored.deleteGuard?.restore??[]).some(h=>h.side==="local"&&h.ns===i&&h.path.startsWith(c.path+"/"));if(p&&!E){let h=!1;for(let x of r.filter(v=>v.kind==="file"&&v.path.startsWith(c.path+"/")&&this.route(v.path,n)===i)){let v=Object.entries(e.stored.files).find(([T,z])=>T.startsWith(i+":")&&z.path===x.path)?.[1];if(!v){h=!0;break}if(!this.sameAsShadow(v,x)){let T=Me(await Gn(x));if(T!==v.hash&&!(v.memoryDeleted&&cs(x.path)&&T===Jn)){h=!0;break}}}if(!h)continue}m=void 0}let y=Vt(c.path),b=y?l.nodes.find(E=>E.path===y&&E.kind==="folder"&&!E.deleted)?.id:"";if(y&&!b)throw Error("Cloud parent is unavailable");if(!m)m=await this.json(e,i,"/nodes","POST",{id:p?yt():g,parentId:b,name:bn(c.path),kind:"folder"}),e.tombstones.get(i)?.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 E=m.path,h=await this.operation(e,c.path,i,"rename",null,()=>this.json(e,i,`/nodes/${m.id}`,"PATCH",{parentId:b,name:bn(c.path),revision:m.revision}));for(let x of l.nodes)x.path.startsWith(E+"/")&&(x.path=c.path+x.path.slice(E.length));Object.assign(m,h);for(let[x,v]of Object.entries(e.stored.files))x.startsWith(i+":")&&v.path.startsWith(E+"/")&&(v.path=c.path+v.path.slice(E.length))}e.stored.folders[De(i,g)]={id:m.id,localId:g,path:c.path,revision:m.revision,parentId:m.parentId,name:m.name}}catch(u){this.block(i,c.path,u);let f=c.localId?e.stored.folders[De(i,c.localId)]:void 0;f&&this.block(i,f.path,u),dt("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,c.path,i,"rename",null);g.state="conflict",g.error=ze(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let o=await this.scan(e);for(let[s,a]of r)for await(let i of nn(a.nodes.filter(l=>l.kind==="folder"&&!l.busy).sort((l,c)=>tn(c.path)-tn(l.path)))){if(this.isBlocked(s,i.path)||this.route(i.path,n,"folder")!==s||Wn(this.scanned.unscanned,i.path))continue;let l=Object.entries(e.stored.folders).find(([u,f])=>u.startsWith(s+":")&&f.id===i.id);if(!l)continue;let c=o.find(u=>u.path===i.path&&u.kind==="folder");if(i.deleted&&c){if(o.some(f=>f.path.startsWith(i.path+"/"))||(await Lr(c.physical)).some(f=>f!==".forsion-sync-id.json"))continue;await this.operation(e,i.path,s,"delete",null,()=>this.lock(e,c.physical,()=>{kt(c.root,Hr(c.root,c.physical).split(Yn).join("/"));let f=Gw(c.physical);if(f.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let g=He(c.physical,".forsion-sync-id.json"),p=f.length?Vn(g):null;p&&ma(g);try{Vw(c.physical)}catch(m){if(p)try{Yw(g,p,{flag:"wx",mode:384})}catch{}throw m}})),this.tally("deletesLocal"),delete e.stored.folders[l[0]]}else if(!i.deleted&&!c){if(e.stored.deleteGuard?.latched||e.stored.deleteGuard?.pending.length||e.stored.deleteGuard?.restore?.length||!await this.absent(e,i.path)||a.nodes.some(u=>u.parentId===i.id&&!u.deleted))continue;await this.operation(e,i.path,s,"delete",null,()=>this.json(e,s,`/nodes/${i.id}`,"DELETE",{revision:i.revision,version:null})),i.deleted=!0,delete e.stored.folders[l[0]]}}}async download(e,n,r,o){if(n.size!==void 0&&n.size>Gt)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:Gt});let s=await this.request(e,r,`/nodes/${n.id}/content`),a=[],i=0;if(s.body){let c=s.body.getReader();for(;;){let u=await c.read();if(u.done)break;if(this.guard(e),i+=u.value.length,i>Gt)throw await c.cancel(),Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:Gt});a.push(u.value),o.done=i}}let l=Buffer.concat(a);if(n.hash&&Me(l)!==n.hash)throw Error("Cloud file changed during download");return l}async fileRenames(e,n,r,o){for(let[s,a]of o)for(let i of a.nodes.filter(l=>l.kind==="file"&&!l.deleted&&!l.busy)){let l=e.stored.files[De(s,i.id)];if(!l||l.path===i.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(i.path,n)!==s)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,c.path,s,"rename",null,()=>ga(e.roots,c.path,i.path,(u,f)=>this.lock(e,u,f))),l.path=i.path}catch(u){this.block(s,c.path,u),this.block(s,i.path,u)}}}async upload(e,n,r,o,s){let a=this.capFor(r,n.path,{limits:this.limitsByNs.get(r)});if(o.length>a)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:a,size:o.length});let i=await this.request(e,r,`/nodes/${n.id}/content`,"PUT",o,u=>{s.done=u},{"X-Content-Version":n.version??"create",...n.version&&n.file?{"X-Content-File":n.file}:{}}),l=await i.json(),c=i.headers.get("x-content-file");return c&&/^[A-Za-z0-9_-]{1,64}$/.test(c)&&(l.file=c),l}async shadow(e,n,r,o,s,a){let i=De(n,r.id),l=Me(o),c=Sa(o);c&&o.length>=gf&&await this.keepBase(e,l,o);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[i],delete e.stored.unconfirmed?.[i],e.stored.files[i]={id:r.id,path:r.path,version:r.version,hash:l,...r.file?{file:r.file}:{},...c&&o.length<gf?{base:o.toString("utf8")}:{},...a?{inode:a.inode,stat:a.key,statAt:a.at}:s?{inode:s.inode}:{}}}async seen(e,n,r){let o=Ze(e.roots,n),s=await Wt(He(o.root,...o.relative.split("/"))).catch(()=>null);if(!s?.isFile())return;let a=qn(s);return{key:$r(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===$r(n)&&mb(n)<=e.statAt-db}unchanged(e,n,r,o,s){let a=De(n,r.id),i=this.sameAsShadow(o,s)&&o.id===r.id&&o.path===s.path&&!r.busy&&!r.deleted&&r.version===o.version&&r.hash===o.hash&&Bo(o.file,r.file)&&!e.stored.unconfirmed?.[a]&&!e.stored.pendingUploads?.[a]&&!this.openJobs.has(n+"\0"+s.path);return i&&o.file===void 0&&r.file&&(o.file=r.file),i}hold(e,n){if(e.path.endsWith("/"+Nr)||n?.stat===$r(e))return!1;let r=e.mtime,o=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(o-r>=Ea(e.path))return!1;s={first:Math.min(o,r),last:r},this.dirty.set(e.path,s)}return this.dueAt(e.path,s)>o}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 o=ka(e),s=He(o,n);if(await Wt(s).then(()=>!0,()=>!1))return;await ya(o,{recursive:!0,mode:448});let a=s+".tmp-"+yt();try{await jr(a,r,{mode:384,flag:"wx"}),await ls(a,s)}finally{await Ur(a).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await Fr(He(ka(e),n.hash)).catch(o=>{if(o.code==="ENOENT")return null;throw o});return r&&Me(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(o=>o.hash)),r=ka(e);for(let o of await Lr(r).catch(()=>[]))n.has(o)||await Ur(He(r,o)).catch(()=>{})}async file(e,n,r,o,s){if(r.size>Gt)return this.noteTooLarge(e,o,r.path,r.size,Gt),"too-large";let a=v=>{let T=this.capFor(o,r.path,s);return v.length<=T?!1:(this.noteTooLarge(e,o,r.path,v.length,T),!0)},i=s.nodes.find(v=>v.kind==="file"&&!v.deleted&&v.path===r.path);if(!i){let v=Object.entries(e.stored.files).find(([T,z])=>T.startsWith(o+":")&&z.inode===r.inode&&z.path!==r.path)?.[1];if(v){let T=Ze(e.roots,v.path),z=await Wt(He(T.root,T.relative)).then(async O=>qn(O).inode!==r.inode||Vt(v.path)!==Vt(r.path)?!0:(await Lr(wn(r.physical))).includes(bn(v.path)),O=>O.code==="ENOENT"?!1:Promise.reject(O)),C=s.nodes.find(O=>O.id===v.id&&!O.deleted);if(!z&&C)try{if(C.path!==v.path)throw Error(`Concurrent file rename: ${r.path}`);let O=Vt(r.path),$=O?s.nodes.find(G=>G.path===O&&G.kind==="folder"&&!G.deleted)?.id:"";if(O&&!$)throw Error("Rename parent unavailable");let q=await this.operation(e,r.path,o,"rename",null,()=>this.json(e,o,`/nodes/${C.id}`,"PATCH",{name:bn(r.path),parentId:$,revision:C.revision}));Object.assign(C,q),v.path=r.path,i=C}catch(O){for(let $ of new Set([v.path,C.path,r.path]))this.block(o,$,O);throw O}}}let l=i?e.stored.files[De(o,i.id)]:Object.entries(e.stored.files).find(([v,T])=>v.startsWith(o+":")&&T.path===r.path)?.[1];if(!l&&i?.version&&o==="default"&&(l=await this.legacyBaseline(r.path,i)),i&&l&&this.unchanged(e,o,i,l,r))return;if(!i&&!l&&r.size>this.capFor(o,r.path,s))return this.noteTooLarge(e,o,r.path,r.size,this.capFor(o,r.path,s)),"too-large";if(this.hold(r,l))return"held";let c=Date.now(),u=await Gn(r),f=Me(u),g={key:$r(r),at:c,inode:r.inode};this.guard(e),this.settled(r.path,c);let p,m;if(!i){if((l?s.nodes.find(q=>q.id===l.id&&q.deleted):null)&&l&&(l.hash===f||l.memoryDeleted&&cs(r.path)&&f===Jn)){if(cs(r.path)){await this.clearDeletedMemory(e,o,r,l,u,f);return}let q=Mt("local",o,l.id),G=this.round;if(!G.restore.has(q)){G.plan.push({key:ff("local",o,l.id,f,r.path),ns:o,id:l.id,path:r.path,side:"local",e:r,hash:f});return}G.restoreHit.add(q),p=q,m=De(o,l.id)}if(a(u))return"too-large";let T=Vt(r.path),z=T?s.nodes.find(q=>q.path===T&&!q.deleted&&q.kind==="folder")?.id:"";if(T&&!z)throw Error("Parent folder is unavailable");let C=Object.entries(e.stored.pendingUploads??{}).find(([q,G])=>q.startsWith(o+":")&&G.path===r.path&&!s.nodes.some(I=>I.id===G.id))?.[1];for(let[q,G]of Object.entries(e.stored.pendingUploads??{}))q.startsWith(o+":")&&G.path===r.path&&s.nodes.some(I=>I.id===G.id&&I.deleted)&&delete e.stored.pendingUploads[q];let O=C?.id??yt(),$=De(o,O);(e.stored.pendingUploads??={})[$]={id:O,path:r.path},await this.persist(e),i=await this.json(e,o,"/nodes","POST",{id:O,parentId:z,name:bn(r.path),kind:"file"}),e.tombstones.get(o)?.delete(i.id),i.id!==O&&delete e.stored.pendingUploads[$],s.nodes.push(i),l=void 0}if(i.busy)return;let y=De(o,i.id);if(i.version&&this.awaitingBytes.delete(y),i.hash===f){await this.shadow(e,o,i,u,r,g);return}if(i.hash&&e.stored.unconfirmed?.[y]===i.hash&&(await this.shadow(e,o,i,await this.operation(e,r.path,o,"download",i.size??null,v=>this.download(e,i,o,v)),r),l=e.stored.files[y]),!i.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<ab)return}if(this.awaitingBytes.delete(y),!i.version||l&&i.version===l.version&&Bo(l.file,i.file)){if(a(u))return"too-large";(e.stored.unconfirmed??={})[y]=f,await this.persist(e);let v=await this.operation(e,r.path,o,"upload",u.length,T=>this.upload(e,i,o,u,T));Object.assign(i,v),await this.shadow(e,o,i,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,o,"download",i.size??null,v=>this.download(e,i,o,v)),E=b,h=!1;if(!l||l.hash!==f){let v=u.toString("utf8"),T=b.toString("utf8"),z=l?await this.readBase(e,l):null,C=Buffer.from(v).equals(u)&&Buffer.from(T).equals(b)?this.host.contentSync.merge(r.path,v,z,T):null;if(C&&!C.conflict&&z!==null&&lb(r.path)&&!Ti(z,v,C.content)&&(C=null),C?(E=Buffer.from(C.content),h=C.conflict):h=!0,h){await this.preserveConflict(e,r.path,u)&&(dt("content","conflicts"),this.tally("conflictCopies"));let O=this.job(e,r.path,o,"merge",u.length);O.state="conflict",O.error="Both versions preserved",O.finishedAt=Date.now()}if(!E.equals(b)){let O=await this.operation(e,r.path,o,"merge",E.length,$=>this.upload(e,i,o,E,$));Object.assign(i,O)}}let x=Date.now();await this.write(e,r.path,E,f),await this.shadow(e,o,i,E,r,await this.seen(e,r.path,x))}async preserveConflict(e,n,r){let o=Ze(e.roots,n),s=await ft(o.root,o.relative),a=bn(n),i=Me(r);for(let l of await Lr(wn(s))){if(l.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==a||!Xo(l))continue;let c=Vt(n)?Vt(n)+"/"+l:l,u=Ze(e.roots,c),f=await ft(u.root,u.relative),g=await Wt(f);if(g.isFile()&&g.size===r.length&&Me(await Fr(f))===i)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 o=1;;o++){let s=Bd(n,r,o),a=Ze(e.roots,s);if(!await Wt(He(a.root,...a.relative.split("/"))).then(()=>!0,i=>i.code==="ENOENT"?!1:Promise.reject(i)))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,o,s){let a=[],i=l=>l.length?Math.max(...l):null;for(let l of n){let c=l.kind==="folder"?Tr(l.path):null;if(!c||Go.has(c))continue;let u=`agents/${c}/`,f=this.route(u+"config.toml",r);if(!f||Object.entries(e.stored.files).some(([b,E])=>b.startsWith(f+":")&&E.path.startsWith(u)))continue;let g=(o.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 E=m.get(b.path);return!!E&&s.get(b.path)!==E.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:i(g.map(b=>b.mtime??0)),localMtime:i(p.map(b=>b.mtime))})}return a}async resolveAsks(e,n,r,o){for(let s of n){try{await this.resolveAsk(e,s,r[s.slug]??"merge",o)}catch(c){throw this.dropShadows(e,s.namespace,`agents/${s.slug}/`),await this.persist(e),Error(`agent_open_failed: ${ze(c)}`)}let a=`agents/${s.slug}`,i=o.rules.find(c=>c.source===a),l=$n(e.stored.config,a,Pu(o,a));i&&(l={...l,rules:l.rules.map(c=>c.source===a?{...i,target:c.target}:c)}),e.stored.config=en(l,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,o){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 i=await this.json(e,s);this.guard(e),ts(i,s);let l=new Map(i.nodes.filter(p=>!p.deleted&&!p.busy&&p.kind==="file"&&p.version&&p.path.startsWith(a)&&this.route(p.path,o)===s).map(p=>[p.path,p])),c=p=>p.endsWith("/"+Nr),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=Ze(e.roots,p);if(wf(He(y.root,y.relative)))continue;let b=await this.operation(e,p,s,"download",m.size??null,E=>this.download(e,m,s,E));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,o)===s&&p.size<=Gt).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 Gn(p),y=Me(m),b=l.get(p.path),E=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}/${E}`,m),b){let z=await this.operation(e,p.path,s,"download",b.size??null,C=>this.download(e,b,s,C));await this.shadow(e,s,b,z,p,await u(p.path,z,y))}else E==="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,z=>this.download(e,b,s,z)),x=s==="default"?await this.legacyBaseline(p.path,b):void 0;if(x?.hash===y){await this.shadow(e,s,b,h,p,await u(p.path,h,y));continue}let v=x?await this.readBase(e,x):null,T=Sa(m)&&Sa(h)?this.host.contentSync.merge(p.path,m.toString("utf8"),v,h.toString("utf8")):null;if(T&&!T.conflict){let z=Buffer.from(T.content);z.equals(m)||await this.write(e,p.path,z,y),await this.shadow(e,s,b,h)}else(b.mtime??0)>p.mtime?(await this.keep(e,`${g}/${E}`,m),await this.shadow(e,s,b,h,p,await u(p.path,h,y))):(await this.keep(e,`${g}/${E}`,h),await this.shadow(e,s,b,h))}await this.persist(e)}dropShadows(e,n,r){for(let[o,s]of Object.entries(e.stored.files))o.startsWith(n+":")&&s.path.startsWith(r)&&(delete e.stored.files[o],delete e.stored.unconfirmed?.[o])}async removedDir(e,n,r="agents"){let o=new Date,s=i=>String(i).padStart(2,"0"),a=`${o.getFullYear()}-${s(o.getMonth()+1)}-${s(o.getDate())} ${s(o.getHours())}${s(o.getMinutes())}`;for(let i=1;;i++){let l=`${r}/.removed/${n} ${a}${i>1?` ${i}`:""}`,c=Ze(e.roots,l);if(!await Wt(He(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 ha(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(kt(n.root,Hr(n.root,n.physical).split(Yn).join("/")),Me(Vn(n.physical))!==r)throw Error("Local file changed before replacing");ma(n.physical)})}async archiveAgent(e,n,r){let o=this.host.readCreds();if(!o.token)throw Error("not_signed_in");let s=await this.gatedFetch(e,o.cloudUrl,"/api/remotesync/agent-archive/agent",{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({namespace:n,slug:r,opId:yt(),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 o=Ze(r,n),s=await ft(o.root,o.relative);try{return await Wt(s),!1}catch(a){if(a.code==="ENOENT")return!0;throw a}}async missing(e,n,r,o,s){let a=e.stored.files[De(r,n.id)],i=e.stored.pendingUploads?.[De(r,n.id)];if(!n.deleted&&a?.inode&&this.blocked.has(r)&&o.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=Wn(this.scanned.unscanned,n.path)||!!a?.inode&&this.scanned.skippedInodes.has(a.inode),c=Li(n,a,!!i,l),u=this.round,f=()=>u.plan.some(y=>y.side==="local"&&y.ns===r&&y.id===n.id)||u.restore.has(Mt("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[De(r,n.id)],i&&delete e.stored.pendingUploads[De(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[De(r,n.id)],n.deleted=!0);return}let g;if(c==="delete"){if(!await this.absent(e,n.path))return;let y=Mt("cloud",r,n.id);if(!u.restore.has(y)){u.plan.push({key:ff("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>Gt){this.noteTooLarge(e,r,n.path,n.size,Gt),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,o=n.plan,s=new Set(o.map(E=>E.key)),a=new Set(o.map(E=>Mt(E.side,E.ns,E.id))),i=new Set((r?.confirmed??[]).filter(E=>s.has(E))),l=Date.now();this.deleteStamps=this.deleteStamps.filter(E=>l-E<ji);let c=o.filter(E=>!i.has(E.key)),u=Ui(c,n.tracked,{latched:!!r?.latched,recent:this.deleteStamps.length});u&&!r?.latched&&dt("content","massDeleteGuard");let f=E=>{let h=e.stored.files[De(E.ns,E.id)];return[E.path,...h?[h.path]:[]].some(v=>n.undecided.has(E.ns+"\0"+v)||Wn(this.scanned.unscanned,v))||!!h?.inode&&this.scanned.skippedInodes.has(h.inode)},g=(r?.pending??[]).filter(E=>!a.has(Mt(E.side,E.ns,E.id))&&f(E)),p=[...n.restore].filter(([E,h])=>!n.restoreDone.has(E)&&(n.restoreHit.has(E)||f(h))).map(([,E])=>E),m={latched:u||g.length>0,pending:[...u?c.map(pf):[],...g],...i.size?{confirmed:[...i]}:{},...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=[...o.filter(E=>i.has(E.key)),...u?[]:c];for(let E=0;E<b.length;E++){let h=b[E],x=i.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}:{}},x?{"X-Content-Delete-Confirmed":"1"}:void 0)),delete e.stored.files[De(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[De(h.ns,h.id)];x?m.confirmed=m.confirmed?.filter(v=>v!==h.key):this.deleteStamps.push(Date.now())}catch(v){if(v?.code!=="MASS_DELETE_BLOCKED"){this.error=ze(v);continue}m.latched||dt("content","massDeleteGuard"),m.latched=!0,m.pending=[...m.pending,...b.slice(E).filter(T=>T.side==="cloud").map(pf)];for(let T of b.slice(E+1))if(T.side==="local")try{await this.operation(e,T.path,T.ns,"delete",T.e.size,()=>this.trashFile(e,T.e,T.hash)),this.tally("deletesLocal"),delete e.stored.files[De(T.ns,T.id)]}catch(z){this.error=ze(z)}break}}y(),await this.persist(e)}async recoverTrash(e){for(let n of[...e.stored.trash??[]]){if(n.parentId){let c=(await as(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);c&&(n.path=c.path+"/"+bn(n.path))}let r=Ze(e.roots,n.path),o=await ft(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),i=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(i&&!an(i,a))throw Error("Sync recovery root changed; journal retained");let l=He(s,n.stage);await Wt(l).then(()=>!0,c=>c.code==="ENOENT"?!1:Promise.reject(c))&&await this.lock(e,o,()=>{if(kt(s,n.stage,!0),Me(Vn(l))!==n.hash)throw Error("Sync recovery content changed");kt(r.root,r.relative),Jw(wn(o),{recursive:!0});let c=wf(o)?o+` (sync recovery ${yt().slice(0,8)})`:o;try{Ww(l,c)}catch(u){if(u.code!=="EXDEV")throw u;if(Kw(l,c,Xw.COPYFILE_EXCL),Me(Vn(c))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}ma(l)},!0),e.stored.trash=e.stored.trash.filter(c=>c!==n)}}async clearDeletedMemory(e,n,r,o,s,a){o.memoryDeleted&&o.hash===Jn&&a===Jn||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!o.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)}o.memoryDeleted=!0,await this.persist(e);let i=Date.now();s.length&&await this.write(e,r.path,Buffer.alloc(0),a);let l=await this.seen(e,r.path,i);e.stored.files[De(n,o.id)]={...o,hash:Jn,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 o=await ft(n.root,Hr(n.root,n.physical).split(Yn).join("/")),s={path:n.path,stage:".forsion-sync-trash-"+yt(),hash:r},a=He(n.root,s.stage),i=await this.rootIdentity(e,n.root);s.stageRoot=n.root,s.stageDev=i.dev,s.stageIno=i.ino,s.stageIdentity=i;try{let l=JSON.parse(Vn(He(wn(o),".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,o,()=>{if(kt(n.root,Hr(n.root,o).split(Yn).join("/")),Me(Vn(o))!==r)throw Error("Local file changed before deletion");qw(o,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 wb(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))xr.test(n)&&Ru.includes(r)&&(e[n]=r);return e}function wf(t){try{return zw(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}Ka(Ol);function xE(t){Dl(t.contentSync?.withWriteLock?.bind(t.contentSync)),il(t),ti(t),Sf(t),sc(t),t.log("[forsion-extend] cloud account handlers registered"),zs(t)?Bs(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Ws(t)?Gs(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),li(t)?ci(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),Ai(t)?xi(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),Ri(t)?Di(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Yi(t)?wd(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),Yi(t)&&Ud(t)}export{bc as ACCOUNT_SEAM,mu as AMADEUS_SEAM,Hs as CONNECT_MAX_FILES,Pl as CONNECT_MAX_FILE_BYTES,$l as CONNECT_MAX_TOTAL_BYTES,bo as DIAGNOSTICS_VAULT,Wl as FORSION_CONNECT_LOCAL_SDK,ol as PAY_PERIODS,rl as PAY_TABS,Yl as PENZOR_MAX_FILE,$e as SYNC_IPC,bu as UNIT_SEAM,dr as UPLOAD_MAX_FILE,Er as UnitCapsReporter,kr as UnitHost,et as cloudJson,jl as collectProjectFiles,Co as conflictCopyPath,gg as conflictCopyVariant,Bl as connectMetaOf,wc as createAccountCloud,yu as createAmadeusCloud,wo as createPenzorRemote,Su as createUnitHub,yo as deviceHeader,qs as expectedPartsOf,Je as forsionAccountId,so as forsionRefreshToken,cr as forsionWhoami,li as hasAccountHost,Ai as hasAmadeusHost,zs as hasConnectHost,Ws as hasRemoteSyncHost,Ri as hasUnitHost,ql as makePreviewProxy,hc as multipartFrame,Ul as readConnectMeta,ci as registerAccount,xi as registerAmadeus,xE as registerCloud,Bs as registerConnect,Gs as registerPenzor,ti as registerPenzorTransfers,Di as registerUnit,ko as safeDownloadName,zl as scanSdkUsage,oo as shouldRefreshToken,Xs as speedOf,wu as streamWorthy,tu as stripConflictSuffix,mg as textFingerprint,Es as tokenAgeMs,el as tokenRemainingMs,Zs as uploadError,Hl 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: