@forsion/extend 0.10.13 → 0.10.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/SIGNATURE +6 -6
- package/dist/desktop.mjs +52 -52
- package/dist/main.js +73 -52
- package/manifest.json +1 -1
- package/package.json +1 -1
package/dist/desktop.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var ms=null;function Ha(t){ms=t}function Ee(){if(!ms)throw new Error("core host not set (call setCoreHost first)");return ms}var za=new TextEncoder,wf=new TextDecoder("utf-8",{ignoreBOM:!0}),nr=t=>za.encode(t),Ct=t=>wf.decode(t),ei=t=>typeof t=="string"?za.encode(t).length:t.length;function Ba(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function ti(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),n=>n.charCodeAt(0))}async function qa(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ve(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let i=r.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(i),l=>l.charCodeAt(0)),a=JSON.parse(new TextDecoder().decode(s)),o=a.userId??a.sub;return typeof o!="string"&&typeof o!="number"||!String(o).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(o)}`}catch{return null}}function ys(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Ct(ti(e)));return n&&typeof n=="object"?n:null}catch{return null}}function ws(t,e=Date.now()){let n=ys(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Wa(t,e=Date.now()){let n=ys(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var bf=36e5;function ni(t,e=Date.now()){return!!t&&ws(t,e)>=bf}async function ri(t,e,n=8e3,r){if(!t||!e)return null;let i=t.replace(/\/+$/,"");try{let s=await fetch(`${i}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!s.ok)return null;let a=await s.json().catch(()=>null),o=typeof a?.token=="string"?a.token:"";return o&&o!==e?o:null}catch{return null}}var rr=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,Sf=(t,e)=>new Promise((n,r)=>{let i=()=>{clearTimeout(s),r(new Error("Sign-in cancelled."))},s=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);e.aborted?i():e.addEventListener("abort",i,{once:!0})});function Ga(t,e){let n=f=>e.write(JSON.stringify(f,null,2)),r=()=>{let f;try{f=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(f===null)return[];try{let g=JSON.parse(f);return Array.isArray(g.accounts)?g.accounts.filter(p=>p&&typeof p.token=="string"&&p.id===Ve(p.cloudUrl,p.token)):null}catch{return null}},i=(f,g)=>{let p=Ve(f.cloudUrl||"",f.token||"");if(!p||!f.token||!f.cloudUrl)return;let m=r();if(!m)return;let y=m.find(h=>h.id===p),b=ys(f.token),_={...y,id:p,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:g?.username||y?.username||b?.username,nickname:g?.nickname||y?.nickname};JSON.stringify(y)!==JSON.stringify(_)&&n({version:1,accounts:[...m.filter(h=>h.id!==p),_]})},s=()=>{let f=t.readCreds();i(f);let g=Ve(f.cloudUrl,f.token);return(r()??[]).map(({token:p,...m})=>({...m,active:m.id===g}))},a=f=>{let g=r()?.find(p=>p.id===f);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},o=f=>{let g=Ve(f.cloudUrl||"",f.token||""),p=r();g&&p&&n({version:1,accounts:p.filter(m=>m.id!==g)})},l=null;return{rememberForsionAccount:i,forsionAccounts:s,savedForsionAccount:a,forgetForsionAccount:o,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(f,g,p)=>{if(l)throw new Error("A sign-in is already in progress.");if(!f)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;l=m;let y=()=>{if(m.signal.aborted||l!==m)throw new Error("Sign-in cancelled.")};try{let b=f.replace(/\/+$/,""),_;try{_=await fetch(`${b}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(D=>D.json())}catch(D){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${b}:${D?.message||D}`)}if(y(),!_?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let h=_.verification_uri_complete||`${_.verification_uri}?code=${_.user_code}`,T=new URL(`${b}/auth`);T.searchParams.set("logout","1"),T.searchParams.set("app","forsion-desktop"),T.searchParams.set("redirect",h);let v=T.toString();g?.({url:v,userCode:String(_.user_code||"")}),t.openExternal(v);let I=Date.now()+(_.expires_in||600)*1e3,E=(_.interval||2)*1e3;for(;Date.now()<I;){await Sf(E,m.signal),y();let D=null;try{D=await fetch(`${b}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:_.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),D.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let x=await D.json().catch(()=>({status:"pending"}));if(y(),x.status==="approved"&&x.token){let L={cloudUrl:b,token:x.token};return await p(L,y),y(),{token:x.token,cloudUrl:b}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===m&&(l=null)}},readAccounts:()=>r()??[]}}function Nt(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,i;try{r=new URL(n),i=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||i.origin!==r.origin||!i.pathname.startsWith("/api/")?null:i.toString()}function ir(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function Ze(t,e,n,r,i=6e4){let s=await(t.fetch??fetch)(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token&&!t.fetch?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(i)}),a=await s.json().catch(()=>({}));return{status:s.status,json:a}}var vf=50*1024*1024,kf=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function Ef(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[i,s]of Object.entries(e.fields)){if(!kf.has(i)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(i))return null;n.append(i,s)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>vf)return null;n.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:`${e.id?`/market/mine/${e.id}/update`:"/market/submit"}${e.dryRun===!0?"?dryRun=1":""}`,body:n}}function Va(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=Ef(n);if(!r)return{status:400,json:{error:"invalid_request"}};let i=await t.getCloud();if(!i.token)return{status:401,error:"not_signed_in"};let s=Nt(i.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let a=await ir(i,s,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,error:String(a?.message||a)}}})}async function bs(t){if(!t.token)return"";try{let e=await Ze(t,"POST","/api/auth/handoff",{},5e3);if(e.status===200&&typeof e.json?.code=="string"&&e.json.code)return`code=${encodeURIComponent(e.json.code)}`;if((e.status===404||e.status===405)&&!t.fetch)return`token=${encodeURIComponent(t.token)}`}catch{}return""}var Ya=["membership","credits","storefront"],Ja=["monthly","quarterly","yearly","autorenew","autorenew-quarterly"],_f=t=>t==="autorenew-quarterly"?"autorenew&cycle=quarterly":t,Cf=/^[A-Za-z0-9_-]{1,64}$/,Af=["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","agent-tool","backpack","other"],Ka=t=>Af.includes(t)?t:void 0,ii=(t,e)=>{let n=Ka(e);return n?{...t,entry:n}:t};function Xa(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(i,s)=>{if(!t.isTrustedSender(i))return n;let a=await t.getCloud(),o=a.base;if(!o)return{ok:!1};let l=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",c=await bs(a),u=`${o}/account${c?`?${c}`:""}${l}`;return a.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(i,...s)=>{if(!t.isTrustedSender(i))return n;let a=s.length>=4,[o,l,c]=s.slice(0,3).map(b=>a&&b===null?void 0:b),u=Ka(s[3]);if(o!==void 0&&!Ya.includes(o))return{ok:!1,error:"invalid_tab"};if(l!==void 0&&(typeof l!="string"||!Cf.test(l)))return{ok:!1,error:"invalid_plan"};if(c!==void 0&&!Ja.includes(c))return{ok:!1,error:"invalid_period"};let f=(o??"membership")==="membership"&&l?`&plan=${encodeURIComponent(l)}${c?`&period=${_f(c)}`:""}`:"",g=await t.getCloud(),p=g.base;if(!p)return{ok:!1};let m=await bs(g),y=`${p}/pay?tab=${o??"membership"}${f}${u?`&from=${u}`:""}${m?`&${m}`:""}&redirect=${encodeURIComponent(`${p}/account`)}`;return g.signal?.throwIfAborted(),await t.openExternal(y),{ok:!0}}),t.handle("auth:resumeAutoRenew",async i=>{if(!t.isTrustedSender(i))return n;let s=await t.getCloud(),a=s.base;if(!a)return{ok:!1};let o=await bs(s);if(!o.startsWith("code="))return{ok:!1,error:"handoff_unavailable"};let l=`${a}/pay?tab=membership&action=resume_autorenew&${o}&redirect=${encodeURIComponent(`${a}/account`)}`;return s.signal?.throwIfAborted(),await t.openExternal(l),{ok:!0}}),t.handle("profile:publicOrigin",async i=>{if(!t.isTrustedSender(i))return n;let{base:s}=await t.getCloud();if(!s)return{ok:!1};try{let a=await fetch(`${s}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});a.body?.cancel().catch(()=>{});let o=a.status>=300&&a.status<400?a.headers.get("location"):null;return o&&/^https?:\/\//i.test(o)?{ok:!0,origin:new URL(o).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async i=>{if(!t.isTrustedSender(i))return e;let s=await r();if(!s.token)return{status:401,json:null};try{return await Ze(s,"GET","/api/token-quota/my",void 0,15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:useResetCard",async(i,...s)=>{if(!t.isTrustedSender(i))return e;let a=await r();if(!a.token)return{status:401,json:null};let o=s[0];if(o!==void 0&&o!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${String(o)}`}};let l=o??"both";try{return await Ze(a,"POST","/api/token-quota/reset-card/use",ii({type:l},s[1]),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(!Number.isInteger(s)||s<1||s>100)return{status:400,json:{error:"invalid_percent"}};try{return await Ze(o,"POST","/api/token-quota/background/convert",ii({percent:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:pointsAutoDeduct",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ze(o,"POST","/api/token-quota/auto-deduct",ii({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgAutoMain",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ze(o,"POST","/api/token-quota/background/auto-main",ii({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("feedback:submit",async(i,s)=>{if(!t.isTrustedSender(i))return n;let a=await t.getCloud();if(!a.base||!a.token)return{ok:!1,error:"not-logged-in"};if(s?.expectedAccountId!==void 0){let u=s.expectedAccountId;if(typeof u!="string"||!u||Ve(a.base,a.token)!==u)return{ok:!1,error:"account-changed"}}let o=(s?.description||"").trim();if(!o)return{ok:!1,error:"empty"};if(o.length>1e4)return{ok:!1,error:"description-too-long"};let l=[],c=!1;if(s?.sessionLogJson){let u=nr(s.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};l.push({filename:s.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:Ba(u)})}try{let u=await ir(a,`${a.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:o,attachments:l}),signal:AbortSignal.timeout(2e4)});if(!u.ok){let g=`HTTP ${u.status}`;try{g=(await u.json())?.detail||g}catch{}return{ok:!1,error:g}}return{ok:!0,id:(await u.json().catch(()=>({})))?.id??null,attachmentSkipped:c}}catch(u){return{ok:!1,error:u?.message||String(u)}}}),t.handle("cloud:fetch",async(i,s)=>{if(!t.isTrustedSender(i))return{status:0,error:"untrusted"};let a=s??{},o=typeof a.path=="string"?a.path:"",l=a.projectSource===void 0?null:a.projectSource;if(l!==null&&(typeof l!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(l)))return{status:0,error:"bad_project_source"};let c=Math.min(12e4,Math.max(1e3,Number(a.timeoutMs)||15e3)),u=typeof a.method=="string"?a.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(u))return{status:0,error:"bad_method"};if(!o.startsWith("/"))return{status:0,error:"bad_path"};let f=await t.getCloud();if(!String(f.base||""))return{status:0,error:"no_cloud_url"};let g=Nt(f.base,o);if(!g)return{status:0,error:"bad_path"};if(!f.token)return{status:401,error:"not_signed_in"};let p=a.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,y=setTimeout(()=>m.abort(),c);try{let b=await ir(f,g,{method:u,headers:{...p?{"Content-Type":"application/json"}:{},...l?{"X-Project-Source":l}:{}},body:p?JSON.stringify(a.body):void 0,signal:m.signal});return{status:b.status,json:await b.json().catch(()=>null)}}catch(b){return{status:0,error:String(b?.message||b)}}finally{clearTimeout(y)}}),Va(t)}import{createHash as vl}from"node:crypto";import{existsSync as Ep,promises as _p,readFileSync as Cp,renameSync as Ap,statSync as xp}from"node:fs";import Tp from"node:path";import{setTimeout as Ip}from"node:timers/promises";import{EventEmitter as tp}from"node:events";import{stat as np}from"node:fs";import{readdir as rp,stat as ip}from"node:fs/promises";import*as fe from"node:path";import{lstat as Za,readdir as xf,realpath as Tf,stat as If}from"node:fs/promises";import{join as Rf,resolve as Df,sep as Qa}from"node:path";import{Readable as Of}from"node:stream";var st={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},vn={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:st.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(vn);var rl="READDIRP_RECURSIVE_ERROR",Mf=new Set(["ENOENT","EPERM","EACCES","ELOOP",rl]),el=[st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE],Nf=new Set([st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE]),Pf=new Set([st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE]),$f=t=>Mf.has(t.code),jf=process.platform==="win32",tl=t=>!0,nl=t=>{if(t===void 0)return tl;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return tl},Ss=class extends Of{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??vn.highWaterMark});let n={...vn,...e},r=n.root??vn.root,i=n.type??vn.type;this._fileFilter=nl(n.fileFilter),this._directoryFilter=nl(n.directoryFilter);let s=n.lstat?Za:If;jf?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:vn.depth,this._wantsDir=Nf.has(i),this._wantsFile=Pf.has(i),this._wantsEverything=i===st.EVERYTHING_TYPE,this._root=Df(r),this._relStart=this._root.endsWith(Qa)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let a={path:this._root,depth:1};a.pending=this._exploreDir(this._root,1),this.parents=[a],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:i,depth:s}=n,a=r.splice(0,e).map(l=>this._formatEntry(l,i)),o=this._isDirent?a:await Promise.all(a);for(let l of o){if(!l)continue;if(this.destroyed)return;let c=this._getEntryType(l);typeof c!="string"&&(c=await c),c==="directory"&&this._directoryFilter(l)?(s<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:s+1}),this._wantsDir&&(this.push(l),e--)):(c==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}let s=i.pending??this._exploreDir(i.path,i.depth),a=this.parents[this.parents.length-1];if(a&&!a.pending&&(a.pending=this._exploreDir(a.path,a.depth)),this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await xf(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,i=Rf(n,r),s={path:i.slice(this._relStart),fullPath:i,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(i).then(a=>(s.stats=a,s),a=>{this._onError(a)})}_onError(e){$f(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await Tf(n),i=await Za(r);if(i.isFile())return"file";if(i.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===Qa){let a=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return a.code=rl,this._onError(a),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function il(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=st.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!el.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${el.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new Ss(r)}import{watch as Lf,unwatchFile as sl,watchFile as Ff}from"node:fs";import{realpath as vs,lstat as Uf,open as Hf,stat as al}from"node:fs/promises";import{type as zf}from"node:os";import*as _e from"node:path";var Bf="data",_s="end",ll="close",ci=()=>{};var ui=process.platform,Cs=ui==="win32",qf=ui==="darwin",Wf=ui==="linux",Gf=ui==="freebsd",cl=zf()==="OS400",Te={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},wt=Te,Vf="watch",Yf={lstat:Uf,stat:al},on="listeners",si="errHandlers",kn="rawEmitters",Jf=[on,si,kn],Kf=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Xf=t=>Kf.has(_e.extname(t).slice(1).toLowerCase()),Es=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},sr=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},Zf=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},or=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ul=t=>t instanceof Set?t.size===0:!t,oi=new Map;function ol(t,e,n,r,i){let s=(a,o)=>{n(t),i(a,o,{watchedPath:t}),o&&t!==o&&ai(_e.resolve(t,o),on,_e.join(t,o))};try{return Lf(t,{persistent:e.persistent},s)}catch(a){r(a);return}}var ai=(t,e,n,r,i)=>{let s=oi.get(t);s&&Es(s[e],a=>{a(n,r,i)})},Qf=(t,e,n,r)=>{let{listener:i,errHandler:s,rawEmitter:a}=r,o=oi.get(e),l;if(!n.persistent)return l=ol(t,n,i,s,a),l?l.close.bind(l):void 0;if(o)sr(o,on,i),sr(o,si,s),sr(o,kn,a);else{if(l=ol(t,n,ai.bind(null,e,on),s,ai.bind(null,e,kn)),!l)return;l.on(wt.ERROR,async c=>{let u=ai.bind(null,e,si);if(o&&(o.watcherUnusable=!0),Cs&&c.code==="EPERM")try{await(await Hf(t,"r")).close(),u(c)}catch{}else u(c)}),o={listeners:i,errHandlers:s,rawEmitters:a,watcher:l},oi.set(e,o)}return()=>{or(o,on,i),or(o,si,s),or(o,kn,a),ul(o.listeners)&&(o.watcher.close(),oi.delete(e),Jf.forEach(Zf(o)),o.watcher=void 0,Object.freeze(o))}},ks=new Map,ep=(t,e,n,r)=>{let{listener:i,rawEmitter:s}=r,a=ks.get(e),o=a&&a.options;return o&&(o.persistent<n.persistent||o.interval>n.interval)&&(sl(e),a=void 0),a?(sr(a,on,i),sr(a,kn,s)):(a={listeners:i,rawEmitters:s,options:n,watcher:Ff(e,n,(l,c)=>{Es(a.rawEmitters,f=>{f(wt.CHANGE,e,{curr:l,prev:c})});let u=l.mtimeMs;(l.size!==c.size||u>c.mtimeMs||u===0)&&Es(a.listeners,f=>f(t,l))})},ks.set(e,a)),()=>{or(a,on,i),or(a,kn,s),ul(a.listeners)&&(ks.delete(e),sl(e),a.options=a.watcher=void 0,Object.freeze(a))}},li=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,i=_e.dirname(e),s=_e.basename(e);this.fsw._getWatchedDir(i).add(s);let o=_e.resolve(e),l={persistent:r.persistent};n||(n=ci);let c;if(r.usePolling){let u=r.interval!==r.binaryInterval;l.interval=u&&Xf(s)?r.binaryInterval:r.interval,c=ep(e,o,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else c=Qf(e,o,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(e,n,r){if(this.fsw.closed)return;let i=_e.dirname(e),s=_e.basename(e),a=this.fsw._getWatchedDir(i),o=n;if(a.has(s))return;let l=async(u,f)=>{if(this.fsw._throttle(Vf,e,5)){if(!f||f.mtimeMs===0)try{let g=await al(e);if(this.fsw.closed)return;let p=g.atimeMs,m=g.mtimeMs;if((!p||p<=m||m!==o.mtimeMs)&&this.fsw._emit(wt.CHANGE,e,g),(qf||Wf||Gf)&&o.ino!==g.ino){this.fsw._closeFile(u),o=g;let y=this._watchWithNodeFs(e,l);y&&this.fsw._addPathCloser(u,y)}else o=g}catch{this.fsw._remove(i,s)}else if(a.has(s)){let g=f.atimeMs,p=f.mtimeMs;(!g||g<=p||p!==o.mtimeMs)&&this.fsw._emit(wt.CHANGE,e,f),o=f}}},c=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(wt.ADD,e,0))return;this.fsw._emit(wt.ADD,e,n)}return c}async _handleSymlink(e,n,r,i){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await vs(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(s)!==o&&(this.fsw._symlinkPaths.set(s,o),this.fsw._emit(wt.CHANGE,r,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(s,o),this.fsw._emit(wt.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,i,s,a,o){e=_e.join(e,"");let l=i?`${e}:${i}`:e;if(o=this.fsw._throttle("readdir",l,1e3),!o)return;let c=this.fsw._getWatchedDir(r.path),u=new Set,f=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(f)return f.on(Bf,async g=>{if(this.fsw.closed){f=void 0;return}let p=g.path,m=_e.join(e,p);if(u.add(p),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,m,p))){if(this.fsw.closed){f=void 0;return}(p===i||!i&&!c.has(p))&&(this.fsw._incrReadyCount(),m=_e.join(s,_e.relative(s,m)),this._addToNodeFs(m,n,r,a+1))}}).on(wt.ERROR,this._boundHandleError),new Promise((g,p)=>{if(!f)return p();f.once(_s,()=>{if(this.fsw.closed){f=void 0;return}let m=o?o.clear():!1;g(void 0),c.getChildren().filter(y=>y!==e&&!u.has(y)).forEach(y=>{this.fsw._remove(e,y)}),f=void 0,m&&this._handleRead(e,!1,r,i,s,a,o)})})}async _handleDir(e,n,r,i,s,a,o){let l=this.fsw._getWatchedDir(_e.dirname(e)),c=l.has(_e.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!c&&this.fsw._emit(wt.ADD_DIR,e,n),l.add(_e.basename(e)),this.fsw._getWatchedDir(e);let u,f,g=this.fsw.options.depth;if((g==null||i<=g)&&!this.fsw._symlinkPaths.has(o)){if(!s&&(await this._handleRead(e,r,a,s,e,i,u),this.fsw.closed))return;f=this._watchWithNodeFs(e,(p,m)=>{m&&m.mtimeMs===0||this._handleRead(p,!1,a,s,e,i,u)})}return f}async _addToNodeFs(e,n,r,i,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);r&&(o.filterPath=l=>r.filterPath(l),o.filterDir=l=>r.filterDir(l));try{let l=await Yf[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,l))return a(),!1;let c=this.fsw.options.followSymlinks,u;if(l.isDirectory()){let f=_e.resolve(e),g=c?await vs(e):e;if(this.fsw.closed||(u=await this._handleDir(o.watchPath,l,n,i,s,o,g),this.fsw.closed))return;f!==g&&g!==void 0&&this.fsw._symlinkPaths.set(f,g)}else if(l.isSymbolicLink()){let f=c?await vs(e):e;if(this.fsw.closed)return;let g=_e.dirname(o.watchPath);if(this.fsw._getWatchedDir(g).add(o.watchPath),this.fsw._emit(wt.ADD,o.watchPath,l),u=await this._handleDir(g,l,n,i,e,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(_e.resolve(e),f)}else u=this._handleFile(o.watchPath,l,n);return a(),u&&this.fsw._addPathCloser(e,u),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var As="/",sp="//",gl=".",op="..",ap="string",lp=/\\/g,ml=/\/\//g,cp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,up=/^\.[/\\]/;function di(t){return Array.isArray(t)?t:[t]}var xs=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function dp(t){return typeof t=="function"?t:typeof t=="string"?e=>t===e:t instanceof RegExp?e=>t.test(e):typeof t=="object"&&t!==null?e=>{if(t.path===e)return!0;if(t.recursive){let n=fe.relative(t.path,e);return n?!n.startsWith("..")&&!fe.isAbsolute(n):!1}return!1}:()=>!1}function fp(t){if(typeof t!="string")throw new Error("string expected");t=fe.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ml,"/"),e&&(t="/"+t),t}function dl(t,e,n){let r=fp(e);for(let i=0;i<t.length;i++){let s=t[i];if(s(r,n))return!0}return!1}function pp(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=di(t).map(i=>dp(i));return e==null?(i,s)=>dl(r,i,s):dl(r,e)}var fl=t=>{let e=di(t).flat();if(!e.every(n=>typeof n===ap))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(yl)},pl=t=>{let e=t.replace(lp,As),n=!1;return e.startsWith(sp)&&(n=!0),e=e.replace(ml,As),n&&(e=As+e),e},yl=t=>pl(fe.normalize(pl(t))),hl=(t="")=>e=>typeof e=="string"?yl(fe.isAbsolute(e)?e:fe.join(t,e)):e,hp=(t,e)=>fe.isAbsolute(t)?t:fe.join(e,t),gp=Object.freeze(new Set),Ts=class{path;_removeWatcher;items;constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==gl&&e!==op&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await rp(r)}catch{this._removeWatcher&&this._removeWatcher(fe.dirname(r),fe.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=ci,this.items=gp,Object.freeze(this)}},mp="stat",yp="lstat",Is=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let i=e;this.path=e=e.replace(up,""),this.watchPath=i,this.fullWatchPath=fe.resolve(i),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?mp:yp}entryPath(e){return fe.join(this.watchPath,fe.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},fi=class extends tp{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?di(e.ignored):di([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};cl&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let l=s.toLowerCase();l==="false"||l==="0"?i.usePolling=!1:l==="true"||l==="1"?i.usePolling=!0:i.usePolling=!!l}let a=process.env.CHOKIDAR_INTERVAL;a&&(i.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=ci,this._readyEmitted=!0,process.nextTick(()=>this.emit(Te.READY)))},this._emitRaw=(...l)=>this.emit(Te.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new li(this),Object.freeze(i)}_addIgnoredPath(e){if(xs(e)){for(let n of this._ignoredPaths)if(xs(n)&&n.path===e.path&&n.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let n of this._ignoredPaths)xs(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let s=fl(e);return i&&(s=s.map(a=>hp(a,i))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!r,void 0,0,n);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(fe.dirname(o),fe.basename(n||o))})}),this}unwatch(e){if(this.closed)return this;let n=fl(e),{cwd:r}=this.options;return n.forEach(i=>{!fe.isAbsolute(i)&&!this._closers.has(i)&&(r&&(i=fe.join(r,i)),i=fe.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let i=r();i instanceof Promise&&e.push(i)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let s=(this.options.cwd?fe.relative(this.options.cwd,r):r)||gl;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==Te.ERROR&&this.emit(Te.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let i=this.options;Cs&&(n=fe.normalize(n)),i.cwd&&(n=fe.relative(i.cwd,n));let s=[n];r!=null&&s.push(r);let a=i.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(n)))return o.lastChange=new Date,this;if(i.atomic){if(e===Te.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((l,c)=>{this.emit(...l),this.emit(Te.ALL,...l),this._pendingUnlinks.delete(c)})},typeof i.atomic=="number"?i.atomic:100),this;e===Te.ADD&&this._pendingUnlinks.has(n)&&(e=Te.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(e===Te.ADD||e===Te.CHANGE)&&this._readyEmitted){let l=(c,u)=>{c?(e=Te.ERROR,s[0]=c,this.emitWithAll(e,s)):u&&(s.length>1?s[1]=u:s.push(u),this.emitWithAll(e,s))};return this._awaitWriteFinish(n,a.stabilityThreshold,e,l),this}if(e===Te.CHANGE&&!this._throttle(Te.CHANGE,n,50))return this;if(i.alwaysStat&&r===void 0&&(e===Te.ADD||e===Te.ADD_DIR||e===Te.CHANGE)){let l=i.cwd?fe.join(i.cwd,n):n,c;try{c=await ip(l)}catch{}if(!c||this.closed)return;s.push(c)}return this.emitWithAll(e,s),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(Te.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let s=i.get(n);if(s)return s.count++,!1;let a,o=()=>{let c=i.get(n),u=c?c.count:0;return i.delete(n),clearTimeout(a),c&&clearTimeout(c.timeoutObject),u};a=setTimeout(o,r);let l={timeoutObject:a,clear:o,count:0};return i.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,i){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,o,l=e;this.options.cwd&&!fe.isAbsolute(e)&&(l=fe.join(this.options.cwd,e));let c=new Date,u=this._pendingWrites;function f(g){np(l,(p,m)=>{if(p||!u.has(e)){p&&p.code!=="ENOENT"&&i(p);return}let y=Number(new Date);g&&m.size!==g.size&&(u.get(e).lastChange=y);let b=u.get(e);y-b.lastChange>=n?(u.delete(e),i(void 0,m)):o=setTimeout(f,a,m)})}u.has(e)||(u.set(e,{lastChange:c,cancelWait:()=>(u.delete(e),clearTimeout(o),r)}),o=setTimeout(f,a))}_isIgnored(e,n){if(this.options.atomic&&cp.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(hl(r)),o=[...[...this._ignoredPaths].map(hl(r)),...s];this._userIgnored=pp(o,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Is(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=fe.resolve(e);return this._watched.has(n)||this._watched.set(n,new Ts(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let i=fe.join(e,n),s=fe.resolve(i);if(r=r??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(i).getChildren().forEach(g=>this._remove(i,g));let l=this._getWatchedDir(e),c=l.has(n);l.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=i;if(this.options.cwd&&(u=fe.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Te.ADD)return;this._watched.delete(i),this._watched.delete(s);let f=r?Te.UNLINK_DIR:Te.UNLINK;c&&!this._isIgnored(i)&&this._emit(f,i),this._closePath(i)}_closePath(e){this._closeFile(e);let n=fe.dirname(e);this._getWatchedDir(n).remove(fe.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:Te.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},i=il(e,r);return this._streams.add(i),i.once(ll,()=>{i=void 0}),i.once(_s,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function Rs(t,e={}){let n=new fi(e);return n.add(t),n}var wl={watch:Rs,FSWatcher:fi};import{execFile as wp}from"node:child_process";import{stat as bl}from"node:fs/promises";import{resolve as bp}from"node:path";import{promisify as Sp}from"node:util";function Vt(t){if(!t||typeof t!="object")return!1;let e=t;return Number.isInteger(e.dev)&&e.dev>=0&&Number.isInteger(e.ino)&&e.ino>0&&(e.birthtimeMs===void 0||Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0)&&(e.volumeId===void 0||typeof e.volumeId=="string"&&e.volumeId.length>0)}function an(t,e){return t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)&&(t.volumeId===void 0?t.dev===e.dev:t.volumeId===e.volumeId)}function bt(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Sl=Sp(wp);function vp(t){let e=t.match(/<key>VolumeUUID<\/key>\s*<string>([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})<\/string>/i)?.[1];return e?`darwin:${e.toLowerCase()}`:void 0}async function kp(t){if(process.platform!=="darwin")return;let{stdout:e}=await Sl("/bin/df",["-P",bp(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
|
|
2
|
-
`).slice(1).map(
|
|
3
|
-
`,"utf8")}catch{}}var
|
|
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})}
|
|
4
4
|
|
|
5
|
-
`)}catch{}
|
|
5
|
+
`)}catch{}o.end()}else i(502,y)}finally{clearTimeout(p)}}}var Wl=`
|
|
6
6
|
(function () {
|
|
7
7
|
'use strict';
|
|
8
8
|
if (window.forsion) return;
|
|
@@ -196,69 +196,69 @@ var ms=null;function Ha(t){ms=t}function Ee(){if(!ms)throw new Error("core host
|
|
|
196
196
|
ai: { chat: chat, agent: agentRun, generateImage: generateImage, status: aiStatus }
|
|
197
197
|
};
|
|
198
198
|
})();
|
|
199
|
-
`,Wp=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function Gp(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function js(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Ls(t){t.setPreviewHooks({sdkJs:$l,proxy:Pl(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Nl(n):{}),t.handle("connect:list",async()=>{let e=await t.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:n,json:r}=await Ze(e,"GET","/api/connect/apps");return n===401||n===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:n!==200?{ok:!1,code:"error",detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,...r}}catch(n){return{ok:!1,code:"error",detail:n?.message||String(n)}}}),t.handle("connect:publish",async(e,n)=>{if(!n||typeof n.dir!="string"||!n.dir||!n.name||!n.slug||!n.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r;try{r=_l(n.dir);let s=null;try{s=_l(t.projectsRoot())}catch{}if(!(!!s&&(r===s||r.startsWith(s+jp)))&&!Gp(t,r))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let i=await t.getCloud();if(!i.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:s,totalBytes:a}=Il(r,Wp(t));if(!s.some(u=>u.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:o,json:l}=await Ze(i,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:s},3e5);if(o===401)return{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"};if(o!==200)return{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${o}`,used:l?.used,limit:l?.limit};Ol(r,{slug:String(l.slug)});let c=typeof l.publicUrl=="string"&&/^https?:\/\//i.test(l.publicUrl)?l.publicUrl:`${i.base}${l.url}`;return{ok:!0,slug:l.slug,handle:l.handle,url:c,totalBytes:a}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:unpublish",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return i===401||i===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingApply",async(e,n)=>{if(!n||typeof n.slug!="string"||!n.slug||typeof n.summary!="string"||!n.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200?{ok:!1,code:s?.code||"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0,status:s.status}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await Ze(e,"GET","/api/connect/store");return n!==200?{ok:!1,detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,items:Array.isArray(r.items)?r.items:[]}}catch(n){return{ok:!1,detail:n?.message||String(n)}}}),t.log("[forsion-extend] connect handlers registered")}import{createHash as Vp}from"node:crypto";import{hostname as Yp}from"node:os";async function lr(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let r=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let i=await r.json();if(!i)return{status:"offline"};let s=i.avatar||i.avatarUrl||i.avatar_url||void 0;return s&&/^\/(?!\/)/.test(s)&&(s=n+s),{status:"ok",user:{username:i.username||i.nickname||void 0,nickname:i.nickname||void 0,avatar:s,membershipTier:i.membershipTier||i.membership_tier||void 0}}}catch{return{status:"offline"}}}var jl=t=>`${t.seq}:${t.hash}`,hi=(t=Yp())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},Jp=t=>Vp("sha256").update(t).digest("hex");function Fs(t){if(t===null)return{baseSeq:0,baseHash:null};if(typeof t!="string")return;let e=t.indexOf(":"),n=Number(e===-1?t:t.slice(0,e));if(!Number.isInteger(n)||n<=0)return;let r=e===-1?"":t.slice(e+1);return{baseSeq:n,baseHash:/^[0-9a-f]{64}$/.test(r)?r:null}}function gi(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=hi(),i=async(s,a)=>{let o=t.getToken();if(!o)throw new Error("penzor-not-logged-in");let l=await fetch(s,{...a,headers:{...a.headers,Authorization:`Bearer ${o}`}});if(l.status===409){let c=await l.json().catch(()=>({}));throw new Error(`cas-conflict ${String(c.code??"")}: seq=${String(c.seq??"?")}`)}if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`penzor ${a.method??"GET"} ${l.status}: ${c.slice(0,200)}`)}return l};return{kind:"penzor",async walk(s){let a=await i(n("/manifest"),{method:"GET",signal:s}),{files:o}=await a.json();return o.map(l=>({key:l.path,size:l.size,mtimeMs:l.mtimeMs,id:jl(l),hash:l.hash}))},async readFile(s,a){let l=await(await i(n(`/file?path=${encodeURIComponent(s)}`),{method:"GET",signal:a})).json(),c=await fetch(l.url,{signal:a});if(!c.ok)throw new Error(`penzor blob GET ${c.status}: ${s}`);let u=Buffer.from(await c.arrayBuffer());if(Jp(u)!==l.hash)throw new Error(`penzor hash mismatch: ${s}`);return u},async writeFile(s,a,o,l,c){let u=Fs(c),f=new URLSearchParams({path:s,mtimeMs:String(Math.floor(o)||0)});u&&(f.set("baseSeq",String(u.baseSeq)),u.baseHash&&f.set("baseHash",u.baseHash));let p=await(await i(n(`/file?${f.toString()}`),{method:"PUT",body:new Uint8Array(a),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:l})).json();return{key:s,size:p.size,mtimeMs:p.mtimeMs,id:jl(p)}},async rm(s,a,o){let l=Fs(o),c=new URLSearchParams({path:s});l&&l.baseSeq>0&&(c.set("baseSeq",String(l.baseSeq)),l.baseHash&&c.set("baseHash",l.baseHash)),await i(n(`/file?${c.toString()}`),{method:"DELETE",signal:a})},async check(){try{return await i(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var mi="forsion-diagnostics",Fl=50*1024*1024,Ll=new Map;async function Kp(t,e){let n=Ll.get(e);if(n)return{id:n};let r=await lr(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let i=r.user?.username?.trim();return i?(Ll.set(e,i),{id:i}):{error:"penzor-auth-unverified"}}var Us=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function Hs(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,i=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(i)||i===mi)return{error:"penzor-bad-vault"};let s=await Kp(n.cloudUrl,n.token);if("error"in s)return s;let a=n.token;return{remote:gi({baseUrl:n.cloudUrl,vault:i,getToken:()=>a}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${s.id}|${i}`,maxFileBytes:Fl}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as Zp}from"node:fs";import{access as Qp,link as eh,lstat as th,mkdir as nh,open as rh,readdir as ih,rename as sh,stat as Gl,unlink as qs}from"node:fs/promises";import{request as oh}from"node:http";import{request as ah}from"node:https";import{homedir as lh}from"node:os";import{basename as Vl,extname as ch,isAbsolute as uh,join as ur}from"node:path";import{randomUUID as wi}from"node:crypto";var cr=52428800;var Ul=["bytes","signed","text"],Hl=/^[A-Za-z0-9_-]{1,64}$/,zl=/^[a-z0-9][a-z0-9-]{0,63}$/;function yi(t){if(typeof t!="string")return null;let n=(t.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f<>:"|?*]/g,"").trim().slice(0,200);return n&&n!=="."&&n!==".."?n:null}var Xp={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".svg":"image/svg+xml",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Bl(t){let e=t.lastIndexOf(".");return Xp[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function ql(t,e,n,r){let i=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",s=encodeURIComponent(n).replace(/['()*]/g,o=>`%${o.charCodeAt(0).toString(16).toUpperCase()}`),a="";for(let[o,l]of Object.entries(e))a+=`--${t}\r
|
|
200
|
-
Content-Disposition: form-data; name="${
|
|
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
|
|
201
201
|
\r
|
|
202
202
|
${l}\r
|
|
203
203
|
`;return a+=`--${t}\r
|
|
204
|
-
Content-Disposition: form-data; name="file"; filename="${
|
|
204
|
+
Content-Disposition: form-data; name="file"; filename="${o}"; filename*=UTF-8''${s}\r
|
|
205
205
|
Content-Type: ${r}\r
|
|
206
206
|
\r
|
|
207
207
|
`,{head:a,tail:`\r
|
|
208
208
|
--${t}--\r
|
|
209
|
-
`}}function zs(t,e){let n=t.filter(([o])=>e-o<=3e3);if(n.length<2)return 0;let[r,i]=n[0],[s,a]=n[n.length-1];return s>r?Math.max(0,(a-i)/(s-r)*1e3):0}function Bs(t,e){let n=e??{};return t===401?"not_signed_in":n.code==="STORAGE_QUOTA_EXCEEDED"?"quota":n.code==="STORAGE_BUSY"||n.code==="STORAGE_RECONCILIATION_REQUIRED"?"storage_unavailable":n.code==="FILE_TOO_LARGE"||t===413?"too_large":typeof n.detail=="string"&&/quota exceeded/i.test(n.detail)?"quota":n.code==="STORAGE_NOT_CONFIGURED"?"storage_unavailable":`http_${t}`}var dh=3,Ws=6e4,fh=200,ph=Ul;function Yl(t,e,n,r){let{head:i,tail:s}=ql(t,e,n,r);return{head:Buffer.from(i,"utf8"),tail:Buffer.from(s,"utf8")}}function hh(t,e,n,r,i,s,a,o){return new Promise((l,c)=>{let u=new URL(t),f=(u.protocol==="https:"?ah:oh)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+i+s.length)}},p=>{let m=[];p.on("data",y=>m.push(y)),p.on("end",()=>{let y=null;try{y=JSON.parse(Buffer.concat(m).toString("utf8"))}catch{}l({status:p.statusCode??0,body:y})}),p.on("error",c)}),g=()=>{f.destroy(new Error("aborted"))};if(o.aborted)return g();o.addEventListener("abort",g,{once:!0}),f.setTimeout(Ws,()=>f.destroy(new Error("timeout"))),f.on("error",p=>{o.removeEventListener("abort",g),c(p)}),(async()=>{try{f.write(n);let p=0;for await(let m of Zp(r)){let y=m;if(p+=y.length,p>i)throw new Error("changed");f.write(y)||await new Promise(b=>f.once("drain",b)),a(p)}if(p!==i)throw new Error("changed");f.end(s)}catch(p){f.destroy(p)}})()})}function Gs(t,e={}){let n=e.downloadsDir??(()=>ur(lh(),"Downloads")),r=e.post??hh,i=e.now??Date.now,s=[],a=new Map,o=Promise.resolve(),l=async()=>{let E=await t.getCloud(),D=typeof t.accountId=="function"?t.accountId():null;return{...E,account:D||`${E.base}|${E.token}`}},c=E=>{let{account:D,attempt:x,relDir:L,abort:V,samples:H,dl:N,...Y}=E;return{...Y,speed:E.state==="active"?zs(H,i()):0}},u=(E,D,x=null)=>{E.state=D,E.error=x,E.abort=null,E.finishedAt=i(),E.samples=[];let L=s.filter(V=>V.state==="done"||V.state==="canceled");for(let V of L.slice(0,Math.max(0,L.length-fh)))s.splice(s.indexOf(V),1);f()};function f(){for(let E of["up","down"]){let D=s.filter(x=>x.kind===E&&x.state==="active").length;for(let x of s){if(D>=dh)break;if(x.kind!==E||x.state!=="queued")continue;D++,x.state="active",x.startedAt=i(),x.done=0,x.samples=[[i(),0]],x.abort=new AbortController;let L=++x.attempt,V=()=>x.attempt===L&&x.state==="active";(E==="up"?_(x,V):T(x,V)).catch(H=>{V()&&u(x,"failed",g(H))})}}}let g=E=>{let D=String(E?.message||E);return D==="changed"||D==="too_large"||D==="quota"||D==="account_changed"||D==="not_signed_in"||D.startsWith("http_")||D==="bad_response"||D==="gone"?D:"network"},p=(E,D)=>{E.done=D;let x=i(),L=E.samples[E.samples.length-1];for((!L||x-L[0]>=200)&&E.samples.push([x,D]);E.samples.length>2&&x-E.samples[0][0]>3500;)E.samples.shift()};async function m(E){let D=await l();if(D.account!==E.account)throw new Error("account_changed");if(!D.token)throw new Error("not_signed_in");return D}async function y(E,D,x,L){let V=Nt(E,x);if(!V)throw new Error("bad_path");let H=await fetch(V,{method:L.method??"GET",headers:{Authorization:`Bearer ${D}`,...L.body!==void 0?{"Content-Type":"application/json"}:{},...L.projectSource?{"X-Project-Source":L.projectSource}:{}},body:L.body!==void 0?JSON.stringify(L.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:H.status,json:await H.json().catch(()=>null)}}function b(E,D,x){if(!E.relDir.length)return Promise.resolve(E.targetId);let L=a.get(E.batch);L||a.set(E.batch,L=new Map);let V=L,H=N=>{if(N===0)return Promise.resolve(E.targetId);let Y=E.relDir.slice(0,N).join("/"),ee=V.get(Y);return ee||(ee=H(N-1).then(async J=>{let se=E.relDir[N-1],te=await y(D,x,"/files",{method:"POST",body:{type:"directory",parentId:J,name:se},projectSource:E.projectSource});if(te.status===201&&typeof te.json?.id=="string")return te.json.id;if(te.status===409){let ae=await y(D,x,`/files${J==="ROOT"?"":`?parentId=${encodeURIComponent(J)}`}`,{projectSource:E.projectSource}),Q=Array.isArray(ae.json)?ae.json.find(me=>me?.fileType==="directory"&&me?.name===se):null;if(Q?.id)return String(Q.id)}throw new Error(te.status===401?"not_signed_in":`http_${te.status}`)}),ee.catch(()=>V.delete(Y)),V.set(Y,ee)),ee};return H(E.relDir.length)}async function _(E,D){let{base:x,token:L}=await m(E),V=await Gl(E.localPath).catch(()=>null);if(!V?.isFile())throw new Error("gone");if(V.size>52428800)throw new Error("too_large");E.size=V.size;let H=await b(E,x,L);if(!D())return;E.parentId=H;let N=Nt(x,"/files/upload");if(!N)throw new Error("bad_path");let Y=`----penzor${wi().replace(/-/g,"")}`,{head:ee,tail:J}=Yl(Y,{parentId:H,autoRename:"true"},E.name,Bl(E.name)),se=await r(N,{Authorization:`Bearer ${L}`,"Content-Type":`multipart/form-data; boundary=${Y}`,...E.projectSource?{"X-Project-Source":E.projectSource}:{}},ee,E.localPath,V.size,J,te=>{D()&&p(E,te)},E.abort.signal);D()&&(se.status===201||se.status===200?(E.fileId=typeof se.body?.id=="string"?se.body.id:null,p(E,E.size),u(E,"done")):u(E,"failed",Bs(se.status,se.body)))}function h(E,D,x,L){let V=async()=>{let N=ch(x),Y=N?x.slice(0,-N.length):x;for(let ee=0;ee<1e3;ee++){if(!L())throw new Error("aborted");let J=ur(D,ee===0?x:`${Y} (${ee})${N}`);try{await eh(E,J)}catch(se){let te=se.code;if(te==="EEXIST")continue;if(te!=="EPERM"&&te!=="ENOTSUP"&&te!=="EOPNOTSUPP"&&te!=="ENOSYS"&&te!=="EXDEV")throw se;if(await Qp(J).then(()=>!0,()=>!1))continue;await sh(E,J)}if(!L())throw await qs(J).catch(()=>{}),new Error("aborted");return await qs(E).catch(()=>{}),J}throw new Error("too many duplicates")},H=o.then(V,V);return o=H.catch(()=>{}),H}async function T(E,D){let x=E.dl,{base:L,token:V}=await m(E);if(!D())return;let H=Nt(L,x.path);if(!H)throw new Error("bad_path");let N=E.abort.signal,Y=x.subdir?ur(n(),x.subdir):n();await nh(Y,{recursive:!0});let ee=ur(Y,`.${E.id}-${E.attempt}.penzor-part`),J=await rh(ee,"wx"),se=!1;try{let te=new AbortController,ae=setTimeout(()=>te.abort(),Ws),Q=()=>{clearTimeout(ae),ae=setTimeout(()=>te.abort(),Ws)},me=AbortSignal.any([N,te.signal]);try{let ge=await fetch(H,{headers:{Authorization:`Bearer ${V}`},signal:me});if(!ge.ok)throw new Error(ge.status===401?"not_signed_in":`http_${ge.status}`);let Pe=ge.body,Ce=Number(ge.headers.get("content-length"))||E.size;if(x.mode!=="bytes"){let He=await ge.json().catch(()=>null);if(x.mode==="text"){if(typeof He?.content!="string")throw new Error("bad_response");let Ae=Buffer.from(He.content,"utf8");await J.writeFile(Ae),E.size=Ae.length,p(E,Ae.length),Pe=null}else{if(typeof He?.url!="string"||!/^https?:\/\//i.test(He.url))throw new Error("bad_response");let Ae=await fetch(He.url,{signal:me});if(!Ae.ok)throw new Error(`http_${Ae.status}`);Pe=Ae.body,Ce=Number(Ae.headers.get("content-length"))||E.size}}if(Pe){E.size=Ce;let He=0;for await(let Ae of Pe){Q();for(let ut=0;ut<Ae.length;){let{bytesWritten:M}=await J.write(Ae,ut,Ae.length-ut);if(M<=0)throw new Error("short_write");ut+=M}if(He+=Ae.length,!D())throw new Error("aborted");p(E,He)}He>E.size&&(E.size=He)}}finally{clearTimeout(ae)}if(await J.close(),!D()||(E.localPath=await h(ee,Y,x.name,D),se=!0,!D()))return;u(E,"done")}finally{se||(await J.close().catch(()=>{}),await qs(ee).catch(()=>{}))}}let v=(E,D)=>{let x={...E,id:wi(),attempt:0,done:0,state:D?"failed":"queued",error:D??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:D?i():null};return s.push(x),x};async function I(E){let D=[],x=async(L,V)=>{if(V.length>32)return!0;let H=await(V.length?th(L):Gl(L)).catch(()=>null);if(!H)return!0;if(H.isFile())return D.push({path:L,size:H.size,relDir:V}),D.length<=2e3;if(!H.isDirectory())return!0;let N=(await ih(L).catch(()=>[])).filter(Y=>!Y.startsWith(".")).sort();for(let Y of N)if(!await x(ur(L,Y),[...V,Vl(L)]))return!1;return!0};for(let L of E)if(!await x(L,[]))return"too_many";return D}return t.handle("penzor:device",E=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let D=hi();return{ok:!0,name:D?decodeURIComponent(D):null}}),t.handle("penzor:upload",async(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=Array.isArray(x.paths)?x.paths.filter(Q=>typeof Q=="string"&&uh(Q)):[],V=typeof x.parentId=="string"&&Hl.test(x.parentId)?x.parentId:null,H=typeof x.projectSource=="string"&&zl.test(x.projectSource)?x.projectSource:null;if(!L.length)return{ok:!1,error:"no_files"};if(!V||!H)return{ok:!1,error:"bad_target"};let{base:N,token:Y,account:ee}=await l();if(!Y)return{ok:!1,error:"not_signed_in"};let J=await I(L);if(J==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!J.length)return{ok:!1,error:"no_files"};let se=J.filter(Q=>Q.size<=52428800).reduce((Q,me)=>Q+me.size,0);try{let Q=await y(N,Y,"/storage/quota",{}),me=Number(Q.json?.used),ge=Number(Q.json?.quota);if(Q.status===200&&ge>0&&me+se>ge)return{ok:!1,error:"quota",short:me+se-ge}}catch{}if((await l()).account!==ee)return{ok:!1,error:"account_changed"};let te=wi(),ae=J.map(Q=>v({kind:"up",name:Vl(Q.path),size:Q.size,projectSource:H,parentId:Q.relDir.length?null:V,targetId:V,fileId:null,localPath:Q.path,batch:te,account:ee,relDir:Q.relDir},Q.size>52428800?"too_large":void 0).id);return f(),{ok:!0,ids:ae,batch:te}}),t.handle("penzor:download",async(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=ph.includes(x.mode)?x.mode:null,V=yi(x.name);if(!L)return{ok:!1,error:"bad_mode"};if(!V)return{ok:!1,error:"bad_name"};let{base:H,token:N,account:Y}=await l();if(typeof x.path!="string"||!Nt(H,x.path))return{ok:!1,error:"bad_path"};if(!N)return{ok:!1,error:"not_signed_in"};let ee=x.subdir==null?null:yi(x.subdir),J=v({kind:"down",name:V,size:Math.max(0,Number(x.size)||0),localPath:null,batch:typeof x.batch=="string"&&x.batch.length<=64?x.batch:wi(),account:Y,relDir:[],dl:{path:x.path,mode:L,name:V,subdir:ee}});return f(),{ok:!0,id:J.id}}),t.handle("penzor:transfers",E=>t.isTrustedSender(E)?{ok:!0,items:s.map(c)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=s.find(H=>H.id===x.id);if(!L)return{ok:!1,error:"not_found"};let V=()=>{L.abort?.abort(),L.abort=null,L.done=0,L.samples=[]};switch(x.op){case"pause":(L.state==="active"||L.state==="queued")&&(V(),L.state="paused",f());break;case"resume":L.state==="paused"&&(L.state="queued",f());break;case"cancel":(L.state==="active"||L.state==="queued"||L.state==="paused")&&(V(),u(L,"canceled"));break;case"retry":(L.state==="failed"||L.state==="canceled")&&(L.state="queued",L.error=null,L.finishedAt=null,L.done=0,f());break;case"dismiss":L.state!=="active"&&L.state!=="queued"&&s.splice(s.indexOf(L),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D?.which==="all";for(let L of[...s])(L.state==="done"||L.state==="canceled"||x&&L.state==="failed")&&s.splice(s.indexOf(L),1);return{ok:!0}}),t.addQuitGuard?.(E=>{let D=s.filter(x=>x.state==="active"||x.state==="queued"||x.state==="paused").length;return D?E==="zh"?{message:`\u8FD8\u6709 ${D} \u4E2A\u6587\u4EF6\u6CA1\u4F20\u5B8C`,detail:"\u73B0\u5728\u9000\u51FA\u4F1A\u4E2D\u65AD\uFF0C\u4E0B\u6B21\u6253\u5F00\u8981\u91CD\u65B0\u4F20\u3002"}:{message:D===1?"1 file hasn't finished transferring":`${D} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>s.map(c)}}import{readFileSync as kh,writeFileSync as Eh,mkdirSync as _h,chmodSync as Ch,renameSync as Ah}from"node:fs";import{join as xh}from"node:path";import{mkdirSync as gh,readFileSync as mh,renameSync as yh,unlinkSync as wh,writeFileSync as bh}from"node:fs";import{dirname as Sh,join as vh}from"node:path";import{randomUUID as Jl}from"node:crypto";var Ks=t=>vh(t,"content-sync","active-account.json"),Vs=()=>Error("Invalid content sync account binding; original data was retained");function dr(t){try{let e=JSON.parse(mh(t,"utf8"));if(e?.version!==1||!(e.account===null&&e.pending===!0||typeof e.account=="string"&&/^[a-f0-9]{64}$/.test(e.account))||e.epoch!==void 0&&(typeof e.epoch!="string"||!/^[a-f0-9-]{36}$/i.test(e.epoch))||e.pending!==void 0&&typeof e.pending!="boolean"||e.pending&&!e.epoch)throw Vs();return e}catch(e){if(e?.code==="ENOENT")return null;throw Vs()}}function Xs(t,e){gh(Sh(t),{recursive:!0,mode:448});let n=t+".tmp-"+Jl();try{bh(n,JSON.stringify(e),{flag:"wx",mode:384}),yh(n,t)}finally{try{wh(n)}catch{}}}var Ys=new WeakMap,Js=new WeakSet;function Kl(t,e){let n=Ys.get(t);return n||Ys.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function Zs(t){if(Js.has(t))throw Vs()}function En(t,e,n){if(!t.contentSync||e===n)return;let r=Ks(t.homeDir());try{let i=dr(r);Xs(r,{version:1,account:i?.account??null,epoch:Jl(),pending:!0}),Js.delete(t)}catch(i){throw Js.add(t),i}finally{for(let i of Ys.get(t)??[])i()}}function Th(t){let e=()=>xh(t(),"auth-accounts.json");return{read:()=>kh(e(),"utf8"),write:n=>{_h(t(),{recursive:!0});let r=`${e()}.tmp`;Eh(r,n,{encoding:"utf8",mode:384}),Ch(r,384),Ah(r,e())}}}var Zl=t=>Ga(t,Th(()=>t.homeDir())),Ql=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],Qs=t=>Ql.every(e=>typeof t[e]=="function");function eo(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=Zl(t),i=0,s=()=>{let l=t.readCreds();return rr(l.cloudUrl,l.token)},a=l=>Ve(l.cloudUrl??"",l.token??""),o=null;t.handle("auth:status",async l=>{if(!t.isTrustedSender(l))return n;let c=i,u=s(),{base:f}=await t.getCloud(),g=t.readCreds().token,p=g?await lr(f,g):null,m=await t.accountBackendState(),{base:y}=await t.getCloud(),b=t.readCreds(),_=rr(y,b.token)!==rr(f,g),h=rr(f,g);!_&&p?.status==="ok"&&p.user&&(o={key:h,user:p.user},r.rememberForsionAccount({...b,cloudUrl:f},p.user));let T=_?void 0:p?.status==="ok"?p.user:p?.status==="offline"&&o?.key===h?o.user:void 0;if(_)return{loggedIn:!!b.token,tokenValid:null,cloudUrl:y,accountId:Ve(y,b.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:b.token?"tangu-login":null,backendState:m};if(p?.status==="expired"){await t.accountTransition(async()=>{if(c!==i||s()!==u)return;let I=()=>{if(c!==i||s()!==u)throw Xl};try{await t.accountClear(I,()=>{En(t,t.accountId?.()??null,null),t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++i,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),o=null})}catch(E){if(E!==Xl)throw E}});let v=t.readCreds();return{loggedIn:!!v.token,tokenValid:null,cloudUrl:v.cloudUrl||f,accountId:Ve(v.cloudUrl||f,v.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:v.token?"tangu-login":null,backendState:m}}return{loggedIn:!!g,tokenValid:p&&p.status==="ok"?!0:null,cloudUrl:f,accountId:Ve(f,g),username:T?.username||null,nickname:T?.nickname||null,avatar:T?.avatar||null,membershipTier:T?.membershipTier||null,tokenSource:g?"tangu-login":null,backendState:m}}),t.handle("auth:accounts",l=>t.isTrustedSender(l)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(l,c)=>{if(!t.isTrustedSender(l))return e;if(typeof c!="string")throw new Error("Invalid account.");let u=++i;return r.cancelForsionLogin(),t.accountTransition(async()=>{let f=r.savedForsionAccount(c);return await t.accountCommit(f,()=>{if(u!==i)throw new Error("Account switch cancelled.")},()=>{En(t,t.accountId?.()??null,a(f)),r.rememberForsionAccount(f),o=null}),{ok:!0,cloudUrl:f.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(l,c)=>{if(!t.isTrustedSender(l))return e;let u=++i;r.cancelForsionLogin();let{base:f}=await t.getCloud();if(u!==i)throw new Error("Sign-in cancelled.");let g=(c||f||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(g,m=>t.broadcast("auth:device",m),(m,y)=>t.accountTransition(()=>t.accountCommit(m,()=>{if(y(),u!==i)throw new Error("Sign-in cancelled.")},()=>{En(t,t.accountId?.()??null,a(m)),r.rememberForsionAccount(m),o=null})))).cloudUrl}}),t.handle("auth:logout",async l=>t.isTrustedSender(l)?(++i,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:c}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{En(t,t.accountId?.()??null,null),r.forgetForsionAccount(u),o=null,c&&u.token&&fetch(`${c}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${u.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:l,current:c})=>{try{En(t,a(l),a(c))}catch{t.log("[content-sync] account transition could not be recorded; sync is stopped")}++i,r.cancelForsionLogin(),l.token&&!c.token&&r.forgetForsionAccount(l),o=null,r.rememberForsionAccount(c)}),t.setTokenRefresher(async l=>{let c=i,u=s(),f=t.readCreds().token;if(!ni(f))return;let{base:g}=await t.getCloud(),p=await ri(g,f,l,`desktop/${t.appVersion()}`);if(!p){t.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}c!==i||s()!==u||(r.rememberForsionAccount({cloudUrl:g,token:p}),t.writeCreds({cloudUrl:g,token:p}),t.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),t.log("[forsion-extend] account core registered")}var Xl=Symbol("stale-auth-intent");import{promises as Dn}from"node:fs";import dn from"node:path";import{execFile as dg}from"node:child_process";import fg from"node:os";var to=null;function ec(t){to=t}var tc=null;function nc(t){tc=t}var rc=()=>tc;function Le(){if(!to)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return to}var Be=()=>Le().accountId();function _n(t=Be()){return t?Ee().sha256Hex(t):"signed-out"}var ot=(t=Be())=>Le().readConfig(t),Pt=(t,e=Be())=>Le().writeConfig(t,e),Cn=(t,e=Be())=>Le().updateConfig(t,e),$t=(t=Be())=>Le().cloudVaultDir(t),bi=t=>Le().isManagedCloudVault(t);function Ih(t,e){let n=Object.create(null);for(let s=0;s<e.length;s++){let a=e[s];n[a]?n[a].push(s):n[a]=[s]}let i=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let s=0;s<t.length;s++){let a=t[s],o=n[a]||[],l=0,c=i[0];for(let u of o){let f;for(f=l;f<i.length&&!(i[f].buffer2index<u&&(f===i.length-1||i[f+1].buffer2index>u));f++);if(f<i.length){let g={buffer1index:s,buffer2index:u,chain:i[f]};if(l===i.length?i.push(c):i[l]=c,l=f+1,c=g,l===i.length)break}}i[l]=c}return i[i.length-1]}function ic(t,e){let n=Ih(t,e),r=[],i=t.length,s=e.length;for(let a=n;a!==null;a=a.chain){let o=i-a.buffer1index-1,l=s-a.buffer2index-1;i=a.buffer1index,s=a.buffer2index,(o||l)&&r.push({buffer1:[i+1,o],buffer1Content:t.slice(i+1,i+1+o),buffer2:[s+1,l],buffer2Content:e.slice(s+1,s+1+l)})}return r.reverse(),r}function Rh(t,e,n){let r=[];function i(l,c){r.push({ab:c,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}ic(e,t).forEach(l=>i(l,"a")),ic(e,n).forEach(l=>i(l,"b")),r.sort((l,c)=>l.oStart-c.oStart);let s=[],a=0;function o(l){l>a&&(s.push({stable:!0,buffer:"o",bufferStart:a,bufferLength:l-a,bufferContent:e.slice(a,l)}),a=l)}for(;r.length;){let l=r.shift(),c=l.oStart,u=l.oStart+l.oLength,f=[l];for(o(c);r.length;){let g=r[0],p=g.oStart;if(p>u)break;u=Math.max(u,p+g.oLength),f.push(r.shift())}if(f.length===1){if(l.abLength>0){let g=l.ab==="a"?t:n;s.push({stable:!0,buffer:l.ab,bufferStart:l.abStart,bufferLength:l.abLength,bufferContent:g.slice(l.abStart,l.abStart+l.abLength)})}}else{let g={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;f.length;){l=f.shift();let h=l.oStart,T=h+l.oLength,v=l.abStart,I=v+l.abLength,E=g[l.ab];E[0]=Math.min(v,E[0]),E[1]=Math.max(I,E[1]),E[2]=Math.min(h,E[2]),E[3]=Math.max(T,E[3])}let p=g.a[0]+(c-g.a[2]),m=g.a[1]+(u-g.a[3]),y=g.b[0]+(c-g.b[2]),b=g.b[1]+(u-g.b[3]),_={stable:!1,aStart:p,aLength:m-p,aContent:t.slice(p,m),oStart:c,oLength:u-c,oContent:e.slice(c,u),bStart:y,bLength:b-y,bContent:n.slice(y,b)};s.push(_)}a=u}return o(e.length),s}function sc(t,e,n,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof t=="string"&&(t=t.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof n=="string"&&(n=n.split(r.stringSeparator));let s=[],a=Rh(t,e,n),o=[];function l(){o.length&&s.push({ok:o}),o=[]}function c(u,f){if(u.length!==f.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==f[g])return!1;return!0}return a.forEach(u=>{u.stable?o.push(...u.bufferContent):r.excludeFalseConflicts&&c(u.aContent,u.bContent)?o.push(...u.aContent):(l(),s.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),l(),s}function Si(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),i=n<0?t:t.slice(n+1),s=i.lastIndexOf("."),a=s>0?i.slice(0,s):i,o=s>0?i.slice(s):"",l=u=>String(u).padStart(2,"0"),c=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${r}${a} (conflict ${c})${o}`}function Dh(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),i=r?t.slice(0,n):t,s=r?t.slice(n):"";return`${i}-${e}${s}`}function Oh(t){let e=3735928559,n=1103547991;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=Math.imul(e^s,2654435761),n=Math.imul(n^s,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let r=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${r.toString(36)}`}var An=(t,e)=>e.seq===t.seq&&e.hash!==null&&e.hash!==t.hash,oc=(t,e)=>e.seq!==t.seq||An(t,e);function vi(t,e,n){if(t===null&&e===null&&n===null)return{kind:"none"};if(n===null)return t===null?e?{kind:"dropShadow"}:{kind:"none"}:e?t===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(t===null)return e?oc(e,n)?{kind:"pull"}:{kind:"pushDelete"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"hold"};if(An(e,n))return t===n.hash?{kind:"adopt"}:t===e.hash?{kind:"pull"}:{kind:"hold"};let r=t!==e.hash,i=oc(e,n);return!r&&!i?{kind:"none"}:r?i?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function ac(t,e,n){let r=sc(t.split(`
|
|
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
210
|
`),e.split(`
|
|
211
211
|
`),n.split(`
|
|
212
|
-
`),{excludeFalseConflicts:!0}),
|
|
213
|
-
`)}function fr(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var lc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function cc(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function no(t){let e=t??"";if(/^(?:ENOENT|EACCES|EPERM|EBUSY|EISDIR|ENOTDIR|EEXIST|EMFILE|ENFILE|ENOSPC|EROFS|EIO|ENAMETOOLONG)\b/.test(e))return"errOther";let n=/^(?:cloud|sse) http (\d{3})\b/i.exec(e);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|etimedout/i.test(e)?"errTimeout":!e||/fetch failed|econn|enotfound|eai_again|enetunreach|ehostunreach|enetdown|network|socket|terminated|other side closed|und_err|^cloud http 0\b/i.test(e)?"errOffline":"errOther"}function uc(t){if(!(t instanceof Error))return;let e=t.cause,n=e&&typeof e=="object"?[e.code,e.message].filter(r=>typeof r=="string"&&r).join(" "):"";return n?`${t.message} (${n})`:t.message}function dc(t,e){if(t==="offline")return no(e);if(t==="auth-required")return e==="not-logged-in"?null:"errAuth";if(t!=="error")return null;let n=e??"";return n.startsWith("vault-missing")?"errVaultMissing":n.startsWith("scan-failed")?"errScan":n.startsWith("mirror-missing")?"errMirrorMissing":"errOther"}function ki(t,e=0){if(/^(account_changed|content_sync_closed|paused)$/.test(t)||/^File exceeds \d+ MB/.test(t))return null;if(t==="not_signed_in"||e===401||e===403)return"errAuth";let n=/^content_http_(\d{3})$/.exec(t);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|aborted due to timeout/i.test(t)?"errTimeout":/fetch failed|econn|enotfound|eai_again|network|socket/i.test(t)?"errOffline":/^Sync root (unavailable|changed|is not a directory)|^content_roots_changed/.test(t)?"errVaultMissing":e?"errHttp":"errOther"}function Ei(t){let e=null;return{error(n){n!==e&&(e=n,t?.(n))},ok(){e=null}}}var Mh=/[\u0000-\u001f\u007f]/;function Yt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||Mh.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function ro(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Yt(n):n.startsWith(`${e}/`)?Yt(n.slice(e.length+1)):null}function fc(t,e){return e===""?t:`${e}/${t}`}function pr(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function De(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var qe=t=>t==="page"||t==="db";var Nh=t=>Math.max(3,Math.ceil(t*.1)),Ph=(t,e)=>t===429&&e!=="MASS_DELETE_BLOCKED";function $h(t,e=Date.now()){if(!t)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:Math.max(0,r-e)}function jh(t){let e=t.get("ratelimit"),n,r,i;if(e){let s=a=>Number(new RegExp(`(?:^|[;,\\s])${a}=(\\d+)`).exec(e)?.[1]??NaN);n=s("limit"),r=s("remaining"),i=s("reset")}else n=Number(t.get("ratelimit-limit")??NaN),r=Number(t.get("ratelimit-remaining")??NaN),i=Number(t.get("ratelimit-reset")??NaN);return![n,r,i].every(s=>Number.isFinite(s)&&s>=0)||n<=0?null:{limit:n,remaining:r,resetMs:i*1e3}}function Lh(t={}){let e=t.now??Date.now,n=0,r=null,i=new Set,s=()=>{for(let o of[...i])try{o()}catch{}},a=o=>{let l=e()+Math.min(Math.max(o,0),6e5);l<=n||(n=l,r&&clearTimeout(r),r=setTimeout(()=>{r=null,s()},n-e()),r.unref?.(),s())};return{until:()=>n>e()?n:null,async ready(o){for(;n>e();)o?.throwIfAborted(),await new Promise((l,c)=>{let u=setTimeout(f,n-e());function f(){o?.removeEventListener("abort",g),l()}function g(){clearTimeout(u),c(o.reason??new DOMException("Aborted","AbortError"))}o?.addEventListener("abort",g,{once:!0})});o?.throwIfAborted()},observe(o,l,c,u){let f=jh(l);if(Ph(o,c)){let g=$h(l.get("retry-after"),e())??(typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null)??(f&&f.remaining===0&&f.resetMs>0?f.resetMs:null);return a(Math.max(g??3e4,1e3)),!0}return f&&f.remaining<=Nh(f.limit)&&f.resetMs>0&&a(f.resetMs),!1},subscribe(o){return i.add(o),()=>{i.delete(o)}}}}var pc=new Map;function Jt(t){let e;try{e=new URL(t).origin}catch{e=t.replace(/\/+$/,"")}let n=pc.get(e);return n||(n=Lh(),pc.set(e,n)),n}var Fh=1024,ye=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},hc=t=>12e4+Math.ceil(t/256);function Uh(t,e){let n=AbortSignal.timeout(t);if(!e)return n;let r=new AbortController;for(let i of[n,e])i.addEventListener("abort",()=>r.abort(i.reason),{once:!0});return r.signal}function gc(t,e){if(!t||!e)return t??e;let n=new AbortController;for(let r of[t,e]){if(r.aborted){n.abort(r.reason);break}r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}function mc(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=t.gate??Jt(t.baseUrl),r=()=>t.getToken?.()??t.token,i=async(o,l)=>{let c=r();for(let u=0;;u++){let f={...l.headers,Authorization:`Bearer ${c}`},g=await fetch(o,{...l,headers:f});if(r(),g.status!==401||g.redirected)return g;let p=await g.text(),m=r();if(m===c||u>0)return new Response(p,{status:g.status,statusText:g.statusText,headers:g.headers});c=m}},s=async(o,l,c)=>{let u={Authorization:`Bearer ${t.token}`,...c?.headers};o!=="GET"&&(u["X-Amadeus-Client"]=t.clientId);let f;for(c?.json!==void 0?(u["Content-Type"]="application/json",f=JSON.stringify(c.json),f.length>=Fh&&(u["Content-Encoding"]="gzip",f=await qa(f))):c?.form&&(f=c.form);;){n.until()!==null&&await n.ready(gc(c?.signal,t.signal));let g=await i(l,{method:o,headers:u,body:f,signal:Uh(c?.timeoutMs??3e4,c?.signal)});if(!g.ok){let m=null;try{m=await g.json()}catch{}if(r(),n.observe(g.status,g.headers,m?.code,m?.retryAfterMs))continue;throw new ye(g.status,m,l)}n.observe(g.status,g.headers);let p=await g.json();return r(),p}},a=o=>new URLSearchParams(o).toString();return{clientId:t.clientId,async listVaults(){return((await s("GET",`${e}/vaults`)).vaults??[]).map(l=>({id:String(l.id),name:String(l.name),lastChangeSeq:Number(l.lastChangeSeq??0)}))},async tree(o){let l=await s("GET",`${e}/vaults/${o}/tree`);if(!Array.isArray(l.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:l.folders??[],seq:Number(l.seq??0),maxFileBytes:Number.isInteger(l.maxFileBytes)&&l.maxFileBytes>0?l.maxFileBytes:void 0,entries:l.entries.map(c=>({path:String(c.path),kind:c.kind,seq:Number(c.seq??0),hash:c.hash??null,size:Number(c.size??0),updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}))}},async getFile(o,l){let c=await s("GET",`${e}/vaults/${o}/file?${a({path:l})}`);return{content:String(c.content??""),seq:Number(c.seq??0),hash:c.hash??null,updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}},putFile(o,l,c,u,f=!1,g){return s("PUT",`${e}/vaults/${o}/file`,{json:{path:l,content:c,baseSeq:u,...f?{force:!0}:{},...g?{expectedHash:g}:{}}})},async deleteFile(o,l,c,u){let f={path:l};c!==void 0&&(f.baseSeq=String(c)),u?.expectedHash&&(f.expectedHash=u.expectedHash),await s("DELETE",`${e}/vaults/${o}/file?${a(f)}`,u?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(o,l,c){return s("POST",`${e}/vaults/${o}/move`,{json:{from:l,to:c}})},renameFolder(o,l,c){return s("POST",`${e}/vaults/${o}/folders/rename`,{json:{path:l,newName:c}})},moveFolder(o,l,c){return s("POST",`${e}/vaults/${o}/folders/move`,{json:{path:l,dest:c}})},async deleteFolder(o,l){await s("DELETE",`${e}/vaults/${o}/folders?${a({path:l})}`)},putBinary(o,l,c,u){let f=new FormData;return f.set("path",l),u?.ifAbsent&&f.set("ifAbsent","true"),u?.baseSeq!==void 0&&f.set("baseSeq",String(u.baseSeq)),u?.expectedHash&&f.set("expectedHash",u.expectedHash),f.set("file",new Blob([new Uint8Array(c)]),l.split("/").pop()||"file"),s("POST",`${e}/vaults/${o}/binary`,{form:f,timeoutMs:hc(c.length),signal:u?.signal})},async listVersions(o,l){return((await s("GET",`${e}/vaults/${o}/file/versions?${a({path:l})}`)).versions??[]).map(u=>({id:String(u.id),seq:Number(u.seq??0)}))},async getVersion(o,l){let c=await s("GET",`${e}/vaults/${o}/file/versions/${l}`);return String(c.content??"")},async getAsset(o,l,c){let u=new AbortController;c?.addEventListener("abort",()=>u.abort(c.reason),{once:!0});let f=()=>u.abort(new DOMException("Asset download timed out","TimeoutError")),g;try{let p;for(;;){if(clearTimeout(g),n.until()!==null&&await n.ready(gc(c,t.signal)),g=setTimeout(f,12e4),p=await i(`${e}/vaults/${o}/asset?${a({ref:l})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:u.signal}),p.status!==429){n.observe(p.status,p.headers);break}let y=await p.json().catch(()=>null);if(!n.observe(p.status,p.headers,y?.code,y?.retryAfterMs))break}if(!p.ok)throw new ye(p.redirected&&(p.status===401||p.status===403)?502:p.status,null,"asset:"+l);clearTimeout(g),g=setTimeout(f,hc(Number(p.headers.get("content-length"))||0));let m=new Uint8Array(await p.arrayBuffer());return r(),m}finally{clearTimeout(g)}},async changes(o,l){let c=await s("GET",`${e}/vaults/${o}/changes?${a({since:String(l)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function yc(t,e){let n=!1,r=0,i=null,s=null,a=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,o=(c,u=!1)=>{if(n)return;i?.abort(),e.onDown(c,u);let f=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,s=setTimeout(()=>void l(),f)},l=async()=>{if(n)return;i=new AbortController;try{await t.gate?.ready(i.signal)}catch{return}if(n)return;let c;try{if(c=await fetch(a(),{headers:{Authorization:`Bearer ${t.getToken?.()??t.token}`,Accept:"text/event-stream"},signal:i.signal}),n){await c.body?.cancel();return}t.getToken?.()}catch(_){o(_);return}if(c.status===429&&t.gate&&(c.body?.cancel().catch(()=>{}),t.gate.observe(c.status,c.headers))){if(n)return;s=setTimeout(()=>void l(),Math.max(0,(t.gate.until()??Date.now())-Date.now()));return}if(!c.ok||!c.body){o(new Error(`sse http ${c.status}`));return}t.gate?.observe(c.status,c.headers),r=0;let u=Date.now();e.onOpen();let f=c.body.getReader(),g=new TextDecoder,p="",m="",y=[],b=()=>{if(t.getToken?.(),!y.length&&!m)return;let _=y.join(`
|
|
214
|
-
`),h=m||"message";m="",y=[];let
|
|
215
|
-
`);if(T<0)break;let v=p.slice(0,T).replace(/\r$/,"");if(p=p.slice(T+1),v==="")b();else{if(v.startsWith(":"))continue;v.startsWith("event:")?m=v.slice(6).trim():v.startsWith("data:")&&y.push(v.slice(5).replace(/^ /,""))}}}}catch(_){n||o(_,Date.now()-u>=1e4);return}o(new Error("sse stream ended"),Date.now()-u>=1e4)};return l(),{stop:()=>{n=!0,s&&clearTimeout(s),i?.abort()}}}var un=t=>Ee().path.join(Le().userDataDir(),Le().isDevMode()?`${t}.dev.json`:`${t}.json`),io=un,St=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,ln=t=>typeof t=="string"&&Yt(t)===t,hr=t=>typeof t=="string"&&t.length>0,wc=t=>St(t)&&cn(t.seq)&&hr(t.hash)&&cn(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),bc=t=>typeof t=="number"&&Number.isFinite(t),Hh=t=>St(t)&&hr(t.localHash)&&cn(t.localSize)&&bc(t.localMtimeMs)&&cn(t.remoteSeq)&&(t.remoteHash===null||hr(t.remoteHash))&&(t.remoteUpdatedAt===null||typeof t.remoteUpdatedAt=="string")&&bc(t.since),zh=t=>St(t)&&ln(t.from)&&ln(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||St(t.hashes)&&Object.values(t.hashes).every(hr));async function so(t){let e;try{e=await Ee().fs.readFile(io(t),"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let n;try{n=JSON.parse(e)}catch{throw Error("Invalid cloud vault sync state; original data was retained")}if(!St(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Vt(n.rootIdentity)||n.mirrorMissing!==void 0&&n.mirrorMissing!==!0||n.mirrorRestore!==void 0&&n.mirrorRestore!=="list"&&(!St(n.mirrorRestore)||!Object.entries(n.mirrorRestore).every(([r,i])=>ln(r)&&St(i)&&cn(i.seq)&&(i.hash===null||hr(i.hash))))||!St(n.files)||!Object.entries(n.files).every(([r,i])=>ln(r)&&wc(i))||n.cursor!==void 0&&!cn(n.cursor)||n.lastSyncAt!=null&&!cn(n.lastSyncAt)||n.pending!==void 0&&(!St(n.pending)||!Object.entries(n.pending).every(([r,i])=>ln(r)&&(i==="local"||i==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(zh))||n.held!==void 0&&(!St(n.held)||!Object.entries(n.held).every(([r,i])=>ln(r)&&Hh(i)))||n.dormant!==void 0&&(!St(n.dormant)||!Object.entries(n.dormant).every(([r,i])=>ln(r)&&wc(i)))||n.dormantRoot!==void 0&&!Vt(n.dormantRoot))throw Error("Invalid cloud vault sync state; original data was retained");return{...n,cursor:n.cursor??0,lastSyncAt:n.lastSyncAt??null}}function Sc(t){let e=null,n=null,r=Promise.resolve(),i=null,s=()=>{if(!e)return r;let a=e,o=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let l=io(t),c=`${l}.tmp-${Ee().tmpTag()}-${Date.now()}-0`;await Ee().fs.writeFile(c,o,"utf8"),await Ee().fs.rename(c,l),i=null}catch(l){e??=a,i=l}}),r};return{save(a){e=a,!n&&(n=setTimeout(()=>{n=null,s()},500))},async flush(a=!1){if(n&&(clearTimeout(n),n=null),await s(),a&&i)throw i}}}async function vc(t){try{await Ee().fs.unlink(io(t))}catch{}}var gr=/^[0-9a-f]{64}$/;function kc(t){let e=Ee(),n=()=>un(t).replace(/\.json$/,".bases"),r=o=>e.path.join(n(),o),i=o=>e.fs.access(r(o)).then(()=>!0,()=>!1),s=new Map,a=(o,l)=>{let c=(s.get(o)??Promise.resolve()).then(l,l);return s.set(o,c),c.finally(()=>{s.get(o)===c&&s.delete(o)}),c};return{put(o,l){return gr.test(o)?a(o,async()=>{try{if(await i(o))return;await e.fs.mkdir(n(),{recursive:!0});let c=`${r(o)}.tmp-${e.tmpTag()}-${Date.now()}`;await e.fs.writeFile(c,l,"utf8"),await e.fs.rename(c,r(o))}catch{}}):Promise.resolve()},async get(o){if(!gr.test(o))return null;try{let l=await e.fs.readFile(r(o),"utf8");return e.sha256Hex(l)===o?l:null}catch{return null}},drop(o,l){return gr.test(o)?a(o,async()=>{if(!(l&&!l()))try{await e.fs.rm(r(o),{force:!0})}catch{}}):Promise.resolve()},async has(o){return gr.test(o)&&i(o)},async prune(o){let l;try{l=(await e.fs.readdir(n(),{withFileTypes:!0})).filter(c=>c.isFile()).map(c=>c.name)}catch{return}for(let c of l)if(!o.has(c)&&!(!gr.test(c)&&!/^[0-9a-f]{64}\.tmp-/.test(c)))try{await e.fs.rm(e.path.join(n(),c),{force:!0})}catch{}}}}var Bh=720*60*60*1e3,qh=/^[0-9a-f]{64}$/,_i=new Map,Ec=(t,e)=>{let n=(_i.get(t)??Promise.resolve()).then(e,e),r=n.catch(()=>{});return _i.set(t,r),r.then(()=>{_i.get(t)===r&&_i.delete(t)}),n},oo=class extends Error{constructor(e){super(`sync recovery save failed: ${e?.message??String(e)}`),this.name="RecoveryError"}};function _c(t){let e=Ee(),n=()=>e.path.join(Le().homeDir(),"sync-recovery",t),r=o=>e.fs.access(o).then(()=>!0,()=>!1),i=async(o,l)=>{let c=`${o}.tmp-${e.tmpTag()}-${Date.now()}`;try{await e.fs.writeFile(c,l),await e.fs.rename(c,o)}catch(u){throw await e.fs.rm(c,{force:!0}).catch(()=>{}),u}},s={async save(o,l){let c=n(),u=await Ec(c,async()=>{try{let f=e.path.join(c,e.sha256Hex(o));await e.fs.mkdir(c,{recursive:!0}),await r(f)||await i(f,o);let g=`${f}.json`,p=[];try{let m=JSON.parse(await e.fs.readFile(g,"utf8"));Array.isArray(m)&&(p=m)}catch{}return p.push({...l,savedAt:Date.now()}),await i(g,JSON.stringify(p)),f}catch(f){throw new oo(f)}});return s.prune(),u},prune(o=Date.now()){let l=n();return Ec(l,()=>a(l,o))}},a=async(o,l)=>{let c;try{c=(await e.fs.readdir(o,{withFileTypes:!0})).filter(u=>u.isFile()).map(u=>u.name)}catch{return}for(let u of c){if(!qh.test(u))continue;let f=e.path.join(o,u),g=0;try{let p=JSON.parse(await e.fs.readFile(`${f}.json`,"utf8"));g=Math.max(0,...p.map(m=>Number(m?.savedAt)||0))}catch{try{g=(await e.fs.stat(f)).mtimeMs}catch{continue}}if(!(l-g<=Bh))try{await e.fs.rm(f,{force:!0}),await e.fs.rm(`${f}.json`,{force:!0})}catch{}}};return s}var Wh=5*1024*1024,Gh=5*1024*1024,Vh=3e4,Yh=5e3,Jh=5*6e4,Kh=2500,Xh=3e3,Zh=5,Qh=256*1024,eg=5,Ci=1024*1024,Cc=200,tg=6e4,ng=50,rg=".sync-trash",Ye=t=>Ee().sha256Hex(t);function mr(t,e){let n=e??{localRoot:$t(),shadowName:`amadeus-sync-${_n()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]},r=d=>{let w=ro(d,"");if(!w)return null;for(let k of n.excludePrefixes??[])if(w===k.replace(/\/$/,"")||w.startsWith(k))return null;if(n.ignoreNames?.length&&w.split("/").some(k=>n.ignoreNames.includes(k)))return null;let S=n.serverDir?`${n.serverDir}/${w}`:w;return n.inScope&&!n.inScope(S,De(S))?null:S},i=d=>{let w;if(n.serverDir){if(!d.startsWith(`${n.serverDir}/`))return null;w=d.slice(n.serverDir.length+1)}else{for(let S of n.excludePrefixes??[])if(d.startsWith(S))return null;w=d}return w.split("/").some(S=>pr(S)||!!n.ignoreNames?.includes(S))?null:w},s=(d,w)=>!n.inScope||n.inScope(d,w),a=n.accountId??Be(),{fs:o,path:l,directoryIdentity:c}=Ee(),u=d=>o.access(d).then(()=>!0,()=>!1),f=!1,g=!1,p=0,m=Promise.resolve(),y=new Set,b="disabled",_=null,h=null,T=null,v=null,I=null,E=null,D=null,x=null,L=null,V=()=>{let d=t.loadCreds();if(!E||a!==Be()||!d.token||d.cloudUrl?.replace(/\/+$/,"")!==E.cloudUrl.replace(/\/+$/,""))throw new ye(401,{code:"ACCOUNT_CHANGED"},"sync-session");return d.token},H=null,N=0,Y=new Map,ee=null,J=Sc(n.shadowName),se=kc(n.shadowName),te=_c(_n(a)),ae=!1,Q=new Map,me=!1,ge=!1,Pe=[],Ce=(d,w,S)=>{try{t.onHealth?.(d,w,S)}catch{}},He=Ei(Ce),Ae=0,ut=()=>{ge||Ce("massDeleteGuard"),ge=!0},M=()=>{h&&(h.pending=Q.size?Object.fromEntries(Q):void 0,J.save(h))},U=()=>{ge=!1,Pe.length=0},C=()=>{if(ge)return!0;let d=Date.now();for(;Pe.length&&d-Pe[0]>tg;)Pe.shift();return Pe.length>=ng?(ut(),!0):!1},A=[],j=new Set,F=!1,z=null,q=null,ne=null,re=null,Z=()=>{!f||re||(re=setTimeout(()=>{re=null,t.onStatus(_t())},200))},ie=(d,w,S)=>{let k=b;b=d,w!==void 0&&(_=w),pe(k,d,S),Z()},oe=!1,pe=(d,w,S)=>{if(w==="syncing"&&d!=="syncing"&&(Ae=Date.now()),w==="idle"&&d==="syncing"&&(Ce("cycles"),Ce("cycleMsTotal",Math.max(0,Date.now()-Ae))),w==="idle"||w==="disabled"){oe=!1,He.ok();return}if(S===null)return;let k=S??dc(w,_);k&&He.error(k)},le=(d,w)=>{Y.set(d,w),Ce(cc(w),1,d)},X=(d,w=!1)=>{if(!(!f||!g)){if(d.key){if(j.has(d.key))return;j.add(d.key)}w?A.unshift(d):A.push(d),rf()}},ve=new Map,nn=d=>{if(!f)return;let w=(h?.files[d]?.size??0)>Qh,S=(n.pushQuietMs??Xh)*(w?eg:1),k=Date.now(),R=ve.get(d);R&&clearTimeout(R.timer);let P=R?.since??k,W=Math.max(0,Math.min(S,P+S*Zh-k)),O=setTimeout(()=>{ve.delete(d),X({key:d,run:()=>xe(d,!0)})},W);ve.set(d,{timer:O,since:P}),Z()},Jn=()=>{for(let{timer:d}of ve.values())clearTimeout(d);ve.clear()},yt=new Set(["EACCES","EPERM","EISDIR","ENOTDIR","ENAMETOOLONG","EILSEQ","EINVAL","ELOOP","EBUSY","EFBIG","EIO"]),os=d=>!(d instanceof ye)&&typeof d?.code=="string"&&yt.has(d.code),Ur=d=>!(d instanceof ye)||d.status>=500||d.status===0,tf=d=>!!d&&!d.startsWith("\0"),nf=d=>d instanceof ye?d.body?.code||`http ${d.status}`:d?.code??"error",Kn=d=>d instanceof ye&&(d.status===401||d.status===403),Hr=(d,w)=>{le(d,nf(w)),Z()},rf=async()=>{if(!F){F=!0;try{for(;A.length;){(b==="idle"||b==="starting")&&ie("syncing");let d=A.shift();d.key&&j.delete(d.key);try{await d.run()}catch(w){if(!f)return;if(Kn(w)){A.length=0,j.clear(),er(),ie("auth-required","login-expired");return}if(Ur(w)&&!(os(w)&&tf(d.key))){X(d,!0),er(),ie("offline",w?.message||"network error"),Xn();return}Hr(d.key??"(op)",w)}}f&&b==="syncing"&&(h&&(h.lastSyncAt=Date.now(),J.save(h)),ie("idle",null))}finally{F=!1;for(let d of y)d();y.clear()}}},Xn=()=>{!f||z||(z=setTimeout(()=>{z=null,tr()},Vh))},we=new Map,rn=0,Me=null,zr=()=>!!q||!!Me||!f,as=d=>d instanceof ye&&d.status>=500||d?.name==="TimeoutError",ma=n.pushRetryMs??Yh,ya=d=>{we.get(d)&&(we.delete(d),Y.delete(d))},Zn=(d,w)=>{(w||!we.has(d))&&we.set(d,w)},wa=(d,w,S)=>{le(d,w instanceof ye?`http ${w.status}`:"timeout"),Zn(d,S),rn=Math.min(rn*2||ma,Jh),q=setTimeout(Br,rn),Z()},ba=(d,w,S)=>{let k=new AbortController,R=w(k.signal).then(W=>()=>W,W=>()=>{throw W}),P={path:d,abort:k,after:[],settle:async()=>{let W=await R;if(Me===P){Me=null;try{await S(W)}catch(O){if(Kn(O)||Ur(O))throw O;Hr(d,O)}finally{for(let O of P.after)X(O);Sa(d)}}}};Me=P,R.then(()=>X({run:P.settle}))},Sn=(d,w)=>{for(let[S,k]of[...we])!k||!We(S,d)||(we.delete(S),Y.delete(S),w!==null&&we.set(w+S.slice(d.length),k));Z()},Br=()=>{q=null;let[d]=we;if(d===void 0)return;let[w]=d;j.delete(w),X({key:w,run:async()=>{if(Me?.path===w)return;let S=we.get(w),k=!S&&we.delete(w);(S||k)&&Y.delete(w);try{S?await Xe(w,S.seq):k&&await xe(w,!0)}finally{k&&je(w)&&Zn(w),Sa(w)}}})},Sa=d=>{if(!zr())if(we.has(d)){let w=we.get(d);we.delete(d),we.set(d,w),q=setTimeout(Br,rn||ma)}else Br()},$e=d=>{if(!H||!h)throw new Error("engine not bound");let w=i(d);if(w===null)throw new Error("path outside binding: "+d);let S=l.resolve(H,fc(w,h.folder)),k=l.relative(H,S);if(k.startsWith("..")||l.isAbsolute(k))throw new Error("path escapes vault: "+d);return S},qr=d=>({size:d,mtimeMs:-1}),va=async d=>{try{let w=await o.stat(d);return w.isFile()?{size:w.size,mtimeMs:Math.floor(w.mtimeMs)}:null}catch{return null}},ka=async d=>{if(!o.lstat||!H)return va(d);let w=l.relative(H,d).split(l.sep),S=H;for(let[k,R]of w.entries()){S=l.join(S,R);let P=await o.lstat(S).catch(W=>{if(W?.code==="ENOENT")return null;throw W});if(!P)return null;if(P.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(k===w.length-1&&P.isFile())return{size:P.size,mtimeMs:Math.floor(P.mtimeMs)};if(k===w.length-1||!P.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},sf=0,ls=async(d,w,S,k)=>{if(!await et())throw Error("Cloud vault sync root is unavailable or changed");let R=H&&T?{path:H,identity:T}:void 0;await o.mkdir(l.dirname(d),{recursive:!0});let P=`${d}.tmp-${Ee().tmpTag()}-${Date.now()}-${sf++}`;await o.writeFile(P,w);let W=await va(P)??qr(ei(w));try{if(!k())return null;let O=Ee().compareAndReplace;if(!O)throw new Error("Host does not support safe cloud download commits");let B=await O(P,d,S,k,R);if(!B&&!await et())throw Error("Cloud vault sync root is unavailable or changed");return B?W:null}finally{await et()&&await o.rm(P,{force:!0})}},Ea=async d=>{let w;try{w=await o.readdir(d,{withFileTypes:!0})}catch{return}for(let S of w)S.isDirectory()&&await Ea(l.join(d,S.name));try{await o.rmdir(d)}catch{}},dt=async d=>{let w=$e(d),S=await ka(w);if(!await et())throw Error("Cloud vault sync root is unavailable or changed");if(o.lstat&&!S)return null;let k;try{k=await o.readFile(w)}catch(P){if(P?.code!=="ENOENT")throw P;if(!await et())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:qe(De(d))?Ye(Ct(k)):Ye(k),size:S?.size??k.length,mtimeMs:S?.mtimeMs??-1,buf:k}},Qe=async(d,w,S,k,R)=>{if(!h)return;let P=h.files[d]?.hash;h.files[d]={seq:w,hash:S,size:k.size,mtimeMs:k.mtimeMs},h.mirrorRestore&&h.mirrorRestore!=="list"&&delete h.mirrorRestore[d],J.save(h),R!==void 0&&await _a(d,S,R),P&&P!==S&&await cs(P)},_a=async(d,w,S)=>{if(!qe(De(d))||ei(S)>Ci)return;let k=typeof S=="string"?S:Ct(S);Ye(k)===w&&await se.put(w,k)},cs=async d=>{let w=()=>!!h&&!Object.values(h.files).some(S=>S.hash===d)&&!Object.values(h.dormant??{}).some(S=>S.hash===d);w()&&await se.drop(d,w)},ft=d=>{if(h&&d in h.files){let w=h.files[d].hash;delete h.files[d],J.save(h),cs(w)}},pt=(d,w,S)=>{if(!h)return;let k=h.held?.[d];ft(d),h.held={...h.held,[d]:{localHash:w.hash,localSize:w.size,localMtimeMs:w.mtimeMs,remoteSeq:S.seq,remoteHash:S.hash,remoteUpdatedAt:S.updatedAt!==void 0?S.updatedAt:k&&k.remoteSeq===S.seq?k.remoteUpdatedAt:null,since:k?.since??Date.now()}},J.save(h),Z()},Se=d=>{if(!h?.held||!Object.hasOwn(h.held,d))return;let{[d]:w,...S}=h.held;h.held=Object.keys(S).length?S:void 0,J.save(h),Z()},Mt=d=>h?.held&&Object.hasOwn(h.held,d)?h.held[d]:void 0,kt=d=>i(d)!==null&&s(d,De(d)),us=d=>{!h||!Object.hasOwn(h.files,d)||(h.dormant={...h.dormant,[d]:h.files[d]},T&&(h.dormantRoot??=T),delete h.files[d],J.save(h))},Wr=d=>{if(!h?.dormant||!Object.hasOwn(h.dormant,d))return;let w=h.dormant[d].hash,{[d]:S,...k}=h.dormant;h.dormant=Object.keys(k).length?k:void 0,h.dormant||delete h.dormantRoot,J.save(h),cs(w)},Ca=d=>!!h?.dormant&&Object.hasOwn(h.dormant,d)&&!Object.hasOwn(h.files,d)&&kt(d),Aa=()=>X({key:"\0full",run:sn}),xa=()=>{if(h){for(let d of Object.keys(h.files))!kt(d)&&!je(d)&&us(d);for(let d of Object.keys(h.held??{}))!kt(d)&&!je(d)&&Se(d)}},Xe=async(d,w)=>{if(!v||!h||je(d))return;if(Ca(d)){Aa();return}let S=ke,k=De(d),R=Mt(d);if(R&&!qe(k)){ya(d),w!==null&&w!==R.remoteSeq&&pt(d,{hash:R.localHash,size:R.localSize,mtimeMs:R.localMtimeMs},{seq:w,hash:null,updatedAt:null});return}if(qe(k)){let B;try{B=await v.getFile(h.vaultId,d),Ce("downloads")}catch(K){if(K instanceof ye&&K.status===404){await ds(d);return}throw K}await Ta(d,k,B.content,B.seq,B.hash??Ye(B.content),S);return}if(zr()){Zn(d,{seq:w}),Z();return}let{vaultId:P}=h,W=v,O={seq:w};we.set(d,O),ba(d,B=>W.getAsset(P,d,B),async B=>{let K=we.get(d)===O,$;try{$=B(),rn=0,Ce("downloads")}catch(G){if(!K)return;if(we.delete(d),G instanceof ye&&G.status===404){le(d,"ASSET_404"),Z();return}if(as(G)){wa(d,G,{seq:w});return}throw G}K&&await Ta(d,k,$,w??0,Ye($),S)}),Z()},Ta=async(d,w,S,k,R,P)=>{if(!h)return;let W=async Ie=>{await Qe(d,k,R,Ie,S),we.get(d)&&(we.delete(d),Y.delete(d))},O=await dt(d);if(P!==ke||je(d))return;let B=h.mirrorRestore,K=B&&B!=="list"&&Object.hasOwn(B,d)?B[d]:void 0;if(K&&(K.hash!==R||K.seq!==k)){let Ie={...K};Object.assign(K,{hash:R,seq:k}),J.save(h);try{await J.flush(!0)}catch(nt){throw Object.assign(K,Ie),J.save(h),nt}if(!f||P!==ke||je(d))return}if(O&&O.hash===R){await W(O),Se(d);return}let $=h.files[d];if(O&&(!$||Mt(d)||An($,{seq:k,hash:R})&&O.hash!==$.hash)){ya(d),pt(d,O,{seq:k,hash:R});return}if(Se(d),O&&$&&R===$.hash&&O.hash!==$.hash){await W(qr($.size)),X({key:d,run:()=>xe(d)});return}let G=O?Ye(O.buf):null;if(O&&(!$||O.hash!==$.hash)){if($&&qe(w)&&typeof S=="string"&&await of(d,$,O,S,k,R,()=>P===ke&&!je(d))||P!==ke||je(d)||!await Ia(d,()=>P===ke&&!je(d)))return;G=null}let he=await ls($e(d),S,G,()=>f&&P===ke&&!je(d));if(!he){X({key:d,run:()=>xe(d)});return}await W(he)},of=async(d,w,S,k,R,P,W)=>{try{if(!v||!h||S.buf.length>Ci||k.length>Ci)return!1;let O=await se.get(w.hash);if(O===null){let G=(await v.listVersions(h.vaultId,d)).find(Ie=>Ie.seq===w.seq);if(!G)return!1;let he=await v.getVersion(h.vaultId,G.id);if(Ye(he)!==w.hash)return!1;O=he}let B=Ct(S.buf),K;if(De(d)==="db"){let $=rc(),G=$?$(d,B,O,k):null;K=G&&!G.conflict?G.content:null}else K=ac(B,O,k);return K===null?!1:await ls($e(d),K,Ye(S.buf),()=>f&&W())?(await Qe(d,R,P,qr(ei(K)),k),X({key:d,run:()=>xe(d)}),!0):(X({key:d,run:()=>xe(d)}),!0)}catch{return!1}},Ia=async(d,w)=>{let S=Yt(Si(d,new Date));if(!S)return!0;let k=S.lastIndexOf("."),R=k>S.lastIndexOf("/"),P=R?S.slice(0,k):S,W=R?S.slice(k):"",O=S,B=Ee().existsSync;if(B)for(let K=2;B($e(O));K++)O=`${P}-${K}${W}`;else for(let K=2;await u($e(O));K++)O=`${P}-${K}${W}`;if(!w())return!1;try{await o.rename($e(d),$e(O))}catch(K){if(K?.code==="ENOENT")return!0;throw K}return N++,Ce("conflicts"),X({key:O,run:()=>xe(O)}),Z(),!0},Ra=async d=>{if(!H)return;let w=$e(d),S=i(d)??d,k=l.join(H,rg,new Date().toISOString().slice(0,10),...S.split("/")),R=await u(k)?`${k}.${Date.now()}`:k;try{await o.mkdir(l.dirname(R),{recursive:!0}),await o.rename(w,R)}catch(P){if(P?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${w}: ${P?.message??String(P)}`)}},ds=async d=>{if(!h)return;Sn(d,null),Se(d),Wr(d);let w=await dt(d);if(je(d))return;let S=h.files[d]??null,k=vi(w?.hash??null,S,null);if(k.kind==="deleteLocal"){if(!me&&C()){Q.set(d,"local"),M(),Z();return}Pe.push(Date.now()),await Ra(d),ft(d)}else k.kind==="pushCreate"?(ft(d),X({key:d,run:()=>xe(d)})):ft(d)},Da=(d,w)=>{if(h){Sn(d,w);for(let S of Object.keys(h.files))if(S===d||S.startsWith(`${d}/`)){let k=w+S.slice(d.length);h.files[k]=h.files[S],delete h.files[S]}for(let S of[h.held,h.dormant])if(S)for(let k of Object.keys(S))(k===d||k.startsWith(`${d}/`))&&(S[w+k.slice(d.length)]=S[k],delete S[k]);J.save(h),Z()}},Oa=async d=>{if(!v||!h||d.seq<=h.cursor||!await et())return;if(d.origin.client&&v.clientId===d.origin.client){h.cursor=d.seq,J.save(h);return}let w=d.type==="structure"?"folder":d.type,S=R=>i(R)!==null&&s(R,w);if(!S(d.path)&&!(d.newPath&&S(d.newPath))){h.cursor=d.seq,J.save(h);return}let k=d.path;if(d.op!=="write"&&d.op!=="mkdir"){for(;Me&&(We(Me.path,k)||d.newPath&&We(Me.path,d.newPath));)await Me.settle();if(!f)return}switch(d.op){case"write":await Xe(k,d.fileSeq);break;case"delete":await ds(k);break;case"move":{let R=d.newPath;if(!R)break;let P=h.files[k],W=await dt(k),O=!!we.get(k);Sn(k,R),Wr(k),Mt(k)&&(Se(k),X({key:k,run:()=>xe(k)})),O&&Zn(R,{seq:d.fileSeq});let B=R!==k&&await ka($e(R)).then(K=>K!==null,()=>!0);if(W&&P&&B)await Xe(R,d.fileSeq);else if(W&&P)try{await o.mkdir(l.dirname($e(R)),{recursive:!0}),await o.rename($e(k),$e(R)),h.files[R]={...P,seq:O?P.seq:d.fileSeq??P.seq},delete h.files[k],J.save(h)}catch{await Xe(R,d.fileSeq)}else ft(k),await Xe(R,d.fileSeq);break}case"mkdir":await o.mkdir($e(k),{recursive:!0});break;case"rename-folder":case"move-folder":{let R=d.newPath;if(!R)break;try{await o.mkdir(l.dirname($e(R)),{recursive:!0}),await o.rename($e(k),$e(R))}catch{}Da(k,R);break}case"delete-folder":{let R=`${k}/`;for(let P of[...Object.keys(h.files),...Object.keys(h.held??{}),...Object.keys(h.dormant??{})])(P===k||P.startsWith(R))&&await ds(P);Sn(k,null),await Ea($e(k));break}}if(h.cursor=d.seq,J.save(h),d.op==="move"||d.op==="rename-folder"||d.op==="move-folder"||d.op==="delete"||d.op==="delete-folder")try{await t.onRemoteApplied?.(d)}catch{}},af=async(d,w,S)=>{let k=Number(w?.seq??0),R=w?.content??null,P;if(w?.seq===void 0&&v&&h)try{let B=await v.getFile(h.vaultId,d);k=B.seq,R=B.content,P=B.updatedAt}catch(B){if(!(B instanceof ye)||B.status!==404)throw B;k=0,R=null}if(R!==null&&Ye(R)===S.hash){await Qe(d,k,S.hash,S,R),Se(d);return}if(R===null&&k===0){if(!h?.files[d]){le(d,w?.code||"EXISTS"),Z();return}ft(d),X({key:d,run:()=>xe(d)});return}let W=h?.files[d],O=R===null?null:Ye(R);if(!W||An(W,{seq:k,hash:O})){pt(d,S,{seq:k,hash:O,updatedAt:P});return}await Xe(d,k)},Gr=async(d,w)=>{if(!v||!h)return;let S=await dt(d);if(!S){X({key:d,run:()=>xe(d)});return}if(S.size>Wh){le(d,"TOO_LARGE"),Z();return}let k=Ct(S.buf),R=w>0?h.files[d]?.hash:void 0;try{let P=await v.putFile(h.vaultId,d,k,w,!1,R);Ce("uploads"),Y.delete(d),await Qe(d,P.seq,P.hash??S.hash,S,S.buf),Se(d)}catch(P){if(P instanceof ye&&P.status===409){await af(d,P.body,S);return}throw P}},Vr=async(d,w)=>{if(!v||!h)return;let S=await dt(d);if(!S){X({key:d,run:()=>xe(d)});return}if(S.size>(ee??Gh)){le(d,"TOO_LARGE"),Z();return}if(Zn(d),Z(),zr())return;let{vaultId:k}=h,R=v,P=w>0?h.files[d]?.hash:void 0;ba(d,W=>R.putBinary(k,d,S.buf,{baseSeq:w,signal:W,expectedHash:P}),async W=>{if(h){we.get(d)||we.delete(d);try{let O=W();rn=0,Ce("uploads"),Y.delete(d),await Qe(d,O.seq,S.hash,S),Se(d)}catch(O){if(as(O)){wa(d,O);return}if(!(O instanceof ye)||O.status!==409)throw O;let B=Number(O.body?.seq??0),K=O.body?.hash??null;if(K!==null&&K===S.hash){await Qe(d,B,S.hash,S),Se(d);return}if(B===0){if(!h.files[d]){le(d,O.body?.code||"EXISTS"),Z();return}ft(d),X({key:d,run:()=>xe(d)});return}let $=h.files[d];if(!$||An($,{seq:B,hash:K})){pt(d,S,{seq:B,hash:K});return}await Xe(d,B)}}})},Ma=async d=>{if(!v||!h||je(d))return;let w=ke,S=h.files[d];if(S){if(qe(De(d)))try{let k=await v.getFile(h.vaultId,d);if(k.seq!==S.seq||k.hash!==null&&k.hash!==S.hash){await Xe(d,k.seq);return}}catch(k){if(k instanceof ye&&k.status===404){ft(d);return}throw k}if(!(!await et()||w!==ke||je(d))){try{await v.deleteFile(h.vaultId,d,S.seq,{confirmed:me,expectedHash:S.hash})}catch(k){if(k instanceof ye&&k.status===409){await Xe(d,Number(k.body?.seq??0)||null);return}if(k instanceof ye&&k.status===429&&k.body?.code==="MASS_DELETE_BLOCKED"){Q.set(d,"remote"),ut(),M(),Z();return}throw k}ft(d)}}},Yr=d=>o.stat(d).catch(w=>{if(w?.code==="ENOENT")return null;throw w}),fs=async d=>{let w=Le();if(e||!a||a!==Be()||d!==$t(a)||!w.isManagedCloudVault(d)||!o.lstat)return!1;let S=w.homeDir(),k=l.relative(S,d);if(!k||k.startsWith("..")||l.isAbsolute(k))return!1;let R=S;for(let P of k.split(l.sep)){R=l.join(R,P);let W=await o.lstat(R).catch(O=>{if(O.code==="ENOENT")return null;throw O});if(W&&(!W.isDirectory()||W.isSymbolicLink()))return!1}return!0},Gt=d=>(g=!1,me=!1,A.length=0,j.clear(),gs(),er(),ie("error",`${d}: ${H}`),Xn(),!1),ps=d=>{let w=T??h?.rootIdentity,S=d!==null&&d.isDirectory();return S&&(!w||bt(w,d))?!0:Gt(S?"vault-changed":"vault-missing")},et=async()=>!!H&&ps(await Yr(H)),ke=0,Jr=new Set,Kr=new Map,tt=d=>JSON.stringify([d.from,d.to]),We=(d,w)=>d===w||d.startsWith(`${w}/`),je=d=>[...h?.moves??[],...Jr].some(w=>We(d,w.from)||We(d,w.to)),Et=()=>!!(h?.moves?.length||Jr.size),Xr=async d=>{if(!v||!h)return;let{from:w,to:S,kind:k}=d;if(i(w)===null||i(S)===null)throw new Error("Invalid queued cloud move");if(Me&&(We(Me.path,w)||We(Me.path,S))){Me.after.push({key:`move:${tt(d)}`,run:()=>Xr(d)});return}if(d.hashes??=Object.fromEntries([...Object.entries(h.held??{}).filter(([O,B])=>We(O,w)&&B.remoteHash!==null).map(([O,B])=>[O.slice(w.length),B.remoteHash]),...Object.entries(h.files).filter(([O])=>We(O,w)).map(([O,B])=>[O.slice(w.length),B.hash])]),J.save(h),await J.flush(!0),!await et())return;let R,P=!1;try{if(k==="folder"){let O=l.posix.dirname(w)==="."?"":l.posix.dirname(w),B=l.posix.dirname(S)==="."?"":l.posix.dirname(S);O===B?await v.renameFolder(h.vaultId,w,l.posix.basename(S)):await v.moveFolder(h.vaultId,w,B)}else{let O=await v.move(h.vaultId,w,S);R=Number(O.seq)}}catch(O){if(!(O instanceof ye)||O.status!==404)throw O;let B=await v.tree(h.vaultId);if(B.entries.some(G=>We(G.path,w))||B.folders.some(G=>We(G,w)))throw O;let $=B.entries.find(G=>G.path===S);if(R=$?.seq,P=!$&&!B.entries.some(G=>We(G.path,S))&&!B.folders.some(G=>We(G,S)),!P){let G=Object.entries(d.hashes);if(!(G.length>0&&G.every(([Ie,nt])=>B.entries.some(Ge=>Ge.path===S+Ie&&Ge.hash===nt))))throw new ye(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(P){for(let O of Object.keys(h.files))We(O,w)&&delete h.files[O];for(let O of Object.keys(h.held??{}))We(O,w)&&Se(O);for(let O of Object.keys(h.dormant??{}))We(O,w)&&Wr(O);Sn(w,null)}else Da(w,S),R!==void 0&&h.files[S]&&!we.get(S)&&(h.files[S].seq=R);h.moves=(h.moves??[]).filter(O=>tt(O)!==tt(d)),J.save(h);try{await J.flush(!0)}catch(O){throw h.moves.unshift(d),J.save(h),O}let W=Kr.get(tt(d));Kr.delete(tt(d)),W?.(),je(S)||(k==="folder"?await hs():await xe(S))},xe=async(d,w=!1)=>{if(!h||je(d))return;if(Me?.path===d){Me.after.push({key:d,run:()=>xe(d,w)});return}if(!s(d,De(d))){us(d),Se(d);return}if(!await et())return;let S=await dt(d);if(je(d))return;let k=h.files[d]??null;if(!k&&Ca(d)){Aa();return}let R=Mt(d);if(R){S&&S.hash===R.remoteHash&&qe(De(d))?await Xe(d,null):S&&S.hash===R.remoteHash?(await Qe(d,R.remoteSeq,S.hash,S),Se(d)):S&&S.hash!==R.localHash&&pt(d,S,{seq:R.remoteSeq,hash:R.remoteHash});return}let P=vi(S?.hash??null,k,k?{seq:k.seq,hash:k.hash}:null);switch(P.kind){case"push":qe(De(d))?await Gr(d,P.baseSeq):await Vr(d,P.baseSeq);break;case"pushCreate":qe(De(d))?await Gr(d,0):await Vr(d,0);break;case"pushDelete":if(w){Qr();break}if(!me&&(Q.has(d)||C())){Q.set(d,"remote"),M(),Z();break}Pe.push(Date.now()),await Ma(d);break;case"dropShadow":ft(d);break;default:S&&k&&S.hash===k.hash&&S.mtimeMs>=0&&(k.size!==S.size||k.mtimeMs!==S.mtimeMs)&&await Qe(d,k.seq,k.hash,S,S.buf);break}},lf=async(d,w)=>{if(!v||!h)return;let S=await v.tree(h.vaultId);if(!h)return;let k=new Map(S.entries.map(R=>[R.path,R]));for(let R of d){if(!f||!h||!Mt(R)||je(R)||Me?.path===R)continue;if(!kt(R)){Se(R);continue}let P=await dt(R),W=k.get(R)??null;if(!P||!W){Se(R),P?X({key:R,run:()=>xe(R)}):await Xe(R,W?.seq??null);continue}if(P.hash===W.hash){await Qe(R,W.seq,P.hash,P,qe(De(R))?P.buf:void 0),Se(R);continue}let O;if(w==="newer"){let $=W.updatedAt?Date.parse(W.updatedAt):NaN;if(!Number.isFinite($)||P.mtimeMs<0)continue;O=P.mtimeMs>$?"local":"cloud"}else O=w;let B=ke,K=()=>f&&B===ke&&!je(R)&&kt(R);try{if(O==="both"){if(!await Ia(R,K))continue;Se(R),await Xe(R,W.seq);continue}let $=qe(De(R));if(!$&&zr())continue;O==="local"?await cf(R,P,W,$):await uf(R,P,W,$,K)}catch($){let G=$?.name==="RecoveryError";if(Kn($)||($ instanceof ye?$.status===0:!G&&!as($)&&Ur($)))throw $;le(R,$ instanceof ye?$.body?.code||`http ${$.status}`:$?.name==="TimeoutError"?"timeout":G?"RECOVERY_FAILED":"RESOLVE_FAILED"),Z()}}},cf=async(d,w,S,k)=>{if(!v||!h)return;let{vaultId:R}=h;if(k){let O=await v.getFile(R,d),B=Ye(O.content);if(O.seq!==S.seq||O.hash!==null&&O.hash!==B||S.hash!==null&&B!==S.hash){pt(d,w,{seq:O.seq,hash:O.hash??B,updatedAt:O.updatedAt});return}if(await te.save(O.content,{binding:n.shadowName,path:d,side:"cloud"}),!kt(d)){Se(d);return}try{let K=await v.putFile(R,d,Ct(w.buf),O.seq,!1,B);Ce("uploads"),Y.delete(d),await Qe(d,K.seq,K.hash??w.hash,w,w.buf),Se(d)}catch(K){if(!(K instanceof ye)||K.status!==409)throw K;await Na(d,w)}return}let P=await v.getAsset(R,d),W=Ye(P);if(S.hash!==null&&W!==S.hash){pt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}if(await te.save(P,{binding:n.shadowName,path:d,side:"cloud"}),!kt(d)){Se(d);return}try{let O=await v.putBinary(R,d,w.buf,{baseSeq:S.seq,expectedHash:W});Ce("uploads"),Y.delete(d),await Qe(d,O.seq,w.hash,w),Se(d)}catch(O){if(!(O instanceof ye)||O.status!==409)throw O;pt(d,w,{seq:Number(O.body?.seq??S.seq),hash:O.body?.hash??null,updatedAt:null})}},uf=async(d,w,S,k,R)=>{if(!v||!h)return;let{vaultId:P}=h,W,O,B;if(k){let $=await v.getFile(P,d);W=$.content,O=$.seq,B=Ye($.content)}else if(W=await v.getAsset(P,d),O=S.seq,B=Ye(W),S.hash!==null&&B!==S.hash){pt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}await te.save(w.buf,{binding:n.shadowName,path:d,side:"local"});let K=await ls($e(d),W,Ye(w.buf),R);if(!K){if(!kt(d)){Se(d);return}await Na(d,null);return}Ce("downloads"),Y.delete(d),await Qe(d,O,B,K,W),Se(d)},Na=async(d,w)=>{if(!v||!h)return;let S=w??await dt(d);if(!S){Se(d),await Xe(d,null);return}if(!qe(De(d))){let P=Mt(d);pt(d,S,{seq:P?.remoteSeq??0,hash:null});return}let k;try{k=await v.getFile(h.vaultId,d)}catch(P){if(!(P instanceof ye)||P.status!==404)throw P;Se(d),X({key:d,run:()=>xe(d)});return}let R=Ye(k.content);if(R===S.hash){await Qe(d,k.seq,S.hash,S,k.content),Se(d);return}pt(d,S,{seq:k.seq,hash:R,updatedAt:k.updatedAt})},Pa=async()=>{let d=new Map;if(!H||!h)return d;let w=H,S=null,k=async R=>{if(S)return;let P;try{P=await o.readdir(R,{withFileTypes:!0})}catch(W){S=`${R}: ${W?.message??String(W)}`;return}for(let W of P){if(pr(W.name)||W.isDirectory()&&n.ignoreNames?.includes(W.name))continue;let O=l.join(R,W.name);if(W.isDirectory())await k(O);else if(W.isFile()){let B=l.relative(w,O).split(l.sep).join("/"),K=r(B);if(!K)continue;try{let $=await o.stat(O);if(!$.isFile())continue;d.set(K,{size:$.size,mtimeMs:Math.floor($.mtimeMs)})}catch($){if($?.code==="ENOENT")continue;S=`${O}: ${$?.message??String($)}`;return}}}};return await k(w),S?(ie("error",`scan-failed: ${S}`),Xn(),null):d},hs=async()=>{let d=ke;if(Et()||d!==ke||!h||!await et())return;let w=await Pa();if(!w||Et()||d!==ke||!await et())return;let S=!1;for(let[P,W]of[...Q])(W==="remote"&&w.has(P)||W==="local"&&!w.has(P))&&(Q.delete(P),S=!0);Q.size||U();for(let[P,W]of w){let O=h.files[P];if(O&&O.size===W.size&&O.mtimeMs===W.mtimeMs)continue;let B=Mt(P);B&&B.localSize===W.size&&B.localMtimeMs===W.mtimeMs||X({key:P,run:()=>xe(P)})}for(let P of Object.keys(h.files))kt(P)||us(P);let k=Object.keys(h.files),R=k.filter(P=>!w.has(P));if(R.length&&!me&&(ge||fr(R.length,k.length,Cc))){ut();for(let P of R)Q.set(P,"remote");M(),Z();return}S&&(M(),Z());for(let P of R)Q.has(P)||X({key:P,run:()=>xe(P)})},df=async d=>{if(!h)return;let w=new Set;for(let[S,k]of Object.entries(h.files)){if(!qe(De(S))||k.size>Ci)continue;w.add(k.hash);let R=d.get(S);if(!(!R||R.size!==k.size||R.mtimeMs!==k.mtimeMs||await se.has(k.hash)))try{let P=await dt(S);P&&P.hash===k.hash&&await _a(S,k.hash,P.buf)}catch{}}for(let S of Object.values(h.dormant??{}))w.add(S.hash);await se.prune(w)},sn=async()=>{if(Me){Me.after.push({run:sn});return}let d=ke;if(Et()||d!==ke||!v||!h||!H||!await et())return;let w=await v.tree(h.vaultId);if(w.maxFileBytes!==void 0&&w.maxFileBytes!==ee&&(ee=w.maxFileBytes,Z()),Et()||d!==ke)return;let S=new Map;for(let $ of w.entries)i($.path)===null||!s($.path,$.kind)||S.set($.path,$);for(let[$,G]of[...we])G&&!S.has($)&&Sn($,null);let k=await Pa();if(!k||Et()||d!==ke||!await et())return;if(h.mirrorRestore==="list"){for(let G of Object.keys(h.files))!k.has(G)&&!Q.has(G)&&delete h.files[G];let $=Object.create(null);for(let[G,{seq:he,hash:Ie}]of S)Object.hasOwn(h.files,G)||($[G]={seq:he,hash:Ie});h.mirrorRestore=$,J.save(h);try{await J.flush(!0)}catch(G){throw h.mirrorRestore="list",J.save(h),G}}let R=h.mirrorRestore;if(xa(),h.dormant){let $=!h.dormantRoot||!T||an(h.dormantRoot,T);for(let[G,he]of Object.entries(h.dormant))kt(G)&&($&&k.has(G)&&S.has(G)&&!Object.hasOwn(h.files,G)?(h.files[G]=he,delete h.dormant[G]):Wr(G));h.dormant&&!Object.keys(h.dormant).length&&(delete h.dormant,delete h.dormantRoot),J.save(h)}ae||(ae=!0,await df(k));let P=new Set([...S.keys(),...k.keys(),...Object.keys(h.files),...Object.keys(R??{}),...Object.keys(h.held??{})]),W=Object.keys(h.files).length,O=[];for(let $ of P){if(Et()||d!==ke)return;let G=h.files[$]??null,he=S.get($)??null,Ie=k.get($)??null,nt=null,Ge=qr(Ie?.size??0);if(Ie)if(G&&G.size===Ie.size&&G.mtimeMs===Ie.mtimeMs)nt=G.hash,Ge=Ie;else{let rt;try{rt=await dt($)}catch(ze){if(!os(ze))throw ze;Hr($,ze);continue}rt&&(nt=rt.hash,Ge=rt)}if(R&&Object.hasOwn(R,$)){let rt=R[$];!G&&nt!==null&&rt.hash===nt&&(G=h.files[$]={seq:rt.seq,hash:nt,size:Ge.size,mtimeMs:Ge.mtimeMs}),(G||!he)&&delete R[$]}O.push({sp:$,d:vi(nt,G,he?{seq:he.seq,hash:he.hash}:null),rSeq:he?.seq??null,rHash:he?.hash??null,rUpdatedAt:he?.updatedAt??null,localHash:nt,localStat:Ge})}if(Et()||d!==ke)return;let B=O.filter($=>$.d.kind==="deleteLocal"||$.d.kind==="pushDelete").length,K=!me&&(ge||fr(B,W,Cc));K&&B&&ut(),Q.clear();for(let{sp:$,d:G,rSeq:he,rHash:Ie,rUpdatedAt:nt,localHash:Ge,localStat:rt}of O){if(Et()||d!==ke)return;if(G.kind!=="hold"&&Mt($)&&Se($),K&&(G.kind==="deleteLocal"||G.kind==="pushDelete")){Q.set($,G.kind==="deleteLocal"?"local":"remote");continue}try{if((G.kind==="deleteLocal"||G.kind==="pushDelete")&&((await dt($))?.hash??null)!==Ge){X({key:$,run:()=>xe($)});continue}if(Et()||d!==ke)return;switch(G.kind){case"adopt":{let ze=qe(De($))?await dt($):null;await Qe($,he,Ge,rt,ze&&ze.hash===Ge?ze.buf:void 0);break}case"pull":await Xe($,he);break;case"push":qe(De($))?await Gr($,G.baseSeq):await Vr($,G.baseSeq);break;case"pushCreate":qe(De($))?await Gr($,0):await Vr($,0);break;case"pushDelete":await Ma($);break;case"deleteLocal":await Ra($),ft($);break;case"conflict":await Xe($,he);break;case"hold":pt($,{hash:Ge,size:rt.size,mtimeMs:rt.mtimeMs},{seq:he,hash:Ie,updatedAt:nt});break;case"dropShadow":ft($);break;case"none":break}}catch(ze){if(!f||Kn(ze)||Ur(ze)&&!os(ze))throw ze;Hr($,ze)}}me&&(me=!1,Pe.length=0),Q.size||U(),M(),K&&Z();for(let $ of w.folders)if(!(i($)===null||!s($,"folder")))try{await o.mkdir($e($),{recursive:!0})}catch{}h.cursor=w.seq,h.lastSyncAt=Date.now(),R&&!Object.keys(R).length&&delete h.mirrorRestore,J.save(h)},ff=async()=>{if(!v||!h)return;let d=h.cursor,w=await v.changes(h.vaultId,d);if(w.changes.length===0&&w.seq>d||w.changes.length>0&&w.changes[0].seq!==d+1){await sn();return}for(let k of w.changes)await Oa(k)},Qn=null,$a=[],gs=()=>{Qn&&$a.push(Qn.close()),Qn=null},pf=()=>{if(!f||Qn||!H)return;let d=Ee();if(!d.watch)return;let w=S=>{if(!H)return;let k=l.relative(H,S);if(!k||k.startsWith(".."))return;let R=r(k);R&&nn(R)};Qn=d.watch(H,{depth:12,ignored:S=>{let k=l.basename(S);return pr(k)||!!n.ignoreNames?.includes(k)}},{change:w,add:w,unlink:()=>Qr(),unlinkDir:()=>Qr()})},er=()=>{I?.stop(),I=null},hf=()=>{if(!f||!v||!h||I)return;let d=E;d&&(I=yc({baseUrl:d.cloudUrl,vaultId:h.vaultId,token:d.token,getToken:V,gate:D??void 0},{getSince:()=>h?.cursor??0,onHello:w=>{h&&w>h.cursor&&X({run:ff})},onChange:w=>{X({run:()=>Oa(w)})},onReset:()=>{X({run:sn})},onOpen:()=>{(b==="offline"||b==="starting")&&ie("idle",null),X({run:hs})},onDown:(w,S)=>{let k=no(uc(w));b==="idle"||b==="syncing"?(ie("offline",void 0,S?null:k),oe=!!S):b==="offline"&&oe&&!S&&(oe=!1,He.error(k))},onPresence:w=>t.onPresence?.(h?.vaultId??"",w),onPresenceRoster:w=>t.onPresenceRoster?.(h?.vaultId??"",w)}))},gf=async()=>{let d=await ot(a);if(d.cloudSync?.deviceId)return d.cloudSync.deviceId;let w=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Pt({cloudSync:{...d.cloudSync??{},deviceId:w}},a),w},mf=async d=>{er(),gs(),T=null,A.length=0,j.clear(),Q.clear(),me=!1,ge=!1,Pe.length=0;let w=await ot(a);if(d!==p)return;let S=w.cloudSync;if(S?.enabled===!1){H=null,v=null,ie("disabled",null);return}if(!a||a!==Be()){ie("auth-required","not-logged-in");return}if(H=n.localRoot,n.requireRootExists){let W=await o.stat(H).then(O=>O.isDirectory()).catch(()=>!1);if(d!==p)return;if(!W){ie("error",`vault-missing: ${H}`),Xn();return}}if(d!==p)return;let k=t.loadCreds();if(!k.cloudUrl||!k.token){v=null,ie("auth-required","not-logged-in");return}ie("starting",null);let R=S?.deviceId??await gf();if(d!==p)return;let P=n.clientIdSuffix?`${R}#${n.clientIdSuffix}`:R;E={cloudUrl:k.cloudUrl,token:k.token},D=Jt(k.cloudUrl),x=new AbortController,L?.(),L=D.subscribe(Z),v=mc({baseUrl:k.cloudUrl,token:k.token,clientId:P,gate:D,signal:x.signal,getToken:()=>{if(d!==p)throw new ye(401,{code:"ACCOUNT_CHANGED"},"sync-session");return V()}});try{let W=n.vaultId==="first"?S?.vaultId:n.vaultId;if(!W){let $=await v.listVaults();if(d!==p)return;if(!$.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");W=$[0].id,await Pt({cloudSync:{...S??{},vaultId:W}},a)}if(d!==p)return;let O=await so(n.shadowName);if(d!==p||(h=O&&O.vaultRoot===H&&O.vaultId===W&&O.folder===""?O:{vaultRoot:H,folder:"",vaultId:W,cursor:0,lastSyncAt:null,files:{}},d!==p))return;for(let[$,G]of Object.entries(h.pending??{}))Q.set($,G);Q.size&&(ge=!0);let B=await Yr(H);if(d!==p)return;let K=()=>Et()||!!Object.keys(h?.pending??{}).length;if(!B&&!n.requireRootExists){if(h.rootIdentity||Object.keys(h.files).length||h.mirrorMissing||K()){let $=await fs(H);if(d!==p)return;if(!$||K()){Gt("vault-missing");return}if(h.mirrorMissing=!0,J.save(h),await J.flush(!0),d!==p)return;let G=await fs(H);if(d!==p)return;if(!G||K()){Gt("vault-missing");return}}if(await o.mkdir(H,{recursive:!0}),B=await Yr(H),d!==p)return}if(!B?.isDirectory()){ps(B);return}if(typeof B.dev=="number"&&Number.isInteger(B.dev)&&B.dev>=0&&typeof B.ino=="number"&&Number.isInteger(B.ino)&&B.ino>0){let $=c?await c(H):{dev:B.dev,ino:B.ino,...B.birthtimeMs&&B.birthtimeMs>0?{birthtimeMs:B.birthtimeMs}:{}};if(d!==p)return;if(!Vt($))throw Error("Invalid sync root identity; original state retained");let G=h.rootIdentity,he=G&&!an(G,$);if(!bt($,B)){Gt("vault-changed");return}let Ie=!G&&!e&&Le().isManagedCloudVault(H)&&(Object.keys(h.files).length>0||K());if(he||h.mirrorMissing||Ie){let Ge=(!G||(G.volumeId?G.volumeId===$.volumeId:G.dev===$.dev))&&await fs(H),rt=Ge&&(await o.readdir(H,{withFileTypes:!0})).every(Ua=>Ua.isDirectory()&&n.excludePrefixes?.includes(Ua.name+"/")),ze=rt&&await Yr(H);if(d!==p)return;if(rt){if(!ze||!bt($,ze)||K()){Gt("vault-changed");return}h.files={},h.cursor=0,h.lastSyncAt=null,h.mirrorRestore="list"}else if(he||h.mirrorMissing&&!G){Gt("vault-changed");return}else if(Ie){if(!Ge||K()){Gt("vault-changed");return}h.mirrorRestore="list"}}if(T=$,(h.mirrorMissing||JSON.stringify(G)!==JSON.stringify($))&&(delete h.mirrorMissing,h.rootIdentity=$,J.save(h),await J.flush(!0)),d!==p||!await et())return}else{if(h.mirrorMissing){Gt("vault-changed");return}if(!ps(B))return}if(d!==p)return;g=!0,pf();for(let $ of h.moves??[])X({key:`move:${tt($)}`,run:()=>Xr($)});X({run:sn}),X({run:async()=>{hf()}})}catch(W){if(d!==p)return;Kn(W)?ie("auth-required","login-expired"):(ie("offline",W?.message||String(W)),Xn())}},ja=()=>{f=!1,g=!1,er(),gs(),A.length=0,j.clear(),Jn();for(let d of[z,q,ne,re])d&&clearTimeout(d);z=q=ne=re=null,Me?.abort.abort(),Me=null,x?.abort(new DOMException("sync engine stopped","AbortError")),L?.(),L=null},La=async()=>{F&&await new Promise(d=>y.add(d)),await Promise.all($a.splice(0)),await J.flush(),h=null,T=null,v=null,E=null,D=null,x=null,H=null,N=0,Y.clear(),we.clear(),rn=0,ee=null,Q.clear(),me=!1,ge=!1,Pe.length=0,b="disabled",_=null},yf=()=>{Fa()},Zr=null,tr=()=>{ae=!1,Zr?.(),Zr=Le().onBeforeQuit(yf);let d=++p;ja();let w=m.catch(()=>{}).then(async()=>{await La(),d===p&&(f=!0,await mf(d))});return m=w,w},Fa=()=>{Zr?.(),Zr=null,++p,ja();let d=m.catch(()=>{}).then(La);return m=d,d},_t=()=>{let d=Object.entries(h?.held??{}).map(([w,S])=>({...S,path:w,local:i(w)??w}));return{enabled:b!=="disabled",state:b==="idle"&&(ve.size||we.size)?"syncing":b,lastSyncAt:h?.lastSyncAt??null,pending:A.length+ve.size+we.size,conflicts:N,skipped:[...[...Y].map(([w,S])=>({path:w,reason:S})),...d.map(w=>({path:w.path,reason:"HELD"}))],error:_,pendingDeletions:Q.size,maxFileBytes:ee,held:d,heldCount:d.length,rateLimitedUntil:b!=="disabled"?D?.until()??null:null}};return{getStatus:_t,start(){tr()},notifyLocal(d,w,S){if(!h||b==="disabled"||b==="auth-required")return;let k=r(d),R=S?r(S):null;if(w==="write"&&k){pr(k.split("/").pop()||"")||nn(k);return}if(w==="remove"){if(!k)return;let P=`${k}/`,W=!1;for(let O of Object.keys(h.files))(O===k||O.startsWith(P))&&(W=!0,X({key:O,run:()=>xe(O)}));!W&&k&&X({key:k,run:()=>xe(k)})}},holdLocalMove(d,w){let S=R=>n.serverDir?`${n.serverDir}/${R.replace(/\\/g,"/").normalize("NFC")}`:R.replace(/\\/g,"/").normalize("NFC"),k={from:S(d),to:S(w)};return++ke,Jr.add(k),()=>{Jr.delete(k)}},async notifyLocalMove(d,w,S,k){let R=r(d),P=r(w),W=h??await so(n.shadowName),O=ro(d,""),B=O&&(n.serverDir?`${n.serverDir}/${O}`:O);if(!R&&P&&B&&W&&Object.keys(W.files).some(K=>K===B||K.startsWith(`${B}/`))&&(R=B),!R&&!P){S?.();return}if(R&&P){let K=h??W;if(!K){S?.();return}let $=k??(Object.keys(K.files).some(he=>he.startsWith(`${R}/`))?"folder":"file"),G={from:R,to:P,kind:$};K.moves??=[],K.moves.some(he=>tt(he)===tt(G))||(K.moves.push(G),++ke),S&&Kr.set(tt(G),S),J.save(K);try{await J.flush(!0)}catch(he){throw K.moves=K.moves.filter(Ie=>tt(Ie)!==tt(G)),Kr.delete(tt(G)),J.save(K),he}h===K&&f&&b!=="disabled"&&b!=="auth-required"&&X({key:`move:${tt(G)}`,run:()=>Xr(G)});return}R&&this.notifyLocal(d,"remove"),P&&(X({key:P,run:()=>xe(P)}),Qr()),S?.()},async setEnabled(d){let w=await ot(a);return await Pt({cloudSync:{...w.cloudSync??{},enabled:d}},a),await tr(),_t()},async restart(){return await tr(),_t()},async syncNow(){if(Y.clear(),!g){let d=p;if(await m,d!==p)return _t()}if(b==="disabled"||b==="auth-required"||b==="error"||b==="offline"||!g||!v)await tr();else{q&&(clearTimeout(q),Br());for(let d of h?.moves??[])X({key:`move:${tt(d)}`,run:()=>Xr(d)});X({run:sn})}return _t()},resolveHeld(d,w){if(!g||!h?.held||!["local","cloud","both","newer"].includes(w))return _t();let S=[...new Set(d)].filter(k=>typeof k=="string"&&!!Mt(k));return S.length&&X({run:()=>lf(S,w)}),_t()},rescope(){f&&X({key:"\0rescope",run:async()=>xa()})},confirmMassDeletions(){return!g||!Q.size||(me=!0,X({run:sn})),_t()},stop:Fa};function Qr(){f&&(ne&&clearTimeout(ne),ne=setTimeout(()=>{ne=null,X({run:hs})},Kh))}}function ao(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function lo(t){return/\.md$/i.test(t)?ao(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function Ac(t,e,n){return!!(e===t.root||e.startsWith(t.fdPrefix)||`${e}/`===t.fdPrefix||n==="binary"&&e.startsWith(t.assetPrefix)||n==="folder"&&(`${e}/`===t.assetPrefix||e.startsWith(t.assetPrefix)))}var ig=t=>Ee().sha256Hex(t).slice(0,8),sg=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Ai="\u4E0E\u6211\u5171\u4EAB";function xc(t,e){let n=ig(`${t.vaultId}:${t.path}`),r=t.path.includes("/")?t.path.slice(0,t.path.lastIndexOf("/")):"";return{key:n,vaultId:t.vaultId,rootPath:t.path,title:t.title,localRelDir:`${Ai}/${sg(t.title)}-${n}`,serverDir:r,inScope:(i,s)=>e.some(a=>Ac(a,i,s)),scopeKey:e.map(i=>i.root).join("\0")}}function Tc(t){return xc(t,[ao(t.path),...(t.items??[]).map(lo)])}function Ic(t){let e=t.map(Tc),n=t.flatMap((i,s)=>{let a=e[s].serverDir?`${e[s].serverDir}/`:"";return(i.items??[]).filter(o=>!o.startsWith(a)).map(o=>xc({vaultId:i.vaultId,path:o,title:(o.split("/").pop()??o).replace(/\.md$/i,"")},[lo(o)]))}),r=new Map;for(let i of[...e,...n])r.has(i.key)||r.set(i.key,i);return[...r.values()]}var og=t=>{let e=[];for(let n of t.split("/"))!n||n==="."||(n===".."&&e.length&&e[e.length-1]!==".."?e.pop():e.push(n));return e.join("/")};function Rc(t,e){let n=l=>l.normalize("NFC"),r=n(e.replace(/\\/g,"/")),i=t.find(l=>r.startsWith(`${n(l.localRelDir)}/`));if(!i)return null;let s=r.slice(n(i.localRelDir).length+1),a=og(i.serverDir?`${i.serverDir}/${s}`:s);if(!a||a===".."||a.startsWith("../"))return null;let o=[i,...t].find(l=>l.vaultId===i.vaultId&&(!l.serverDir||a.startsWith(`${l.serverDir}/`))&&l.inScope(a,De(a)));return o?`${o.localRelDir}/${o.serverDir?a.slice(o.serverDir.length+1):a}`:null}function co(){let t=Le().readCreds(),e=Ve(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let f=Le().readCreds();if(n.signal.aborted||!e||Ve(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},i=()=>{let f=r();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},s=async(f,g,p)=>{let m=r();if(!m.cloudUrl||!m.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let y=await fetch(`${m.cloudUrl.replace(/\/+$/,"")}/api/amadeus${g}`,{method:f,headers:{Authorization:`Bearer ${m.token}`,...p!==void 0?{"Content-Type":"application/json"}:{}},body:p!==void 0?JSON.stringify(p):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!y.ok){let _=null;try{_=await y.json()}catch{}throw Object.assign(new Error(_?.detail||`http ${y.status}`),{status:y.status,code:_?.code})}let b=await y.json();return r(),b},a=null,o=async()=>(r(),a||(a=(await s("GET","/vaults")).vaults[0]?.id??"default",a)),l=()=>{try{let f=(r().token??"").split(".")[1],g=JSON.parse(Ct(ti(f)));return typeof g.userId=="string"?g.userId:null}catch{return null}},c=async()=>(await s("GET","/shared-with-me")).items.map(g=>{let p=Tc(g),m=g.path.split("/").pop()??g.path;return{...g,localPath:`${p.localRelDir}/${m}`}}),u=null;return{stop:()=>n.abort(),call:s,ensureOwnVault:o,myUserId:l,sharedWithMe:c,linkBase:async()=>{if(r(),u)return u;try{u=((await s("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||i()}catch{u=i()}return u},async heartbeat(f,g){let p=(f??"").replace(/\\/g,"/"),m,y=null,b=g.find(_=>p.startsWith(`${_.localRelDir}/`));b?(m=b.vaultId,y=b.serverDir?`${b.serverDir}/${p.slice(b.localRelDir.length+1)}`:p.slice(b.localRelDir.length+1)):(m=await o(),y=p||null),await s("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:y})}}}import{promises as Mc}from"node:fs";import ag from"node:path";var uo=".forsion-vault.md",Dc=t=>`${t}/${uo}`;function xi(t){let e=/^devices:\s*(\[.*\])\s*$/m.exec(t??"");if(!e)return null;try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(r=>!!r&&typeof r.id=="string"&&typeof r.name=="string").map(r=>({id:r.id,name:r.name,...typeof r.since=="string"?{since:r.since}:{}})):null}catch{return null}}var Oc=t=>`---
|
|
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&>(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&>(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
216
|
devices: ${JSON.stringify(t.map(e=>({id:e.id,name:e.name,...e.since?{since:e.since}:{}})))}
|
|
217
217
|
---
|
|
218
|
-
`;var at=t=>t.replace(/\\/g,"/").normalize("NFC");function fo(t){let e=at(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function xn(t,e,n){let r=at(n);if(!r)return!1;if(t.some(i=>at(i.path)===r))return!0;for(let i of e??[]){let s=at(i);if(!s)continue;let a=`${s.replace(/\.md$/i,"")}.fd`;if(r===s||r.startsWith(`${s}/`)||r===a||r.startsWith(`${a}/`))return!1}return t.some(i=>{let s=fo(i);return!!s&&r.startsWith(s)})}function po(t,e,n){let r=at(t),i=at(e);return r===i?at(n):r.startsWith(`${i}/`)?at(n)+r.slice(i.length):null}function yr(t,e,n){let r=!1,i=t.map(s=>{let a=po(s,e,n);return a===null?s:(r=!0,a)});return{changed:r,next:i}}async function Nc(t){let e=await Mc.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let i of e){if(!i.isDirectory()||i.name.startsWith("."))continue;let s=await Mc.readFile(ag.join(t,i.name,uo),"utf8").catch(()=>null);if(s===null)continue;n.push(i.name);let a=xi(s);a?.length&&(r[i.name]=a)}return{names:n.sort(),devices:r}}var Ne={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",resolveHeld:"amadeus:sync:resolve-held",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryMark:"amadeus:entry-sync:mark",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};var Ti=t=>Ee().sha256Hex(t).slice(0,8);function Pc(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Kt(t,e=[]){let n=[],r=[];for(let i of t){let s=at(i.path);if(!s)continue;r.push(s);let a=fo(i);a&&n.push(a)}return{entries:t,exclude:e,prefixes:n,paths:r}}function $c(t,e){let n=Pc(at(e));if(!n)return!1;if(xn(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let i of t.paths)if(i.startsWith(r))return!0;for(let i of t.prefixes)if(i.startsWith(r))return!0;return!1}function wr(t,e,n){let r=!1,i=t.map(s=>{let a=po(s.path,e,n);return a===null?s:(r=!0,{...s,path:a})});return{changed:r,next:i}}function jc(t,e,n,r){if(e==="delete"||e==="delete-folder"){let i=at(n),s=t.filter(a=>{let o=at(a.path);return!(o===i||e==="delete-folder"&&o.startsWith(`${i}/`))});return{changed:s.length!==t.length,next:s}}return r?wr(t,n,r):{changed:!1,next:t}}function ho(t,e){let n=Yt(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Ai?`\u300C${Ai}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(n)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}import{constants as lg,promises as Lc}from"node:fs";async function Fc(t,e){try{await Lc.copyFile(un(t),un(e),lg.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await Lc.unlink(un(t)).catch(()=>{}),!0}var cg=/^\d{4}-\d{2}-\d{2}$/,Uc=["vault","content"],Hc=new Set(lc),ug=40,Tn=t=>new Date(t).toISOString().slice(0,10),In=t=>typeof t=="string"&&cg.test(t),zc=!1,ht=Object.create(null),Rn=!1,go=()=>Date.now(),br=new Set,Ii="";function lt(t,e,n=1,r){try{if(!zc||!Hc.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let i=Tn(go());if(r!==void 0){i!==Ii&&(br.clear(),Ii=i);let o=`${t}\0${e}\0${r}`;if(br.has(o))return;br.add(o)}let s=ht[i]??={},a=s[t]??={};a[e]=(a[e]??0)+Math.round(n),Rn=!0}catch{}}function mo(t){zc=t}function Bc(t){if(ht=Object.create(null),br.clear(),Ii="",Rn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!In(e)||!n||typeof n!="object"))for(let r of Uc){let i=n[r];if(!i||typeof i!="object")continue;let s={};for(let[a,o]of Object.entries(i))Hc.has(a)&&typeof o=="number"&&Number.isFinite(o)&&o>0&&(s[a]=Math.round(o));Object.keys(s).length&&((ht[e]??={})[r]=s)}}}function qc(){let t=Tn(go()-ug*864e5),e={};for(let n of Object.keys(ht).sort()){if(n<t){delete ht[n];continue}e[n]=JSON.parse(JSON.stringify(ht[n]))}return e}var Wc=()=>Rn,Gc=()=>{Rn=!1};function Vc(t,e){let n=[];for(let r of Object.keys(ht).sort())if(!(r<=t||r>e))for(let i of Uc){let s=ht[r][i];s&&Object.keys(s).length&&n.push({day:r,system:i,counts:{...s}})}return n}function yo(t){for(let e of Object.keys(ht))e<=t&&(delete ht[e],Rn=!0)}function Yc(){Object.keys(ht).length&&(Rn=!0),ht=Object.create(null),br.clear(),Ii=""}function Jc(t){go=t}var Kc=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],wo=t=>Kc.every(e=>typeof t[e]=="function"),pg=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,held:[],heldCount:0,rateLimitedUntil:null,side:"local"});function bo(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Ne.get,()=>e?e.get():pg()),t.handle(Ne.setEnabled,(r,i)=>n().setEnabled(i)),t.handle(Ne.syncNow,()=>n().syncNow()),t.handle(Ne.confirmDeletions,()=>n().confirmDeletions()),t.handle(Ne.resolveHeld,(r,i)=>n().resolveHeld(i)),t.handle(Ne.entryGet,()=>n().entryGet()),t.handle(Ne.otherSideDbs,()=>n().otherSideDbs()),t.handle(Ne.entryEnable,(r,i)=>n().entryEnable(i)),t.handle(Ne.entryDisable,(r,i)=>n().entryDisable(i)),t.handle(Ne.entryMark,(r,i,s)=>n().entryMark(i,s)),t.handle(Ne.entryClosure,(r,i,s)=>n().entryClosure(i,s)),t.handle(Ne.collabCall,(r,i,s)=>n().collabCall(i,s)),t.handle(Ne.switchSide,(r,i)=>n().switchSide(r.sender.id,i)),t.setAmadeusSyncFactory(r=>{ec(r),nc(hg(t));let i=Xc(r);return e=i.handlers,i.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function hg(t){let e=t.contentSync?.merge;return e?(n,r,i,s)=>{if(!/\.db$/i.test(n)||/^(agents|human)(\/|$)/.test(n))return null;let a;try{a=e(n,r,i,s)}catch{return null}return a&&!a.conflict&&!So(i,r,a.content)?null:a}:null}function So(t,e,n){let r,i,s;try{[r,i,s]=[JSON.parse(t),JSON.parse(e),JSON.parse(n)]}catch{return!1}let a=c=>Array.isArray(c)&&c.every(u=>u&&typeof u=="object"&&typeof u.id=="string")?c.map(u=>u.id):null,o=(c,u)=>c.filter(f=>u.includes(f)),l=(c,u)=>c.length===u.length&&c.every((f,g)=>f===u[g]);for(let c of Object.keys(i)){let u=a(i[c]),f=a(r?.[c]);if(!u||!f||l(o(f,u),o(u,f)))continue;let g=a(s?.[c]);if(!g||!l(o(u,g),o(g,u)))return!1}return!0}function Xc(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,i=!1,s=co(),a=new Map,o=()=>{let M=Date.now();for(let[U,C]of a)M-C.at>7e4&&a.delete(U);e(Ne.presence,[...a.values()])},c={loadCreds:()=>t.readCreds(),onHealth:(M,U,C)=>lt("vault",M,U,C),onStatus:M=>e(Ne.status,{...M,pendingDeletions:me(),side:b()?"cloud":"local"}),onPresence:(M,U)=>{let C=U;C?.userId&&(a.set(C.userId,{userId:C.userId,username:String(C.username??"user"),page:C.page??null,at:Number(C.at)||Date.now()}),o())},onPresenceRoster:(M,U)=>{if(Array.isArray(U)){for(let C of U){let A=C;A?.userId&&a.set(A.userId,{userId:A.userId,username:String(A.username??"user"),page:A.page??null,at:Number(A.at)||Date.now()})}o()}}},u=()=>{let M=r;return{...c,onStatus:U=>{M===r&&c.onStatus(U)},onPresence:(U,C)=>{M===r&&c.onPresence(U,C)},onPresenceRoster:(U,C)=>{M===r&&c.onPresenceRoster(U,C)}}},f=mr(u()),g=new Map,p=[],m=0,y=async()=>{if(!i||!Be())return;let M=r,U=++m,C=s,A;try{A=await C.sharedWithMe()}catch{return}if(M!==r||!i||U!==m)return;let j=Ic(A);p=j;let F=new Map(j.map(z=>[z.key,z.scopeKey]));for(let[z,q]of g)if(F.get(z)!==q.plan.scopeKey){if(await q.engine.stop(),M!==r)return;g.delete(z)}for(let z of j){if(g.has(z.key))continue;let q=u(),ne=mr({...q,onStatus:re=>q.onStatus({...re,shareKey:z.key})},{localRoot:dn.join($t(),...z.localRelDir.split("/")),shadowName:`amadeus-sync-${_n()}-share-${z.key}`,vaultId:z.vaultId,serverDir:z.serverDir,inScope:z.inScope});g.set(z.key,{engine:ne,plan:z}),ne.start()}},b=()=>n()===$t(),_=(M,U=M.base)=>{M.base=U;let C=[U,...M.pendingMoves];M.scope.current=Kt(C.flatMap(A=>A.entries),C.flatMap(A=>A.exclude)),M.engine.rescope()},h=new Map,T=new Set,v=new Set,I=null,E=()=>I??=new Promise(M=>{let U=()=>fg.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return M(U());dg("scutil",["--get","ComputerName"],{timeout:1500},(C,A)=>M(!C&&String(A).trim()||U()))}),D=async()=>{let M=(await ot()).cloudSync?.deviceId;return M?{id:M,name:await E()}:null},x=new Map,L=(M,U,C)=>{let A=r,j=(x.get(M)??Promise.resolve()).catch(()=>{}).then(async()=>{A!==r||C&&!await C()||A!==r||await V(M,U,A)});return x.set(M,j),j.finally(()=>{x.get(M)===j&&x.delete(M)}).catch(()=>{}),j},V=async(M,U,C)=>{let A=s,j=encodeURIComponent(await A.ensureOwnVault()),F=Dc(M);for(let z=0;z<3;z++){let q=null;try{q=await A.call("GET",`/vaults/${j}/file?path=${encodeURIComponent(F)}`)}catch(re){if(re?.status!==404)throw re}let ne=U(!!q,q?xi(q.content):null);if(ne===void 0||C!==r)return;try{if(ne===null){q&&await A.call("DELETE",`/vaults/${j}/file?path=${encodeURIComponent(F)}&baseSeq=${q.seq}`);return}await A.call("PUT",`/vaults/${j}/file`,{path:F,content:Oc(ne),baseSeq:q?.seq??0});return}catch(re){if(re?.status!==409)throw re}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},H=async M=>!!(await ot()).entrySync?.some(U=>U.cloudName===M&&U.entries.length>0),N=(M,U)=>L(M,(C,A)=>{let j=A?.find(z=>z.id===U.id);if(j&&j.name===U.name)return;let F=j?.since??new Date().toISOString().slice(0,10);return[...(A??[]).filter(z=>z.id!==U.id),{...U,since:F}]},()=>H(M)),Y=(M,U)=>L(M,(C,A)=>{if(!C||!A?.some(F=>F.id===U))return;let j=A.filter(F=>F.id!==U);return j.length?j:null},async()=>!await H(M)),ee=()=>{e(Ne.entryChange)},J=async(M,U)=>{let C=h.get(M);if(!C)return;let A=z=>z&&z.startsWith(`${C.cloudName}/`)?z.slice(C.cloudName.length+1):null,j=A(U.path);if(!j)return;let F=!1;await Cn(z=>{if(h.get(M)!==C)return!1;let q=(z.entrySync??[]).find(oe=>oe.vaultRoot===M);if(!q)return!1;let ne=U.op,re=A(U.newPath),Z=jc(q.entries,ne,j,re),ie=re?yr(q.exclude??[],j,re):{changed:!1,next:q.exclude??[]};if(!Z.changed&&!ie.changed)return!1;F=!0,q.entries=Z.next,ie.changed&&(q.exclude=ie.next),_(C,Kt(q.entries,q.exclude??[]))}),F&&h.get(M)===C&&ee()},se=M=>{let U=r;return{...u(),onStatus:C=>{U===r&&e(Ne.status,{...C,pendingDeletions:me(),side:"local",binding:M})},onRemoteApplied:async C=>{U===r&&await J(M,C)}}},te=async()=>{let M=Be();if(!i||!M)return;let U=r,C=s,A=_n(M);await t.adoptLegacyCloudState(M,Fc);let j=await ot(M),F=j.entrySync??[];if(U!==r||!i||M!==Be())return;let z=new Map(F.map(q=>[q.vaultRoot,q]));for(let[q,ne]of h){let re=z.get(q);if(!(re&&re.cloudName===ne.cloudName)&&(await ne.engine.stop(),U!==r||(h.delete(q),re&&await vc(`amadeus-sync-${A}-entry-${Ti(q)}`),U!==r)))return}for(let q of F){let ne=h.get(q.vaultRoot);if(ne){_(ne,Kt(q.entries,q.exclude??[]));continue}let re={current:Kt(q.entries,q.exclude??[])},Z=q.cloudName,ie=mr(se(q.vaultRoot),{accountId:M,localRoot:q.vaultRoot,shadowName:`amadeus-sync-${A}-entry-${Ti(q.vaultRoot)}`,vaultId:"first",serverDir:Z,clientIdSuffix:`entry-${Ti(q.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:oe=>oe===Z?!0:oe.startsWith(`${Z}/`)?$c(re.current,oe.slice(Z.length+1)):!1});h.set(q.vaultRoot,{engine:ie,scope:re,cloudName:Z,base:re.current,pendingMoves:new Set}),ie.start()}if(j.cloudSync?.enabled!==!1)for(let q of F){let ne=q.entries.length>0,re=ne?T:v;re.has(q.cloudName)||((ne?v:T).delete(q.cloudName),(async()=>{try{let Z=await D();if(!Z||U!==r||(await(ne?N(q.cloudName,Z):Y(q.cloudName,Z.id)),U!==r))return;re.add(q.cloudName),(ne?v:T).delete(q.cloudName)}catch{}})())}},ae=async(M,U,C,A,j)=>{let F=U.replace(/\\/g,"/").normalize("NFC"),z=C.replace(/\\/g,"/").normalize("NFC"),q=!1,ne,re,Z,ie=j??"file";try{await Cn(async oe=>{if(h.get(M)!==A)return!1;let pe=(oe.entrySync??[]).find(yt=>yt.vaultRoot===M);if(!pe)return!1;let le=wr(pe.entries,F,z),X=yr(pe.exclude??[],F,z),ve=xn(pe.entries,pe.exclude,F);!j&&await Dn.stat(dn.join(M,...z.split("/"))).then(yt=>yt.isDirectory(),()=>!1)&&(ie="folder");let nn=ie==="folder"?"folder":/\.md$/i.test(z)?"page":"asset";ve&&!xn(le.next,X.next,z)&&(le.next.push({path:z,kind:nn}),le.changed=!0),q=le.changed||X.changed;let Jn=pe.entries.filter(yt=>wr([yt],F,z).changed);return ve&&!Jn.some(yt=>yt.path===F)&&Jn.push({path:F,kind:nn}),ne=Kt(Jn,(pe.exclude??[]).filter(yt=>yr([yt],F,z).changed)),re=A.base,A.pendingMoves.add(ne),pe.entries=le.next,pe.exclude=X.next,Z=Kt(pe.entries,pe.exclude),_(A,Z),q})}catch(oe){throw ne&&A.pendingMoves.delete(ne),_(A,A.base===Z&&re?re:A.base),oe}try{ne&&await A.engine.notifyLocalMove(F,z,()=>{A.pendingMoves.delete(ne),_(A)},ie)}catch(oe){throw ne&&A.pendingMoves.delete(ne),await Cn(pe=>{let le=pe.entrySync?.find(X=>X.vaultRoot===M);if(!le)return!1;le.entries=wr(le.entries,z,F).next,le.exclude=yr(le.exclude??[],z,F).next,_(A,Kt(le.entries,le.exclude))}),oe}q&&h.get(M)===A&&ee()},Q=M=>{let U=M.replace(/\\/g,"/");for(let{engine:C,plan:A}of g.values())if(U.startsWith(`${A.localRelDir}/`))return{engine:C,rel:U.slice(A.localRelDir.length+1)};return{engine:f,rel:U}};t.setMutationHooks((M,U)=>{if(b()){let C=Q(M);C.engine.notifyLocal(C.rel,U);return}h.get(n()??"")?.engine.notifyLocal(M,U)},(M,U,C)=>{if(b()){let F=Q(M),z=Q(U);if(F.engine===z.engine)return F.engine.notifyLocalMove(F.rel,z.rel,void 0,C);F.engine.notifyLocal(F.rel,"remove"),z.engine.notifyLocal(z.rel,"write");return}let A=n()??"",j=h.get(A);if(j)return ae(A,M,U,j,C)},(M,U)=>{if(b()){let C=Q(M),A=Q(U),j=[C.engine.holdLocalMove(C.rel,A.rel)];return C.engine!==A.engine&&j.push(A.engine.holdLocalMove(C.rel,A.rel)),()=>{for(let F of j)F()}}return h.get(n()??"")?.engine.holdLocalMove(M,U)});let me=()=>{let M=f.getStatus().pendingDeletions;for(let{engine:U}of g.values())M+=U.getStatus().pendingDeletions;for(let{engine:U}of h.values())M+=U.getStatus().pendingDeletions;return M},ge=M=>({...M,pendingDeletions:me(),side:b()?"cloud":"local"}),Pe=()=>{if(!i)return Promise.resolve(f.getStatus());y();for(let{engine:M}of g.values())M.syncNow();for(let{engine:M}of h.values())M.syncNow();return f.syncNow()},Ce=async()=>{let M=++r;i=!1,s.stop();let U=[f.stop(),...[...g.values()].map(({engine:A})=>A.stop()),...[...h.values()].map(({engine:A})=>A.stop())];if(g.clear(),h.clear(),p=[],T.clear(),v.clear(),a.clear(),o(),await Promise.all(U),await t.awaitPendingVaultWrites(),M!==r)return;let C=n();if(C&&bi(C)){let A=await ot();if(M!==r)return;let j=A.localVault&&!bi(A.localVault)?A.localVault:dn.join(t.workspaceDir(),"Amadeus");if(await Dn.mkdir(j,{recursive:!0}),M!==r||(await Pt({lastVault:j,localVault:j,lastPage:void 0}),M!==r))return;await t.activateRoot(j,!1)}M===r&&ee()};return{handlers:{get:()=>ge(f.getStatus()),setEnabled:async M=>{if(!i)throw new Error("Cloud account is changing");let U=r;return await f.setEnabled(M),U!==r?f.getStatus():(await Promise.all([...g.values(),...h.values()].map(({engine:C})=>C.restart())),ge(f.getStatus()))},syncNow:()=>Pe(),resolveHeld:M=>{let U=Array.isArray(M?.paths)?M.paths.filter(z=>typeof z=="string"):[],C=typeof M?.binding=="string"?M.binding:null,A=!C&&typeof M?.shareKey=="string"?M.shareKey:null,j=C?h.get(C)?.engine:A?g.get(A)?.engine:f;if(!j)return{error:"binding-not-found"};let F=j.resolveHeld(U,M.choice);return C?{...F,binding:C}:A?{...ge(F),shareKey:A}:ge(F)},confirmDeletions:()=>{for(let{engine:M}of g.values())M.confirmMassDeletions();for(let{engine:M}of h.values())M.confirmMassDeletions();return ge(f.confirmMassDeletions())},entryGet:async()=>{let M=await ot(),U=$t(),C=await Nc(U);return{vaults:M.entrySync??[],activeRoot:n(),cloudRoot:U,mirrorVaults:C.names,mirrorVaultDevices:C.devices,deviceId:M.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let M=n();if(!M)return null;let U=$t(),C=await ot(),A=M===U?C.localVault&&C.localVault!==U?C.localVault:null:U;if(!A)return null;let j=[],F=500,z=async(q,ne)=>{if(j.length>=F)return;let re;try{re=await Dn.readdir(q,{withFileTypes:!0})}catch{return}for(let Z of re){if(j.length>=F)break;if(Z.name.startsWith(".")||Z.isSymbolicLink())continue;let ie=ne?`${ne}/${Z.name}`:Z.name;if(Z.isDirectory())await z(dn.join(q,Z.name),ie);else if(Z.isFile()&&/\.db$/i.test(Z.name))try{j.push({rel:ie,source:await Dn.readFile(dn.join(q,Z.name),"utf8")})}catch{}}};return await z(A,""),{root:A,vaultName:A===U?"\u4E91\u7AEF":dn.basename(A),dbs:j}},entryEnable:async M=>{let U=r,C=s;if(!i||!Be())return{error:"Sign in to enable cloud sync"};let A=n();if(!A||b())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let j=await ot(),F=j.entrySync??[],z=F.find(q=>q.vaultRoot===A);if(!z){let q=(M.cloudName??dn.basename(A)).normalize("NFC").trim(),ne=ho(q,F.map(re=>re.cloudName));if(ne)return{error:ne};if(!M.merge)try{let re=await C.ensureOwnVault(),Z=await C.call("GET",`/vaults/${encodeURIComponent(re)}/tree`);if((Z.folders??[]).some(oe=>oe===q||oe.startsWith(`${q}/`))||(Z.entries??[]).some(oe=>oe.path===q||oe.path.startsWith(`${q}/`)))return{conflict:q}}catch(re){return{error:re?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}z={vaultRoot:A,cloudName:q,entries:[]},F.push(z)}return U!==r||!i?{error:"Cloud account changed; retry from the current account"}:(await Cn(q=>{if(U!==r||!i)return!1;let ne=q.entrySync??[],re=ne.find(X=>X.vaultRoot===A);if(!re){let X=ho(z.cloudName,ne.map(ve=>ve.cloudName));if(X)throw new Error(X);re={vaultRoot:A,cloudName:z.cloudName,entries:[]},ne.push(re)}let Z=X=>String(X??"").replace(/\\/g,"/").normalize("NFC"),ie=new Set;for(let X of M.entries??[]){let ve=Z(X.path);ve&&(ie.add(ve),!re.entries.some(nn=>nn.path===ve)&&re.entries.push({path:ve,kind:X.kind==="folder"||X.kind==="asset"?X.kind:"page"}))}let oe=(M.exclude??[]).map(Z).filter(Boolean),pe=new Set([...ie,...(M.include??[]).map(Z).filter(Boolean)]);re.exclude=[...new Set([...(re.exclude??[]).filter(X=>!pe.has(X)),...oe])];let le=new Set(oe);re.entries=re.entries.filter(X=>!le.has(X.path)),q.entrySync=ne,z=re},j.cloudAccountId),U!==r?{error:"Cloud account changed; retry from the current account"}:(await te(),h.get(A)?.engine.syncNow(),ee(),{ok:!0,cloudName:z.cloudName}))},entryDisable:async M=>{let U=n(),C=!1,A=r;return await Cn(j=>{if(A!==r||!i)return!1;let F=(j.entrySync??[]).find(ne=>ne.vaultRoot===U);if(!U||!F)return!1;let z=String(M??"").replace(/\\/g,"/").normalize("NFC"),q=F.entries.length;if(F.entries=F.entries.filter(ne=>ne.path!==z),xn(F.entries,F.exclude,z))F.exclude=[...new Set([...F.exclude??[],z])];else if(F.entries.length===q)return!1;C=!0}),!C||A!==r?{ok:!1}:(await te(),ee(),{ok:!0})},entryMark:async(M,U)=>{let C=String(M??"").normalize("NFC");if(!C||C.includes("/")||C.startsWith("."))return{error:"invalid name"};if(!i||!Be())return{error:"Sign in first"};try{await L(C,A=>U?A?void 0:[]:A?null:void 0)}catch(A){return{error:A?.message||String(A)}}return f.syncNow(),{ok:!0}},entryClosure:(M,U)=>t.relatedClosure(String(M??""),U==="folder"?"folder":"page"),collabCall:async(M,U)=>{let C=s,A=async()=>C.ensureOwnVault(),j=z=>String((U??[])[z]??""),F=z=>(U??[])[z]??{};switch(M){case"listVaults":return(await C.call("GET","/vaults")).vaults;case"activeVaultId":return A();case"pageShare":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/page-shares?path=${encodeURIComponent(j(0))}`);case"relatedItems":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}/related`);case"setShareItem":return C.call("POST",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}/items`,{path:j(1),included:(U??[])[2]===!0});case"createPageShare":return C.call("POST",`/vaults/${encodeURIComponent(await A())}/page-shares`,{path:j(0),...F(1)});case"updatePageShare":return C.call("PATCH",`/vaults/${encodeURIComponent(j(2)||await A())}/page-shares/${encodeURIComponent(j(0))}`,F(1));case"revokePageShare":return C.call("DELETE",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}`);case"setParticipantRole":return C.call("PATCH",`/vaults/${encodeURIComponent(j(3)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(j(1))}`,{role:j(2)});case"removeParticipant":return C.call("DELETE",`/vaults/${encodeURIComponent(j(2)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(j(1))}`);case"sharedWithMe":{let z=await C.sharedWithMe();return y(),z}case"leaveShare":{let z=C.myUserId();if(!z)throw new Error("\u672A\u767B\u5F55");let q=await C.call("DELETE",`/vaults/${encodeURIComponent(j(1)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(z)}`);return y(),q}case"publishes":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/shares`);case"listAllShares":{let z=(await C.call("GET","/vaults")).vaults||[],q=C.myUserId(),ne=[],re=[];for(let Z of z){try{let ie=await C.call("GET",`/vaults/${encodeURIComponent(Z.id)}/shares`);for(let oe of ie.shares||[])ne.push({...oe,vaultId:Z.id,vaultName:Z.name||""})}catch(ie){t.log(`[connect] listAllShares publishes vault ${Z.id} failed: ${ie?.message}`)}try{let ie=await C.call("GET",`/vaults/${encodeURIComponent(Z.id)}/page-shares?expired=1`),oe=ie?.shares||ie?.pageShares||(Array.isArray(ie)?ie:[]);for(let pe of oe){let le=pe.created_by??pe.createdBy;(!q||!le||le===q)&&re.push({...pe,vaultId:Z.id,vaultName:Z.name||""})}}catch(ie){t.log(`[connect] listAllShares pageShares vault ${Z.id} failed: ${ie?.message}`)}}return{publishes:ne,pageShares:re,linkBase:await C.linkBase()}}case"createPublish":{let z=await C.call("POST",`/vaults/${encodeURIComponent(await A())}/shares`,{mode:j(0),path:j(1)});return{...z,url:`${await C.linkBase()}/share/${z.token}`}}case"revokePublish":return C.call("DELETE",`/vaults/${encodeURIComponent(await A())}/shares/${encodeURIComponent(j(0))}`);case"revokePublishIn":return C.call("DELETE",`/vaults/${encodeURIComponent(j(0))}/shares/${encodeURIComponent(j(1))}`);case"revokePageShareIn":return C.call("DELETE",`/vaults/${encodeURIComponent(j(0))}/page-shares/${encodeURIComponent(j(1))}`);case"myUserId":return C.myUserId();case"linkBase":return C.linkBase();case"heartbeat":return C.heartbeat((U??[])[0]??null,p);default:throw new Error(`unknown collab fn: ${M}`)}},switchSide:async(M,U)=>{let C=await ot();if(U==="cloud"){if(!i||!Be())throw new Error("Sign in to open cloud notes");let F=$t();await Dn.mkdir(F,{recursive:!0}),C.lastVault&&!bi(C.lastVault)&&await Pt({localVault:C.lastVault}),await Pt({lastVault:F});let z=await t.activateRoot(F,!1);return t.bindRenderer(M,F),{...z,side:"cloud"}}let A=C.localVault&&await Dn.stat(C.localVault).then(F=>F.isDirectory()).catch(()=>!1)?C.localVault:null;if(!A){let F=await t.ensureDefaultVault();return t.bindRenderer(M,F.root),{...F,side:"local"}}await Pt({lastVault:A});let j=await t.activateRoot(A,!1);return t.bindRenderer(M,A),{...j,side:"local"}}},instance:{start:()=>{i=!0,f.start(),y(),te()},stopAllSync:Ce,restartAllSync:async()=>{let M=Ce(),U=r;await M,U===r&&(s=co(),f=mr(u()),i=!0,await Promise.all([f.restart(),y(),te()]),U===r&&(ee(),e(Ne.status,ge(f.getStatus()))))},resolveSharedAsset:M=>Rc(p,M)}}}import{hostname as gg}from"node:os";var mg=256*1024;function Zc(t,e,n){if(n?.hasSecHeaders&&!n.gatewayStreamsSecHeaders)return!1;if(t.includes("text/event-stream"))return!0;let r=Number(e||NaN);return!Number.isFinite(r)||r>mg}var vo=45e3,yg=3e3,wg=16*1024,bg=6e4,Ri=t=>`${t.replace(/\/+$/,"")}/api`,Sr=class{deps;ctrl=null;conn=null;wake=null;redialNow=!1;inflight=new Map;connected=!1;lastError=null;hubCaps=new Set;constructor(e){this.deps=e}hubFetch(e,n){return(this.deps.hubFetch??fetch)(e,n)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??bg}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(n),r.ctrl.abort())}sleep(e){return new Promise(n=>{let r=setTimeout(i,e);function i(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,i()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,i=()=>r.abort();e.signal.addEventListener("abort",i,{once:!0}),this.conn=r;try{let{cloudUrl:s,token:a}=this.deps.getCreds();if(!a)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let o=this.deps.getPairing();if(!o){if(o=await this.register(s,a,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(o),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${o.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let c=this.deps.readIdleMs??vo,u=c?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(c/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},c):null,f;try{f=await this.hubFetch(`${Ri(s)}/units/${o.unitId}/channel`,{headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":o.secret,...l?{"X-Unit-Lan-Url":l}:{}},signal:r.signal})}finally{u&&clearTimeout(u)}if(f.status===403||f.status===404){let g=Number(f.headers.get("content-length"))>wg,p=setTimeout(()=>r.abort(),g?0:yg),m=await f.json().then(y=>y?.code,()=>null);throw clearTimeout(p),m==="UNIT_NOT_FOUND"||m==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${f.status} ${m}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${f.status} (not a hub verdict; keeping pairing and retrying)`)}if(!f.ok||!f.body)throw new Error(`channel HTTP ${f.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(f.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(s){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(s?.message||s),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",i),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,r){let i=this.deps.readIdleMs??vo,s=i?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(i/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},i):null;try{let a=await this.hubFetch(`${Ri(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:gg(),platform:process.platform}),signal:r.signal});if(!a.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${a.status}`);let o=await a.json();if(!o.unitId||!o.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:o.unitId,secret:o.secret}}finally{s&&clearTimeout(s)}}async consume(e,n){let r=e.getReader(),i=new TextDecoder,s="",a=this.deps.readIdleMs??vo,o=null,l=()=>{a&&(o&&clearTimeout(o),o=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(a/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),n.abort(),r.cancel().catch(()=>{})},a))};l();try{for(;;){let{done:c,value:u}=await r.read();if(c||n.signal.aborted)return;l(),s=this.parseFrames(s+i.decode(u,{stream:!0}),n)}}finally{o&&clearTimeout(o)}}parseFrames(e,n){let r=e,i;for(;(i=r.indexOf(`
|
|
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(`
|
|
219
219
|
|
|
220
|
-
`))>=0;){let s=r.slice(0,
|
|
221
|
-
`).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(
|
|
222
|
-
`).find(o=>o.startsWith("data: "))?.slice(6);if(a)try{let o=JSON.parse(a);this.dispatch(o,n).catch(l=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${l?.message||l}`))}catch{}}return r}async dispatch(e,n){let r=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let i={ctrl:r,conn:n};this.inflight.set(e.id,i);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===i&&this.inflight.delete(e.id)}}async handle(e,n){let r=this.deps.getUnitWeb();if(!r.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,n.signal);return}let i={"x-unit-internal":r.internalSecret};e.ct&&(i["Content-Type"]=e.ct),e.accept&&(i.Accept=e.accept);let s;try{let u=new URL(`${r.url}${e.path}`);Object.assign(i,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:u,proxyCaller:e.proxyCaller,proxyOperator:e.proxyOperator})),s=await fetch(u,{method:e.method,headers:i,body:e.body??void 0,signal:n.signal})}catch(u){if(n.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${u?.message||u}`})),void 0,n.signal);return}let a=s.headers.get("content-type")||"",o={};for(let u of["content-security-policy","x-content-type-options"]){let f=s.headers.get(u);f&&(o[u]=f)}let l=a||"application/octet-stream";s.body&&Zc(a,s.headers.get("content-length"),{hasSecHeaders:Object.keys(o).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,s,n,l,o):await this.respond(e.id,s.status,l,Buffer.from(await s.arrayBuffer()),o,n.signal)}async respond(e,n,r,i,s,a){if(a?.aborted)return;let{cloudUrl:o,token:l}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let u=this.requestTimeoutMs*2,f=[...u?[AbortSignal.timeout(u)]:[],...a?[a]:[]],g=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${Ri(o)}/units/${c.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":c.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":r,...s},bodyB64:i.toString("base64")}),...g?{signal:g}:{}}).then(p=>{p.body?.cancel().catch(()=>{})}).catch(p=>{a?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${p?.name==="TimeoutError"?`${Math.round(u/1e3)}s \u672A\u5B8C\u6210`:p?.message||p}`)})}async streamBack(e,n,r,i,s){let{cloudUrl:a,token:o}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let c=s?.["content-security-policy"],u=s?.["x-content-type-options"],f=`${Ri(a)}/units/${l.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(i)}`+(c?`&csp=${encodeURIComponent(c)}`:"")+(u?`&xcto=${encodeURIComponent(u)}`:""),g=n.body;if(!g)return;let p=g.getReader(),m=0,y=this.requestTimeoutMs,b=y?setTimeout(()=>{m>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(y/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},y):null,_=new ReadableStream({async pull(h){++m===2&&b&&clearTimeout(b);let{done:T,value:v}=await p.read();T?h.close():h.enqueue(v)},cancel(h){return p.cancel(h)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${o}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:_,signal:r.signal,duplex:"half"})}catch(h){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${h?.message||h}`);try{await p.cancel()}catch{}}finally{b&&clearTimeout(b)}}};function Sg(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(typeof n!="string"||n.length===0||n.length>64)&&!e.includes(n)&&(e.push(n),e.length>=16))break;return e}var vr=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}capsChanged(){this.engineChanged()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(c){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${c?.message||c}`);return}let n={engine:e,tools:[]};if(typeof this.d.features=="function"){let c=[];try{c=this.d.features()}catch(u){this.d.log(`[unit-caps] \u8BFB\u80FD\u529B\u58F0\u660E\u5931\u8D25:${u?.message||u}`)}n.features=Sg(c)}let r=JSON.stringify(n);if(r===this.lastSent)return;let i=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!i||!s.token||!s.cloudUrl)return;let a=this.gen;this.inflight=!0;let o=new AbortController,l=setTimeout(()=>o.abort(),this.d.timeoutMs??1e4);try{let c=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(i.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(c,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":i.secret,"Content-Type":"application/json"},body:r,signal:o.signal});try{await u.text()}catch{}if(a!==this.gen)return;u.ok?(this.lastSent=r,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}${n.features?`(\u80FD\u529B\u58F0\u660E ${n.features.length} \u9879)`:""}`)):u.status===404||u.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${u.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):u.status===400||u.status===401||u.status===403?this.warned.has(u.status)||(this.warned.add(u.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${u.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${u.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(c){a===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${o.signal.aborted?"\u8D85\u65F6":c?.message||c}`)}finally{clearTimeout(l),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var Qc=["setUnitHubFactory"],ko=t=>Qc.every(e=>typeof t[e]=="function");function eu(t){let e=new vr({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),...typeof t.capsFeatures=="function"?{features:()=>t.capsFeatures()}:{},log:r=>t.log(r)}),n=new Sr({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged(),capsChanged:()=>e.capsChanged()}}function Eo(t){let e=async(n,r,i)=>{let{base:s,token:a}=await t.getCloud();if(!a)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let o=await fetch(`${s}/api${r}`,{method:n,headers:{Authorization:`Bearer ${a}`,...i!==void 0?{"Content-Type":"application/json"}:{}},body:i!==void 0?JSON.stringify(i):void 0});return{status:o.status,json:await o.json().catch(()=>null)}}catch(o){return{status:0,json:{detail:String(o?.message||o)}}}};t.handle("units:list",(n,r)=>e("GET",r!=null&&typeof r=="object"&&r.shared===!0?"/units?shared=1":"/units")),t.handle("units:update",(n,r,i)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:i?.name,icon:i?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:i,token:s}=await t.getCloud();await t.openExternal(`${i}/api/units/${r}/open${s?`#token=${encodeURIComponent(s)}`:""}`)}),t.setUnitHubFactory(eu),t.log("[forsion-extend] unit hub registered")}import{createHash as Gg}from"node:crypto";import{constants as Au,mkdirSync as Vg,readFileSync as Yg,renameSync as Jg,writeFileSync as Kg}from"node:fs";import{lstat as Ft,open as Uu,readFile as Xg,readdir as Hu,statfs as Zg}from"node:fs/promises";import{cpus as Qg,freemem as em,homedir as xu,hostname as zu,release as tm,totalmem as nm}from"node:os";import{basename as Bu,join as de}from"node:path";var vg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,kr=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,i="Z";if(typeof e=="string"){let s=e.match(vg);s?(s[1]||(n=!1,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=!1,n.#e=null,n}};function kg(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Eg(t,e,n){let r=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let a=e-1;a<=e+1;a++){let o=r[a-1];o&&(i+=a.toString().padEnd(s," "),i+=": ",i+=o,i+=`
|
|
223
|
-
`,a===e&&(
|
|
224
|
-
`))}return
|
|
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}
|
|
225
225
|
|
|
226
|
-
${s}`,n),this.line=r,this.column=
|
|
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
227
|
`?e++:t[e]==="\r"&&t[e+1]===`
|
|
228
|
-
`&&(e+=2));let a="",
|
|
228
|
+
`&&(e+=2));let a="",i=e,l=0;for(let c=e;c<t.length;c++)if(n=t[c],s&&(n===`
|
|
229
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(
|
|
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});
|
|
232
|
-
`,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function
|
|
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
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
|
|
235
|
-
`||
|
|
236
|
-
`);)e++;if(r||
|
|
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
237
|
`||a==="\r"&&t[s+1]===`
|
|
238
|
-
`))return s}}throw new ce("cannot find end of structure",{toml:t,ptr:e})}function
|
|
239
|
-
`&&t[c]!=="\r")throw new ce("unexpected character encountered",{toml:t,ptr:c});t[c]===","&&c++}return[l,c]}let a=
|
|
240
|
-
`&&a!=="\r"){let
|
|
241
|
-
`&&s!=="\r"){let a=
|
|
242
|
-
`&&t[o]!=="\r")throw new ce("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:o});o=At(t,o)}return r}var $i=14,Ig=1440*6e4,Rg=12e4,Dg=15e3,_o=1792*1024,Og=7,jt=t=>t.toISOString().slice(0,10),xt=t=>Date.parse(jt(t))-(Og-1)*Ig,ou=["sessions","activity"],Pi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Co(t,e,n){let r=t?.day===jt(n)?t:void 0;return Object.fromEntries(ou.map(i=>[i,Pi(r?.[i])??Math.min(Math.max(Pi(e[i])??0,xt(n)),n.getTime())]))}function Ao(t,e,n,r,i,s){let a=e?.day===jt(r)?e:void 0,o={sent:{...t},file:{day:jt(r)}};for(let l of ou){let c=l in i&&!s.includes(l)&&!(`${l}Error`in i),u=Pi(a?.[l]);c?(o.file[l]=n[l],o.sent[l]=r.getTime()):u!==void 0&&(o.sent[l]=Math.min(Pi(t[l])??u,u))}return o}function au(t,e=[]){let n={...t},r=nr(JSON.stringify(n));for(let i of["activity","sessions","memory","runs","engine"]){if(r.length<=_o)break;i in n&&(delete n[i],e.push(i),r=nr(JSON.stringify({...n,truncated:e})))}return r.length>_o?null:r}async function xo(t,e,n,r=new Date){let i=AbortSignal.timeout(Rg);await t.writeFile(`${e}/${jt(r)}.json`,n,r.getTime(),i);try{let s=jt(new Date(r.getTime()-$i*24*60*6e4));for(let a of await t.walk(i)){let o=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(a.key);o&&o[1]===e&&o[2]<s&&await t.rm(a.key,i)}}catch{}}var To={mode:"scheduled",intervalHours:24,requestedAt:0};function _r(t){let e=t&&typeof t=="object"?t:{},n=Number(e.intervalHours),r=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(n)&&n>=1&&n<=720?n:To.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Io(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Dg)});return e.status===404?{...To}:e.ok?_r(await e.json()):null}catch{return null}}var uu=["merge","cloud","local"],du={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Xt(t,e=!1){if(typeof t!="string"||!t&&!e||t.length>512||t.startsWith("/")||/[\\\u0000-\u001f\u007f]/.test(t)||t&&t.split("/").some(n=>!n||n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||n.startsWith(".forsion-sync")))throw Error("Invalid content path");return t}function Mg(t){if(t==="default"||t==="off"||typeof t=="string"&&/^device-[A-Za-z0-9_-]{1,64}$/.test(t))return t;throw Error("Invalid content target")}function Zt(t,e){let n=t;if(!n||n.version!==1||typeof n.enabled!="boolean"||!Array.isArray(n.rules)||n.rules.length>512)throw Error("Invalid content sync configuration");let r=new Set,i=new Set,s=n.rules.map(a=>{let o=Xt(a.source,!0),l=Mg(a.target);if(typeof a.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(a.id)||i.has(a.id)||r.has(o))throw Error("Duplicate or invalid sync rule");return i.add(a.id),r.add(o),{id:a.id,source:o,target:l,...a.sourceId&&/^[a-f0-9-]{36}$/i.test(a.sourceId)?{sourceId:a.sourceId}:{}}});return{version:1,revision:e,enabled:n.enabled,rules:s}}function Mn(t,e){let n=null;for(let r of e)(!r.source||t===r.source||t.startsWith(r.source+"/"))&&(!n||r.source.length>n.source.length)&&(n=r);return n}var gt={get:"penzor:sync:get",preview:"penzor:sync:preview",apply:"penzor:sync:apply",run:"penzor:sync:run",pause:"penzor:sync:pause",retry:"penzor:sync:retry",rename:"penzor:sync:rename",setup:"penzor:sync:setup",archiveSeen:"penzor:sync:archiveSeen",confirmDeletes:"penzor:sync:confirmDeletes",abandonDeletes:"penzor:sync:abandonDeletes"},lu=200,Ro=6e4,Ng=50;function Do(t,e,n,r){return t.deleted?"forget":t.busy||r?"skip":t.version?e&&e.version===t.version&&Li(e.file,t.file)?"delete":"download":n?"cancel":"skip"}var Li=(t,e)=>t===void 0||e===void 0||t===e,Pg=(t,e)=>{let n=e.indexOf("/");return t+":"+(n<0?"":e.slice(0,n))};function Oo(t,e,n){if(!t.length)return!1;if(n.latched||t.length>=lu||n.recent+t.length>Ng)return!0;let r=a=>{let o=new Map;for(let l of a){let c=Pg(l.ns,l.path);o.set(c,(o.get(c)??0)+1)}return o},i=r(t),s=r(e);for(let[a,o]of i)if(fr(o,s.get(a)??0,lu))return!0;return!1}var Fi=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,cu=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Mo=(t,e,n)=>{let r=cu(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(i=>i.id!==n&&cu(i.name)===r)?"taken":null:null},fu=["Amadeus","agents","human","Plugins"],fn=1024*1024,ji=50*fn,$g=[{prefix:"Amadeus/",ext:[".md",".db"],maxBytes:5*fn},{prefix:"Amadeus/",maxBytes:5*fn},{prefix:"agents/",maxBytes:5*fn},{prefix:"human/",maxBytes:5*fn},{prefix:"",maxBytes:50*fn}],jg=[{prefix:"",maxBytes:50*fn}];function Ui(t,e,n){let r=Array.isArray(n)&&n.length?n:e==="default"?$g:jg,i=t.toLowerCase();for(let s of r)if(!(!s||typeof s.prefix!="string"||!Number.isSafeInteger(s.maxBytes)||s.maxBytes<=0)&&t.startsWith(s.prefix)&&!(Array.isArray(s.ext)&&s.ext.length&&!s.ext.some(a=>typeof a=="string"&&i.endsWith(a.toLowerCase()))))return Math.min(s.maxBytes,ji);return ji}var Lg=6e4,Fg=10*6e4,pu=t=>t<=1?0:Math.min(Lg*2**(t-2),Fg),No="delete-guard";var Lt=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var Cr=/^[a-z0-9][a-z0-9-]{0,63}$/,Hi=new Set(["muse"]),Ar=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&Cr.test(e[1])?e[1]:null},Ug=t=>[...Hi].some(e=>Po(t,`agents/${e}`));function hu(t){let e=t.split(/^\s*\[/m)[0]??"",n=s=>{let a=new RegExp(`^[ \\t]*${s}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(a?.[1]!=null?a[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):a?.[2])?.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,80)||void 0},r=n("name"),i=n("name_en");return{...r?{name:r}:{},...i?{nameEn:i}:{}}}var Nn=(t,e)=>Mn(e,t)?.target??"off",Po=(t,e)=>t===e||t.startsWith(e+"/"),Hg=t=>Lt.some(e=>Po(t,e.path)),$o=t=>t.some(e=>e.id==="default")?zi():"default",gu=(t,e)=>t.enabled?Nn(t.rules,e):"off";function mu(t,e,n){n==="off"&&(t=t.filter(s=>e?!s.source.startsWith(e+"/"):!s.source||Hg(s.source)));let r=t.find(s=>s.source===e),i=t.filter(s=>s!==r);return e&&Nn(i,e)===n?i:r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:e?zi():$o(t),source:e,target:n}]}function Pn(t,e,n,r=!1){if(Ug(e))return t;let i=t.rules;if(!t.enabled){let s=i.find(o=>!o.source),a=e?i.filter(o=>o.source&&Po(o.source,e)):[];i=[{id:s?.id??$o(a),source:"",target:"off"},...a],e!=="agents"&&(i=jo(i,"agents","off"))}if(!e)for(let s of Lt)i.some(a=>a.source===s.path)||(i=[...i,{id:zi(),source:s.path,target:Nn(i,s.path)}]);return yu({...t,rules:mu(i,e,n)},r)}function yu(t,e=!1){let n=r=>Nn(t.rules,r)!=="off";return{...t,enabled:Lt.some(r=>n(r.path))||t.rules.some(r=>r.source&&r.target!=="off")||e&&n("")}}function wu(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:$o(t.rules),source:"",target:"default"},...t.rules];for(let n of Lt)n.id!=="agents"&&Nn(e,n.path)==="off"&&(e=mu(e,n.path,"default"));return e=jo(e,"agents","off"),{...t,enabled:!0,rules:e}}function jo(t,e,n){let r=t.find(i=>i.source===e);return r?t.map(i=>i===r?{...i,target:n}:i):[...t,{id:zi(),source:e,target:n}]}function bu(t,e){let n=t;for(let r of new Set(e))Cr.test(r)&&!Hi.has(r)&&(n=Pn(n,`agents/${r}`,"default"));return n}function Su(t){let e=Nn(t.rules,"agents")!=="off"||t.rules.some(i=>i.source.startsWith("agents/")&&i.target!=="off"),n=t.rules.some(i=>i.source.startsWith("agents/"));if(!e&&!n)return null;let r=jo(t.rules.filter(i=>!i.source.startsWith("agents/")),"agents","off");return t.enabled?yu({...t,rules:r},!0):{...t,rules:r}}var zg=0,zi=()=>`rule-${Date.now().toString(36)}-${(zg++).toString(36)}`;var vu=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var Bg=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function ku(t,e=[]){let n=t;for(let r of[...e].filter(i=>i&&i.length>=2).sort((i,s)=>s.length-i.length))n=n.split(r).join("[path]");return n.replace(/^(Duplicate folder sync identity|Concurrent (?:folder|file) rename): [\s\S]*$/,"$1: [path]")}var xr=class{since;cur=null;last=null;runs=[];totals={runs:0,completedRuns:0,idleRuns:0};errors=[];clock;constructor(e=Date.now){this.clock=e,this.since=e()}reset(){this.since=this.clock(),this.cur=null,this.last=null,this.runs=[],this.errors=[],this.totals={runs:0,completedRuns:0,idleRuns:0}}begin(e=this.clock()){this.cur={at:e,counts:{}}}count(e,n=1){n>0&&(this.cur&&(this.cur.counts[e]=(this.cur.counts[e]??0)+n),this.totals[e]=(this.totals[e]??0)+n)}fault(e,n=[],r=this.clock()){if(!e||Bg.test(e))return;this.count("errors"),/^File exceeds \d+ MB/.test(e)&&this.count("tooLarge");let i=this.errors[this.errors.length-1];if(i&&i.text===e){i.n++,i.at=r,this.addPaths(n);return}this.errors.push({first:r,at:r,n:1,text:e}),this.addPaths(n),this.errors.length>20&&this.errors.shift()}addPaths(e){let n=this.errors[this.errors.length-1],r=e.filter(i=>typeof i=="string"&&i);!n||!r.length||(n.paths=[...new Set([...n.paths??[],...r])].slice(0,8))}end(e,n=this.clock()){let r=this.cur;if(!r)return;this.cur=null;let i={at:r.at,ms:Math.max(0,n-r.at),completed:e,counts:r.counts};this.last=i,this.totals.runs++,e&&this.totals.completedRuns++,!e||Object.keys(r.counts).length?(this.runs.push(i),this.runs.length>20&&this.runs.shift()):this.totals.idleRuns++}snapshot(){let e=n=>({...n,counts:{...n.counts}});return{since:this.since,lastRun:this.last&&e(this.last),runs:this.runs.map(e),totals:{...this.totals},errors:this.errors.map(n=>({...n,...n.paths?{paths:[...n.paths]}:{}}))}}},Eu=null;function _u(t){Eu=t}function Cu(){try{return Eu?.()??null}catch{return null}}var rm=(t,e=[])=>{let n=au(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},qu=60*6e4,im=2*6e4,sm=10*6e4,Tu=qu,om=4*1024*1024,am=256*1024,Iu=["user","teamwork","discussion","delegate"],lm=/^(?:New remarks in the team chat:|You are activated now \()/,Wu={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Fo=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,Gu=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,i)=>Fo.test(i)||e&&!/\s/.test(i)?n:`${r}[path]${r}`),Vu=t=>Gu(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>Fo.test(e)?e:"[path]"),Rr=4e3,qi=(t,e)=>typeof t=="string"&&t?It(Vu(Rt(t.slice(0,Rr))),e):void 0,cm={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},um=64*1024,Lo=500,dm={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},fm=256*1024,Ru=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],pm=["description","developer_instructions"],hm=["memory","harness","project_memory","human","dream","log_appended"],gm=["homeDir","readCreds","accountId","appVersion"],Uo=t=>gm.every(e=>typeof t[e]=="function"),Du=xu().length>3?xu():null;function Rt(t){return typeof t=="string"?(Du?t.split(Du).join("~"):t).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,(e,n,r)=>/^[a-f0-9]{48}$/.test(e)&&/(?:^|[^\w-])pr-$/.test(r.slice(Math.max(0,n-4),n))?e:`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(t)?t.map(Rt):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":Rt(n)])):t}var mm=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ue=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,ym=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function $n(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[r,[i,s]]of Object.entries(t).slice(0,100).entries())n[ym(i,r)]=mm.test(i)&&ue(s,80)!==void 0?s:$n(s,e+1);return n}var wm={"":/^(?:name|version|description|model|model_reasoning_effort|approval_mode|max_iterations|tools|enabled_skill_ids|enabled_mcp_servers|library_order|apps|avatar|share_default_memory|cloud_sync|activity_access|tools_strict|tools_mode|tools_list|created_by|created_at|developer_instructions|compaction|lead|slug|members|mode|max_rounds)$/,compaction:/^(?:enabled|reserveTokens|thresholdPercent|keepRecentTokens|summaryMaxTokens|thinking|model|instructions|prompt)$/,members:/^(?:slug|role)$/},Ou={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},bm=/^(?:apps|enabled_skill_ids)$/,Mu=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Sm(t){try{let e=Ni(t),n=[],r=[],i=8192,s=(l,c)=>i<=0?!1:(i-=c.length+1,l.push(c),!0),a=(l,c,u)=>{let f=wm[l].test(c)?c:`[key:${c.length}]`,g=Ou[l].test(c),p;return typeof u=="boolean"||typeof u=="number"?p=String(u):g&&typeof u=="string"&&!/[\r\n]/.test(u)&&JSON.stringify(u).length<=120?p=JSON.stringify(u):g&&u instanceof Date?p=u.toISOString():l===""&&bm.test(c)&&Array.isArray(u)&&u.every(m=>typeof m=="string"&&!/[\r\n]/.test(m))&&JSON.stringify(u).length<=2e3&&(p=`[${u.map(m=>JSON.stringify(m)).join(", ")}]`),`${f} = ${p??`"[text:${typeof u=="string"?u.length:JSON.stringify(u).length}]"`}`},o=(l,c,u)=>{if(s(r,c)){for(let[f,g]of Object.entries(u))if(!s(r,a(l,f,g)))return}};for(let[l,c]of Object.entries(e)){let u=l!==""&&Object.hasOwn(Ou,l);if(u&&Mu(c))o(l,`[${l}]`,c);else if(u&&Array.isArray(c)&&c.length>0&&c.every(Mu))for(let f of c)o(l,`[[${l}]]`,f);else s(n,a("",l,c));if(i<=0)break}return[...n,...r].join(`
|
|
243
|
-
`)}catch{return`[unparsed:${t.length}]`}}var
|
|
244
|
-
`)+1):a}finally{await n.close()}}function
|
|
245
|
-
`).filter(
|
|
246
|
-
`)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:pn(g)}}return{activity:c.reverse(),...f?{activityTruncated:!0}:{}}}var
|
|
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
|
|
247
247
|
FROM chat_messages m JOIN chat_sessions s ON s.id = m.session_id
|
|
248
|
-
WHERE s.kind IN (${
|
|
249
|
-
FROM chat_messages m WHERE m.session_id = ? AND ${c} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),p=[],m=0,y=f.length>n.sessions;for(let b of f.slice(0,n.sessions)){let
|
|
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
|
|
250
250
|
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(
|
|
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,
|
|
252
252
|
json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
|
|
253
253
|
json_extract(e.payload, '$.reasoningTokens') AS reasoning, json_extract(e.payload, '$.llmMs') AS llm_ms, json_extract(e.payload, '$.ttftMs') AS ttft_ms,
|
|
254
|
-
json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${
|
|
255
|
-
FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),u=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},
|
|
256
|
-
`),...s?{logTruncated:!0}:{}}}var
|
|
257
|
-
WHERE created_at >= ? AND created_at < ? AND (${
|
|
258
|
-
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(Ln(xt(e)),Ln(e.getTime()),n.activity+1);b.length>n.activity&&(a.truncated=!0);for(let _ of b.slice(0,n.activity))if(!l(a.activity,{at:ue(_.created_at,40)??null,agent:ue(_.agent,64)??null,action:ue(_.action,64)??null,detail:typeof _.detail=="string"&&_.detail?It(Rt(_.detail),n.detailChars):void 0,session:ue(_.session_ref,64)}))break}catch(m){a.activityError=pn(m)}finally{try{p?.close()}catch{}}}for(let p of await Tt(de(r,"project-memory"),100)){let m=de(r,"project-memory",p);if(!await Ir(m))continue;let y=await Tr(de(m,"MEMORY.md"),n.fileChars),b=await Fu(m);if(!y&&!b)continue;let _=(await jn(de(m,"PROJECT.json")))?.project;if(!l(a.projects,{id:ue(p,64)??null,name:typeof _=="string"?ue(Bu(_.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:b,memory:y}))break}for(let p of await Tt(de(r,"teams"),100)){if(!await Ir(de(r,"teams",p)))continue;let m=await Tr(de(r,"teams",p,"TEAM.md"),n.fileChars);if(m&&!l(a.teams,{id:p,files:{"TEAM.md":m}}))break}let g=[];for(let p of await Tt(de(r,"agents"),100)){let m=de(r,"agents",p);await Ir(m)&&g.push({id:p,dir:m,at:Math.max(0,...await Promise.all([...Ru,".memory-state.json"].map(y=>i(de(m,y)))))})}for(let{id:p,dir:m,at:y}of g.sort((b,_)=>_.at-b.at||b.id.localeCompare(_.id))){let b={};for(let I of Ru){let E=await Tr(de(m,I),n.fileChars);E&&(b[I]=E)}let _=[];if(await Ir(de(m,"LOG")))for(let I of(await Tt(de(m,"LOG"),400)).filter(E=>/^\d{4}-\d{2}-\d{2}\.md$/.test(E)&&E.slice(0,10)>=s&&E.slice(0,10)<=jt(e))){let E=await Tr(de(m,"LOG",I),n.logChars);E&&_.push({date:I.slice(0,10),text:E})}let h=(await jn(de(m,".memory-dream.json")))?.last,T=await Fu(m),v=await Lm(m,n.fileChars);!Object.keys(b).length&&!_.length&&!T&&!v||l(a.agents,{id:p,updatedAt:y?new Date(y).toISOString():null,config:v,state:T,dream:h&&typeof h=="object"?{state:ue(h.state,32),startedAt:ue(h.startedAt,40),finishedAt:ue(h.finishedAt,40),calls:typeof h.calls=="number"?h.calls:void 0,detail:typeof h.detail=="string"?It(Rt(h.detail),n.detailChars):void 0}:void 0,files:Object.keys(b).length?b:void 0,log:_.length?_:void 0})}return a}async function Xu(t){let e=(await jn(de(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Gg("sha256").update(zu()).digest("hex").slice(0,8)}`}async function Um(t){let{home:e}=t,n=de(e,"tangu"),r=t.now??new Date,i=a=>t.since?.[a]??xt(r),s=Tm(t.engineLogs);return Rt({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:tm(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:Bu(e),cloudUrl:t.cloudUrl},device:{id:await Xu(e),name:zu()},system:await xm(e),config:km(await jn(de(e,"config.json"))),agents:await Nu(de(n,"agents")),teams:await Nu(de(n,"teams")),plugins:{desktop:await Pu(de(e,"plugins")),engine:await Pu(de(n,"plugins"))},inventory:{skills:await Tt(de(n,"skills")),spaces:await Tt(de(e,"spaces")),themes:await Tt(de(e,"themes"))},...t.activity?{...await _m(de(e,"activity"),r,i("activity")),activitySince:new Date(i("activity")).toISOString()}:{},...t.sessions?{...await Cm(e,r,Wu,i("sessions")),sessionsSince:new Date(i("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await Fm(e,r)}:{},...await Am(e,r),runsSince:new Date(xt(r)).toISOString(),...s?{engine:s}:{},sync:{content:Pm(t.contentSync),legacy:$m(t.engineLogs)}})}function Zu(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(v=>gi({baseUrl:v.cloudUrl,vault:mi,getToken:()=>v.token})),i=e.policyFor??Io,s=()=>de(t.homeDir(),"extend-diagnostics.json"),a=()=>{let v=I=>I&&typeof I=="object"?I:{};try{let I=JSON.parse(Yg(s(),"utf8"));return{accounts:v(I?.accounts),sent:v(I?.sent)}}catch{return{accounts:{},sent:{}}}},o=()=>a().accounts,l=(v,I,E)=>{let D=a();D.accounts[v]={...D.accounts[v],...I},Object.assign(D.sent,E),Vg(t.homeDir(),{recursive:!0});let x=`${s()}.${process.pid}.tmp`;Kg(x,JSON.stringify(D,null,2),{encoding:"utf8",mode:384}),Jg(x,s())},c=()=>{let v=t.readCreds();return v.token&&v.cloudUrl?t.accountId():null},u=()=>{let v=c(),I=v?o()[v]??{}:{},E=_r(I.policy);return{signedIn:!!v,enabled:I.enabled===!0,activity:I.activity!==!1,sessions:I.sessions??I.enabled!==!0,memory:I.memory??I.enabled!==!0,lastUploadAt:I.lastUploadAt??null,lastError:I.lastError??null,retainDays:$i,mode:E.mode,intervalHours:E.intervalHours}},f=()=>{try{return ju(t)?t.diagnosticLogs():null}catch{return null}},g=null,p=new Map,m=async()=>{let v=c();if(!v)return!1;if(g)return g.id===v?g.done:(await g.done,m());let I={...t.readCreds()},E=n(),D=a(),x=D.accounts[v],L=I.cloudUrl.replace(/\/+$/,""),V=Co(x?.file,D.sent[L]??{},E),H=(async()=>{try{let N=await Um({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:I.cloudUrl,activity:x?.activity!==!1,sessions:x?.sessions===!0,now:E,since:V,engineLogs:f(),contentSync:Cu(),memory:()=>{let ae=c()===v?o()[v]:void 0;return ae?.enabled===!0&&ae.memory===!0}}),Y=await Xu(t.homeDir()),ee=o()[v];if(c()!==v||ee?.enabled!==!0)return!1;if(ee.activity===!1)for(let ae of["activity","activityTruncated","activityError","activitySince"])delete N[ae];if(ee.sessions!==!0)for(let ae of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete N[ae];ee.memory!==!0&&delete N.memory;let J=[],se=rm(N,J);if(!se)throw new Error("snapshot too large");await xo(r(I),Y,se,E),p.delete(v);let te=Ao(a().sent[L]??{},x?.file,V,E,N,J);return l(v,{lastUploadAt:n().getTime(),lastError:void 0,file:te.file},{[L]:te.sent}),t.log(`[forsion-extend] diagnostics uploaded (${se.length} bytes)`),!0}catch(N){p.set(v,n().getTime());let Y=String(N?.message||N).slice(0,300);try{l(v,{lastError:Y})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${Y}`),!1}finally{g=null}})();return g={id:v,done:H},H},y=async()=>{try{let v=c();if(!v||o()[v]?.enabled!==!0)return;let I=await i({...t.readCreds()}),E=c()===v?o()[v]:void 0;if(E?.enabled!==!0)return;I&&(I.mode!==E.policy?.mode||I.intervalHours!==E.policy?.intervalHours)&&l(v,{policy:{mode:I.mode,intervalHours:I.intervalHours}}),I&&E.requestSeen===void 0&&l(v,{requestSeen:I.requestedAt});let D=I??{..._r(E.policy),requestedAt:0},x=D.requestedAt>(E.requestSeen??D.requestedAt),L=E.lastUploadAt??0,V=!L||D.mode==="scheduled"&&n().getTime()-L>=D.intervalHours*qu;if(!x&&!V||n().getTime()-(p.get(v)??-Tu)<Tu)return;await m()&&x&&l(v,{requestSeen:D.requestedAt})}catch(v){t.log(`[forsion-extend] diagnostics tick failed: ${String(v?.message||v)}`)}},b=Promise.resolve(),_={ok:!1,error:"untrusted"};t.handle("diagnostics:get",v=>t.isTrustedSender(v)?u():_),t.handle("diagnostics:set",(v,I)=>{if(!t.isTrustedSender(v))return _;let E=c();if(!E)return u();let D={};typeof I?.enabled=="boolean"&&(D.enabled=I.enabled),D.enabled&&(D.requestSeen=void 0),typeof I?.activity=="boolean"&&(D.activity=I.activity),typeof I?.sessions=="boolean"&&(D.sessions=I.sessions),typeof I?.memory=="boolean"&&(D.memory=I.memory);let x=o()[E];for(let L of["sessions","memory"])D[L]!==void 0||x?.[L]!==void 0||(x?.enabled===!0?D[L]=!1:D.enabled&&(D[L]=!0));return l(E,D),D.enabled&&(p.delete(E),b=Promise.all([b,y()]).then(()=>{})),u()}),t.handle("diagnostics:uploadNow",async v=>t.isTrustedSender(v)?(u().enabled&&await m(),u()):_);let h=setTimeout(()=>void y(),im),T=setInterval(()=>void y(),sm);return h.unref?.(),T.unref?.(),t.log(`[forsion-extend] diagnostics registered${ju(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(h),clearInterval(T)},{tick:y,settled:()=>b})}import{randomUUID as dd}from"node:crypto";import{appendFileSync as Zm,existsSync as Qm,mkdirSync as Vo,readFileSync as fd,renameSync as pd,rmSync as Yo,statSync as ey,writeFileSync as hd}from"node:fs";import{lstat as bd}from"node:fs/promises";import{homedir as ty,release as ny}from"node:os";import{join as Un}from"node:path";var Dr={$comment:"\u5E2E\u52A9\u6539\u8FDB Forsion(\u533F\u540D\u9065\u6D4B)\u4E8B\u4EF6\u767D\u540D\u5355 v3(v1\u3001v2 \u539F\u6837\u4FDD\u7559,\u6BCF\u7248\u53EA\u52A0\u4E8B\u4EF6\u3001\u5B57\u6BB5\u4E0E\u679A\u4E3E\u503C;\u5951\u7EA6\u89C1\u540C\u76EE\u5F55 contract.md \xA76\u2013\xA715\u3001v3 \u89C1 \xA716\u2013\xA724)\u3002\u6B63\u5178\u5728\u4ED3\u6839 docs/ToBeImproved/\u9ED8\u8BA4\u6570\u636E\u91C7\u96C6\u65B9\u6848_2026-10-28/telemetry-schema.json;server(src/config/telemetry-schema.json)\u4E0E Forsion-Extend(src/core/telemetry-schema.json)\u5404\u5B58\u4E00\u4EFD\u539F\u6837\u526F\u672C,\u6539\u4E00\u5904\u4E09\u5904\u540C\u6539,\u5E76\u540C\u6B65\u9690\u79C1\u653F\u7B56\u300C\u6539\u8FDB\u6570\u636E\u300D\u4E00\u8282\u3002\u7C7B\u578B:int = 0..2147483647 \u7684\u6574\u6570;bool;enum = \u53EA\u80FD\u53D6\u5217\u51FA\u7684\u503C;id = \u5339\u914D ^[A-Za-z0-9._:/@+-]{1,max}$ \u7684\u77ED\u4E32;text = \u81EA\u7531\u6587\u672C,\u5FC5\u987B\u5148\u8FC7 sanitize \u518D\u622A\u5230 max\u3002\u4E0D\u5728\u8868\u91CC\u7684\u4E8B\u4EF6\u4E0E\u5B57\u6BB5\u4E00\u5F8B\u4E22\u3002",version:3,limits:{maxBatchBytes:65536,maxEvents:200},envelope:{installId:{type:"uuid"},app:{type:"enum",values:["desktop","web","mobile"]},appVersion:{type:"id",max:40},coreVersion:{type:"id",max:40},channel:{type:"enum",values:["stable","beta"]},os:{type:"enum",values:["darwin","win32","linux","android","ios","other"]},osVersion:{type:"id",max:40},arch:{type:"enum",values:["arm64","x64","ia32","other"]},locale:{type:"enum",values:["zh","en"]},region:{type:"enum",values:["CN","other"]}},eventFields:{event:{type:"enum",values:["crash","agent_run","tool_call","perf","feature","approval","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","sync_health","daily_muse","daily_muse_card","daily_memory","daily_judge","daily_human","quota_prompt","plugin_inventory","model_feedback","first_run"]},ts:{type:"iso-time"},sessionId:{type:"uuid"}},events:{crash:{process:{type:"enum",values:["main","renderer","engine","plugin-host","extend","other"]},errorName:{type:"id",max:60},stack:{type:"stack",max:4e3},uptimeS:{type:"int"},exitCode:{type:"int"},reason:{type:"enum",values:["exception","rejection","crashed","oom","killed","abnormal-exit","launch-failed","integrity-failure","other"]},pluginId:{type:"id",max:64}},agent_run:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},mode:{type:"enum",values:["chat","agent","muse","historian","team","task","other"]},steps:{type:"int"},llmCalls:{type:"int"},tokensIn:{type:"int"},tokensOut:{type:"int"},tokensCached:{type:"int"},retries:{type:"int"},durationMs:{type:"int"},outcome:{type:"enum",values:["done","error","aborted","other"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},recallEntries:{type:"int"},recallHistory:{type:"int"},recallTruncated:{type:"bool"},memoryTokens:{type:"int"},humanTokens:{type:"int"},profileTokens:{type:"int"},projectTokens:{type:"int"}},tool_call:{tool:{type:"id",max:80},calls:{type:"int"},failures:{type:"int"},totalMs:{type:"int"},maxMs:{type:"int"},runOutcome:{type:"enum",values:["done","error","aborted","other"]},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},pluginId:{type:"id",max:80}},perf:{kind:{type:"enum",values:["startup","hourly"]},startupMs:{type:"int"},engineReadyMs:{type:"int"},rssMb:{type:"int"},heapMb:{type:"int"},longTasks:{type:"int"}},feature:{name:{type:"enum",values:["space_open","view_open","plugin_open","setting_change"]},kind:{type:"id",max:60},id:{type:"id",max:80},key:{type:"id",max:80},value:{type:"id",max:40}},approval:{tool:{type:"id",max:80},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},reasonKind:{type:"enum",values:["custom-ask","escalate","mode","protected","control","always","other"]},mode:{type:"enum",values:["readonly","auto-edit","full-auto","custom","other"]},asked:{type:"int"},approved:{type:"int"},rejected:{type:"int"},expired:{type:"int"},decideSecTotal:{type:"int"},remoteAnswers:{type:"int"}},plugin_install:{id:{type:"id",max:80},entry:{type:"enum",values:["store","chat-card","muse-card","plugin-onboarding","deps","other"]},kind:{type:"enum",values:["plugin","skill","agent","space","theme","amadeus-plugin","other"]},source:{type:"enum",values:["github","npm","zip","other"]},stage:{type:"enum",values:["resolve","download","install","activate","done"]},outcome:{type:"enum",values:["done","error","canceled"]},errorClass:{type:"enum",values:["timeout","network","http","too-large","not-zip","integrity","identity","version","min-app","platform","deps","builtin","activate","disk","other"]},durationMs:{type:"int"},sizeKb:{type:"int"},restart:{type:"bool"}},plugin_deps:{total:{type:"int"},installed:{type:"int"},failedAt:{type:"int"},outcome:{type:"enum",values:["ready","not-ready","not-running","failed"]}},plugin_lifecycle:{id:{type:"id",max:80},action:{type:"enum",values:["uninstall","enable","disable","blocked"]},blockedReason:{type:"enum",values:["min-app","api","invalid","dev-fileext","deps","other"]},daysSinceInstall:{type:"int"},reason:{type:"enum",values:["unused","broken","slow","mistake"]}},plugin_load:{id:{type:"id",max:80},outcome:{type:"enum",values:["ok","error"]},activateMs:{type:"int"}},update:{target:{type:"enum",values:["app","engine","ui","builtin-plugin","store-plugin","first-boot-prefetch"]},id:{type:"id",max:80},outcome:{type:"enum",values:["available","not-available","staged","applied","current","error","incompatible","rolled-back","timeout","skipped"]},errorClass:{type:"enum",values:["network","http","integrity","signature","version","identity","incompatible","disk","other"]}},onboarding:{mode:{type:"enum",values:["full","returning","brief","update"]},outcome:{type:"enum",values:["finish","skip","error-skip"]},screens:{type:"int"},backJumps:{type:"int"},msStart:{type:"int"},msTheme:{type:"int"},msYou:{type:"int"},msTeam:{type:"int"},msWelcome:{type:"int"},signedIn:{type:"bool"},syncNotes:{type:"bool"},syncAgents:{type:"bool"},syncPlugins:{type:"bool"},addedAgent:{type:"bool"},museOn:{type:"bool"},computerHistoryOn:{type:"bool"},youWritten:{type:"bool"}},guide_tip:{pluginId:{type:"id",max:80},tipId:{type:"id",max:60},result:{type:"enum",values:["ok","learned","mute","gone","missing","replaced","closed"]}},command_use:{id:{type:"id",max:80},source:{type:"enum",values:["palette","hotkey","ribbon","agent","other"]},n:{type:"int"}},app_counts:{achChatSend:{type:"int"},achChatGroup:{type:"int"},achNoteCreate:{type:"int"},achNoteWikilink:{type:"int"},achNoteCanvas:{type:"int"},achBaseCreate:{type:"int"},achSpaceSave:{type:"int"},achSpaceSwitch:{type:"int"},achAgentCreate:{type:"int"},achAutomationCreate:{type:"int"},achMuseOpen:{type:"int"},achComputerUse:{type:"int"},achMarketInstall:{type:"int"},achThemeChange:{type:"int"},achTodoDone:{type:"int"},achCalendarEvent:{type:"int"},achAccountLogin:{type:"int"},achImageGenerate:{type:"int"},achDrawingCreate:{type:"int"},achMiniOpen:{type:"int"},achSpecialEnable:{type:"int"},chatStop:{type:"int"},chatRegenerate:{type:"int"},chatEditResend:{type:"int"},chatTruncateResend:{type:"int"},chatRetry:{type:"int"},chatRewind:{type:"int"},chatBranch:{type:"int"},chatSteer:{type:"int"},chatSteerWithdraw:{type:"int"},chatCompact:{type:"int"},chatRetryFailed:{type:"int"},searchOpen:{type:"int"},searchPick:{type:"int"},searchCloseEmpty:{type:"int"},providerLoginOk:{type:"int"},providerLoginFail:{type:"int"},byokSave:{type:"int"},byokImport:{type:"int"},byokImportStale:{type:"int"},byokDelete:{type:"int"},connTestOk:{type:"int"},connTestFail:{type:"int"},connTestAuthRejected:{type:"int"},modelSwitchUser:{type:"int"},modelSwitchRemember:{type:"int"},engineDefaultModelSet:{type:"int"},homeWidgetAdd:{type:"int"},homeWidgetRemove:{type:"int"},homeWidgetMove:{type:"int"},openNote:{type:"int"},openDatabase:{type:"int"},openDashboard:{type:"int"},openPdf:{type:"int"},openBoard:{type:"int"},openPluginFile:{type:"int"},openOther:{type:"int"}},sync_health:{system:{type:"enum",values:["vault","content","remote"]},day:{type:"id",max:10},cycles:{type:"int"},cycleMsTotal:{type:"int"},errAuth:{type:"int"},errOffline:{type:"int"},errVaultMissing:{type:"int"},errScan:{type:"int"},errMirrorMissing:{type:"int"},errHttp:{type:"int"},errTimeout:{type:"int"},errBlocked:{type:"int"},errOther:{type:"int"},conflicts:{type:"int"},skippedTooLarge:{type:"int"},skippedNotFound:{type:"int"},skippedExists:{type:"int"},skippedOther:{type:"int"},massDeleteGuard:{type:"int"},uploads:{type:"int"},downloads:{type:"int"}},daily_muse:{day:{type:"id",max:10},cyclesRule:{type:"int"},cyclesSchedule:{type:"int"},cyclesHeartbeat:{type:"int"},cyclesRunEnd:{type:"int"},cyclesModeAsk:{type:"int"},cyclesModeAgent:{type:"int"},cyclesModeAuto:{type:"int"},cyclesDone:{type:"int"},cyclesError:{type:"int"},cyclesAborted:{type:"int"},cyclesSilent:{type:"int"},cycleTokens:{type:"int"},cycleMs:{type:"int"},producedCards:{type:"int"},producedDms:{type:"int"},producedTodos:{type:"int"},producedStarters:{type:"int"},inboxMarked:{type:"int"},inboxUnmarked:{type:"int"},skipNoModel:{type:"int"},skipOutsideHours:{type:"int"},skipUserActive:{type:"int"},skipNothingDue:{type:"int"},skipAlreadyRunning:{type:"int"},skipBudgetBillable:{type:"int"},skipBudgetGross:{type:"int"},skipRestartCap:{type:"int"},skipRemoteLock:{type:"int"},skipSleepCleared:{type:"int"},dmProactive:{type:"int"},dmTodo:{type:"int"},dmApproval:{type:"int"},dmCard:{type:"int"},dmNotice:{type:"int"},dmRemind:{type:"int"},dmSuppressed:{type:"int"},dmAwaitingUser:{type:"int"},dmReadIn24h:{type:"int"},dmRepliedIn24h:{type:"int"},feedbackUp:{type:"int"},feedbackDown:{type:"int"},feedbackText:{type:"int"},todoCreated:{type:"int"},todoApproved:{type:"int"},todoInjected:{type:"int"},todoDone:{type:"int"},todoDismissed:{type:"int"},starterCreated:{type:"int"},starterUsed:{type:"int"},starterDismissed:{type:"int"},starterMuted:{type:"int"},ruleCreatedMuse:{type:"int"},ruleCreatedUser:{type:"int"},ruleObserveForced:{type:"int"},rulePromoted:{type:"int"},ruleExtended:{type:"int"},rulePaused:{type:"int"},ruleObservedHits:{type:"int"},approvalByAgent:{type:"int"},approvalUserApproved:{type:"int"},approvalUserRejected:{type:"int"},introAnswered:{type:"int"},introSkipped:{type:"int"},introWhenAnytime:{type:"int"},introWhenDaytime:{type:"int"},introWhenOpen:{type:"int"},introPaceAsNeeded:{type:"int"},introPaceDaily:{type:"int"},introPaceFree:{type:"int"},introFocusSchedule:{type:"int"},introFocusStudy:{type:"int"},introFocusProjects:{type:"int"},introFocusInbox:{type:"int"},introFocusCustom:{type:"int"},summarySent:{type:"int"},summaryProposed:{type:"int"},summaryAdopted:{type:"int"},summaryAskUpgrade:{type:"int"},sleepSet:{type:"int"},digestSent:{type:"int"},gEnabled:{type:"int"},gDaysEnabled:{type:"int"},gModeAsk:{type:"int"},gModeAgent:{type:"int"},gModeAuto:{type:"int"},gNotifyDigest:{type:"int"},gHeartbeatMin:{type:"int"},gMaxDmPerDay:{type:"int"},gOnboardingDay:{type:"int"},gRulesObserving:{type:"int"},gRulesEnabled:{type:"int"}},daily_muse_card:{day:{type:"id",max:10},cardKind:{type:"enum",values:["plugin","feature","inbox-ask","inbox-list","channel","settings","intro","summary","rule","rule-observed"]},created:{type:"int"},accept:{type:"int"},observe:{type:"int"},edit:{type:"int"},dismiss:{type:"int"},open:{type:"int"},apply:{type:"int"},yes:{type:"int"},later:{type:"int"},ignore:{type:"int"},ack:{type:"int"},item:{type:"int"},enable:{type:"int"},extend:{type:"int"},pause:{type:"int"},answer:{type:"int"},skip:{type:"int"},ok:{type:"int"},remove:{type:"int"},installed:{type:"int"},gone:{type:"int"},dismissIrrelevant:{type:"int"},dismissTiming:{type:"int"},dismissFrequent:{type:"int"},dismissKnown:{type:"int"},decideSecTotal:{type:"int"},decidedRemote:{type:"int"},gPendingOver3d:{type:"int"}},daily_memory:{day:{type:"id",max:10},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},addAgent:{type:"int"},addProject:{type:"int"},addPerson:{type:"int"},updateAgent:{type:"int"},updateProject:{type:"int"},updatePerson:{type:"int"},forgetAgent:{type:"int"},forgetProject:{type:"int"},forgetPerson:{type:"int"},moveScope:{type:"int"},srcExplicit:{type:"int"},srcHistorian:{type:"int"},srcDream:{type:"int"},srcManual:{type:"int"},srcRestore:{type:"int"},srcExternalEdit:{type:"int"},srcSync:{type:"int"},srcMigration:{type:"int"},errFull:{type:"int"},errVersionConflict:{type:"int"},errPortraitFull:{type:"int"},userEditAgentWritten7d:{type:"int"},userForgetAgentWritten7d:{type:"int"},userRestoreDreamRetired:{type:"int"},userEdit:{type:"int"},userForget:{type:"int"},userAdd:{type:"int"},userForgetWrong:{type:"int"},userForgetStale:{type:"int"},userForgetUnwanted:{type:"int"},userForgetDuplicate:{type:"int"},retellExisting:{type:"int"},retellForgotten:{type:"int"},candidatesAdded:{type:"int"},dreamAuto:{type:"int"},dreamManual:{type:"int"},dreamArchive:{type:"int"},dreamCompleted:{type:"int"},dreamSkipped:{type:"int"},dreamFailed:{type:"int"},dreamCancelled:{type:"int"},dreamCalls:{type:"int"},dreamSources:{type:"int"},dreamGroups:{type:"int"},dreamMerges:{type:"int"},dreamDiscarded:{type:"int"},dreamToPortrait:{type:"int"},dreamPending:{type:"int"},dreamDeferred:{type:"int"},dreamVerifyFail:{type:"int"},dreamRetried:{type:"int"},dreamMs:{type:"int"},harnessUpsertAgent:{type:"int"},harnessUpsertHistorian:{type:"int"},harnessUpsertMuse:{type:"int"},harnessUpsertUser:{type:"int"},harnessDelete:{type:"int"},harnessRollback:{type:"int"},gEntries:{type:"int"},gCharsPct:{type:"int"},gTombstones:{type:"int"},gCandidatesPending:{type:"int"},gCandidatesOldestDays:{type:"int"},gHarnessEntries:{type:"int"}},daily_judge:{day:{type:"id",max:10},rounds:{type:"int"},roundsIndependent:{type:"int"},roundsAssist:{type:"int"},roundsFork:{type:"int"},isolationSkips:{type:"int"},memCandidates:{type:"int"},projCandidatesAuto:{type:"int"},projCandidatesQueued:{type:"int"},projAdopted:{type:"int"},projDismissed:{type:"int"},projForgotten:{type:"int"},projRestored:{type:"int"},projCompacted:{type:"int"},harnessCandidatesAuto:{type:"int"},harnessCandidatesQueued:{type:"int"},signalStop:{type:"int"},signalToolLoop:{type:"int"},signalNudge:{type:"int"},signalCorrectionDecision:{type:"int"},signalCorrectionLexical:{type:"int"},titleUpdated:{type:"int"},summaryUpdated:{type:"int"},iconUpdated:{type:"int"}},daily_human:{day:{type:"id",max:10},wAgentShared:{type:"int"},wAgentAgent:{type:"int"},wAgentProject:{type:"int"},wAgentPortrait:{type:"int"},wAgentAgentMd:{type:"int"},wAgentMemory:{type:"int"},wUserShared:{type:"int"},wUserAgent:{type:"int"},wUserProject:{type:"int"},wUserPortrait:{type:"int"},wUserAgentMd:{type:"int"},wUserMemory:{type:"int"},srcRemember:{type:"int"},srcDream:{type:"int"},srcMove:{type:"int"},srcPromote:{type:"int"},srcUser:{type:"int"},userUndoAgentWrite7d:{type:"int"},moveScan:{type:"int"},moveMoved:{type:"int"},moveKept:{type:"int"},moveUndo:{type:"int"},promoteToAgentMd:{type:"int"},coldstartAgents:{type:"int"},coldstartPersonWrites:{type:"int"},coldstartRelearned:{type:"int"},mirrorConflicts:{type:"int"},syncConflictCopies:{type:"int"},gHumanMdEntries:{type:"int"},gAgentMdEntries:{type:"int"},gPortraitEntries:{type:"int"},gMemoryEntries:{type:"int"},gCalendarRows:{type:"int"},gAgentsWithHumanMd:{type:"int"},gAgentsTotal:{type:"int"}},quota_prompt:{entry:{type:"enum",values:["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","other"]},shown:{type:"int"},dismiss:{type:"int"},card:{type:"int"},points:{type:"int"},upgrade:{type:"int"},topup:{type:"int"},bgConvert:{type:"int"},bgSettings:{type:"int"},more:{type:"int"}},plugin_inventory:{day:{type:"id",max:10},id:{type:"id",max:80},source:{type:"enum",values:["store","builtin","local"]},installed:{type:"int"},enabled:{type:"int"},localCount:{type:"int"}},model_feedback:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},regenerate:{type:"int"},stop:{type:"int"},editResend:{type:"int"}},first_run:{outcome:{type:"enum",values:["done","error","aborted"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},sinceFirstLaunchS:{type:"int"},durationMs:{type:"int"}}}};var zm=Dr.events,Bm=Dr.envelope,Bo=Dr.limits,td=Dr.version,qm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Wm=/^[A-Za-z0-9._:/@+-]+$/,nd=t=>typeof t=="string"&&qm.test(t),Qu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Gm=[[/\/Users\/[^/\s]+\//gi,"~/"],[/\/home\/[^/\s]+\//gi,"~/"],[/[a-z]:\\Users\\[^\\\s]+\\/gi,"~\\"],[/~([/\\])[^\s"'`」:()]+/g,"~$1\u2026"],[/\/Volumes\/[^\s"'`」:()]+/g,"/Volumes/\u2026"],[/\b([d-z]):\\[^\s"'`」:()]+/gi,"$1:\\\u2026"],[/forsion-agent-space\/[^/\s]+\//g,"forsion-agent-space/\u2026/"],[/"[^"]{1,200}"/g,'"\u2026"'],[/'[^']{1,200}'/g,"'\u2026'"],[/`[^`]{1,200}`/g,"`\u2026`"],[/「[^「」]{1,200}」/g,"\u300C\u2026\u300D"],[/(https?:\/\/[^\s?#"'`」]+)[?#][^\s"'`」]*/gi,"$1"],[/sk-[A-Za-z0-9_-]{10,}/g,"[redacted]"],[/Bearer\s+\S+/gi,"[redacted]"],[/[0-9a-f]{32,}/gi,"[redacted]"],[/[A-Za-z0-9+/]{40,}={0,2}/g,"[redacted]"],[/[A-Za-z0-9_-]{40,}/g,"[redacted]"],[/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]"]],rd=t=>Gm.reduce((e,[n,r])=>e.replace(n,r),t);function ed(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(Qu,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=rd(r),(r.length>e?r.slice(0,e):r).replace(Qu,"\uFFFD")}var id=/^pr-[a-f0-9]{48}$/,Vm=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,sd=t=>id.test(t)||Vm.test(t)||rd(t)===t;function Ym(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function zo(t,e,n){switch(t.type){case"enum":return typeof e=="string"&&t.values.includes(e)?e:void 0;case"int":return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.min(Math.round(e),2147483647):void 0;case"bool":return typeof e=="boolean"?e:void 0;case"uuid":return nd(e)?e.toLowerCase():void 0;case"iso-time":return typeof e=="string"&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():void 0;case"id":return typeof e=="string"&&e.length<=t.max&&Wm.test(e)&&sd(e)?e:void 0;case"text":return typeof e=="string"&&e?ed(e,t.max,n):void 0;case"stack":{let r=Ym(e);return r?ed(r,t.max,n):void 0}}}function Qt(t,e){let n=typeof t?.event=="string"?zm[t.event]:void 0;if(!n)return null;let r={},i=t.props&&typeof t.props=="object"?t.props:{};for(let[a,o]of Object.entries(n)){let l=zo(o,i[a],e);l!==void 0&&(r[a]=l)}let s=zo({type:"iso-time"},t.ts);return{event:t.event,ts:s??new Date().toISOString(),...nd(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function od(t){let e={};for(let[n,r]of Object.entries(Bm)){if(n==="installId")continue;let i=zo(r,t[n]);e[n]=typeof i=="string"?i:null}return e}function ad(t,e){if(e==="aborted")return"aborted";if(!t)return;let n=t.toLowerCase();return/abort|cancel/.test(n)?"aborted":/timeout|timed out|etimedout/.test(n)?"timeout":/token_quota_exceeded/.test(n)?"quota":/\b429\b|rate.?limit|too many requests|quota/.test(n)?"rate_limit":/\b40[13]\b|unauthori[sz]ed|forbidden|invalid api key|authentication/.test(n)?"auth":/context.{0,20}(length|window|too long)|maximum context|too many tokens|prompt is too long/.test(n)?"context_length":/econn|enotfound|eai_again|socket|network|fetch failed|getaddrinfo/.test(n)?"network":/\b5\d\d\b|upstream|bad gateway|overloaded|service unavailable/.test(n)?"upstream":/tool/.test(n)?"tool":"other"}function ld(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function Wi(t){return t?/^pr-/.test(t)?"forsion":/^codex\//.test(t)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(t)?"local":"byok":"other"}var Jm=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function qo(t,e){if(typeof t!="string"||!t)return;let n=Wi(t);if((n==="codex"||n==="forsion"&&id.test(t))&&(e===void 0||e===n))return t;let i=t.slice(t.lastIndexOf("/")+1);return Jm.test(i)?i:void 0}function Wo(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function Go(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}var Km=/^market-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i,Xm=/^[a-z0-9][a-z0-9-]{0,79}$/;function cd(t,e){if(typeof t!="string"||!t)return;let n=Km.exec(t);if(n)return n[1].toLowerCase();if((e===!0||e===1)&&t.length<=80&&Xm.test(t)&&sd(t))return t}function ud(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var ry=10*6e4,iy=6e4,sy=50,gd=1024*1024,oy=168*36e5,md=15e3,ay=200,ly=2e3,Jo=7,cy=5e3,yd=864e5,uy=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","quota_prompt","plugin_inventory","model_feedback","first_run"]),dy=new Set(["shown","dismiss","card","points","upgrade","topup","bgConvert","bgSettings","more"]),fy=1e3,wd=36e5,Ko=2,Xo={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},py=new Set(["custom-ask","escalate","mode","protected","control","always"]);function hy(t){let e=t.props&&typeof t.props=="object"?t.props:{};if(t.event==="model_feedback"){let n=typeof e.modelId=="string"?e.modelId:void 0,r=qo(n,typeof e.providerKind=="string"?e.providerKind:"other");return r?{...t,props:{...e,modelId:r,providerKind:typeof e.providerKind=="string"?e.providerKind:Wi(n)}}:null}if(t.event==="plugin_inventory"){if(!In(e.day))return null;if(e.source==="local"||e.id==="local")return{...t,props:{day:e.day,id:"local",source:"local",localCount:e.localCount}};let n=typeof e.id=="string"?e.id:"";return(e.source==="store"?!gy.test(n):e.source!=="builtin"||!(n.length<=80&&my.test(n)))?null:{...t,props:{day:e.day,id:n,source:e.source,installed:e.installed,enabled:e.enabled}}}return t}var gy=/^(?:market-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,my=/^[a-z0-9][a-z0-9-]{0,79}$/,yy={model_feedback:"modelId",plugin_inventory:"id",quota_prompt:"entry"},wy=new Set(["readonly","auto-edit","full-auto","custom"]),Sd=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),Zo=t=>({at:Sd(t),id:"~"}),Fn=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function by(t,e,n,r){let i=Un(t,"tangu","state.db");if(!await bd(i).then(a=>a.isFile(),()=>!1))return{events:[],cursor:e};let s;try{let{DatabaseSync:a}=await import("node:sqlite");s=new a(i,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let o=s.prepare(`SELECT r.id, r.status, r.current_step, r.model_id, substr(r.error, 1, 2000) AS error, r.created_at, r.updated_at, s.kind
|
|
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
|
|
259
259
|
FROM agent_runs r LEFT JOIN chat_sessions s ON s.id = r.session_id
|
|
260
260
|
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",
|
|
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,
|
|
262
262
|
json_extract(e.payload, '$.isError') AS failed, json_extract(e.payload, '$.elapsedMs') AS ms,
|
|
263
263
|
json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
|
|
264
264
|
json_extract(e.payload, '$.phase') AS phase,
|
|
@@ -275,16 +275,16 @@ ${s}`,n),this.line=r,this.column=i,this.codeblock=s}};var _g=/^((0x[0-9a-fA-F](_
|
|
|
275
275
|
${c("profile")} AS profileTokens, ${c("project")} AS projectTokens
|
|
276
276
|
FROM agent_run_events e
|
|
277
277
|
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
|
|
279
|
-
WHERE day > ? AND day < ? AND day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' AND event IN (${
|
|
280
|
-
ORDER BY day LIMIT ?`).all(e,n,...
|
|
281
|
-
`).filter(Boolean)}catch{return[]}},h=()=>
|
|
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(`
|
|
282
282
|
`)+`
|
|
283
|
-
`,{encoding:"utf8",mode:384}),
|
|
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(`
|
|
284
284
|
`)+`
|
|
285
|
-
`,{encoding:"utf8",mode:384});try{if(ey(o()).size>gd){let A=h(),j=A.length,F=0;for(;j>0&&F+Buffer.byteLength(JSON.stringify(A[j-1]))+1<=gd/2;)F+=Buffer.byteLength(JSON.stringify(A[--j]))+1;T(o(),A.slice(j))}}catch{}h().length>=sy&&Q()}},ee=()=>{let C=f();return{available:!!c,enabled:C.enabled!==!1,noticeSeen:C.noticeSeen===!0,signedIn:y(),active:b(C),packaged:c?.packaged===!0,installId:m(),queued:Qm(o())?h().length:0,lastSentAt:C.lastSentAt??null,lastError:C.lastError??null}},J=()=>od({app:"desktop",appVersion:t.appVersion(),coreVersion:c?.coreVersion()??void 0,channel:c?.channel(),os:ky(process.platform),osVersion:ny(),arch:Ey(process.arch),locale:_y()}),se=td,te=async C=>{try{let A=await C.json?.();return!!A&&typeof A=="object"&&A.detail==="unsupported v"}catch{return!1}},ae=null,Q=()=>{if(ae)return ae;if(L||n().getTime()<V)return Promise.resolve();let C=x,A=v,j=(async()=>{try{for(let F=0;F<5;F++){let z=h();if(!z.length)return;let q=m(),ne={v:se,installId:q,...J()},re=[],Z=Buffer.byteLength(JSON.stringify({...ne,events:[]}));for(let X of z){let ve=Buffer.byteLength(JSON.stringify(X))+1;if(re.length>=Bo.maxEvents||Z+ve>Bo.maxBatchBytes)break;re.push(X),Z+=ve}if(!re.length){T(o(),z.slice(1));continue}let{base:ie}=await t.getCloud(),oe={...ne,events:re};if(!H()||C!==x)return;let pe=await r(`${ie.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(oe),signal:AbortSignal.timeout(md)}).catch(X=>({ok:!1,status:0,error:String(X?.message||X)})),le=pe.status;if(le===400&&ne.v>Ko&&await te(pe)){se=Ko,t.log(`[forsion-extend] telemetry server does not accept v${ne.v}; resending as v${Ko}`);continue}if(le>=200&&le<300||le===400||le===413){let X=new Set(re.map(ve=>JSON.stringify(ve)));T(o(),h().filter(ve=>!X.has(JSON.stringify(ve))))}if(le>=200&&le<300){let X=n().getTime();A===v&&T(l(),[...D(),{at:X,body:oe}]),p({lastSentAt:X,lastError:void 0});continue}if(le!==400&&le!==413){let X=Number(pe.headers?.get?.("retry-after"));V=n().getTime()+(Number.isFinite(X)&&X>0?Math.min(X,3600)*1e3:5*6e4)}p({lastError:le?`HTTP ${le}`:String(pe.error??"network error").slice(0,200)});return}}catch(F){try{p({lastError:String(F?.message||F).slice(0,200)})}catch{}}})();return ae=j,j.finally(()=>{ae===j&&(ae=null)}),j},me=C=>{if(!I||!C&&Math.floor(n().getTime()/wd)===I.hour)return;let A=I;if(I=null,A.gen!==x||!H())return;let j=Qt({event:"quota_prompt",ts:n().toISOString(),sessionId:c?.sessionId,props:{...A.counts,entry:"quota-page"}});try{j&&Object.keys(j.props).some(F=>F!=="entry")&&Y([j])}catch(F){throw I=A,F}},ge=async()=>{try{if(D(),me(!1),!H())return;let C=f(),A=x,j=C.cursor??Zo(n().getTime()),F=await by(i(),j,c?.sessionId,Sd(n().getTime()));if(!H()||A!==x)return;Y(F.events),F.cursor!==j&&p({cursor:F.cursor}),await Pe(A),await Q()}catch(C){t.log(`[forsion-extend] telemetry tick failed: ${String(C?.message||C)}`)}},Pe=async C=>{let A=n().getTime(),j=Tn(A),F=Tn(A-yd),z=f().ledgerCursor;if(In(z)||(z=F,p({ledgerCursor:z})),yo(z),z>=F){Ce();return}let q=await Sy(i(),z,j);if(!(!H()||C!==x)){if(q){let ne=q.complete?F:q.days[q.days.length-1]?.day??z;if(ne>z){let re=Vc(z,ne),Z=[...new Set([...q.days.map(oe=>oe.day),...re.map(oe=>oe.day)])].filter(oe=>oe>z&&oe<=ne).sort(),ie=[];for(let oe of Z){ie.push(...q.days.find(pe=>pe.day===oe)?.events??[]);for(let pe of re)if(pe.day===oe){let le=vy(oe,pe.system,pe.counts);le&&ie.push(le)}}Y(ie),p({ledgerCursor:ne}),yo(ne)}}Ce()}},Ce=()=>{if(!Wc())return;let C=g();if(!C)return;let A=qc();p({syncHealth:Object.keys(A).length?A:void 0},C),Gc()},He=c?.subscribe(C=>{try{if(!uy.has(C?.event)||!H())return;let A=hy(C);if(!A)return;let j=Qt({...A,sessionId:c.sessionId},ty()),F=yy[C.event];j&&(!F||j.props[F]!==void 0)&&Y([j])}catch(A){t.log(`[forsion-extend] telemetry event dropped: ${String(A?.message||A)}`)}}),Ae={ok:!1,error:"untrusted"};t.handle("telemetry:get",C=>t.isTrustedSender(C)?(H(),ee()):Ae),t.handle("telemetry:set",(C,A)=>{if(!t.isTrustedSender(C))return Ae;let j=f(),F={};typeof A?.enabled=="boolean"&&(F.enabled=A.enabled),A?.noticeSeen===!0&&(F.noticeSeen=!0);let z={...j,...F};return!b(j)&&b(z)&&(F.cursor=Zo(n().getTime()),F.ledgerCursor=u()),b(j)&&!b(z)&&x++,F.enabled===!1&&(F.syncHealth=void 0),p(F),F.enabled===!1&&E(),H(),ee()}),t.handle("telemetry:quotaPrompt",(C,A)=>{if(!t.isTrustedSender(C))return Ae;let j=A?.action;return A?.entry!=="quota-page"||typeof j!="string"||!dy.has(j)?{ok:!1,error:"invalid"}:(me(!1),H()?((!I||I.gen!==x)&&(I={hour:Math.floor(n().getTime()/wd),gen:x,counts:{}}),I.counts[j]=Math.min((I.counts[j]??0)+1,fy),{ok:!0,counted:!0}):{ok:!0,counted:!1})}),t.handle("telemetry:sent",C=>t.isTrustedSender(C)?{batches:D()}:Ae),t.handle("telemetry:delete",async C=>{if(!t.isTrustedSender(C))return Ae;L=!0,x++;try{await ae?.catch(()=>{});let A=m(),{base:j}=await t.getCloud(),z=(await r(`${j.replace(/\/+$/,"")}/api/telemetry/install/${A}`,{method:"DELETE",signal:AbortSignal.timeout(md)}).catch(q=>({ok:!1,status:0,error:String(q?.message||q)}))).status;return z>=200&&z<300?(E(),p({installId:dd(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),ee()):{ok:!1,error:z?`HTTP ${z}`:"network error"}}finally{L=!1}});try{Bc(f().syncHealth),N(),H()}catch(C){t.log(`[forsion-extend] telemetry startup check failed: ${String(C?.message||C)}`)}let ut=t.addFlushHook?.(C=>{if(C!=="blur"){try{Ce()}catch{}try{me(!0)}catch{}}}),M=setTimeout(()=>void ge(),iy),U=setInterval(()=>void ge(),ry);return M.unref?.(),U.unref?.(),t.log(`[forsion-extend] telemetry registered (${c?c.packaged?"packaged":"dev build: never sends":"host has no telemetry seam: never sends"})`),Object.assign(()=>{clearTimeout(M),clearInterval(U),He?.(),ut?.()},{tick:ge,flush:Q})}import{readFileSync as Gn,lstatSync as Zy,statSync as Qy,renameSync as ew,linkSync as tw,unlinkSync as aa,readdirSync as nw,rmdirSync as rw,writeFileSync as iw,mkdirSync as sw,copyFileSync as ow,constants as aw}from"node:fs";import{readFile as Pr,writeFile as $r,mkdir as la,rename as rs,readdir as jr,lstat as Bt,stat as ca,unlink as Lr}from"node:fs/promises";import{join as Fe,dirname as wn,relative as Fr,sep as Vn}from"node:path";import{hostname as ua}from"node:os";import{createHash as lw,randomUUID as mt}from"node:crypto";import{isUtf8 as da}from"node:buffer";import{Readable as cw}from"node:stream";import{performance as fa}from"node:perf_hooks";import{setImmediate as uw}from"node:timers/promises";var Cy=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],Ay=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],Or=".memory-tombstones.json",Ed=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),kd=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),xy=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)&&Number.isFinite(Date.parse(`${t}T00:00:00Z`))&&new Date(`${t}T00:00:00Z`).toISOString().slice(0,10)===t,Ty=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function Iy(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===Or)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:Cy.includes(t)||Ed(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&xy(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var Ry=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),Dy=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,Oy=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function Gi(t){let e=t.slice(t.lastIndexOf("/")+1);return Dy.test(e)||Oy.test(e)}function _d(t,e,n=1){let r=t.lastIndexOf("/"),i=r<0?"":t.slice(0,r+1),s=r<0?t:t.slice(r+1),a=s.lastIndexOf("."),o=a>0?s.slice(0,a):s,l=a>0?s.slice(a):"",c=f=>String(f).padStart(2,"0"),u=`${e.getFullYear()}-${c(e.getMonth()+1)}-${c(e.getDate())} ${c(e.getHours())}${c(e.getMinutes())}${n>1?` ${n}`:""}`;return`${i}${o} (conflict ${u})${l}`}function Qo(t,e="file"){if(t==="agents"||t==="human")return e==="folder";let n=t.startsWith("human/"),r=t.startsWith("agents/");if(!n&&!r)return null;if(Gi(t))return!1;if(n){let c=t.slice(6);return e==="folder"?kd(c):Ay.includes(c)||Ed(c)}let i=t.slice(7),s=i.indexOf("/"),a=s<0?i:i.slice(0,s),o=s<0?"":i.slice(s+1);if(!Ty(a)||Ry(a))return!1;if(e==="file")return Iy(o);if(o===""||o==="LOG"||kd(o))return!0;let l=o.split("/");return l[0]==="Library"&&l.every(c=>c&&!c.startsWith(".")&&!c.endsWith(".")&&!c.endsWith(" "))}import{isAbsolute as My}from"node:path";var it=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Dt=t=>typeof t=="string",hn=t=>Dt(t)&&t.length>0,Ut=t=>typeof t=="boolean",gn=t=>typeof t=="number"&&Number.isFinite(t),zn=t=>gn(t)&&Number.isSafeInteger(t)&&t>=0,Cd=t=>gn(t)&&Number.isInteger(t)&&t>=0,xd=t=>zn(t)&&t>0,mn=t=>Dt(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),Ji=t=>Dt(t)&&/^[a-f0-9]{64}$/.test(t),ea=t=>Dt(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),Mr=(t,e)=>Dt(t)&&e.includes(t),be=(t,e)=>t===void 0||e(t),Td=(t,e,n)=>e.every(r=>be(t[r],n)),Id=t=>Dt(t)&&!t.includes("\0")&&My(t);function Ht(t,e=!1){try{return Xt(t,e),!0}catch{return!1}}var Rd=t=>Ht(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,Dd=t=>t===""||mn(t);function Yi(t,e){let n=t.indexOf(":");return n>0&&mn(e)&&t.slice(n+1)===e&&ea(t.slice(0,n))}function Ny(t,e){return it(e)&&Yi(t,e.id)&&Ht(e.path)&&hn(e.version)&&Ji(e.hash)&&Td(e,["base","inode","stat"],Dt)&&be(e.statAt,gn)&&be(e.memoryDeleted,Ut)&&be(e.file,hn)}function Py(t,e){return it(e)&&Yi(t,e.localId)&&mn(e.id)&&Ht(e.path)&&xd(e.revision)&&Dd(e.parentId)&&Rd(e.name)}function $y(t){return it(t)&&mn(t.id)&&Ht(t.path)&&ea(t.target)&&Mr(t.direction,["upload","download","merge","rename","delete"])&&Mr(t.state,["queued","active","done","failed","paused","conflict"])&&zn(t.done)&&(t.size===null||zn(t.size))&&gn(t.at)&&be(t.error,Dt)&&be(t.finishedAt,gn)}function jy(t){return it(t)&&Ht(t.path)&&Ji(t.hash)&&Dt(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&be(t.parentId,mn)&&be(t.stageRoot,Id)&&be(t.stageIdentity,Vt)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&Cd(t.stageDev)&&Cd(t.stageIno))}function Ly(t){return it(t)&&Ht(t.prefix,!0)&&Id(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Vt(t))}function Fy(t){return it(t)&&Mr(t.state,["running","done"])&&Ut(t.seen)&&Td(t,["name","folderId","shelfId","shelfName"],Dt)&&be(t.files,zn)&&be(t.at,gn)&&be(t.rewritten,Ut)}function Ad(t){return it(t)&&hn(t.key)&&ea(t.ns)&&mn(t.id)&&Ht(t.path)&&Mr(t.side,["cloud","local"])}function Uy(t){return it(t)&&Ut(t.latched)&&Hn(t.pending,Ad)&&be(t.confirmed,e=>Hn(e,hn))&&be(t.restore,e=>Hn(e,Ad))}var Vi=(t,e)=>it(t)&&Object.entries(t).every(([n,r])=>e(n,r)),Hn=(t,e)=>Array.isArray(t)&&t.every(e);function Od(t){if(!it(t)||!it(t.config)||!zn(t.config.revision)||!Ut(t.owned)||!Ut(t.paused)||!Vi(t.files,Ny)||!Vi(t.folders,Py)||!Hn(t.jobs,$y)||!be(t.accountReview,Ut)||!be(t.deleteGuard,Uy)||!be(t.agentArchive,Fy)||!be(t.roots,e=>Hn(e,Ly))||!be(t.trash,e=>Hn(e,jy))||!be(t.unconfirmed,e=>Vi(e,(n,r)=>Yi(n,n.slice(-36))&&Ji(r)))||!be(t.pendingUploads,e=>Vi(e,(n,r)=>it(r)&&Yi(n,r.id)&&Ht(r.path))))throw Error("Invalid content sync state; original data was retained");Zt(t.config,t.config.revision)}function Md(t){return it(t)&&mn(t.id)&&Dd(t.parentId)&&Rd(t.name)&&Ht(t.path)&&Mr(t.kind,["file","folder"])&&xd(t.revision)&&Ut(t.deleted)&&be(t.busy,Ut)&&be(t.version,hn)&&be(t.hash,Ji)&&be(t.size,zn)&&be(t.mtime,gn)&&be(t.file,hn)&&t.version===void 0==(t.hash===void 0)}function Nd(t){return Md(t)&&t.deleted===!0}function Ki(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!it(t)||t.schemaVersion!==1||t.namespace!==e||!hn(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,i=new Set;for(let s of t.nodes){if(!Md(s)||r.has(s.id)||!s.deleted&&i.has(s.path))throw n();r.set(s.id,s),s.deleted||i.add(s.path)}for(let s of r.values()){let a=s.parentId?r.get(s.parentId):void 0;if(s.parentId&&(!a||a.kind!=="folder"||a.deleted&&!s.deleted)||s.path!==(a?a.path+"/"+s.name:s.name))throw n()}}import{constants as Pd,lstatSync as yn,readdirSync as Hy,readFileSync as zy,renameSync as Xi,unlinkSync as By,linkSync as qy,mkdirSync as es,realpathSync as ta,rmdirSync as Wy}from"node:fs";import{open as Fd,lstat as Zi,readdir as $d,realpath as Ud,readFile as na,writeFile as Gy,mkdir as Hd,unlink as Vy}from"node:fs/promises";import{join as zt,dirname as Qi,relative as ra,sep as ts}from"node:path";import{randomUUID as zd,createHash as Yy}from"node:crypto";var Nr=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,Bn=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),Bd=".forsion-sync-id.json",Jy=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),jd=t=>!Jy.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),Oe=t=>Yy("sha256").update(t).digest("hex");function qd(t){if(process.platform==="win32"&&t.split("/").some(e=>/[:*?"<>|]/.test(e)||/^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\..*)?$/i.test(e)))throw Error("This name is not a safe Windows file destination")}async function ct(t,e,n=!1){if(n){if(e.split("/").some(o=>o===".."||o==="."||!o)||e.startsWith("/")||e.includes("\\"))throw Error("Invalid internal content path")}else Xt(e,!0);qd(e);let r=await Ud(t),i=zt(r,...e.split("/").filter(Boolean)),s=ra(r,i);if(s===".."||s.startsWith(".."+ts))throw Error("Content path escapes root");let a=r;for(let o of s.split(ts).filter(Boolean)){a=zt(a,o);try{if((await Zi(a)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(l){if(l.code!=="ENOENT")throw l}}return i}function vt(t,e,n=!1){if(n||Xt(e,!0),qd(e),e.split("/").some(s=>s===".."||s===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let i=ta(t);for(let s of e.split("/").filter(Boolean)){i=zt(i,s);try{if(yn(i).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(a){if(a.code!=="ENOENT")throw a}}return i}var Ld=t=>t?.code!=="ENOENT";async function ns(t){let e=new Map,n=[],r=[],i=new Set,s=t.filter(u=>u.prefix).map(u=>u.prefix),a=[];for(let u of t)try{a.push({...u,root:await Ud(u.root)})}catch(f){if(f.code!=="ENOENT")throw f}if(new Set(a.map(u=>u.root)).size!==a.length)throw Error("Managed roots refer to the same directory; choose a separate vault folder");let o=u=>{try{return Xt(u),!0}catch{return!1}},l=async u=>{let f;try{f=await $d(u,{withFileTypes:!0})}catch{return}for(let g of f){if(!jd(g.name)||!g.isDirectory()&&!g.isFile())continue;let p=zt(u,g.name);try{let m=await Zi(p);if(m.isSymbolicLink())continue;i.add(Bn(m).inode),m.isDirectory()&&await l(p)}catch{}}};for(let u of a){let f=u.root;if(!(await Zi(f)).isDirectory())throw Error(`Sync root is not a directory: ${u.prefix||"Forsion"}`);let g=async(p,m)=>{let y;try{y=await Zi(p)}catch(h){if(!m||p===f)throw h;Ld(h)&&(n.push({path:m,reason:"unreadable"}),r.push(m));return}if(y.isSymbolicLink()||p!==f&&a.some(h=>h!==u&&h.root===p)||m&&u.prefix===""&&s.some(h=>m===h||m.startsWith(h+"/")))return;if(m&&!o(m)){n.push({path:m,reason:"invalid-name"}),i.add(Bn(y).inode),y.isDirectory()&&await l(p);return}let b,_=null;if(y.isDirectory())try{try{let h=JSON.parse(await na(zt(p,Bd),"utf8"));/^[a-f0-9-]{36}$/i.test(h.id)&&(b=h.id)}catch(h){if(h.code!=="ENOENT"&&!(h instanceof SyntaxError))throw h}_=await $d(p,{withFileTypes:!0})}catch(h){if(!m||p===f)throw h;if(!Ld(h))return;n.push({path:m,reason:"unreadable"}),r.push(m);return}if(m&&e.set(m,{path:m,physical:p,root:f,kind:y.isDirectory()?"folder":"file",localId:b,...Bn(y),size:y.isFile()?y.size:0}),!!_)for(let h of _)!jd(h.name)||!h.isDirectory()&&!h.isFile()||await g(zt(p,h.name),m?`${m}/${h.name}`:h.name)};await g(f,u.prefix)}let c=[...e.values()].sort((u,f)=>u.path.split("/").length-f.path.split("/").length||u.path.localeCompare(f.path));return Ky(c,{skipped:n,unscanned:r,skippedInodes:i})}function Ky(t,e){for(let[n,r]of Object.entries(e))Object.defineProperty(t,n,{value:r,enumerable:!1,configurable:!0});return t}var qn=(t,e)=>t.some(n=>e===n||e.startsWith(n+"/"));async function ia(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await ct(t.root,ra(t.root,zt(t.physical,Bd)).split(ts).join("/"),!0),n=zd();try{let r=await Fd(e,"wx",384);try{await r.writeFile(JSON.stringify({version:1,id:n})+`
|
|
286
|
-
`)}finally{await r.close()}return t.localId=n,n}catch(r){if(r.code!=="EEXIST")throw r;let
|
|
287
|
-
`)).digest("hex").slice(0,24),dw=(t,e)=>t.length===e.length&&t.every(n=>e.some(r=>n.prefix===r.prefix&&n.root===r.root&&(n.dev===void 0||an(n,r)))),fw=()=>({config:structuredClone(du),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),qt=ji,pw=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CLOSED"]),hw=t=>{let e=t;return!!e&&(e.name==="TypeError"&&/fetch failed/i.test(e.message??"")||pw.has(String(e.cause?.code??e.code??"")))},gw=t=>{let e=t;return e&&e.code==="TOO_LARGE"&&Number.isSafeInteger(e.maxBytes)&&e.maxBytes>0?e.maxBytes:null},mw=t=>`l:${t.size}:${t.mtime}`,yw=10*6e4,Jd=1024*1024,Re=(t,e)=>`${t}:${e}`,Wt=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",bn=t=>t.slice(t.lastIndexOf("/")+1),Yn=Oe(""),ww=t=>/\.db$/i.test(t)&&!/^(agents|human)(\/|$)/.test(t),is=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),en=t=>t.split("/").length,Ue=t=>t instanceof Error?t.message:String(t),bw={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},pa=t=>t.file.replace(/\.json$/,".bases"),Qd=5e3,Sw=3e4,Kd=3e4,vw=3e3,ss=10*6e4,kw=60*6e4,Ew=10*6e4,_w=3*6e4,Xd=2e3,Cw=1440*6e4,ha=t=>/^(agents|human)\//.test(t)?Sw:Qd,Aw=t=>Math.max(t.mtime,t.ctime);async function*tn(t){let e=fa.now()+8;for(let n of t)fa.now()>=e&&(await uw(),e=fa.now()+8),yield n}function ef(t){if(!t.contentSync)return;let e=new ga(t);for(let[n,r]of Object.entries({[gt.get]:(i,s)=>e.snapshot(i,s),[gt.preview]:i=>e.preview(i),[gt.apply]:(i,s)=>e.apply(typeof i=="string"?i:"",s),[gt.run]:()=>{e.retrySoon(),e.touch(),e.kick()},[gt.pause]:i=>e.pause(i===!0),[gt.retry]:()=>{e.retryFailed(),e.touch(),e.kick()},[gt.rename]:i=>e.rename(i),[gt.setup]:i=>e.setup(i),[gt.archiveSeen]:()=>e.archiveSeen(),[gt.confirmDeletes]:i=>e.confirmDeletes(typeof i=="string"?i:""),[gt.abandonDeletes]:i=>e.abandonDeletes(typeof i=="string"?i:"")}))t.handle(n,async(i,...s)=>{if(!t.isTrustedSender(i))return{ok:!1,error:"untrusted"};try{return{ok:!0,value:await r(...s)}}catch(a){return{ok:!1,error:Ue(a)}}});t.addQuitGuard?.(n=>e.running&&!e.quitting?{message:n==="zh"?"\u8FD8\u6709\u5185\u5BB9\u6B63\u5728\u540C\u6B65":"Content is still syncing"}:null),t.addFlushHook?.(n=>e.flush(n)),_u(()=>e.stats()),e.start()}var ga=class{session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;activeAt=Date.now();lastRunAt=0;focused=!1;devices=[];others;deviceId="";customName="";serial=Promise.resolve();scheduled=null;tick=null;first=null;blocked=new Map;phase="idle";lastError;get error(){return this.lastError}set error(e){this.lastError=e,e&&this.fault(e)}runLog=new xr;logAccount=null;runAccount=null;blockedError=void 0;live(){let e=this.host.accountId();return!!e&&e===this.logAccount&&(!this.running||!this.runAccount||this.runAccount===e)}tally(e){this.live()&&this.runLog.count(e)}fault(e,n=[]){this.live()&&this.runLog.fault(e,n)}health=Ei((e,n,r)=>lt("content",e,n,r));httpStatus=0;closed=!1;runFinished=Promise.resolve();archiving=null;archiveRetry={account:"",at:0};resolving=!1;awaitingBytes=new Map;scanned={skipped:[],unscanned:[],skippedInodes:new Set};deleteStamps=[];failures=new Map;tooLarge=new Map;tooLargeSeen=null;recordsAccount=null;roundVisited=null;bypassBackoff=!1;bypassThisRound=!1;limitsByNs=new Map;round=null;uiLocale=null;running=!1;quitting=!1;again=!1;flushing=null;flushRequest=0;flushThrough=0;dirty=new Map;flushAt=0;due=null;registered=null;devicesAt=0;changedAt=0;wroteLocal=!1;openJobs=new Set;host;options;accountGeneration=0;stopAccountWatch;constructor(e,n={}){this.host=e,this.options=n,this.stopAccountWatch=Kl(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{this.idleSkip()||this.run()},3e4)).unref?.(),(this.first=setTimeout(()=>{this.run()},5e3)).unref?.()}locale(){if(this.uiLocale)return this.uiLocale;try{return/^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en"}catch{return"zh"}}archiveStep(e){if(e.stored.accountReview||e.stored.agentArchive?.state==="done"||this.archiveRetry.account===e.account&&Date.now()<this.archiveRetry.at)return Promise.resolve();let n=()=>{this.archiveRetry={account:e.account,at:Date.now()+ss}};return this.archiving??=(async()=>{try{let r=this.host.readCreds();if(!r.token)return;let i=await this.gatedFetch(e,r.cloudUrl,"/api/remotesync/agent-archive",{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({locale:this.locale()})},6e4);if(this.guard(e),!i.ok){n();return}let s=await i.json();if(this.guard(e),s.state!=="done"&&s.state!=="running"){n();return}let a=e.stored.agentArchive,o=s.archive;a?.rewritten||this.turnAgentsOff(e);let l={rewritten:!0,seen:a?.seen??!1,state:s.state};s.state==="done"&&(o?.folderId?Object.assign(l,{folderId:o.folderId,name:o.name??void 0,shelfId:o.shelfId??void 0,shelfName:o.shelfName??void 0,files:o.files??0,at:o.at??Date.now()}):l.seen=!0),e.stored.agentArchive=l,await this.persist(e)}catch(r){if(Ue(r)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${Ue(r)}`)}finally{this.archiving=null}})()}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=Su(n);if(!r)return;e.stored.config=Zt(r,n.revision+1);let i=s=>s==="agents"||s.startsWith("agents/");for(let[s,a]of Object.entries(e.stored.files))i(a.path)&&(delete e.stored.files[s],delete e.stored.unconfirmed?.[s]);for(let[s,a]of Object.entries(e.stored.folders))i(a.path)&&delete e.stored.folders[s];for(let[s,a]of Object.entries(e.stored.pendingUploads??{}))i(a.path)&&delete e.stored.pendingUploads[s];this.previewValue=null}async archiveSeen(){let e=await this.getSession();e.stored.agentArchive&&(e.stored.agentArchive.seen=!0,await this.persist(e))}async close(){this.closed=!0,this.stopAccountWatch(),this.tick&&clearInterval(this.tick),this.first&&clearTimeout(this.first),this.scheduled&&clearTimeout(this.scheduled),this.due&&clearTimeout(this.due),this.session?.abort.abort(),await this.watcher?.close(),await this.runFinished}currentBinding(e){if(!e.binding)return!0;let n=dr(e.binding.file);return n!==null&&!n.pending&&n.account===e.binding.account&&n.epoch===e.binding.epoch}guard(e,n=!0){if(this.closed)throw Error("content_sync_closed");if(Zs(this.host),this.host.accountId()!==e.account||this.session!==e||e.generation!==this.accountGeneration)throw Error("account_changed");if(!this.currentBinding(e))throw Error("content_account_changed_preview_required");n&&e.abort.signal.throwIfAborted()}async accountWrite(e,n){let r=async()=>{this.guard(e),await n(e.account),this.guard(e)};this.host.accountTransition?await this.host.accountTransition(r):await r()}async persist(e){let n=e.writes.catch(()=>{}).then(async()=>{this.guard(e,!1);let r=JSON.stringify(e.stored);if(r===e.persisted)return;await la(wn(e.file),{recursive:!0,mode:448});let i=e.file+".tmp-"+mt();try{await $r(i,r,{mode:384,flag:"wx"}),this.guard(e,!1),await rs(i,e.file),e.persisted=r}finally{await Lr(i).catch(()=>{})}});return e.writes=n,n}async getSession(){let e=this.host.accountId();if(!e)throw this.logAccount&&(this.runLog.reset(),this.logAccount=null),this.session?.abort.abort(),this.session=null,Error("not_signed_in");let n=this.accountGeneration;return Zs(this.host),this.initializing?this.initializing.then(r=>(this.guard(r),r)):this.session?.account===e&&this.session.generation===n&&this.currentBinding(this.session)?(this.guard(this.session,!1),this.session):(this.session?.abort.abort(new Error("account_changed")),this.logAccount!==e&&(this.runLog.reset(),this.logAccount=e),this.initializing=(async()=>{await this.watcher?.close(),this.watcher=null,this.previewValue=null,this.sources=[],this.agentNames.clear(),this.cloudAgents=void 0,this.devices=[],this.dirty.clear(),this.registered=null,this.devicesAt=0,this.changedAt=0;let r=Fe(this.host.homeDir(),"content-sync"),i=Fe(r,Oe(e)+".json"),s=fw();try{let f=JSON.parse(await Pr(i,"utf8"));Od(f),s={...s,...f,config:Zt(f.config,f.config.revision)},s.jobs=Array.isArray(f.jobs)?f.jobs.slice(-200):[]}catch(f){if(f.code!=="ENOENT")throw Error("Invalid content sync state; original data was retained")}let a,o=Fe(this.host.homeDir(),"content-sync-device.json"),l=async()=>{let f=JSON.parse(await Pr(o,"utf8"));if(typeof f?.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(f.id))throw Error("Invalid device sync ID");return f};try{a=await l()}catch(f){if(f.code!=="ENOENT")throw f;a={id:mt()},await la(wn(o),{recursive:!0});try{await $r(o,JSON.stringify(a),{flag:"wx",mode:384})}catch(g){if(g.code!=="EEXIST")throw g;a=await l()}}if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=a.id,this.customName=typeof a.name=="string"?a.name:"";let c=await this.host.contentSync.roots();if(this.host.accountId()!==e)throw Error("account_changed");let u={account:e,generation:n,file:i,stored:s,roots:c,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map,tombstones:new Map};return this.session=u,await this.bindAccount(u),await this.recoverTrash(u),this.guard(u),s.owned&&await this.accountWrite(u,f=>this.host.contentSync.claim(!0,f)),this.setSources(await this.scan(u,c).catch(f=>(this.error=Ue(f),[]))),await this.register(u,!0),await this.watchRoots(u),u})().catch(r=>{throw this.session?.account===e&&(this.session.abort.abort(),this.session=null),r}).finally(()=>{this.initializing=null}),this.initializing)}async bindAccount(e){let n=wn(e.file),r=Ks(this.host.homeDir()),i=Oe(e.account),s=dr(r),a=!s?.account&&(await jr(n).catch(l=>{if(l.code==="ENOENT")return[];throw l})).some(l=>/^[a-f0-9]{64}\.json$/.test(l)&&l!==i+".json"),o=s?.pending&&(e.stored.owned||e.stored.config.revision>0);if((s?.account&&s.account!==i||a||o)&&(e.stored.accountReview=!0,e.stored.owned=!0,e.stored.config.enabled&&(e.stored.config={...e.stored.config,enabled:!1,revision:e.stored.config.revision+1}),await this.persist(e)),s?.account!==i||s.pending){this.guard(e,!1);let l=dr(r);if(l?.account!==s?.account||l?.epoch!==s?.epoch||l?.pending!==s?.pending)throw Error("account_changed");Xs(r,{version:1,account:i,...s?.epoch?{epoch:s.epoch}:{}})}e.binding={file:r,account:i,epoch:s?.epoch},this.guard(e,!1)}async rootIdentity(e,n){let r=e.rootIdentities.get(n);if(r){let s=await ca(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!s.isDirectory()||!bt(r,s))throw Error("Sync root changed; preview before rebinding");return r}let i=await ar(n).catch(s=>{throw s.code==="ENOENT"?Error("Sync root unavailable: "+n):s});return this.guard(e),e.rootIdentities.set(n,i),i}async scan(e,n=e.roots){let r=!1;for(let s of e.stored.roots??[]){let a=n.find(l=>l.prefix===s.prefix);if(!a||a.root!==s.root)throw Error("content_roots_changed_preview_required");let o=await this.rootIdentity(e,s.root);if(s.dev!==void 0&&!an(s,o))throw Error("Sync root changed; preview before rebinding");if(s.dev!==void 0&&s.dev!==o.dev){let l=String(s.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(l)&&Ke(n,c.path).root===s.root&&(c.inode=String(o.dev)+":"+c.inode.slice(l.length),delete c.stat,delete c.statAt)}JSON.stringify(s)!==JSON.stringify({...s,...o})&&(Object.assign(s,o),r=!0)}r&&await this.persist(e);let i=await ns(n);return this.scanned={skipped:i.skipped,unscanned:i.unscanned,skippedInodes:i.skippedInodes},i}async write(e,n,r,i){this.guard(e),await sa(e.roots,n,r,i,(s,a)=>this.lock(e,s,a)),await this.recordRoots(e)}async recordRoots(e){this.guard(e);let n=!1;for(let r of e.roots){if(e.stored.roots?.some(s=>s.prefix===r.prefix&&s.root===r.root))continue;await ca(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&((e.stored.roots??=[]).push({...r,...await this.rootIdentity(e,r.root)}),n=!0)}n&&await this.persist(e)}lock(e,n,r,i=!1){let s=()=>{if(this.guard(e),e.stored.paused&&!i)throw Error("paused");for(let[a,o]of e.rootIdentities){let l;try{l=Qy(a)}catch{throw Error("Sync root unavailable: "+a)}if(!l.isDirectory()||!bt(o,l))throw Error("Sync root changed; restart before retrying")}r(),this.wroteLocal=!0};return this.host.contentSync.withWriteLock?.(n,s)??Promise.resolve().then(s)}async previewScan(e,n){for(let r of e.stored.roots??[])n.some(i=>i.prefix===r.prefix&&i.root===r.root)&&await Bt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return ns(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Rs(e.roots.map(n=>n.root),{ignoreInitial:!0,ignored:n=>{let r=n.split(/[\\/]/).at(-1)??"";return r.startsWith(".")&&r!==".memory-tombstones.json"||r==="node_modules"||r==="__pycache__"}}),this.watcher.on("all",(n,r)=>{let i=this.logical(e,r),s=Date.now();if(this.activeAt=s,i){let a=this.dirty.get(i);a?a.last=s:this.dirty.set(i,{first:s,last:s})}this.schedule(i?void 0:s+Qd)}))}logical(e,n){let r=null;for(let a of e.roots)(n===a.root||n.startsWith(a.root+Vn))&&(!r||a.root.length>r.root.length)&&(r=a);if(!r)return null;let i=Fr(r.root,n).split(Vn).join("/");return(r.prefix?i?`${r.prefix}/${i}`:r.prefix:i)||null}dueAt(e,n){return n.last<=this.flushAt?0:Math.min(n.last+ha(e),n.first+Kd)}schedule(e){let n=e??1/0;for(let[r,i]of this.dirty)n=Math.min(n,this.dueAt(r,i));this.due&&clearTimeout(this.due),this.due=null,!(n===1/0||this.closed)&&(this.due=setTimeout(()=>{this.due=null;let r=this.session;r?.stored.config.enabled&&!r.stored.paused&&this.kick()},Math.max(0,n-Date.now())+50),this.due.unref?.())}kick(){if(this.running){this.again=!0;return}this.run()}touch(){this.activeAt=Date.now()}idleSkip(e=Date.now()){return e-this.activeAt>=Ew&&e-this.lastRunAt<_w-5e3}flush(e){let n=this.session;if(!(this.closed||!this.host.accountId()||n&&(!n.stored.config.enabled||n.stored.paused)))return this.flushRequest++,this.flushThrough=Math.max(this.flushThrough,Date.now()),this.bypassBackoff=!0,e==="quit"&&(this.quitting=!0),this.flushAt=this.quitting?1/0:this.flushThrough,this.flushing?this.flushing:this.flushing=(async()=>{try{for(;!this.closed;){let r=this.serial;if(await r,r!==this.serial)continue;if(this.running){await this.runFinished;continue}let i=this.flushRequest;if(await this.run(),i===this.flushRequest)return}}finally{this.flushing=null,this.quitting=!1,this.flushAt=this.flushThrough}})()}async request(e,n,r="",i="GET",s,a,o){for(;;){this.guard(e);let l=this.host.readCreds();if(!l.token)throw Error("not_signed_in");let c=Jt(l.cloudUrl);await c.ready(e.abort.signal),this.guard(e);let u=l.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(n)}${r}`,f={Authorization:`Bearer ${l.token}`,"X-Content-Device":this.deviceId,"X-Content-Caps":No,...o},g;if(s instanceof Buffer){f["Content-Type"]="application/octet-stream",f["Content-Length"]=String(s.length);let y=async function*(){for(let b=0;b<s.length;b+=64*1024)e.abort.signal.throwIfAborted(),yield s.subarray(b,b+64*1024),a?.(Math.min(s.length,b+64*1024))};g=cw.from(y())}else s!==void 0&&(f["Content-Type"]="application/json",g=JSON.stringify(s));let p={method:i,headers:f,body:g,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...s instanceof Buffer?{duplex:"half"}:{}},m=await fetch(u,p);if(this.guard(e),!m.ok&&!(m.status===304&&o?.["If-None-Match"])){let y=await m.json().catch(()=>({}));if(c.observe(m.status,m.headers,y?.code,y?.retryAfterMs))continue;throw this.httpStatus=m.status,Object.assign(new Error(typeof y?.detail=="string"?y.detail:`content_http_${m.status}`),{status:m.status,...typeof y?.code=="string"?{code:y.code}:{},...Number.isSafeInteger(y?.maxBytes)&&y.maxBytes>0?{maxBytes:y.maxBytes}:{}})}return c.observe(m.status,m.headers),i==="DELETE"&&this.tally("deletesSent"),m}}async gatedFetch(e,n,r,i,s){let a=Jt(n);for(;;){await a.ready(e.abort.signal),this.guard(e);let o=await fetch(n.replace(/\/+$/,"")+r,{...i,headers:{...i.headers,"X-Content-Caps":No},signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(s)])});if(o.status===429){let l=await o.clone().json().catch(()=>({}));if(a.observe(o.status,o.headers,l?.code,l?.retryAfterMs))continue}return a.observe(o.status,o.headers),o}}async json(e,n,r="",i="GET",s,a){let o=await(await this.request(e,n,r,i,s,void 0,a)).json();return this.guard(e),o}async manifests(e,n){let r=new Map;for(let s of new Set(n.rules.filter(a=>a.target!=="off").map(a=>a.target))){let a=JSON.parse(await this.manifestText(e,s));Ki(a,s),await this.knownTombstones(e,s,a),r.set(s,a)}let i=[r.get("default"),r.get(`device-${this.deviceId}`)].filter(Boolean);return i.length&&(this.cloudAgents=[...new Set(i.flatMap(s=>s.nodes.filter(a=>!a.deleted&&a.kind==="file").map(a=>/^agents\/([^/]+)\/config\.toml$/.exec(a.path)?.[1]).filter(a=>!!a&&Cr.test(a))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),i=r&&Date.now()-r.at<kw?r:void 0,s=await this.request(e,n,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...i?{"If-None-Match":i.etag}:{}});if(s.status===304)return await s.body?.cancel(),i?i.text:(e.manifests.delete(n),this.manifestText(e,n));let a=await s.text();this.guard(e),Ki(JSON.parse(a),n);let o=s.headers.get("etag");return r?.text!==a&&this.touch(),o?e.manifests.set(n,{etag:o,text:a,at:Date.now()}):e.manifests.delete(n),a}async knownTombstones(e,n,r){if(typeof r.tombstonesSince!="string")return;let i=new Set(r.nodes.map(c=>c.id)),s=new Set;for(let[c,u]of Object.entries(e.stored.files))c.startsWith(n+":")&&s.add(u.id);for(let[c,u]of Object.entries(e.stored.folders))c.startsWith(n+":")&&s.add(u.id);for(let[c,u]of Object.entries(e.stored.pendingUploads??{}))c.startsWith(n+":")&&s.add(u.id);let a=e.tombstones.get(n);a||e.tombstones.set(n,a=new Map);for(let c of[...a.keys()])i.has(c)&&a.delete(c);let o=Date.now(),l=[...s].filter(c=>{if(i.has(c))return!1;let u=a.get(c);return!u||!u.node&&o-u.at>=Cw});for(let c=0;c<l.length;c+=Xd){let u=l.slice(c,c+Xd),f=new Set(u),g=await this.json(e,n,"/tombstones","POST",{ids:u}),p=new Map((Array.isArray(g?.nodes)?g.nodes:[]).filter(m=>Nd(m)&&f.has(m.id)).map(m=>[m.id,m]));for(let m of u)a.set(m,{node:p.get(m)??null,at:o})}for(let c of s)if(!i.has(c)){let u=a.get(c)?.node;u&&r.nodes.push(structuredClone(u))}}route(e,n,r="file"){if(Gi(e)||Qo(e,r)===!1)return null;let i=Mn(e,n.rules);return i&&i.target!=="off"?i.target:null}effective(e,n){let r=new Map(n.filter(i=>i.localId).map(i=>[i.localId,i.path]));return{...e,rules:e.rules.map(i=>i.sourceId&&r.has(i.sourceId)?{...i,source:r.get(i.sourceId)}:i)}}deviceName(){return this.customName||Fi(ua())}setSources(e){let n=new Map,r={files:0,size:0};for(let s of e)s.kind==="folder"&&n.set(s.path,{size:0,files:0});for(let s of e)if(s.kind==="file"){fu.some(a=>s.path.startsWith(a+"/"))||(r.files++,r.size+=s.size);for(let a=Wt(s.path);a;a=Wt(a)){let o=n.get(a);o&&(o.size+=s.size,o.files++)}}let i=new Map(e.filter(s=>s.kind==="file"&&/^agents\/[^/]+\/config\.toml$/.test(s.path)).map(s=>[s.path.slice(0,-12),s]));this.others=r,this.sources=[...n].sort(([s],[a])=>en(s)-en(a)||(s<a?-1:1)).slice(0,2e3).map(([s,a])=>({path:s,kind:"folder",size:a.size,files:a.files,...Ar(s)&&i.has(s)?{agent:!0}:{}})),this.sourcesAt=Date.now(),this.readAgentNames(i)}async readAgentNames(e){for(let n of this.agentNames.keys())e.has(n)||this.agentNames.delete(n);for(let[n,r]of e){let i=`${r.mtime}:${r.size}`;if(!(this.agentNames.get(n)?.key===i||r.size>256*1024))try{this.agentNames.set(n,{key:i,...hu((await Wn(r)).toString("utf8"))})}catch{this.agentNames.set(n,{key:i})}}}async rename(e){let n=typeof e=="string"?e.trim():"";if(n.length>64||/[\u0000-\u001f\u007f]/.test(n))throw Error("Invalid device name");let r=await this.getSession(),i=n||Fi(ua()),s=Mo(i,this.devices,this.deviceId);if(s)throw Error(s==="taken"?"device_name_taken":s==="reserved"?"device_name_reserved":"device_name_invalid");return await this.json(r,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:i,unique:!0}),await this.saveName(n),await this.register(r,!0),this.deviceName()}async saveName(e){let n=Fe(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+mt();try{await $r(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await rs(r,n)}finally{await Lr(r).catch(()=>{})}this.customName=e}async register(e,n=!1){let r=Date.now();if(!n&&this.registered?.name===this.deviceName()&&r-this.registered.at<ss){r-this.devicesAt>=ss&&await this.refreshDevices(e);return}let i=(o,l)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:o,...l?{unique:!0}:{}}),s=async()=>(await this.json(e,"devices")).devices,a=o=>/device_name_(taken|reserved|invalid)/.test(Ue(o));try{await i(this.deviceName(),!0)}catch(o){if(!a(o))throw o;let l=!1;if(!this.customName){let c=Fi(ua());for(let u=0;u<5&&!l;u++){let f=await s(),g=null;for(let p=2;p<100&&!g;p++){let m=`${c} ${p}`;Mo(m,f,this.deviceId)||(g=m)}if(!g)break;try{await i(g,!0),await this.saveName(g),l=!0}catch(p){if(!a(p))throw p}}}l||await i(this.deviceName(),!1)}this.registered={name:this.deviceName(),at:r},await this.refreshDevices(e)}async refreshDevices(e){this.devicesAt=Date.now(),this.devices=(await this.json(e,"devices")).devices,await this.cacheDevices()}cachedDevices="";async cacheDevices(){let e=Fe(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let o=JSON.parse(await Pr(e,"utf8"));Array.isArray(o?.devices)&&(n=o.devices)}catch{}let r=new Map(n.filter(o=>o&&typeof o.id=="string").map(o=>[o.id,o])),i=this.devices.map(o=>{let l=r.get(o.id),c=[...Array.isArray(l?.aliases)?l.aliases:[],...l&&typeof l.name=="string"&&l.name!==o.name?[l.name]:[]],u=c.filter((f,g)=>typeof f=="string"&&f!==o.name&&c.lastIndexOf(f)===g).slice(-5);return{id:o.id,name:o.name,...u.length?{aliases:u}:{}}}),s=JSON.stringify({devices:i});if(s===this.cachedDevices)return;let a=e+".tmp-"+mt();try{await $r(a,s,{mode:384,flag:"wx"}),await rs(a,e),this.cachedDevices=s}catch(o){this.error=Ue(o)}finally{await Lr(a).catch(()=>{})}}async setup(e){let n=await this.getSession(),r=e&&typeof e=="object"?e:{};if(n.stored.config.enabled||n.stored.config.revision>0)return null;let i=Pn(wu(n.stored.config),"","off");for(let o of Lt)o.id!=="agents"&&r[o.id]===!1&&(i=Pn(i,o.path,"off"));let s=new Set(this.sources.filter(o=>o.agent).map(o=>o.path.slice(7))),a=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(o=>typeof o=="string"&&s.has(o)):[];return this.preview(bu(i,a))}retryFailed(){this.failures.clear(),this.tooLarge.clear(),this.bypassBackoff=!0}retrySoon(){this.bypassBackoff=!0}rateLimitedUntil(){let e=this.host.readCreds();return e.cloudUrl?Jt(e.cloudUrl).until():null}capFor(e,n,r){let i=Ui(n,e,r?.limits),s=this.tooLarge.get(e+"\0"+n)?.learned;return s&&s.published===i?Math.min(i,s.maxBytes):i}noteTooLarge(e,n,r,i,s,a){let o=n+"\0"+r,l=this.tooLarge.get(o);this.tooLargeSeen?.add(o),this.failures.delete(o),lt("content","skippedTooLarge",1,r),e.stored.jobs=e.stored.jobs.filter(c=>!(c.path===r&&c.target===n&&(c.state==="failed"||c.state==="paused")&&(c.direction==="upload"||c.direction==="download"))),this.tooLarge.set(o,{ns:n,path:r,size:i,maxBytes:s,...a??l?.learned?{learned:a??l.learned}:{}})}tooLargeList(){return[...this.tooLarge.values()].map(e=>({path:e.path,reason:"too-large",size:e.size,maxBytes:e.maxBytes}))}backingOff(e,n,r){let i=e+"\0"+n,s=this.failures.get(i);return this.roundVisited?.add(i),s?s.fp!==r?(this.failures.delete(i),!1):!this.bypassThisRound&&Date.now()<s.retryAt:!1}succeeded(e,n){this.failures.delete(e+"\0"+n)}fileFailed(e,n,r,i,s,a){if(e.abort.signal.aborted||hw(i))throw i;let o=n+"\0"+r,l=gw(i);if(l!==null){let m=i.size,y=Number.isSafeInteger(m)?m:a??0;this.noteTooLarge(e,n,r,y,l,{maxBytes:l,published:Ui(r,n,this.limitsByNs.get(n))});return}this.error=Ue(i);let c=this.failures.get(o),u=(c&&c.fp===s?c.count:0)+1,f=Date.now()+pu(u),g=i?.code;this.failures.set(o,{ns:n,path:r,reason:Ue(i),...typeof g=="string"?{code:g}:{},count:u,retryAt:f,fp:s});let p=e.stored.jobs.findLast(m=>m.path===r&&m.target===n&&m.state==="failed");p&&(p.retryAt=f)}failureList(){return[...this.failures.values()].sort((e,n)=>e.retryAt-n.retryAt).slice(0,200).map(e=>({path:e.path,target:e.ns,reason:e.reason,...e.code?{code:e.code}:{},count:e.count,retryAt:e.retryAt}))}async snapshot(e,n){(e==="zh"||e==="en")&&(this.uiLocale=e);let r=await this.getSession(),i=n&&typeof n=="object"?n:{};if(i.focused===!0){let s=!this.focused;this.focused=!0,this.touch(),s&&r.stored.config.enabled&&!r.stored.paused&&Date.now()-this.lastRunAt>3e4&&this.kick()}else i.focused===!1&&(this.focused=!1);return!r.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(r).then(s=>{this.session===r&&this.setSources(s)},()=>{})),i.devices===!0&&Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(r).catch(()=>{})),{available:!0,account:Oe(r.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(r.stored.config),running:this.running,paused:r.stored.paused,phase:this.phase,jobs:structuredClone(r.stored.jobs),devices:this.devices,sources:this.sources.map(s=>{let a=s.agent&&this.agentNames.get(s.path);return a?{...s,...a.name?{name:a.name}:{},...a.nameEn?{nameEn:a.nameEn}:{}}:s}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...r.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...r.stored.agentArchive?{agentArchive:(({rewritten:s,...a})=>a)(r.stored.agentArchive)}:{},...(s=>s&&(s.latched||s.pending.length)?{deletes:{latched:s.latched,pending:s.pending.length,token:Yd(s.pending),items:s.pending.slice(0,200).map(a=>({path:a.path,side:a.side}))}}:{})(r.stored.deleteGuard),...(s=>s.length?{skipped:s.slice(0,200),skippedCount:s.length}:{})([...this.scanned.skipped,...this.recordsAccount===r.account?this.tooLargeList():[]]),...(s=>s?{rateLimitedUntil:s}:{})(this.rateLimitedUntil()),...this.failures.size&&this.recordsAccount===r.account?{failures:this.failureList()}:{}}}async confirmDeletes(e){await this.decideDeletes("confirm",e)}async abandonDeletes(e){await this.decideDeletes("restore",e)}deferredDecision=[];async decideDeletes(e,n){let r=await this.getSession(),i=r.stored.deleteGuard?.pending??[],s=i.map(a=>a.key);if(n!==void 0&&n!==Yd(i))throw Error("deletes_changed");if(!(!s.length&&!r.stored.deleteGuard?.latched)){if(this.running){this.deferredDecision.push({kind:e,keys:s}),this.again=!0;return}this.applyDecision(r,e,s),await this.persist(r),this.touch(),this.kick()}}applyDecision(e,n,r){let i=e.stored.deleteGuard;if(!i)return;let s=new Set(r),a=i.pending.filter(f=>!s.has(f.key)),o=i.pending.filter(f=>s.has(f.key)),l=[...new Set([...i.confirmed??[],...o.map(f=>f.key)])],c=[...new Map([...i.restore??[],...o].map(f=>[Ot(f.side,f.ns,f.id),f])).values()],u={latched:a.length>0,pending:a,...n==="confirm"?{confirmed:l}:i.confirmed?.length?{confirmed:i.confirmed}:{},...n==="restore"?{restore:c}:i.restore?.length?{restore:i.restore}:{}};u.latched||u.pending.length||u.confirmed?.length||u.restore?.length?e.stored.deleteGuard=u:delete e.stored.deleteGuard,n==="confirm"&&(this.deleteStamps=[])}stats(){let e=this.host.accountId(),n=e&&this.session?.account===e?this.session:null,r=n?.stored,i={},s=e&&e===this.logAccount?this.runLog.snapshot():new xr().snapshot();for(let a of r?.jobs??[])i[a.state]=(i[a.state]??0)+1;return{deviceId:this.deviceId||null,session:!!n,enabled:!!r?.config.enabled,paused:!!r?.paused,running:!!n&&this.running,phase:n?this.phase:"idle",revision:r?.config.revision??0,rules:(r?.config.rules??[]).map(a=>({source:a.source,target:a.target})),backlog:r?{jobs:i,blocked:[...this.blocked.values()].reduce((a,o)=>a+o.length,0),pendingUploads:Object.keys(r.pendingUploads??{}).length,unconfirmed:Object.keys(r.unconfirmed??{}).length,trash:r.trash?.length??0,awaitingBytes:this.awaitingBytes.size,dirty:this.dirty.size}:null,archive:r?.agentArchive?.state??null,...s}}async preview(e){let n=await this.getSession();if(e?.revision!==n.stored.config.revision)throw Error("config_changed");let i=Zt(e,n.stored.config.revision+1),s=await this.host.contentSync.roots();this.guard(n);let a=await this.previewScan(n,s),o=this.effective(i,a);if(n.stored.agentArchive?.state==="running"&&a.some(N=>N.kind==="file"&&N.path.startsWith("agents/")&&this.route(N.path,o)))throw Error("agent_archive_running");let l=await this.manifests(n,o);this.guard(n),this.setSources(a);let c=0,u=0,f=0,g=0,p=await this.bindingsOf(s),m=new Map,y=new Map;for(let[N,Y]of Object.entries(n.stored.files))this.survives(n.stored,o,p,Y.path)&&(m.set(N,Y),y.set(N.slice(0,N.indexOf(":"))+"\0"+Y.path,Y));let b=n.stored.deleteGuard,_=new Set((b?.restore??[]).map(N=>Ot(N.side,N.ns,N.id))),h=[],T=new Map,v=new Set(a.map(N=>N.path));for await(let N of tn(a.filter(Y=>Y.kind==="file"))){let Y=this.route(N.path,o);if(!Y)continue;let ee=l.get(Y),J=ee?.nodes.find(te=>!te.deleted&&te.kind==="file"&&te.path===N.path);if(N.size>Ui(N.path,Y,ee?.limits))continue;let se=Oe(await Wn(N));if(this.guard(n),T.set(N.path,se),!J){let te=y.get(Y+"\0"+N.path),ae=te&&ee?.nodes.find(Q=>Q.id===te.id&&Q.deleted);if(ae&&te&&is(N.path)&&(te.hash===se||te.memoryDeleted&&se===Yn))continue;if(ae&&te&&te.hash===se&&!_.has(Ot("local",Y,te.id))){h.push({ns:Y,path:N.path});continue}}se!==J?.hash&&(c++,g+=N.size,J?.version&&f++)}let I=i.enabled?this.agentAsks(n,a,o,l,T):[],E=h.length;for(let[N,Y]of l)for await(let ee of tn(Y.nodes)){if(ee.deleted||ee.kind!=="file"||this.route(ee.path,o)!==N||v.has(ee.path))continue;let J=m.get(Re(N,ee.id)),se=qn(a.unscanned,ee.path)||!!J?.inode&&a.skippedInodes.has(J.inode);if(J&&J.path!==ee.path&&v.has(J.path))continue;let te=Do(ee,J,!!n.stored.pendingUploads?.[Re(N,ee.id)],se);te==="download"?u++:te==="delete"&&await this.absent(n,ee.path,s)&&(_.has(Ot("cloud",N,ee.id))?u++:h.push({ns:N,path:ee.path}))}let D=h.length-E,x=[...m].map(([N,Y])=>({ns:N.slice(0,N.indexOf(":")),path:Y.path})),L=Oo(h,x,{latched:!!b?.latched,recent:this.deleteStamps.filter(N=>Date.now()-N<Ro).length}),V=this.signature(a,l,s),H={token:mt(),config:o,upload:i.enabled?c:0,download:i.enabled?u:0,conflicts:i.enabled?f:0,bytes:i.enabled?g:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,deleteCloud:i.enabled?D:0,deleteLocal:i.enabled?E:0,...i.enabled&&L?{deletesHeld:!0}:{},...I.length?{agentAsks:I}:{}};return this.previewValue={value:H,account:n.account,signature:V},H}async bindingsOf(e){let n=[];for(let r of e)await ca(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&n.push({...r,...await ar(r.root)});return n}survives(e,n,r,i,s="file"){return e.config.enabled===n.enabled&&dw(e.roots??r,r)&&this.route(i,e.config,s)===this.route(i,n,s)}signature(e,n,r){return Oe(JSON.stringify([r,e.map(i=>[i.path,i.size,i.mtime,i.inode]),[...n].map(([i,s])=>[i,s.nodes.map(a=>[a.id,a.revision,a.version,a.deleted])])]))}async apply(e,n){let r=this.serial,i;this.serial=new Promise(s=>{i=s}),await r;try{let s=await this.getSession(),a=this.previewValue;if(!a||a.value.token!==e||a.account!==s.account||a.value.expiresAt<Date.now()||a.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let o=a.value.agentAsks??[],l=xw(n);this.resolving=!0;try{let c=await this.host.contentSync.roots(),u=await this.previewScan(s,c),f=await this.manifests(s,a.value.config);if(this.signature(u,f,c)!==a.signature)throw Error("preview_changed");let g=await this.bindingsOf(c),p=structuredClone(a.value.config);for(let b of p.rules){let _=u.find(h=>h.kind==="folder"&&h.path===b.source);_&&(b.sourceId=await ia(_))}let m=o.length?Zt(o.reduce((b,_)=>Pn(b,`agents/${_.slug}`,"off"),p),p.revision):p;if(this.guard(s),this.previewValue!==a||a.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");let y=structuredClone(s.stored);s.stored.config=m,s.stored.owned=!0,s.stored.paused=!1,delete s.stored.unconfirmed;for(let[b,_]of Object.entries(s.stored.files))this.survives(y,s.stored.config,g,_.path)||delete s.stored.files[b];for(let[b,_]of Object.entries(s.stored.folders))this.survives(y,s.stored.config,g,_.path,"folder")||delete s.stored.folders[b];s.stored.roots=g,s.rootIdentities=new Map(g.map(b=>[b.root,b])),await this.persist(s);try{await this.accountWrite(s,b=>this.host.contentSync.claim(!0,b))}catch(b){throw s.stored=y,await this.persist(s),await this.accountWrite(s,_=>this.host.contentSync.claim(y.owned,_)).catch(()=>{}),b}if(this.previewValue=null,s.roots=c,await this.watchRoots(s),o.length)try{await this.resolveAsks(s,o,l,p)}catch(b){throw this.fault(Ue(b)),b}s.stored.accountReview&&(delete s.stored.accountReview,await this.persist(s))}finally{this.resolving=!1}}finally{i()}this.run()}async pause(e){let n=await this.getSession();if(!e&&n.stored.accountReview)throw Error("content_account_changed_preview_required");n.stored.paused=e,e?(n.abort.abort(new Error("paused")),this.phase="paused"):this.running||(n.abort=new AbortController),await this.persist(n),e||this.run()}job(e,n,r,i,s){let a=e.stored.jobs.findLast(l=>l.path===n&&l.target===r&&l.direction===i&&["failed","paused","queued"].includes(l.state));if(a)return Object.assign(a,{state:"active",done:0,size:s,at:Date.now(),error:void 0,finishedAt:void 0}),a;let o={id:mt(),path:n,target:r,direction:i,state:"active",done:0,size:s,at:Date.now()};return e.stored.jobs.push(o),e.stored.jobs=e.stored.jobs.slice(-200),o}done(e){e.state="done",e.done=e.size??e.done,e.finishedAt=Date.now()}async operation(e,n,r,i,s,a){if(this.guard(e),e.stored.paused)throw Error("paused");this.activeAt=Date.now();let o=this.job(e,n,r,i,s);try{let l=await a(o);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(o),i==="upload"?lt("content","uploads"):i==="download"&<("content","downloads");let c=bw[i];return c&&this.tally(c),l}catch(l){throw o.state=e.stored.paused?"paused":"failed",o.error=Ue(l),o.finishedAt=Date.now(),l}}async run(){if(this.running||this.closed||this.resolving)return;this.running=!0;let e;this.runFinished=new Promise(o=>{e=o});let n=Date.now();this.lastRunAt=n,this.wroteLocal=!1;let r=new Set,i,s=!1,a=!1;try{if(i=await this.getSession(),this.runAccount=i.account,i.stored.accountReview){this.error="content_account_changed_preview_required";return}if(await this.archiveStep(i),!i.stored.config.enabled||i.stored.paused)return;i.abort.signal.aborted&&(i.abort=new AbortController),this.blocked.clear(),this.phase="scanning",this.error=void 0,s=!0,this.httpStatus=0,this.live()&&this.runLog.begin(n);let o=await this.host.contentSync.roots();this.guard(i),i.roots=o,this.tooLargeSeen=new Set,this.roundVisited=new Set,this.recordsAccount!==i.account&&(this.failures.clear(),this.tooLarge.clear(),this.recordsAccount=i.account),this.bypassThisRound=this.bypassBackoff,this.bypassBackoff=!1,await this.host.contentSync.agentFiles?.prepare().catch(T=>{this.error=Ue(T)}),this.guard(i);let l=await this.scan(i,o);await this.recordRoots(i);let c=this.effective(i.stored.config,l),u=await this.manifests(i,c);this.guard(i),this.limitsByNs=new Map([...u].map(([T,v])=>[T,v.limits]));let f=new Map;for(let[T,v]of u)for(let I of v.nodes)I.kind==="file"&&!I.deleted&&f.set(T+"\0"+I.path,I.version??"");let g=(T,v)=>`${mw(v)}|c:${f.get(T+"\0"+v.path)??""}`;await this.register(i),this.openJobs=new Set(i.stored.jobs.filter(T=>["failed","paused","active"].includes(T.state)&&["upload","download","merge"].includes(T.direction)).map(T=>T.target+"\0"+T.path)),await this.folders(i,c,l,u),await this.recordRoots(i),await this.fileRenames(i,c,l,u),l=await this.scan(i,o),c=this.effective(c,l),i.stored.config=c,this.setSources(l),this.phase="syncing",this.round={plan:[],restore:new Map((i.stored.deleteGuard?.restore??[]).map(T=>[Ot(T.side,T.ns,T.id),T])),restoreHit:new Set,restoreDone:new Set,tracked:Object.entries(i.stored.files).map(([T,v])=>({ns:T.slice(0,T.indexOf(":")),path:v.path})),undecided:new Set};let p=(T,v)=>this.round.undecided.add(T+"\0"+v),m=T=>T.endsWith("/"+Or),y=new Set,b=new Set,_=T=>T.startsWith("agents/")?T.slice(0,T.lastIndexOf("/")+1):null,h=T=>T.endsWith("/MEMORY.md")&&b.has(_(T)??"");for(let[T,v]of u)for await(let I of tn(v.nodes.filter(E=>E.kind==="file"&&!E.busy&&m(E.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(I.path,c)!==T||l.some(E=>E.path===I.path))){if(this.isBlocked(T,I.path)){b.add(_(I.path)??""),p(T,I.path);continue}if(this.backingOff(T,I.path,`c:${I.version??""}`)){b.add(_(I.path)??""),p(T,I.path);continue}y.add(I.id);try{await this.missing(i,I,T,l,c)==="unknown"?b.add(_(I.path)??""):this.succeeded(T,I.path)}catch(E){this.fileFailed(i,T,I.path,E,`c:${I.version??""}`,I.size),b.add(_(I.path)??""),p(T,I.path)}}}for await(let T of tn(l.filter(v=>v.kind==="file").sort((v,I)=>+!m(v.path)-+!m(I.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");let v=this.route(T.path,c);if(v){if(h(T.path)){p(v,T.path);continue}if(this.isBlocked(v,T.path)){m(T.path)&&b.add(_(T.path)??""),p(v,T.path);continue}if(this.backingOff(v,T.path,g(v,T))){p(v,T.path),m(T.path)&&b.add(_(T.path)??"");continue}try{let I=await this.file(i,c,T,v,u.get(v));I==="held"?(r.add(T.path),p(v,T.path)):I==="too-large"?(p(v,T.path),m(T.path)&&b.add(_(T.path)??"")):this.succeeded(v,T.path)}catch(I){this.fileFailed(i,v,T.path,I,g(v,T),T.size),p(v,T.path),m(T.path)&&b.add(_(T.path)??"")}}}for(let[T,v]of u)for await(let I of tn(v.nodes.filter(E=>E.kind==="file"&&!E.busy&&!y.has(E.id)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(I.path,c)!==T||l.some(E=>E.path===I.path))){if(this.isBlocked(T,I.path)||h(I.path)){p(T,I.path);continue}if(this.holdGone(I.path)){r.add(I.path),p(T,I.path);continue}if(this.backingOff(T,I.path,`c:${I.version??""}`)){p(T,I.path);continue}try{await this.missing(i,I,T,l,c),this.succeeded(T,I.path)}catch(E){this.fileFailed(i,T,I.path,E,`c:${I.version??""}`,I.size),p(T,I.path)}}}await this.executeDeletes(i,this.round),await this.cleanupFolders(i,c,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(i).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=ss)&&(await this.accountWrite(i,T=>this.host.contentSync.changed(T)),this.changedAt=Date.now()),this.guard(i),await this.persist(i),await this.pruneBases(i),a=!0;for(let T of[...this.tooLarge.keys()])this.tooLargeSeen?.has(T)||this.tooLarge.delete(T);for(let T of[...this.failures.keys()])this.roundVisited?.has(T)||this.failures.delete(T);!this.error&&this.failures.size&&(this.error=[...this.failures.values()].reduce((T,v)=>T.retryAt>v.retryAt?T:v).reason)}catch(o){this.error=Ue(o)}finally{if(this.round=null,this.phase=i?.stored.paused?"paused":"idle",i&&this.host.accountId()===i.account)for(let o of this.deferredDecision.splice(0))this.applyDecision(i,o.kind,o.keys);s&&(this.noteHealth(n,a),this.live()&&this.runLog.end(a));for(let[o,l]of this.dirty)!r.has(o)&&l.last<n&&this.dirty.delete(o);i&&this.host.accountId()===i.account&&(await this.persist(i).catch(()=>{}),!this.closed&&i.abort.signal.aborted&&!i.stored.paused&&i.stored.config.enabled&&(i.abort=new AbortController,this.again=!0)),this.running=!1,this.runAccount=null,this.again&&!this.closed?(this.again=!1,queueMicrotask(()=>void this.run())):this.schedule(),e()}}noteHealth(e,n){n&&(lt("content","cycles"),lt("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?ki(this.error,this.httpStatus):null;r?this.health.error(r):this.error||this.health.ok()}holdGone(e){let n=this.dirty.get(e);if(!n)return!1;let r=Date.now();return n.last>this.flushAt&&r-n.last<ha(e)&&r-n.first<Kd}isBlocked(e,n){return(this.blocked.get(e)??[]).some(r=>n===r||n.startsWith(r+"/"))}block(e,n,r){if(this.blocked.set(e,[...this.blocked.get(e)??[],n]),this.lastError=Ue(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(Ue(r),[n])}async folders(e,n,r,i){let s=r.filter(o=>o.kind==="folder"),a=new Map;for(let o of s)if(o.localId){if(a.has(o.localId))throw Error(`Duplicate folder sync identity: ${o.path}`);a.set(o.localId,o.path)}for(let[o,l]of i){for await(let c of tn(l.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,f)=>en(u.path)-en(f.path))))if(!(this.isBlocked(o,c.path)||qn(this.scanned.unscanned,c.path)))try{let u=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(o+":")&&p.id===c.id)?.[1],f=(u?s.find(g=>g.localId===u.localId):null)??s.find(g=>g.path===c.path);if(u&&f&&c.path!==u.path&&f.path!==u.path&&c.path!==f.path)throw Error(`Concurrent folder rename: ${f.path}`);if(u&&f&&c.path!==u.path&&f.path===u.path){if(this.route(f.path,n,"folder")!==o)continue;if(this.route(c.path,n,"folder")!==o)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,f.path,o,"rename",null,()=>oa(e.roots,f.path,c.path,(p,m)=>this.lock(e,p,m)));let g=f.path;for(let p of r)if(p.path===g||p.path.startsWith(g+"/")){let m=p.path;p.path=c.path+m.slice(g.length);let y=Ke(e.roots,p.path);p.physical=Fe(y.root,y.relative)}for(let[p,m]of Object.entries(e.stored.files))p.startsWith(o+":")&&m.path.startsWith(u.path+"/")&&(m.path=c.path+m.path.slice(u.path.length));for(let p of n.rules)(p.source===u.path||p.source.startsWith(u.path+"/"))&&(p.source=c.path+p.source.slice(u.path.length))}if(!f&&this.route(c.path,n,"folder")===o&&!u){await Wd(e.roots,c.path,(p,m)=>this.lock(e,p,m));let g=(await this.scan(e)).find(p=>p.path===c.path);g&&(r.push(g),s.push(g))}}catch(u){this.block(o,c.path,u),this.tally("folderConflicts");let f=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(o+":")&&p.id===c.id)?.[1];f&&this.block(o,f.path,u)}for await(let c of tn(s.sort((u,f)=>en(u.path)-en(f.path))))if(!this.isBlocked(o,c.path))try{let u=this.route(c.path,n,"folder"),f=n.rules.some(_=>_.target===o&&_.source.startsWith(c.path+"/"));if(u!==o&&!f||Qo(c.path,"folder")===!1)continue;let g=await ia(c),p=e.stored.folders[Re(o,g)],m=p?l.nodes.find(_=>_.id===p.id):l.nodes.find(_=>_.path===c.path&&!_.deleted);if(m?.deleted){let _=(e.stored.deleteGuard?.restore??[]).some(h=>h.side==="local"&&h.ns===o&&h.path.startsWith(c.path+"/"));if(p&&!_){let h=!1;for(let T of r.filter(v=>v.kind==="file"&&v.path.startsWith(c.path+"/")&&this.route(v.path,n)===o)){let v=Object.entries(e.stored.files).find(([I,E])=>I.startsWith(o+":")&&E.path===T.path)?.[1];if(!v){h=!0;break}if(!this.sameAsShadow(v,T)){let I=Oe(await Wn(T));if(I!==v.hash&&!(v.memoryDeleted&&is(T.path)&&I===Yn)){h=!0;break}}}if(!h)continue}m=void 0}let y=Wt(c.path),b=y?l.nodes.find(_=>_.path===y&&_.kind==="folder"&&!_.deleted)?.id:"";if(y&&!b)throw Error("Cloud parent is unavailable");if(!m)m=await this.json(e,o,"/nodes","POST",{id:p?mt():g,parentId:b,name:bn(c.path),kind:"folder"}),e.tombstones.get(o)?.delete(m.id),l.nodes.push(m);else if(p&&m.path!==c.path){if(m.revision!==p.revision)throw Error(`Concurrent folder rename: ${c.path}`);let _=m.path,h=await this.operation(e,c.path,o,"rename",null,()=>this.json(e,o,`/nodes/${m.id}`,"PATCH",{parentId:b,name:bn(c.path),revision:m.revision}));for(let T of l.nodes)T.path.startsWith(_+"/")&&(T.path=c.path+T.path.slice(_.length));Object.assign(m,h);for(let[T,v]of Object.entries(e.stored.files))T.startsWith(o+":")&&v.path.startsWith(_+"/")&&(v.path=c.path+v.path.slice(_.length))}e.stored.folders[Re(o,g)]={id:m.id,localId:g,path:c.path,revision:m.revision,parentId:m.parentId,name:m.name}}catch(u){this.block(o,c.path,u);let f=c.localId?e.stored.folders[Re(o,c.localId)]:void 0;f&&this.block(o,f.path,u),lt("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,c.path,o,"rename",null);g.state="conflict",g.error=Ue(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let i=await this.scan(e);for(let[s,a]of r)for await(let o of tn(a.nodes.filter(l=>l.kind==="folder"&&!l.busy).sort((l,c)=>en(c.path)-en(l.path)))){if(this.isBlocked(s,o.path)||this.route(o.path,n,"folder")!==s||qn(this.scanned.unscanned,o.path))continue;let l=Object.entries(e.stored.folders).find(([u,f])=>u.startsWith(s+":")&&f.id===o.id);if(!l)continue;let c=i.find(u=>u.path===o.path&&u.kind==="folder");if(o.deleted&&c){if(i.some(f=>f.path.startsWith(o.path+"/"))||(await jr(c.physical)).some(f=>f!==".forsion-sync-id.json"))continue;await this.operation(e,o.path,s,"delete",null,()=>this.lock(e,c.physical,()=>{vt(c.root,Fr(c.root,c.physical).split(Vn).join("/"));let f=nw(c.physical);if(f.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let g=Fe(c.physical,".forsion-sync-id.json"),p=f.length?Gn(g):null;p&&aa(g);try{rw(c.physical)}catch(m){if(p)try{iw(g,p,{flag:"wx",mode:384})}catch{}throw m}})),this.tally("deletesLocal"),delete e.stored.folders[l[0]]}else if(!o.deleted&&!c){if(e.stored.deleteGuard?.latched||e.stored.deleteGuard?.pending.length||e.stored.deleteGuard?.restore?.length||!await this.absent(e,o.path)||a.nodes.some(u=>u.parentId===o.id&&!u.deleted))continue;await this.operation(e,o.path,s,"delete",null,()=>this.json(e,s,`/nodes/${o.id}`,"DELETE",{revision:o.revision,version:null})),o.deleted=!0,delete e.stored.folders[l[0]]}}}async download(e,n,r,i){if(n.size!==void 0&&n.size>qt)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:qt});let s=await this.request(e,r,`/nodes/${n.id}/content`),a=[],o=0;if(s.body){let c=s.body.getReader();for(;;){let u=await c.read();if(u.done)break;if(this.guard(e),o+=u.value.length,o>qt)throw await c.cancel(),Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:qt});a.push(u.value),i.done=o}}let l=Buffer.concat(a);if(n.hash&&Oe(l)!==n.hash)throw Error("Cloud file changed during download");return l}async fileRenames(e,n,r,i){for(let[s,a]of i)for(let o of a.nodes.filter(l=>l.kind==="file"&&!l.deleted&&!l.busy)){let l=e.stored.files[Re(s,o.id)];if(!l||l.path===o.path)continue;let c=r.find(u=>u.kind==="file"&&u.path===l.path);if(!(!c||this.route(c.path,n)!==s))try{if(this.route(o.path,n)!==s)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,c.path,s,"rename",null,()=>oa(e.roots,c.path,o.path,(u,f)=>this.lock(e,u,f))),l.path=o.path}catch(u){this.block(s,c.path,u),this.block(s,o.path,u)}}}async upload(e,n,r,i,s){let a=this.capFor(r,n.path,{limits:this.limitsByNs.get(r)});if(i.length>a)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:a,size:i.length});let o=await this.request(e,r,`/nodes/${n.id}/content`,"PUT",i,u=>{s.done=u},{"X-Content-Version":n.version??"create",...n.version&&n.file?{"X-Content-File":n.file}:{}}),l=await o.json(),c=o.headers.get("x-content-file");return c&&/^[A-Za-z0-9_-]{1,64}$/.test(c)&&(l.file=c),l}async shadow(e,n,r,i,s,a){let o=Re(n,r.id),l=Oe(i),c=da(i);c&&i.length>=Jd&&await this.keepBase(e,l,i);for(let u of e.stored.jobs)u.path===r.path&&u.target===n&&["failed","paused","active"].includes(u.state)&&["upload","download","merge"].includes(u.direction)&&this.done(u);e.stored.pendingUploads&&delete e.stored.pendingUploads[o],delete e.stored.unconfirmed?.[o],e.stored.files[o]={id:r.id,path:r.path,version:r.version,hash:l,...r.file?{file:r.file}:{},...c&&i.length<Jd?{base:i.toString("utf8")}:{},...a?{inode:a.inode,stat:a.key,statAt:a.at}:s?{inode:s.inode}:{}}}async seen(e,n,r){let i=Ke(e.roots,n),s=await Bt(Fe(i.root,...i.relative.split("/"))).catch(()=>null);if(!s?.isFile())return;let a=Bn(s);return{key:Nr(a),at:r,inode:a.inode}}sameAsShadow(e,n){return!this.dirty.has(n.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===Nr(n)&&Aw(n)<=e.statAt-vw}unchanged(e,n,r,i,s){let a=Re(n,r.id),o=this.sameAsShadow(i,s)&&i.id===r.id&&i.path===s.path&&!r.busy&&!r.deleted&&r.version===i.version&&r.hash===i.hash&&Li(i.file,r.file)&&!e.stored.unconfirmed?.[a]&&!e.stored.pendingUploads?.[a]&&!this.openJobs.has(n+"\0"+s.path);return o&&i.file===void 0&&r.file&&(i.file=r.file),o}hold(e,n){if(e.path.endsWith("/"+Or)||n?.stat===Nr(e))return!1;let r=e.mtime,i=Date.now(),s=this.dirty.get(e.path);if(Math.floor(r)<=this.flushAt)return!1;if(s)s.last=Math.max(s.last,r);else{if(i-r>=ha(e.path))return!1;s={first:Math.min(i,r),last:r},this.dirty.set(e.path,s)}return this.dueAt(e.path,s)>i}settled(e,n){let r=this.dirty.get(e);r&&(r.last<n?this.dirty.delete(e):r.first=n)}async keepBase(e,n,r){let i=pa(e),s=Fe(i,n);if(await Bt(s).then(()=>!0,()=>!1))return;await la(i,{recursive:!0,mode:448});let a=s+".tmp-"+mt();try{await $r(a,r,{mode:384,flag:"wx"}),await rs(a,s)}finally{await Lr(a).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await Pr(Fe(pa(e),n.hash)).catch(i=>{if(i.code==="ENOENT")return null;throw i});return r&&Oe(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(i=>i.hash)),r=pa(e);for(let i of await jr(r).catch(()=>[]))n.has(i)||await Lr(Fe(r,i)).catch(()=>{})}async file(e,n,r,i,s){if(r.size>qt)return this.noteTooLarge(e,i,r.path,r.size,qt),"too-large";let a=v=>{let I=this.capFor(i,r.path,s);return v.length<=I?!1:(this.noteTooLarge(e,i,r.path,v.length,I),!0)},o=s.nodes.find(v=>v.kind==="file"&&!v.deleted&&v.path===r.path);if(!o){let v=Object.entries(e.stored.files).find(([I,E])=>I.startsWith(i+":")&&E.inode===r.inode&&E.path!==r.path)?.[1];if(v){let I=Ke(e.roots,v.path),E=await Bt(Fe(I.root,I.relative)).then(async x=>Bn(x).inode!==r.inode||Wt(v.path)!==Wt(r.path)?!0:(await jr(wn(r.physical))).includes(bn(v.path)),x=>x.code==="ENOENT"?!1:Promise.reject(x)),D=s.nodes.find(x=>x.id===v.id&&!x.deleted);if(!E&&D)try{if(D.path!==v.path)throw Error(`Concurrent file rename: ${r.path}`);let x=Wt(r.path),L=x?s.nodes.find(H=>H.path===x&&H.kind==="folder"&&!H.deleted)?.id:"";if(x&&!L)throw Error("Rename parent unavailable");let V=await this.operation(e,r.path,i,"rename",null,()=>this.json(e,i,`/nodes/${D.id}`,"PATCH",{name:bn(r.path),parentId:L,revision:D.revision}));Object.assign(D,V),v.path=r.path,o=D}catch(x){for(let L of new Set([v.path,D.path,r.path]))this.block(i,L,x);throw x}}}let l=o?e.stored.files[Re(i,o.id)]:Object.entries(e.stored.files).find(([v,I])=>v.startsWith(i+":")&&I.path===r.path)?.[1];if(!l&&o?.version&&i==="default"&&(l=await this.legacyBaseline(r.path,o)),o&&l&&this.unchanged(e,i,o,l,r))return;if(!o&&!l&&r.size>this.capFor(i,r.path,s))return this.noteTooLarge(e,i,r.path,r.size,this.capFor(i,r.path,s)),"too-large";if(this.hold(r,l))return"held";let c=Date.now(),u=await Wn(r),f=Oe(u),g={key:Nr(r),at:c,inode:r.inode};this.guard(e),this.settled(r.path,c);let p,m;if(!o){if((l?s.nodes.find(V=>V.id===l.id&&V.deleted):null)&&l&&(l.hash===f||l.memoryDeleted&&is(r.path)&&f===Yn)){if(is(r.path)){await this.clearDeletedMemory(e,i,r,l,u,f);return}let V=Ot("local",i,l.id),H=this.round;if(!H.restore.has(V)){H.plan.push({key:Gd("local",i,l.id,f,r.path),ns:i,id:l.id,path:r.path,side:"local",e:r,hash:f});return}H.restoreHit.add(V),p=V,m=Re(i,l.id)}if(a(u))return"too-large";let I=Wt(r.path),E=I?s.nodes.find(V=>V.path===I&&!V.deleted&&V.kind==="folder")?.id:"";if(I&&!E)throw Error("Parent folder is unavailable");let D=Object.entries(e.stored.pendingUploads??{}).find(([V,H])=>V.startsWith(i+":")&&H.path===r.path&&!s.nodes.some(N=>N.id===H.id))?.[1];for(let[V,H]of Object.entries(e.stored.pendingUploads??{}))V.startsWith(i+":")&&H.path===r.path&&s.nodes.some(N=>N.id===H.id&&N.deleted)&&delete e.stored.pendingUploads[V];let x=D?.id??mt(),L=Re(i,x);(e.stored.pendingUploads??={})[L]={id:x,path:r.path},await this.persist(e),o=await this.json(e,i,"/nodes","POST",{id:x,parentId:E,name:bn(r.path),kind:"file"}),e.tombstones.get(i)?.delete(o.id),o.id!==x&&delete e.stored.pendingUploads[L],s.nodes.push(o),l=void 0}if(o.busy)return;let y=Re(i,o.id);if(o.version&&this.awaitingBytes.delete(y),o.hash===f){await this.shadow(e,i,o,u,r,g);return}if(o.hash&&e.stored.unconfirmed?.[y]===o.hash&&(await this.shadow(e,i,o,await this.operation(e,r.path,i,"download",o.size??null,v=>this.download(e,o,i,v)),r),l=e.stored.files[y]),!o.version&&l&&l.hash===f&&!e.stored.pendingUploads?.[y]){let v=this.awaitingBytes.get(y)??Date.now();if(this.awaitingBytes.set(y,v),Date.now()-v<yw)return}if(this.awaitingBytes.delete(y),!o.version||l&&o.version===l.version&&Li(l.file,o.file)){if(a(u))return"too-large";(e.stored.unconfirmed??={})[y]=f,await this.persist(e);let v=await this.operation(e,r.path,i,"upload",u.length,I=>this.upload(e,o,i,u,I));Object.assign(o,v),await this.shadow(e,i,o,u,r,g),p&&(this.round.restoreDone.add(p),m&&m!==y&&delete e.stored.files[m]);return}let b=await this.operation(e,r.path,i,"download",o.size??null,v=>this.download(e,o,i,v)),_=b,h=!1;if(!l||l.hash!==f){let v=u.toString("utf8"),I=b.toString("utf8"),E=l?await this.readBase(e,l):null,D=Buffer.from(v).equals(u)&&Buffer.from(I).equals(b)?this.host.contentSync.merge(r.path,v,E,I):null;if(D&&!D.conflict&&E!==null&&ww(r.path)&&!So(E,v,D.content)&&(D=null),D?(_=Buffer.from(D.content),h=D.conflict):h=!0,h){await this.preserveConflict(e,r.path,u)&&(lt("content","conflicts"),this.tally("conflictCopies"));let x=this.job(e,r.path,i,"merge",u.length);x.state="conflict",x.error="Both versions preserved",x.finishedAt=Date.now()}if(!_.equals(b)){let x=await this.operation(e,r.path,i,"merge",_.length,L=>this.upload(e,o,i,_,L));Object.assign(o,x)}}let T=Date.now();await this.write(e,r.path,_,f),await this.shadow(e,i,o,_,r,await this.seen(e,r.path,T))}async preserveConflict(e,n,r){let i=Ke(e.roots,n),s=await ct(i.root,i.relative),a=bn(n),o=Oe(r);for(let l of await jr(wn(s))){if(l.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==a||!Gi(l))continue;let c=Wt(n)?Wt(n)+"/"+l:l,u=Ke(e.roots,c),f=await ct(u.root,u.relative),g=await Bt(f);if(g.isFile()&&g.size===r.length&&Oe(await Pr(f))===o)return!1}return await this.write(e,await this.copyName(e,n),r,null),!0}async copyName(e,n){let r=new Date;for(let i=1;;i++){let s=_d(n,r,i),a=Ke(e.roots,s);if(!await Bt(Fe(a.root,...a.relative.split("/"))).then(()=>!0,o=>o.code==="ENOENT"?!1:Promise.reject(o)))return s}}async legacyBaseline(e,n){let r=await this.host.contentSync.agentFiles?.baseline(e).catch(()=>null);if(!(!r||!n.version)&&!(r.pending&&Number(n.version.split(":")[0])!==r.seq))return{id:n.id,path:e,version:`${r.seq}:${r.hash}`,hash:r.hash,...r.base!==void 0?{base:r.base}:{}}}agentAsks(e,n,r,i,s){let a=[],o=l=>l.length?Math.max(...l):null;for(let l of n){let c=l.kind==="folder"?Ar(l.path):null;if(!c||Hi.has(c))continue;let u=`agents/${c}/`,f=this.route(u+"config.toml",r);if(!f||Object.entries(e.stored.files).some(([b,_])=>b.startsWith(f+":")&&_.path.startsWith(u)))continue;let g=(i.get(f)?.nodes??[]).filter(b=>!b.deleted&&b.kind==="file"&&b.version&&b.path.startsWith(u)&&this.route(b.path,r)===f),p=n.filter(b=>b.kind==="file"&&b.path.startsWith(u)&&this.route(b.path,r)===f);if(!g.length||!p.length)continue;let m=new Map(g.map(b=>[b.path,b])),y=p.filter(b=>{let _=m.get(b.path);return!!_&&s.get(b.path)!==_.hash}).length;!y&&p.length===g.length&&p.every(b=>m.has(b.path))||a.push({slug:c,namespace:f,cloudFiles:g.length,localFiles:p.length,differ:y,cloudMtime:o(g.map(b=>b.mtime??0)),localMtime:o(p.map(b=>b.mtime))})}return a}async resolveAsks(e,n,r,i){for(let s of n){try{await this.resolveAsk(e,s,r[s.slug]??"merge",i)}catch(c){throw this.dropShadows(e,s.namespace,`agents/${s.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Ue(c)}`)}let a=`agents/${s.slug}`,o=i.rules.find(c=>c.source===a),l=Pn(e.stored.config,a,gu(i,a));o&&(l={...l,rules:l.rules.map(c=>c.source===a?{...o,target:c.target}:c)}),e.stored.config=Zt(l,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,i){let s=n.namespace,a=`agents/${n.slug}/`;if(this.dropShadows(e,s,a),r==="local"){await this.archiveAgent(e,s,n.slug),await this.persist(e);return}let o=await this.json(e,s);this.guard(e),Ki(o,s);let l=new Map(o.nodes.filter(p=>!p.deleted&&!p.busy&&p.kind==="file"&&p.version&&p.path.startsWith(a)&&this.route(p.path,i)===s).map(p=>[p.path,p])),c=p=>p.endsWith("/"+Or),u=async(p,m,y)=>{let b=Date.now();return await this.write(e,p,m,y),this.seen(e,p,b)};for(let[p,m]of l){if(!c(p))continue;let y=Ke(e.roots,p);if(Zd(Fe(y.root,y.relative)))continue;let b=await this.operation(e,p,s,"download",m.size??null,_=>this.download(e,m,s,_));await this.shadow(e,s,m,b,void 0,await u(p,b,null))}let f=(await this.scan(e)).filter(p=>p.kind==="file"&&p.path.startsWith(a)&&this.route(p.path,i)===s&&p.size<=qt).sort((p,m)=>+!c(p.path)-+!c(m.path)),g=await this.removedDir(e,n.slug);for(let p of f){this.guard(e);let m=await Wn(p),y=Oe(m),b=l.get(p.path),_=p.path.slice(a.length);if(b&&b.hash===y){await this.shadow(e,s,b,m,p);continue}if(r==="cloud"){if(await this.keep(e,`${g}/${_}`,m),b){let E=await this.operation(e,p.path,s,"download",b.size??null,D=>this.download(e,b,s,D));await this.shadow(e,s,b,E,p,await u(p.path,E,y))}else _==="MEMORY.md"?await this.write(e,p.path,Buffer.alloc(0),y):await this.removeLocal(e,p,y);continue}if(!b)continue;let h=await this.operation(e,p.path,s,"download",b.size??null,E=>this.download(e,b,s,E)),T=s==="default"?await this.legacyBaseline(p.path,b):void 0;if(T?.hash===y){await this.shadow(e,s,b,h,p,await u(p.path,h,y));continue}let v=T?await this.readBase(e,T):null,I=da(m)&&da(h)?this.host.contentSync.merge(p.path,m.toString("utf8"),v,h.toString("utf8")):null;if(I&&!I.conflict){let E=Buffer.from(I.content);E.equals(m)||await this.write(e,p.path,E,y),await this.shadow(e,s,b,h)}else(b.mtime??0)>p.mtime?(await this.keep(e,`${g}/${_}`,m),await this.shadow(e,s,b,h,p,await u(p.path,h,y))):(await this.keep(e,`${g}/${_}`,h),await this.shadow(e,s,b,h))}await this.persist(e)}dropShadows(e,n,r){for(let[i,s]of Object.entries(e.stored.files))i.startsWith(n+":")&&s.path.startsWith(r)&&(delete e.stored.files[i],delete e.stored.unconfirmed?.[i])}async removedDir(e,n,r="agents"){let i=new Date,s=o=>String(o).padStart(2,"0"),a=`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())} ${s(i.getHours())}${s(i.getMinutes())}`;for(let o=1;;o++){let l=`${r}/.removed/${n} ${a}${o>1?` ${o}`:""}`,c=Ke(e.roots,l);if(!await Bt(Fe(c.root,...c.relative.split("/"))).then(()=>!0,u=>u.code==="ENOENT"?!1:Promise.reject(u)))return l}}async keep(e,n,r){this.guard(e),await sa(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(vt(n.root,Fr(n.root,n.physical).split(Vn).join("/")),Oe(Gn(n.physical))!==r)throw Error("Local file changed before replacing");aa(n.physical)})}async archiveAgent(e,n,r){let i=this.host.readCreds();if(!i.token)throw Error("not_signed_in");let s=await this.gatedFetch(e,i.cloudUrl,"/api/remotesync/agent-archive/agent",{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({namespace:n,slug:r,opId:mt(),locale:this.locale()})},12e4);this.guard(e);let a=await s.json().catch(()=>({}));if(this.guard(e),!s.ok||a?.state!=="done")throw Error(typeof a?.detail=="string"?a.detail:`agent_archive_http_${s.status}`)}async absent(e,n,r=e.roots){this.guard(e);let i=Ke(r,n),s=await ct(i.root,i.relative);try{return await Bt(s),!1}catch(a){if(a.code==="ENOENT")return!0;throw a}}async missing(e,n,r,i,s){let a=e.stored.files[Re(r,n.id)],o=e.stored.pendingUploads?.[Re(r,n.id)];if(!n.deleted&&a?.inode&&this.blocked.has(r)&&i.some(y=>y.kind==="file"&&y.inode===a.inode&&this.isBlocked(r,y.path)&&this.route(y.path,s)===r)){this.round?.undecided.add(r+"\0"+n.path);return}let l=qn(this.scanned.unscanned,n.path)||!!a?.inode&&this.scanned.skippedInodes.has(a.inode),c=Do(n,a,!!o,l),u=this.round,f=()=>u.plan.some(y=>y.side==="local"&&y.ns===r&&y.id===n.id)||u.restore.has(Ot("local",r,n.id))||!!e.stored.deleteGuard?.pending.some(y=>y.side==="local"&&y.ns===r&&y.id===n.id);if(c==="forget"){a&&!f()&&delete e.stored.files[Re(r,n.id)],o&&delete e.stored.pendingUploads[Re(r,n.id)];return}if(c==="skip")return u.undecided.add(r+"\0"+n.path),a&&u.undecided.add(r+"\0"+a.path),l?"unknown":void 0;if(c==="cancel"){await this.absent(e,n.path)&&(await this.operation(e,n.path,r,"delete",null,()=>this.json(e,r,`/nodes/${n.id}`,"DELETE",{revision:n.revision,version:null})),delete e.stored.pendingUploads[Re(r,n.id)],n.deleted=!0);return}let g;if(c==="delete"){if(!await this.absent(e,n.path))return;let y=Ot("cloud",r,n.id);if(!u.restore.has(y)){u.plan.push({key:Gd("cloud",r,n.id,n.version,n.path),ns:r,id:n.id,path:n.path,side:"cloud",node:n});return}u.restoreHit.add(y),g=y}if(n.size!==void 0&&n.size>qt){this.noteTooLarge(e,r,n.path,n.size,qt),u.undecided.add(r+"\0"+n.path);return}let p=await this.operation(e,n.path,r,"download",n.size??null,y=>this.download(e,n,r,y)),m=Date.now();await this.write(e,n.path,p,null),await this.shadow(e,r,n,p,void 0,await this.seen(e,n.path,m)),g&&u.restoreDone.add(g)}async executeDeletes(e,n){let r=e.stored.deleteGuard,i=n.plan,s=new Set(i.map(_=>_.key)),a=new Set(i.map(_=>Ot(_.side,_.ns,_.id))),o=new Set((r?.confirmed??[]).filter(_=>s.has(_))),l=Date.now();this.deleteStamps=this.deleteStamps.filter(_=>l-_<Ro);let c=i.filter(_=>!o.has(_.key)),u=Oo(c,n.tracked,{latched:!!r?.latched,recent:this.deleteStamps.length});u&&!r?.latched&<("content","massDeleteGuard");let f=_=>{let h=e.stored.files[Re(_.ns,_.id)];return[_.path,...h?[h.path]:[]].some(v=>n.undecided.has(_.ns+"\0"+v)||qn(this.scanned.unscanned,v))||!!h?.inode&&this.scanned.skippedInodes.has(h.inode)},g=(r?.pending??[]).filter(_=>!a.has(Ot(_.side,_.ns,_.id))&&f(_)),p=[...n.restore].filter(([_,h])=>!n.restoreDone.has(_)&&(n.restoreHit.has(_)||f(h))).map(([,_])=>_),m={latched:u||g.length>0,pending:[...u?c.map(Vd):[],...g],...o.size?{confirmed:[...o]}:{},...p.length?{restore:p}:{}},y=()=>{m.latched||m.pending.length||m.confirmed?.length||m.restore?.length?e.stored.deleteGuard=m:delete e.stored.deleteGuard};y(),await this.persist(e);let b=[...i.filter(_=>o.has(_.key)),...u?[]:c];for(let _=0;_<b.length;_++){let h=b[_],T=o.has(h.key);try{if(h.side==="cloud"){if(!await this.absent(e,h.path))continue;let v=h.node;await this.operation(e,h.path,h.ns,"delete",v.size??null,()=>this.json(e,h.ns,`/nodes/${v.id}`,"DELETE",{revision:v.revision,version:v.version,...v.file?{file:v.file}:{}},T?{"X-Content-Delete-Confirmed":"1"}:void 0)),delete e.stored.files[Re(h.ns,v.id)],v.deleted=!0}else await this.operation(e,h.path,h.ns,"delete",h.e.size,()=>this.trashFile(e,h.e,h.hash)),this.tally("deletesLocal"),delete e.stored.files[Re(h.ns,h.id)];T?m.confirmed=m.confirmed?.filter(v=>v!==h.key):this.deleteStamps.push(Date.now())}catch(v){if(v?.code!=="MASS_DELETE_BLOCKED"){this.error=Ue(v);continue}m.latched||lt("content","massDeleteGuard"),m.latched=!0,m.pending=[...m.pending,...b.slice(_).filter(I=>I.side==="cloud").map(Vd)];for(let I of b.slice(_+1))if(I.side==="local")try{await this.operation(e,I.path,I.ns,"delete",I.e.size,()=>this.trashFile(e,I.e,I.hash)),this.tally("deletesLocal"),delete e.stored.files[Re(I.ns,I.id)]}catch(E){this.error=Ue(E)}break}}y(),await this.persist(e)}async recoverTrash(e){for(let n of[...e.stored.trash??[]]){if(n.parentId){let c=(await ns(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);c&&(n.path=c.path+"/"+bn(n.path))}let r=Ke(e.roots,n.path),i=await ct(r.root,r.relative);if(!/^\.forsion-sync-trash-[a-f0-9-]+$/.test(n.stage))throw Error("Invalid sync recovery journal");let s=n.stageRoot??r.root,a=await this.rootIdentity(e,s),o=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(o&&!an(o,a))throw Error("Sync recovery root changed; journal retained");let l=Fe(s,n.stage);await Bt(l).then(()=>!0,c=>c.code==="ENOENT"?!1:Promise.reject(c))&&await this.lock(e,i,()=>{if(vt(s,n.stage,!0),Oe(Gn(l))!==n.hash)throw Error("Sync recovery content changed");vt(r.root,r.relative),sw(wn(i),{recursive:!0});let c=Zd(i)?i+` (sync recovery ${mt().slice(0,8)})`:i;try{tw(l,c)}catch(u){if(u.code!=="EXDEV")throw u;if(ow(l,c,aw.COPYFILE_EXCL),Oe(Gn(c))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}aa(l)},!0),e.stored.trash=e.stored.trash.filter(c=>c!==n)}}async clearDeletedMemory(e,n,r,i,s,a){i.memoryDeleted&&i.hash===Yn&&a===Yn||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!i.memoryDeleted&&s.length){let c=r.path==="human/MEMORY.md",u=await this.removedDir(e,c?"memory":r.path.split("/")[1],c?"human":"agents");await this.keep(e,`${u}/MEMORY.md`,s)}i.memoryDeleted=!0,await this.persist(e);let o=Date.now();s.length&&await this.write(e,r.path,Buffer.alloc(0),a);let l=await this.seen(e,r.path,o);e.stored.files[Re(n,i.id)]={...i,hash:Yn,base:"",stat:void 0,statAt:void 0,...l?{inode:l.inode,stat:l.key,statAt:l.at}:{}}}),this.tally("deletesLocal"))}async trashFile(e,n,r){this.guard(e);let i=await ct(n.root,Fr(n.root,n.physical).split(Vn).join("/")),s={path:n.path,stage:".forsion-sync-trash-"+mt(),hash:r},a=Fe(n.root,s.stage),o=await this.rootIdentity(e,n.root);s.stageRoot=n.root,s.stageDev=o.dev,s.stageIno=o.ino,s.stageIdentity=o;try{let l=JSON.parse(Gn(Fe(wn(i),".forsion-sync-id.json"),"utf8")).id;/^[a-f0-9-]{36}$/i.test(l)&&(s.parentId=l)}catch{}(e.stored.trash??=[]).push(s),await this.persist(e);try{await this.lock(e,i,()=>{if(vt(n.root,Fr(n.root,i).split(Vn).join("/")),Oe(Gn(i))!==r)throw Error("Local file changed before deletion");ew(i,a)}),await this.host.contentSync.trash(a),e.stored.trash=e.stored.trash.filter(l=>l!==s)}catch(l){throw this.host.accountId()===e.account&&!e.abort.signal.aborted&&await this.recoverTrash(e),l}}};function xw(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))Cr.test(n)&&uu.includes(r)&&(e[n]=r);return e}function Zd(t){try{return Zy(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}Ha(El);function Rk(t){kl(t.contentSync?.withWriteLock?.bind(t.contentSync)),Xa(t),Gs(t),ef(t),t.log("[forsion-extend] cloud account handlers registered"),js(t)?Ls(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Us(t)?Hs(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),Qs(t)?eo(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),wo(t)?bo(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),ko(t)?Eo(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Uo(t)?Zu(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),Uo(t)&&vd(t)}export{Ql as ACCOUNT_SEAM,Kc as AMADEUS_SEAM,$s as CONNECT_MAX_FILES,Al as CONNECT_MAX_FILE_BYTES,xl as CONNECT_MAX_TOTAL_BYTES,mi as DIAGNOSTICS_VAULT,$l as FORSION_CONNECT_LOCAL_SDK,Ja as PAY_PERIODS,Ya as PAY_TABS,Fl as PENZOR_MAX_FILE,Ne as SYNC_IPC,Qc as UNIT_SEAM,cr as UPLOAD_MAX_FILE,vr as UnitCapsReporter,Sr as UnitHost,Ze as cloudJson,Il as collectProjectFiles,Si as conflictCopyPath,Dh as conflictCopyVariant,Nl as connectMetaOf,Zl as createAccountCloud,Xc as createAmadeusCloud,gi as createPenzorRemote,eu as createUnitHub,hi as deviceHeader,Fs as expectedPartsOf,Ve as forsionAccountId,ri as forsionRefreshToken,lr as forsionWhoami,Qs as hasAccountHost,wo as hasAmadeusHost,js as hasConnectHost,Us as hasRemoteSyncHost,ko as hasUnitHost,Pl as makePreviewProxy,Yl as multipartFrame,Dl as readConnectMeta,eo as registerAccount,bo as registerAmadeus,Rk as registerCloud,Ls as registerConnect,Hs as registerPenzor,Gs as registerPenzorTransfers,Eo as registerUnit,yi as safeDownloadName,Ml as scanSdkUsage,ni as shouldRefreshToken,zs as speedOf,Zc as streamWorthy,Pc as stripConflictSuffix,Oh as textFingerprint,ws as tokenAgeMs,Wa as tokenRemainingMs,Bs as uploadError,Ol as writeConnectMeta};
|
|
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};
|
|
288
288
|
/*! Bundled license information:
|
|
289
289
|
|
|
290
290
|
chokidar/index.js:
|