@forsion/extend 0.10.3 → 0.10.4
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/README.md +7 -0
- package/SIGNATURE +6 -6
- package/dist/desktop.mjs +46 -46
- package/manifest.json +1 -1
- package/package.json +2 -1
package/dist/desktop.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var xs=null;function Li(t){xs=t}function _e(){if(!xs)throw new Error("core host not set (call setCoreHost first)");return xs}var Ui=new TextEncoder,zu=new TextDecoder("utf-8",{ignoreBOM:!0}),Tn=t=>Ui.encode(t),Ct=t=>zu.decode(t),As=t=>typeof t=="string"?Ui.encode(t).length:t.length;function Hi(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Er(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 zi(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ne(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 s=r.replace(/-/g,"+").replace(/_/g,"/"),o=Uint8Array.from(atob(s),c=>c.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(o)),a=i.userId??i.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function Ts(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Ct(Er(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Is(t,e=Date.now()){let n=Ts(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Bi(t,e=Date.now()){let n=Ts(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var Bu=36e5;function _r(t,e=Date.now()){return!!t&&Is(t,e)>=Bu}async function Cr(t,e,n=8e3,r){if(!t||!e)return null;let s=t.replace(/\/+$/,"");try{let o=await fetch(`${s}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!o.ok)return null;let i=await o.json().catch(()=>null),a=typeof i?.token=="string"?i.token:"";return a&&a!==e?a:null}catch{return null}}var In=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,qu=(t,e)=>new Promise((n,r)=>{let s=()=>{clearTimeout(o),r(new Error("Sign-in cancelled."))},o=setTimeout(()=>{e.removeEventListener("abort",s),n()},t);e.aborted?s():e.addEventListener("abort",s,{once:!0})});function qi(t,e){let n=d=>e.write(JSON.stringify(d,null,2)),r=()=>{let d;try{d=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(d===null)return[];try{let g=JSON.parse(d);return Array.isArray(g.accounts)?g.accounts.filter(h=>h&&typeof h.token=="string"&&h.id===Ne(h.cloudUrl,h.token)):null}catch{return null}},s=(d,g)=>{let h=Ne(d.cloudUrl||"",d.token||"");if(!h||!d.token||!d.cloudUrl)return;let m=r();if(!m)return;let y=m.find(v=>v.id===h),p=Ts(d.token),b={...y,id:h,cloudUrl:d.cloudUrl.replace(/\/+$/,""),token:d.token,username:g?.username||y?.username||p?.username,nickname:g?.nickname||y?.nickname};JSON.stringify(y)!==JSON.stringify(b)&&n({version:1,accounts:[...m.filter(v=>v.id!==h),b]})},o=()=>{let d=t.readCreds();s(d);let g=Ne(d.cloudUrl,d.token);return(r()??[]).map(({token:h,...m})=>({...m,active:m.id===g}))},i=d=>{let g=r()?.find(h=>h.id===d);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},a=d=>{let g=Ne(d.cloudUrl||"",d.token||""),h=r();g&&h&&n({version:1,accounts:h.filter(m=>m.id!==g)})},c=null;return{rememberForsionAccount:s,forsionAccounts:o,savedForsionAccount:i,forgetForsionAccount:a,cancelForsionLogin:()=>{c?.abort(),c=null},forsionDeviceLogin:async(d,g,h)=>{if(c)throw new Error("A sign-in is already in progress.");if(!d)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;c=m;let y=()=>{if(m.signal.aborted||c!==m)throw new Error("Sign-in cancelled.")};try{let p=d.replace(/\/+$/,""),b;try{b=await fetch(`${p}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(x=>x.json())}catch(x){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${p}:${x?.message||x}`)}if(y(),!b?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let v=b.verification_uri_complete||`${b.verification_uri}?code=${b.user_code}`,$=new URL(`${p}/auth`);$.searchParams.set("logout","1"),$.searchParams.set("app","forsion-desktop"),$.searchParams.set("redirect",v);let R=$.toString();g?.({url:R,userCode:String(b.user_code||"")}),t.openExternal(R);let O=Date.now()+(b.expires_in||600)*1e3,w=(b.interval||2)*1e3;for(;Date.now()<O;){await qu(w,m.signal),y();let x=null;try{x=await fetch(`${p}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:b.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),x.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let C=await x.json().catch(()=>({status:"pending"}));if(y(),C.status==="approved"&&C.token){let D={cloudUrl:p,token:C.token};return await h(D,y),y(),{token:C.token,cloudUrl:p}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{c===m&&(c=null)}},readAccounts:()=>r()??[]}}function gt(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,s;try{r=new URL(n),s=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||s.origin!==r.origin||!s.pathname.startsWith("/api/")?null:s.toString()}function Rn(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,s=6e4){let o=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(s)}),i=await o.json().catch(()=>({}));return{status:o.status,json:i}}var Wu=50*1024*1024,Vu=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"]);function Yu(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[s,o]of Object.entries(e.fields)){if(!Vu.has(s)||typeof o!="string"||(r+=o.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"].includes(s))return null;n.append(s,o)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>Wu)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 Wi(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=Yu(n);if(!r)return{status:400,json:{error:"invalid_request"}};let s=await t.getCloud();if(!s.token)return{status:401,error:"not_signed_in"};let o=gt(s.base,r.path);if(!o)return{status:0,error:"no_cloud_url"};try{let i=await Rn(s,o,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:i.status,json:await i.json().catch(()=>null)}}catch(i){return{status:0,error:String(i?.message||i)}}})}async function Vi(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 Yi=["membership","credits","storefront"],Gi=["monthly","quarterly","yearly"],Gu=/^[A-Za-z0-9_-]{1,64}$/;function Ji(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(s,o)=>{if(!t.isTrustedSender(s))return n;let i=await t.getCloud(),a=i.base;if(!a)return{ok:!1};let c=o&&/^[a-z0-9-]+$/i.test(o)?`#${o}`:"",l=await Vi(i),u=`${a}/account${l?`?${l}`:""}${c}`;return i.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(s,o,i,a)=>{if(!t.isTrustedSender(s))return n;if(o!==void 0&&!Yi.includes(o))return{ok:!1,error:"invalid_tab"};if(i!==void 0&&(typeof i!="string"||!Gu.test(i)))return{ok:!1,error:"invalid_plan"};if(a!==void 0&&!Gi.includes(a))return{ok:!1,error:"invalid_period"};let c=(o??"membership")==="membership"&&i?`&plan=${encodeURIComponent(i)}${a?`&period=${a}`:""}`:"",l=await t.getCloud(),u=l.base;if(!u)return{ok:!1};let d=await Vi(l),g=`${u}/pay?tab=${o??"membership"}${c}${d?`&${d}`:""}&redirect=${encodeURIComponent(`${u}/account`)}`;return l.signal?.throwIfAborted(),await t.openExternal(g),{ok:!0}}),t.handle("profile:publicOrigin",async s=>{if(!t.isTrustedSender(s))return n;let{base:o}=await t.getCloud();if(!o)return{ok:!1};try{let i=await fetch(`${o}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});i.body?.cancel().catch(()=>{});let a=i.status>=300&&i.status<400?i.headers.get("location"):null;return a&&/^https?:\/\//i.test(a)?{ok:!0,origin:new URL(a).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async s=>{if(!t.isTrustedSender(s))return e;let o=await r();if(!o.token)return{status:401,json:null};try{return await ze(o,"GET","/api/token-quota/my",void 0,15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("account:useResetCard",async(s,o)=>{if(!t.isTrustedSender(s))return e;let i=await r();if(!i.token)return{status:401,json:null};if(o!==void 0&&o!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${o}`}};let a=o??"both";try{return await ze(i,"POST","/api/token-quota/reset-card/use",{type:a},15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(s,o)=>{if(!t.isTrustedSender(s))return e;let i=await r();if(!i.token)return{status:401,json:null};if(!Number.isInteger(o)||o<1||o>100)return{status:400,json:{error:"invalid_percent"}};try{return await ze(i,"POST","/api/token-quota/background/convert",{percent:o},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:bgAutoMain",async(s,o)=>{if(!t.isTrustedSender(s))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof o!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await ze(i,"POST","/api/token-quota/background/auto-main",{enabled:o},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("feedback:submit",async(s,o)=>{if(!t.isTrustedSender(s))return n;let i=await t.getCloud();if(!i.base||!i.token)return{ok:!1,error:"not-logged-in"};if(o?.expectedAccountId!==void 0){let u=o.expectedAccountId;if(typeof u!="string"||!u||Ne(i.base,i.token)!==u)return{ok:!1,error:"account-changed"}}let a=(o?.description||"").trim();if(!a)return{ok:!1,error:"empty"};if(a.length>1e4)return{ok:!1,error:"description-too-long"};let c=[],l=!1;if(o?.sessionLogJson){let u=Tn(o.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};c.push({filename:o.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:Hi(u)})}try{let u=await Rn(i,`${i.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:a,attachments:c}),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:l}}catch(u){return{ok:!1,error:u?.message||String(u)}}}),t.handle("cloud:fetch",async(s,o)=>{if(!t.isTrustedSender(s))return{status:0,error:"untrusted"};let i=o??{},a=typeof i.path=="string"?i.path:"",c=i.projectSource===void 0?null:i.projectSource;if(c!==null&&(typeof c!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(c)))return{status:0,error:"bad_project_source"};let l=Math.min(12e4,Math.max(1e3,Number(i.timeoutMs)||15e3)),u=typeof i.method=="string"?i.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(u))return{status:0,error:"bad_method"};if(!a.startsWith("/"))return{status:0,error:"bad_path"};let d=await t.getCloud();if(!String(d.base||""))return{status:0,error:"no_cloud_url"};let g=gt(d.base,a);if(!g)return{status:0,error:"bad_path"};if(!d.token)return{status:401,error:"not_signed_in"};let h=i.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,y=setTimeout(()=>m.abort(),l);try{let p=await Rn(d,g,{method:u,headers:{...h?{"Content-Type":"application/json"}:{},...c?{"X-Project-Source":c}:{}},body:h?JSON.stringify(i.body):void 0,signal:m.signal});return{status:p.status,json:await p.json().catch(()=>null)}}catch(p){return{status:0,error:String(p?.message||p)}}finally{clearTimeout(y)}}),Wi(t)}import{createHash as ba}from"node:crypto";import{existsSync as Wd,promises as Vd,readFileSync as Yd,renameSync as Gd}from"node:fs";import Jd from"node:path";import{EventEmitter as Ed}from"node:events";import{stat as _d}from"node:fs";import{readdir as Cd,stat as xd}from"node:fs/promises";import*as ue from"node:path";import{lstat as Ki,readdir as Ju,realpath as Ku,stat as Xu}from"node:fs/promises";import{join as Zu,resolve as Qu,sep as Xi}from"node:path";import{Readable as ed}from"node:stream";var Ve={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Qt={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Ve.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(Qt);var ta="READDIRP_RECURSIVE_ERROR",td=new Set(["ENOENT","EPERM","EACCES","ELOOP",ta]),Zi=[Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE],nd=new Set([Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE]),rd=new Set([Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE]),sd=t=>td.has(t.code),od=process.platform==="win32",Qi=t=>!0,ea=t=>{if(t===void 0)return Qi;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 Qi},Rs=class extends ed{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??Qt.highWaterMark});let n={...Qt,...e},r=n.root??Qt.root,s=n.type??Qt.type;this._fileFilter=ea(n.fileFilter),this._directoryFilter=ea(n.directoryFilter);let o=n.lstat?Ki:Xu;od?this._stat=a=>o(a,{bigint:!0}):this._stat=o,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:Qt.depth,this._wantsDir=nd.has(s),this._wantsFile=rd.has(s),this._wantsEverything=s===Ve.EVERYTHING_TYPE,this._root=Qu(r),this._relStart=this._root.endsWith(Xi)?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 i={path:this._root,depth:1};i.pending=this._exploreDir(this._root,1),this.parents=[i],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:s,depth:o}=n,i=r.splice(0,e).map(c=>this._formatEntry(c,s)),a=this._isDirent?i:await Promise.all(i);for(let c of a){if(!c)continue;if(this.destroyed)return;let l=this._getEntryType(c);typeof l!="string"&&(l=await l),l==="directory"&&this._directoryFilter(c)?(o<=this._maxDepth&&this.parents.push({path:c.fullPath,depth:o+1}),this._wantsDir&&(this.push(c),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}let o=s.pending??this._exploreDir(s.path,s.depth),i=this.parents[this.parents.length-1];if(i&&!i.pending&&(i.pending=this._exploreDir(i.path,i.depth)),this.parent=await o,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await Ju(e,this._rdOptions)}catch(s){this._onError(s)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,s=Zu(n,r),o={path:s.slice(this._relStart),fullPath:s,basename:r};return this._isDirent?(o.dirent=e,o):this._stat(s).then(i=>(o.stats=i,o),i=>{this._onError(i)})}_onError(e){sd(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 Ku(n),s=await Ki(r);if(s.isFile())return"file";if(s.isDirectory()){let o=r.length;if(n.startsWith(r)&&n[o]===Xi){let i=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return i.code=ta,this._onError(i),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function na(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Ve.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!Zi.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${Zi.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 Rs(r)}import{watch as id,unwatchFile as ra,watchFile as ad}from"node:fs";import{realpath as Ds,lstat as cd,open as ld,stat as oa}from"node:fs/promises";import{type as ud}from"node:os";import*as me from"node:path";var dd="data",Ms="end",ia="close",Rr=()=>{};var Dr=process.platform,$s=Dr==="win32",fd=Dr==="darwin",pd=Dr==="linux",hd=Dr==="freebsd",aa=ud()==="OS400",we={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},nt=we,gd="watch",md={lstat:cd,stat:oa},Lt="listeners",xr="errHandlers",en="rawEmitters",yd=[Lt,xr,en],wd=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"]),bd=t=>wd.has(me.extname(t).slice(1).toLowerCase()),Ps=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Dn=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},Sd=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},On=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ca=t=>t instanceof Set?t.size===0:!t,Ar=new Map;function sa(t,e,n,r,s){let o=(i,a)=>{n(t),s(i,a,{watchedPath:t}),a&&t!==a&&Tr(me.resolve(t,a),Lt,me.join(t,a))};try{return id(t,{persistent:e.persistent},o)}catch(i){r(i);return}}var Tr=(t,e,n,r,s)=>{let o=Ar.get(t);o&&Ps(o[e],i=>{i(n,r,s)})},vd=(t,e,n,r)=>{let{listener:s,errHandler:o,rawEmitter:i}=r,a=Ar.get(e),c;if(!n.persistent)return c=sa(t,n,s,o,i),c?c.close.bind(c):void 0;if(a)Dn(a,Lt,s),Dn(a,xr,o),Dn(a,en,i);else{if(c=sa(t,n,Tr.bind(null,e,Lt),o,Tr.bind(null,e,en)),!c)return;c.on(nt.ERROR,async l=>{let u=Tr.bind(null,e,xr);if(a&&(a.watcherUnusable=!0),$s&&l.code==="EPERM")try{await(await ld(t,"r")).close(),u(l)}catch{}else u(l)}),a={listeners:s,errHandlers:o,rawEmitters:i,watcher:c},Ar.set(e,a)}return()=>{On(a,Lt,s),On(a,xr,o),On(a,en,i),ca(a.listeners)&&(a.watcher.close(),Ar.delete(e),yd.forEach(Sd(a)),a.watcher=void 0,Object.freeze(a))}},Os=new Map,kd=(t,e,n,r)=>{let{listener:s,rawEmitter:o}=r,i=Os.get(e),a=i&&i.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(ra(e),i=void 0),i?(Dn(i,Lt,s),Dn(i,en,o)):(i={listeners:s,rawEmitters:o,options:n,watcher:ad(e,n,(c,l)=>{Ps(i.rawEmitters,d=>{d(nt.CHANGE,e,{curr:c,prev:l})});let u=c.mtimeMs;(c.size!==l.size||u>l.mtimeMs||u===0)&&Ps(i.listeners,d=>d(t,c))})},Os.set(e,i)),()=>{On(i,Lt,s),On(i,en,o),ca(i.listeners)&&(Os.delete(e),ra(e),i.options=i.watcher=void 0,Object.freeze(i))}},Ir=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,s=me.dirname(e),o=me.basename(e);this.fsw._getWatchedDir(s).add(o);let a=me.resolve(e),c={persistent:r.persistent};n||(n=Rr);let l;if(r.usePolling){let u=r.interval!==r.binaryInterval;c.interval=u&&bd(o)?r.binaryInterval:r.interval,l=kd(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})}else l=vd(e,a,c,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,n,r){if(this.fsw.closed)return;let s=me.dirname(e),o=me.basename(e),i=this.fsw._getWatchedDir(s),a=n;if(i.has(o))return;let c=async(u,d)=>{if(this.fsw._throttle(gd,e,5)){if(!d||d.mtimeMs===0)try{let g=await oa(e);if(this.fsw.closed)return;let h=g.atimeMs,m=g.mtimeMs;if((!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(nt.CHANGE,e,g),(fd||pd||hd)&&a.ino!==g.ino){this.fsw._closeFile(u),a=g;let y=this._watchWithNodeFs(e,c);y&&this.fsw._addPathCloser(u,y)}else a=g}catch{this.fsw._remove(s,o)}else if(i.has(o)){let g=d.atimeMs,h=d.mtimeMs;(!g||g<=h||h!==a.mtimeMs)&&this.fsw._emit(nt.CHANGE,e,d),a=d}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(nt.ADD,e,0))return;this.fsw._emit(nt.ADD,e,n)}return l}async _handleSymlink(e,n,r,s){if(this.fsw.closed)return;let o=e.fullPath,i=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Ds(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(i.has(s)?this.fsw._symlinkPaths.get(o)!==a&&(this.fsw._symlinkPaths.set(o,a),this.fsw._emit(nt.CHANGE,r,e.stats)):(i.add(s),this.fsw._symlinkPaths.set(o,a),this.fsw._emit(nt.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(o))return!0;this.fsw._symlinkPaths.set(o,!0)}_handleRead(e,n,r,s,o,i,a){e=me.join(e,"");let c=s?`${e}:${s}`:e;if(a=this.fsw._throttle("readdir",c,1e3),!a)return;let l=this.fsw._getWatchedDir(r.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(d)return d.on(dd,async g=>{if(this.fsw.closed){d=void 0;return}let h=g.path,m=me.join(e,h);if(u.add(h),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===s||!s&&!l.has(h))&&(this.fsw._incrReadyCount(),m=me.join(o,me.relative(o,m)),this._addToNodeFs(m,n,r,i+1))}}).on(nt.ERROR,this._boundHandleError),new Promise((g,h)=>{if(!d)return h();d.once(Ms,()=>{if(this.fsw.closed){d=void 0;return}let m=a?a.clear():!1;g(void 0),l.getChildren().filter(y=>y!==e&&!u.has(y)).forEach(y=>{this.fsw._remove(e,y)}),d=void 0,m&&this._handleRead(e,!1,r,s,o,i,a)})})}async _handleDir(e,n,r,s,o,i,a){let c=this.fsw._getWatchedDir(me.dirname(e)),l=c.has(me.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!o&&!l&&this.fsw._emit(nt.ADD_DIR,e,n),c.add(me.basename(e)),this.fsw._getWatchedDir(e);let u,d,g=this.fsw.options.depth;if((g==null||s<=g)&&!this.fsw._symlinkPaths.has(a)){if(!o&&(await this._handleRead(e,r,i,o,e,s,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(h,m)=>{m&&m.mtimeMs===0||this._handleRead(h,!1,i,o,e,s,u)})}return d}async _addToNodeFs(e,n,r,s,o){let i=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return i(),!1;let a=this.fsw._getWatchHelpers(e);r&&(a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await md[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return i(),!1;let l=this.fsw.options.followSymlinks,u;if(c.isDirectory()){let d=me.resolve(e),g=l?await Ds(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,s,o,a,g),this.fsw.closed))return;d!==g&&g!==void 0&&this.fsw._symlinkPaths.set(d,g)}else if(c.isSymbolicLink()){let d=l?await Ds(e):e;if(this.fsw.closed)return;let g=me.dirname(a.watchPath);if(this.fsw._getWatchedDir(g).add(a.watchPath),this.fsw._emit(nt.ADD,a.watchPath,c),u=await this._handleDir(g,c,n,s,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(me.resolve(e),d)}else u=this._handleFile(a.watchPath,c,n);return i(),u&&this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return i(),e}}};var Ns="/",Ad="//",pa=".",Td="..",Id="string",Rd=/\\/g,ha=/\/\//g,Dd=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Od=/^\.[/\\]/;function Or(t){return Array.isArray(t)?t:[t]}var js=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Pd(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=ue.relative(t.path,e);return n?!n.startsWith("..")&&!ue.isAbsolute(n):!1}return!1}:()=>!1}function Md(t){if(typeof t!="string")throw new Error("string expected");t=ue.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ha,"/"),e&&(t="/"+t),t}function la(t,e,n){let r=Md(e);for(let s=0;s<t.length;s++){let o=t[s];if(o(r,n))return!0}return!1}function $d(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Or(t).map(s=>Pd(s));return e==null?(s,o)=>la(r,s,o):la(r,e)}var ua=t=>{let e=Or(t).flat();if(!e.every(n=>typeof n===Id))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(ga)},da=t=>{let e=t.replace(Rd,Ns),n=!1;return e.startsWith(Ad)&&(n=!0),e=e.replace(ha,Ns),n&&(e=Ns+e),e},ga=t=>da(ue.normalize(da(t))),fa=(t="")=>e=>typeof e=="string"?ga(ue.isAbsolute(e)?e:ue.join(t,e)):e,Nd=(t,e)=>ue.isAbsolute(t)?t:ue.join(e,t),jd=Object.freeze(new Set),Fs=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!==pa&&e!==Td&&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 Cd(r)}catch{this._removeWatcher&&this._removeWatcher(ue.dirname(r),ue.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=Rr,this.items=jd,Object.freeze(this)}},Fd="stat",Ld="lstat",Ls=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let s=e;this.path=e=e.replace(Od,""),this.watchPath=s,this.fullWatchPath=ue.resolve(s),this.dirParts=[],this.dirParts.forEach(o=>{o.length>1&&o.pop()}),this.followSymlinks=n,this.statMethod=n?Fd:Ld}entryPath(e){return ue.join(this.watchPath,ue.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)}},Pr=class extends Ed{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},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Or(e.ignored):Or([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};aa&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let o=process.env.CHOKIDAR_USEPOLLING;if(o!==void 0){let c=o.toLowerCase();c==="false"||c==="0"?s.usePolling=!1:c==="true"||c==="1"?s.usePolling=!0:s.usePolling=!!c}let i=process.env.CHOKIDAR_INTERVAL;i&&(s.interval=Number.parseInt(i,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Rr,this._readyEmitted=!0,process.nextTick(()=>this.emit(we.READY)))},this._emitRaw=(...c)=>this.emit(we.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new Ir(this),Object.freeze(s)}_addIgnoredPath(e){if(js(e)){for(let n of this._ignoredPaths)if(js(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)js(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let o=ua(e);return s&&(o=o.map(i=>Nd(i,s))),o.forEach(i=>{this._removeIgnoredPath(i)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async i=>{let a=await this._nodeFsHandler._addToNodeFs(i,!r,void 0,0,n);return a&&this._emitReady(),a})).then(i=>{this.closed||i.forEach(a=>{a&&this.add(ue.dirname(a),ue.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=ua(e),{cwd:r}=this.options;return n.forEach(s=>{!ue.isAbsolute(s)&&!this._closers.has(s)&&(r&&(s=ue.join(r,s)),s=ue.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,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 s=r();s instanceof Promise&&e.push(s)})),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 o=(this.options.cwd?ue.relative(this.options.cwd,r):r)||pa;e[o]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==we.ERROR&&this.emit(we.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let s=this.options;$s&&(n=ue.normalize(n)),s.cwd&&(n=ue.relative(s.cwd,n));let o=[n];r!=null&&o.push(r);let i=s.awaitWriteFinish,a;if(i&&(a=this._pendingWrites.get(n)))return a.lastChange=new Date,this;if(s.atomic){if(e===we.UNLINK)return this._pendingUnlinks.set(n,[e,...o]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(we.ALL,...c),this._pendingUnlinks.delete(l)})},typeof s.atomic=="number"?s.atomic:100),this;e===we.ADD&&this._pendingUnlinks.has(n)&&(e=we.CHANGE,this._pendingUnlinks.delete(n))}if(i&&(e===we.ADD||e===we.CHANGE)&&this._readyEmitted){let c=(l,u)=>{l?(e=we.ERROR,o[0]=l,this.emitWithAll(e,o)):u&&(o.length>1?o[1]=u:o.push(u),this.emitWithAll(e,o))};return this._awaitWriteFinish(n,i.stabilityThreshold,e,c),this}if(e===we.CHANGE&&!this._throttle(we.CHANGE,n,50))return this;if(s.alwaysStat&&r===void 0&&(e===we.ADD||e===we.ADD_DIR||e===we.CHANGE)){let c=s.cwd?ue.join(s.cwd,n):n,l;try{l=await xd(c)}catch{}if(!l||this.closed)return;o.push(l)}return this.emitWithAll(e,o),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(we.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let o=s.get(n);if(o)return o.count++,!1;let i,a=()=>{let l=s.get(n),u=l?l.count:0;return s.delete(n),clearTimeout(i),l&&clearTimeout(l.timeoutObject),u};i=setTimeout(a,r);let c={timeoutObject:i,clear:a,count:0};return s.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,s){let o=this.options.awaitWriteFinish;if(typeof o!="object")return;let i=o.pollInterval,a,c=e;this.options.cwd&&!ue.isAbsolute(e)&&(c=ue.join(this.options.cwd,e));let l=new Date,u=this._pendingWrites;function d(g){_d(c,(h,m)=>{if(h||!u.has(e)){h&&h.code!=="ENOENT"&&s(h);return}let y=Number(new Date);g&&m.size!==g.size&&(u.get(e).lastChange=y);let p=u.get(e);y-p.lastChange>=n?(u.delete(e),s(void 0,m)):a=setTimeout(d,i,m)})}u.has(e)||(u.set(e,{lastChange:l,cancelWait:()=>(u.delete(e),clearTimeout(a),r)}),a=setTimeout(d,i))}_isIgnored(e,n){if(this.options.atomic&&Dd.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,o=(this.options.ignored||[]).map(fa(r)),a=[...[...this._ignoredPaths].map(fa(r)),...o];this._userIgnored=$d(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Ls(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=ue.resolve(e);return this._watched.has(n)||this._watched.set(n,new Fs(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let s=ue.join(e,n),o=ue.resolve(s);if(r=r??(this._watched.has(s)||this._watched.has(o)),!this._throttle("remove",s,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(s).getChildren().forEach(g=>this._remove(s,g));let c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(o)&&this._symlinkPaths.delete(o);let u=s;if(this.options.cwd&&(u=ue.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===we.ADD)return;this._watched.delete(s),this._watched.delete(o);let d=r?we.UNLINK_DIR:we.UNLINK;l&&!this._isIgnored(s)&&this._emit(d,s),this._closePath(s)}_closePath(e){this._closeFile(e);let n=ue.dirname(e);this._getWatchedDir(n).remove(ue.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:we.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},s=na(e,r);return this._streams.add(s),s.once(ia,()=>{s=void 0}),s.once(Ms,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Us(t,e={}){let n=new Pr(e);return n.add(t),n}var ma={watch:Us,FSWatcher:Pr};import{execFile as Ud}from"node:child_process";import{stat as ya}from"node:fs/promises";import{resolve as Hd}from"node:path";import{promisify as zd}from"node:util";function Ut(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 tn(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 Ht(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var wa=zd(Ud);function Bd(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 qd(t){if(process.platform!=="darwin")return;let{stdout:e}=await wa("/bin/df",["-P",Hd(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
|
|
2
|
-
`).slice(1).map(
|
|
3
|
-
`,"utf8")}catch{}}var
|
|
1
|
+
var Ao=null;function Li(t){Ao=t}function _e(){if(!Ao)throw new Error("core host not set (call setCoreHost first)");return Ao}var Ui=new TextEncoder,zu=new TextDecoder("utf-8",{ignoreBOM:!0}),Tn=t=>Ui.encode(t),xt=t=>zu.decode(t),To=t=>typeof t=="string"?Ui.encode(t).length:t.length;function Hi(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Er(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 zi(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ne(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),c=>c.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(s)),a=i.userId??i.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function Io(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(xt(Er(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Ro(t,e=Date.now()){let n=Io(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Bi(t,e=Date.now()){let n=Io(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var Bu=36e5;function _r(t,e=Date.now()){return!!t&&Ro(t,e)>=Bu}async function Cr(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 i=await s.json().catch(()=>null),a=typeof i?.token=="string"?i.token:"";return a&&a!==e?a:null}catch{return null}}var In=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,qu=(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 qi(t,e){let n=d=>e.write(JSON.stringify(d,null,2)),r=()=>{let d;try{d=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(d===null)return[];try{let g=JSON.parse(d);return Array.isArray(g.accounts)?g.accounts.filter(h=>h&&typeof h.token=="string"&&h.id===Ne(h.cloudUrl,h.token)):null}catch{return null}},o=(d,g)=>{let h=Ne(d.cloudUrl||"",d.token||"");if(!h||!d.token||!d.cloudUrl)return;let m=r();if(!m)return;let y=m.find(v=>v.id===h),p=Io(d.token),b={...y,id:h,cloudUrl:d.cloudUrl.replace(/\/+$/,""),token:d.token,username:g?.username||y?.username||p?.username,nickname:g?.nickname||y?.nickname};JSON.stringify(y)!==JSON.stringify(b)&&n({version:1,accounts:[...m.filter(v=>v.id!==h),b]})},s=()=>{let d=t.readCreds();o(d);let g=Ne(d.cloudUrl,d.token);return(r()??[]).map(({token:h,...m})=>({...m,active:m.id===g}))},i=d=>{let g=r()?.find(h=>h.id===d);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},a=d=>{let g=Ne(d.cloudUrl||"",d.token||""),h=r();g&&h&&n({version:1,accounts:h.filter(m=>m.id!==g)})},c=null;return{rememberForsionAccount:o,forsionAccounts:s,savedForsionAccount:i,forgetForsionAccount:a,cancelForsionLogin:()=>{c?.abort(),c=null},forsionDeviceLogin:async(d,g,h)=>{if(c)throw new Error("A sign-in is already in progress.");if(!d)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;c=m;let y=()=>{if(m.signal.aborted||c!==m)throw new Error("Sign-in cancelled.")};try{let p=d.replace(/\/+$/,""),b;try{b=await fetch(`${p}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(x=>x.json())}catch(x){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${p}:${x?.message||x}`)}if(y(),!b?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let v=b.verification_uri_complete||`${b.verification_uri}?code=${b.user_code}`,$=new URL(`${p}/auth`);$.searchParams.set("logout","1"),$.searchParams.set("app","forsion-desktop"),$.searchParams.set("redirect",v);let R=$.toString();g?.({url:R,userCode:String(b.user_code||"")}),t.openExternal(R);let O=Date.now()+(b.expires_in||600)*1e3,w=(b.interval||2)*1e3;for(;Date.now()<O;){await qu(w,m.signal),y();let x=null;try{x=await fetch(`${p}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:b.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),x.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let C=await x.json().catch(()=>({status:"pending"}));if(y(),C.status==="approved"&&C.token){let D={cloudUrl:p,token:C.token};return await h(D,y),y(),{token:C.token,cloudUrl:p}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{c===m&&(c=null)}},readAccounts:()=>r()??[]}}function yt(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 Rn(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,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)}),i=await s.json().catch(()=>({}));return{status:s.status,json:i}}var Wu=50*1024*1024,Vu=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"]);function Yu(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(!Vu.has(o)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"].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>Wu)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 Wi(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=Yu(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=yt(o.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let i=await Rn(o,s,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:i.status,json:await i.json().catch(()=>null)}}catch(i){return{status:0,error:String(i?.message||i)}}})}async function Vi(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 Yi=["membership","credits","storefront"],Gi=["monthly","quarterly","yearly"],Gu=/^[A-Za-z0-9_-]{1,64}$/;function Ji(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 i=await t.getCloud(),a=i.base;if(!a)return{ok:!1};let c=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",l=await Vi(i),u=`${a}/account${l?`?${l}`:""}${c}`;return i.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(o,s,i,a)=>{if(!t.isTrustedSender(o))return n;if(s!==void 0&&!Yi.includes(s))return{ok:!1,error:"invalid_tab"};if(i!==void 0&&(typeof i!="string"||!Gu.test(i)))return{ok:!1,error:"invalid_plan"};if(a!==void 0&&!Gi.includes(a))return{ok:!1,error:"invalid_period"};let c=(s??"membership")==="membership"&&i?`&plan=${encodeURIComponent(i)}${a?`&period=${a}`:""}`:"",l=await t.getCloud(),u=l.base;if(!u)return{ok:!1};let d=await Vi(l),g=`${u}/pay?tab=${s??"membership"}${c}${d?`&${d}`:""}&redirect=${encodeURIComponent(`${u}/account`)}`;return l.signal?.throwIfAborted(),await t.openExternal(g),{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 i=await fetch(`${s}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});i.body?.cancel().catch(()=>{});let a=i.status>=300&&i.status<400?i.headers.get("location"):null;return a&&/^https?:\/\//i.test(a)?{ok:!0,origin:new URL(a).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 ze(s,"GET","/api/token-quota/my",void 0,15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("account:useResetCard",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(s!==void 0&&s!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${s}`}};let a=s??"both";try{return await ze(i,"POST","/api/token-quota/reset-card/use",{type:a},15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(o,s)=>{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 ze(i,"POST","/api/token-quota/background/convert",{percent:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:bgAutoMain",async(o,s)=>{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 ze(i,"POST","/api/token-quota/background/auto-main",{enabled:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("feedback:submit",async(o,s)=>{if(!t.isTrustedSender(o))return n;let i=await t.getCloud();if(!i.base||!i.token)return{ok:!1,error:"not-logged-in"};if(s?.expectedAccountId!==void 0){let u=s.expectedAccountId;if(typeof u!="string"||!u||Ne(i.base,i.token)!==u)return{ok:!1,error:"account-changed"}}let a=(s?.description||"").trim();if(!a)return{ok:!1,error:"empty"};if(a.length>1e4)return{ok:!1,error:"description-too-long"};let c=[],l=!1;if(s?.sessionLogJson){let u=Tn(s.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};c.push({filename:s.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:Hi(u)})}try{let u=await Rn(i,`${i.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:a,attachments:c}),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:l}}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 i=s??{},a=typeof i.path=="string"?i.path:"",c=i.projectSource===void 0?null:i.projectSource;if(c!==null&&(typeof c!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(c)))return{status:0,error:"bad_project_source"};let l=Math.min(12e4,Math.max(1e3,Number(i.timeoutMs)||15e3)),u=typeof i.method=="string"?i.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(u))return{status:0,error:"bad_method"};if(!a.startsWith("/"))return{status:0,error:"bad_path"};let d=await t.getCloud();if(!String(d.base||""))return{status:0,error:"no_cloud_url"};let g=yt(d.base,a);if(!g)return{status:0,error:"bad_path"};if(!d.token)return{status:401,error:"not_signed_in"};let h=i.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,y=setTimeout(()=>m.abort(),l);try{let p=await Rn(d,g,{method:u,headers:{...h?{"Content-Type":"application/json"}:{},...c?{"X-Project-Source":c}:{}},body:h?JSON.stringify(i.body):void 0,signal:m.signal});return{status:p.status,json:await p.json().catch(()=>null)}}catch(p){return{status:0,error:String(p?.message||p)}}finally{clearTimeout(y)}}),Wi(t)}import{createHash as ba}from"node:crypto";import{existsSync as Wd,promises as Vd,readFileSync as Yd,renameSync as Gd,statSync as Jd}from"node:fs";import Kd from"node:path";import{EventEmitter as Ed}from"node:events";import{stat as _d}from"node:fs";import{readdir as Cd,stat as xd}from"node:fs/promises";import*as ue from"node:path";import{lstat as Ki,readdir as Ju,realpath as Ku,stat as Xu}from"node:fs/promises";import{join as Zu,resolve as Qu,sep as Xi}from"node:path";import{Readable as ed}from"node:stream";var Ve={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Qt={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Ve.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(Qt);var ta="READDIRP_RECURSIVE_ERROR",td=new Set(["ENOENT","EPERM","EACCES","ELOOP",ta]),Zi=[Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE],nd=new Set([Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE]),rd=new Set([Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE]),od=t=>td.has(t.code),sd=process.platform==="win32",Qi=t=>!0,ea=t=>{if(t===void 0)return Qi;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 Qi},Do=class extends ed{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??Qt.highWaterMark});let n={...Qt,...e},r=n.root??Qt.root,o=n.type??Qt.type;this._fileFilter=ea(n.fileFilter),this._directoryFilter=ea(n.directoryFilter);let s=n.lstat?Ki:Xu;sd?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:Qt.depth,this._wantsDir=nd.has(o),this._wantsFile=rd.has(o),this._wantsEverything=o===Ve.EVERYTHING_TYPE,this._root=Qu(r),this._relStart=this._root.endsWith(Xi)?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 i={path:this._root,depth:1};i.pending=this._exploreDir(this._root,1),this.parents=[i],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,i=r.splice(0,e).map(c=>this._formatEntry(c,o)),a=this._isDirent?i:await Promise.all(i);for(let c of a){if(!c)continue;if(this.destroyed)return;let l=this._getEntryType(c);typeof l!="string"&&(l=await l),l==="directory"&&this._directoryFilter(c)?(s<=this._maxDepth&&this.parents.push({path:c.fullPath,depth:s+1}),this._wantsDir&&(this.push(c),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let o=this.parents.pop();if(!o){this.push(null);break}let s=o.pending??this._exploreDir(o.path,o.depth),i=this.parents[this.parents.length-1];if(i&&!i.pending&&(i.pending=this._exploreDir(i.path,i.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 Ju(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=Zu(n,r),s={path:o.slice(this._relStart),fullPath:o,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(o).then(i=>(s.stats=i,s),i=>{this._onError(i)})}_onError(e){od(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 Ku(n),o=await Ki(r);if(o.isFile())return"file";if(o.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===Xi){let i=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return i.code=ta,this._onError(i),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function na(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Ve.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!Zi.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${Zi.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 Do(r)}import{watch as id,unwatchFile as ra,watchFile as ad}from"node:fs";import{realpath as Oo,lstat as cd,open as ld,stat as sa}from"node:fs/promises";import{type as ud}from"node:os";import*as me from"node:path";var dd="data",$o="end",ia="close",Rr=()=>{};var Dr=process.platform,No=Dr==="win32",fd=Dr==="darwin",pd=Dr==="linux",hd=Dr==="freebsd",aa=ud()==="OS400",we={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},rt=we,gd="watch",md={lstat:cd,stat:sa},Ut="listeners",xr="errHandlers",en="rawEmitters",yd=[Ut,xr,en],wd=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"]),bd=t=>wd.has(me.extname(t).slice(1).toLowerCase()),Mo=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Dn=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},Sd=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},On=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ca=t=>t instanceof Set?t.size===0:!t,Ar=new Map;function oa(t,e,n,r,o){let s=(i,a)=>{n(t),o(i,a,{watchedPath:t}),a&&t!==a&&Tr(me.resolve(t,a),Ut,me.join(t,a))};try{return id(t,{persistent:e.persistent},s)}catch(i){r(i);return}}var Tr=(t,e,n,r,o)=>{let s=Ar.get(t);s&&Mo(s[e],i=>{i(n,r,o)})},vd=(t,e,n,r)=>{let{listener:o,errHandler:s,rawEmitter:i}=r,a=Ar.get(e),c;if(!n.persistent)return c=oa(t,n,o,s,i),c?c.close.bind(c):void 0;if(a)Dn(a,Ut,o),Dn(a,xr,s),Dn(a,en,i);else{if(c=oa(t,n,Tr.bind(null,e,Ut),s,Tr.bind(null,e,en)),!c)return;c.on(rt.ERROR,async l=>{let u=Tr.bind(null,e,xr);if(a&&(a.watcherUnusable=!0),No&&l.code==="EPERM")try{await(await ld(t,"r")).close(),u(l)}catch{}else u(l)}),a={listeners:o,errHandlers:s,rawEmitters:i,watcher:c},Ar.set(e,a)}return()=>{On(a,Ut,o),On(a,xr,s),On(a,en,i),ca(a.listeners)&&(a.watcher.close(),Ar.delete(e),yd.forEach(Sd(a)),a.watcher=void 0,Object.freeze(a))}},Po=new Map,kd=(t,e,n,r)=>{let{listener:o,rawEmitter:s}=r,i=Po.get(e),a=i&&i.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(ra(e),i=void 0),i?(Dn(i,Ut,o),Dn(i,en,s)):(i={listeners:o,rawEmitters:s,options:n,watcher:ad(e,n,(c,l)=>{Mo(i.rawEmitters,d=>{d(rt.CHANGE,e,{curr:c,prev:l})});let u=c.mtimeMs;(c.size!==l.size||u>l.mtimeMs||u===0)&&Mo(i.listeners,d=>d(t,c))})},Po.set(e,i)),()=>{On(i,Ut,o),On(i,en,s),ca(i.listeners)&&(Po.delete(e),ra(e),i.options=i.watcher=void 0,Object.freeze(i))}},Ir=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,o=me.dirname(e),s=me.basename(e);this.fsw._getWatchedDir(o).add(s);let a=me.resolve(e),c={persistent:r.persistent};n||(n=Rr);let l;if(r.usePolling){let u=r.interval!==r.binaryInterval;c.interval=u&&bd(s)?r.binaryInterval:r.interval,l=kd(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})}else l=vd(e,a,c,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,n,r){if(this.fsw.closed)return;let o=me.dirname(e),s=me.basename(e),i=this.fsw._getWatchedDir(o),a=n;if(i.has(s))return;let c=async(u,d)=>{if(this.fsw._throttle(gd,e,5)){if(!d||d.mtimeMs===0)try{let g=await sa(e);if(this.fsw.closed)return;let h=g.atimeMs,m=g.mtimeMs;if((!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(rt.CHANGE,e,g),(fd||pd||hd)&&a.ino!==g.ino){this.fsw._closeFile(u),a=g;let y=this._watchWithNodeFs(e,c);y&&this.fsw._addPathCloser(u,y)}else a=g}catch{this.fsw._remove(o,s)}else if(i.has(s)){let g=d.atimeMs,h=d.mtimeMs;(!g||g<=h||h!==a.mtimeMs)&&this.fsw._emit(rt.CHANGE,e,d),a=d}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(rt.ADD,e,0))return;this.fsw._emit(rt.ADD,e,n)}return l}async _handleSymlink(e,n,r,o){if(this.fsw.closed)return;let s=e.fullPath,i=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Oo(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(i.has(o)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(rt.CHANGE,r,e.stats)):(i.add(o),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(rt.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,i,a){e=me.join(e,"");let c=o?`${e}:${o}`:e;if(a=this.fsw._throttle("readdir",c,1e3),!a)return;let l=this.fsw._getWatchedDir(r.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(d)return d.on(dd,async g=>{if(this.fsw.closed){d=void 0;return}let h=g.path,m=me.join(e,h);if(u.add(h),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===o||!o&&!l.has(h))&&(this.fsw._incrReadyCount(),m=me.join(s,me.relative(s,m)),this._addToNodeFs(m,n,r,i+1))}}).on(rt.ERROR,this._boundHandleError),new Promise((g,h)=>{if(!d)return h();d.once($o,()=>{if(this.fsw.closed){d=void 0;return}let m=a?a.clear():!1;g(void 0),l.getChildren().filter(y=>y!==e&&!u.has(y)).forEach(y=>{this.fsw._remove(e,y)}),d=void 0,m&&this._handleRead(e,!1,r,o,s,i,a)})})}async _handleDir(e,n,r,o,s,i,a){let c=this.fsw._getWatchedDir(me.dirname(e)),l=c.has(me.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!l&&this.fsw._emit(rt.ADD_DIR,e,n),c.add(me.basename(e)),this.fsw._getWatchedDir(e);let u,d,g=this.fsw.options.depth;if((g==null||o<=g)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,r,i,s,e,o,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(h,m)=>{m&&m.mtimeMs===0||this._handleRead(h,!1,i,s,e,o,u)})}return d}async _addToNodeFs(e,n,r,o,s){let i=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return i(),!1;let a=this.fsw._getWatchHelpers(e);r&&(a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await md[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return i(),!1;let l=this.fsw.options.followSymlinks,u;if(c.isDirectory()){let d=me.resolve(e),g=l?await Oo(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,o,s,a,g),this.fsw.closed))return;d!==g&&g!==void 0&&this.fsw._symlinkPaths.set(d,g)}else if(c.isSymbolicLink()){let d=l?await Oo(e):e;if(this.fsw.closed)return;let g=me.dirname(a.watchPath);if(this.fsw._getWatchedDir(g).add(a.watchPath),this.fsw._emit(rt.ADD,a.watchPath,c),u=await this._handleDir(g,c,n,o,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(me.resolve(e),d)}else u=this._handleFile(a.watchPath,c,n);return i(),u&&this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return i(),e}}};var jo="/",Ad="//",pa=".",Td="..",Id="string",Rd=/\\/g,ha=/\/\//g,Dd=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Od=/^\.[/\\]/;function Or(t){return Array.isArray(t)?t:[t]}var Fo=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Pd(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=ue.relative(t.path,e);return n?!n.startsWith("..")&&!ue.isAbsolute(n):!1}return!1}:()=>!1}function Md(t){if(typeof t!="string")throw new Error("string expected");t=ue.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ha,"/"),e&&(t="/"+t),t}function la(t,e,n){let r=Md(e);for(let o=0;o<t.length;o++){let s=t[o];if(s(r,n))return!0}return!1}function $d(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Or(t).map(o=>Pd(o));return e==null?(o,s)=>la(r,o,s):la(r,e)}var ua=t=>{let e=Or(t).flat();if(!e.every(n=>typeof n===Id))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(ga)},da=t=>{let e=t.replace(Rd,jo),n=!1;return e.startsWith(Ad)&&(n=!0),e=e.replace(ha,jo),n&&(e=jo+e),e},ga=t=>da(ue.normalize(da(t))),fa=(t="")=>e=>typeof e=="string"?ga(ue.isAbsolute(e)?e:ue.join(t,e)):e,Nd=(t,e)=>ue.isAbsolute(t)?t:ue.join(e,t),jd=Object.freeze(new Set),Lo=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!==pa&&e!==Td&&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 Cd(r)}catch{this._removeWatcher&&this._removeWatcher(ue.dirname(r),ue.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=Rr,this.items=jd,Object.freeze(this)}},Fd="stat",Ld="lstat",Uo=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let o=e;this.path=e=e.replace(Od,""),this.watchPath=o,this.fullWatchPath=ue.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?Fd:Ld}entryPath(e){return ue.join(this.watchPath,ue.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)}},Pr=class extends Ed{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?Or(e.ignored):Or([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};aa&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let c=s.toLowerCase();c==="false"||c==="0"?o.usePolling=!1:c==="true"||c==="1"?o.usePolling=!0:o.usePolling=!!c}let i=process.env.CHOKIDAR_INTERVAL;i&&(o.interval=Number.parseInt(i,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Rr,this._readyEmitted=!0,process.nextTick(()=>this.emit(we.READY)))},this._emitRaw=(...c)=>this.emit(we.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new Ir(this),Object.freeze(o)}_addIgnoredPath(e){if(Fo(e)){for(let n of this._ignoredPaths)if(Fo(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)Fo(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=ua(e);return o&&(s=s.map(i=>Nd(i,o))),s.forEach(i=>{this._removeIgnoredPath(i)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async i=>{let a=await this._nodeFsHandler._addToNodeFs(i,!r,void 0,0,n);return a&&this._emitReady(),a})).then(i=>{this.closed||i.forEach(a=>{a&&this.add(ue.dirname(a),ue.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=ua(e),{cwd:r}=this.options;return n.forEach(o=>{!ue.isAbsolute(o)&&!this._closers.has(o)&&(r&&(o=ue.join(r,o)),o=ue.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?ue.relative(this.options.cwd,r):r)||pa;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==we.ERROR&&this.emit(we.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let o=this.options;No&&(n=ue.normalize(n)),o.cwd&&(n=ue.relative(o.cwd,n));let s=[n];r!=null&&s.push(r);let i=o.awaitWriteFinish,a;if(i&&(a=this._pendingWrites.get(n)))return a.lastChange=new Date,this;if(o.atomic){if(e===we.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(we.ALL,...c),this._pendingUnlinks.delete(l)})},typeof o.atomic=="number"?o.atomic:100),this;e===we.ADD&&this._pendingUnlinks.has(n)&&(e=we.CHANGE,this._pendingUnlinks.delete(n))}if(i&&(e===we.ADD||e===we.CHANGE)&&this._readyEmitted){let c=(l,u)=>{l?(e=we.ERROR,s[0]=l,this.emitWithAll(e,s)):u&&(s.length>1?s[1]=u:s.push(u),this.emitWithAll(e,s))};return this._awaitWriteFinish(n,i.stabilityThreshold,e,c),this}if(e===we.CHANGE&&!this._throttle(we.CHANGE,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===we.ADD||e===we.ADD_DIR||e===we.CHANGE)){let c=o.cwd?ue.join(o.cwd,n):n,l;try{l=await xd(c)}catch{}if(!l||this.closed)return;s.push(l)}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(we.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 i,a=()=>{let l=o.get(n),u=l?l.count:0;return o.delete(n),clearTimeout(i),l&&clearTimeout(l.timeoutObject),u};i=setTimeout(a,r);let c={timeoutObject:i,clear:a,count:0};return o.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,o){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let i=s.pollInterval,a,c=e;this.options.cwd&&!ue.isAbsolute(e)&&(c=ue.join(this.options.cwd,e));let l=new Date,u=this._pendingWrites;function d(g){_d(c,(h,m)=>{if(h||!u.has(e)){h&&h.code!=="ENOENT"&&o(h);return}let y=Number(new Date);g&&m.size!==g.size&&(u.get(e).lastChange=y);let p=u.get(e);y-p.lastChange>=n?(u.delete(e),o(void 0,m)):a=setTimeout(d,i,m)})}u.has(e)||(u.set(e,{lastChange:l,cancelWait:()=>(u.delete(e),clearTimeout(a),r)}),a=setTimeout(d,i))}_isIgnored(e,n){if(this.options.atomic&&Dd.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(fa(r)),a=[...[...this._ignoredPaths].map(fa(r)),...s];this._userIgnored=$d(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Uo(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=ue.resolve(e);return this._watched.has(n)||this._watched.set(n,new Lo(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let o=ue.join(e,n),s=ue.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 c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=o;if(this.options.cwd&&(u=ue.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===we.ADD)return;this._watched.delete(o),this._watched.delete(s);let d=r?we.UNLINK_DIR:we.UNLINK;l&&!this._isIgnored(o)&&this._emit(d,o),this._closePath(o)}_closePath(e){this._closeFile(e);let n=ue.dirname(e);this._getWatchedDir(n).remove(ue.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:we.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=na(e,r);return this._streams.add(o),o.once(ia,()=>{o=void 0}),o.once($o,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function Ho(t,e={}){let n=new Pr(e);return n.add(t),n}var ma={watch:Ho,FSWatcher:Pr};import{execFile as Ud}from"node:child_process";import{stat as ya}from"node:fs/promises";import{resolve as Hd}from"node:path";import{promisify as zd}from"node:util";function Ht(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 tn(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 ct(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var wa=zd(Ud);function Bd(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 qd(t){if(process.platform!=="darwin")return;let{stdout:e}=await wa("/bin/df",["-P",Hd(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 wa("/usr/sbin/diskutil",["info","-plist",n],{timeout:5e3,maxBuffer:256*1024});return Bd(r)}async function Pn(t,e=qd,n=process.platform){let r=await ya(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),i=await ya(t);if(!i.isDirectory()||!ct(o,i))throw Error("Sync root changed while reading its identity");return{...o,...s?{volumeId:s}:{}}}var zo;function Sa(t){zo=t}var va={fs:Vd,path:Kd,directoryIdentity:Pn,sha256Hex:t=>ba("sha256").update(t).digest("hex"),tmpTag:()=>process.pid,existsSync:Wd,async compareAndReplace(t,e,n,r,o){if(!zo)throw new Error("This host needs the shared content write lock for safe cloud downloads");let s=!1;return await zo(e,()=>{if(!r())return;if(o){let a;try{a=Jd(o.path)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||!ct(o.identity,a))return}let i=null;try{i=ba("sha256").update(Yd(e)).digest("hex")}catch(a){if(a.code!=="ENOENT")throw a}i===n&&(Gd(t,e),s=!0)}),s},watch(t,e,n){let r=ma.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 Xd,lstatSync as Wo,readFileSync as Vo,writeFileSync as Zd,realpathSync as ka,opendirSync as Qd,openSync as ef,fstatSync as tf,readSync as nf,closeSync as rf,constants as Bo}from"node:fs";import{join as Mr,extname as Ea,sep as of}from"node:path";var Yo=300,_a=5*1024*1024,Ca=20*1024*1024,sf=50*1024*1024,xa=new Set(["node_modules"]),af=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Aa(t,e){let n=[],r=0,o=(s,i)=>{for(let a of Xd(s)){if(a.startsWith("."))continue;let c=Mr(s,a),l;try{l=Wo(c)}catch{continue}if(l.isSymbolicLink())continue;let u=i?`${i}/${a}`:a;if(l.isDirectory()){xa.has(a)||o(c,u);continue}if(!l.isFile()||a.endsWith(".d.ts"))continue;if(n.length>=Yo)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Yo}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let d=Ea(a).toLowerCase(),g,h=e.mimeOf(d)??"application/octet-stream";if(af.has(d)){let m=e.transpile(Vo(c,"utf8"),d,u);g=Buffer.from(m??"","utf8"),h="text/javascript"}else g=Vo(c);if(g.length>_a)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${u}`);if(r+=g.length,r>Ca)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:h,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 Ta=".forsion-connect.json";function Ia(t){try{return JSON.parse(Vo(Mr(t,Ta),"utf8"))}catch{return{}}}function Ra(t,e){try{Zd(Mr(t,Ta),JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf8")}catch{}}var cf=new Set([".html",".htm",".js",".mjs",".cjs",".ts",".tsx",".jsx",".mts",".cts",".vue",".svelte"]),lf=400,uf=5e3,qo=2*1024*1024,df=12,ff=/\bforsion\.ai\.(chat|generateImage|agent|status)\b/g;function Da(t){try{if(!Wo(t).isDirectory())return null}catch{return null}let e=!1,n=new Set,r=0,o=0,s=null,i=c=>{let l;try{l=ef(c,Bo.O_RDONLY|(Bo.O_NOFOLLOW||0)|(Bo.O_NONBLOCK||0))}catch{return null}try{if(!tf(l).isFile())return null;s??=Buffer.allocUnsafe(qo+1);let u=0;for(;u<s.length;){let d=nf(l,s,u,s.length-u,null);if(d<=0)break;u+=d}return u>qo?null:s.toString("utf8",0,u)}catch{return null}finally{try{rf(l)}catch{}}},a=(c,l)=>{let u;try{u=Qd(c)}catch{return}try{for(;;){if(r>=lf||o>=uf)return;let d;try{d=u.readSync()}catch{return}if(!d)return;o++;let g=d.name;if(g.startsWith(".")||xa.has(g))continue;let h=Mr(c,g),m;try{m=Wo(h)}catch{continue}if(m.isSymbolicLink())continue;if(m.isDirectory()){l<df&&a(h,l+1);continue}if(!m.isFile()||m.size>qo||!cf.has(Ea(g).toLowerCase()))continue;r++;let y=i(h);if(y!==null){!e&&y.includes("forsion-connect.js")&&(e=!0);for(let p of y.matchAll(ff))n.add(`forsion.ai.${p[1]}`)}}}finally{try{u.closeSync()}catch{}}};return a(t,0),{usesSdk:e,sdkMethods:[...n].sort()}}function Oa(t){let e=Ia(t),n=Da(t);return n?{...e,...n}:e}function Pa(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,i]=(r.url||"").split("?"),a=(m,y)=>{o.headersSent||(o.statusCode=m,o.setHeader("Content-Type","application/json")),o.end(JSON.stringify({detail:y}))},c=n(s);if(!c)return a(404,"unknown connect endpoint");if((r.method||"GET")!==c.method)return a(405,"method not allowed");let l="",u="";try{({base:l,token:u}=await t())}catch{}if(!l)return a(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(c.auth&&!u)return a(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let d;if(c.method==="POST"){let m=[],y=0;try{for await(let p of r){if(y+=p.length,y>sf)return r.destroy(),a(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");m.push(p)}}catch(p){return a(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${p?.message||String(p)}`)}d=Buffer.concat(m)}if(c.agentRun){let m;try{m=JSON.parse((d||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return a(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}d=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,h=setTimeout(()=>g.abort(new Error("proxy timeout")),c.timeoutMs??3e5);r.on("close",()=>g.abort());try{let m=await fetch(l+c.path+(i?`?${i}`:""),{method:c.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...u?{Authorization:`Bearer ${u}`}:{}},body:d&&d.length?new Uint8Array(d):void 0,signal:g.signal});if(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 a(502,y)}finally{clearTimeout(h)}}}var Ma=`
|
|
6
6
|
(function () {
|
|
7
7
|
'use strict';
|
|
8
8
|
if (window.forsion) return;
|
|
@@ -196,69 +196,69 @@ var xs=null;function Li(t){xs=t}function _e(){if(!xs)throw new Error("core host
|
|
|
196
196
|
ai: { chat: chat, agent: agentRun, generateImage: generateImage, status: aiStatus }
|
|
197
197
|
};
|
|
198
198
|
})();
|
|
199
|
-
`,ff=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function pf(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function Ys(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Gs(t){t.setPreviewHooks({sdkJs:Ma,proxy:Pa(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Oa(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=ka(n.dir);let o=null;try{o=ka(t.projectsRoot())}catch{}if(!(!!o&&(r===o||r.startsWith(o+rf)))&&!pf(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 s=await t.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:o,totalBytes:i}=Aa(r,ff(t));if(!o.some(u=>u.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:a,json:c}=await ze(s,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:o},3e5);if(a===401)return{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"};if(a!==200)return{ok:!1,code:c?.code||"error",detail:c?.detail||`HTTP ${a}`,used:c?.used,limit:c?.limit};Ra(r,{slug:String(c.slug)});let l=typeof c.publicUrl=="string"&&/^https?:\/\//i.test(c.publicUrl)?c.publicUrl:`${s.base}${c.url}`;return{ok:!0,slug:c.slug,handle:c.handle,url:l,totalBytes:i}}catch(o){return{ok:!1,code:"error",detail:o?.message||String(o)}}}),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:s,json:o}=await ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return s===401||s===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),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:s,json:o}=await ze(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200?{ok:!1,code:o?.code||"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0,status:o.status}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),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:s,json:o}=await ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),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 hf}from"node:crypto";import{hostname as gf}from"node:os";async function Mn(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 s=await r.json();if(!s)return{status:"offline"};let o=s.avatar||s.avatarUrl||s.avatar_url||void 0;return o&&/^\/(?!\/)/.test(o)&&(o=n+o),{status:"ok",user:{username:s.username||s.nickname||void 0,nickname:s.nickname||void 0,avatar:o,membershipTier:s.membershipTier||s.membership_tier||void 0}}}catch{return{status:"offline"}}}var $a=t=>`${t.seq}:${t.hash}`,$r=(t=gf())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},mf=t=>hf("sha256").update(t).digest("hex");function Js(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 Nr(t){let e=t.baseUrl.replace(/\/+$/,""),n=o=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${o}`,r=$r(),s=async(o,i)=>{let a=t.getToken();if(!a)throw new Error("penzor-not-logged-in");let c=await fetch(o,{...i,headers:{...i.headers,Authorization:`Bearer ${a}`}});if(c.status===409){let l=await c.json().catch(()=>({}));throw new Error(`cas-conflict ${String(l.code??"")}: seq=${String(l.seq??"?")}`)}if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`penzor ${i.method??"GET"} ${c.status}: ${l.slice(0,200)}`)}return c};return{kind:"penzor",async walk(o){let i=await s(n("/manifest"),{method:"GET",signal:o}),{files:a}=await i.json();return a.map(c=>({key:c.path,size:c.size,mtimeMs:c.mtimeMs,id:$a(c),hash:c.hash}))},async readFile(o,i){let c=await(await s(n(`/file?path=${encodeURIComponent(o)}`),{method:"GET",signal:i})).json(),l=await fetch(c.url,{signal:i});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${o}`);let u=Buffer.from(await l.arrayBuffer());if(mf(u)!==c.hash)throw new Error(`penzor hash mismatch: ${o}`);return u},async writeFile(o,i,a,c,l){let u=Js(l),d=new URLSearchParams({path:o,mtimeMs:String(Math.floor(a)||0)});u&&(d.set("baseSeq",String(u.baseSeq)),u.baseHash&&d.set("baseHash",u.baseHash));let h=await(await s(n(`/file?${d.toString()}`),{method:"PUT",body:new Uint8Array(i),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:c})).json();return{key:o,size:h.size,mtimeMs:h.mtimeMs,id:$a(h)}},async rm(o,i,a){let c=Js(a),l=new URLSearchParams({path:o});c&&c.baseSeq>0&&(l.set("baseSeq",String(c.baseSeq)),c.baseHash&&l.set("baseHash",c.baseHash)),await s(n(`/file?${l.toString()}`),{method:"DELETE",signal:i})},async check(){try{return await s(n("/manifest"),{method:"GET"}),{ok:!0}}catch(o){return{ok:!1,error:String(o?.message||o)}}}}}var jr="forsion-diagnostics",ja=50*1024*1024,Na=new Map;async function yf(t,e){let n=Na.get(e);if(n)return{id:n};let r=await Mn(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let s=r.user?.username?.trim();return s?(Na.set(e,s),{id:s}):{error:"penzor-auth-unverified"}}var Ks=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function Xs(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,s=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(s)||s===jr)return{error:"penzor-bad-vault"};let o=await yf(n.cloudUrl,n.token);if("error"in o)return o;let i=n.token;return{remote:Nr({baseUrl:n.cloudUrl,vault:s,getToken:()=>i}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${o.id}|${s}`,maxFileBytes:ja}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as bf}from"node:fs";import{access as Sf,link as vf,lstat as kf,mkdir as Ef,open as _f,readdir as Cf,rename as xf,stat as qa,unlink as eo}from"node:fs/promises";import{request as Af}from"node:http";import{request as Tf}from"node:https";import{homedir as If}from"node:os";import{basename as Wa,extname as Rf,isAbsolute as Df,join as Nn}from"node:path";import{randomUUID as Lr}from"node:crypto";var $n=52428800;var Fa=["bytes","signed","text"],La=/^[A-Za-z0-9_-]{1,64}$/,Ua=/^[a-z0-9][a-z0-9-]{0,63}$/;function Fr(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 wf={".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 Ha(t){let e=t.lastIndexOf(".");return wf[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function za(t,e,n,r){let s=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",o=encodeURIComponent(n).replace(/['()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),i="";for(let[a,c]of Object.entries(e))i+=`--${t}\r
|
|
199
|
+
`,pf=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function hf(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function Go(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Jo(t){t.setPreviewHooks({sdkJs:Ma,proxy:Pa(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Oa(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=ka(n.dir);let s=null;try{s=ka(t.projectsRoot())}catch{}if(!(!!s&&(r===s||r.startsWith(s+of)))&&!hf(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:i}=Aa(r,pf(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:a,json:c}=await ze(o,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:s},3e5);if(a===401)return{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"};if(a!==200)return{ok:!1,code:c?.code||"error",detail:c?.detail||`HTTP ${a}`,used:c?.used,limit:c?.limit};Ra(r,{slug:String(c.slug)});let l=typeof c.publicUrl=="string"&&/^https?:\/\//i.test(c.publicUrl)?c.publicUrl:`${o.base}${c.url}`;return{ok:!0,slug:c.slug,handle:c.handle,url:l,totalBytes:i}}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 ze(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 ze(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 ze(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 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 gf}from"node:crypto";import{hostname as mf}from"node:os";async function Mn(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 $a=t=>`${t.seq}:${t.hash}`,$r=(t=mf())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},yf=t=>gf("sha256").update(t).digest("hex");function Ko(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 Nr(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=$r(),o=async(s,i)=>{let a=t.getToken();if(!a)throw new Error("penzor-not-logged-in");let c=await fetch(s,{...i,headers:{...i.headers,Authorization:`Bearer ${a}`}});if(c.status===409){let l=await c.json().catch(()=>({}));throw new Error(`cas-conflict ${String(l.code??"")}: seq=${String(l.seq??"?")}`)}if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`penzor ${i.method??"GET"} ${c.status}: ${l.slice(0,200)}`)}return c};return{kind:"penzor",async walk(s){let i=await o(n("/manifest"),{method:"GET",signal:s}),{files:a}=await i.json();return a.map(c=>({key:c.path,size:c.size,mtimeMs:c.mtimeMs,id:$a(c),hash:c.hash}))},async readFile(s,i){let c=await(await o(n(`/file?path=${encodeURIComponent(s)}`),{method:"GET",signal:i})).json(),l=await fetch(c.url,{signal:i});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${s}`);let u=Buffer.from(await l.arrayBuffer());if(yf(u)!==c.hash)throw new Error(`penzor hash mismatch: ${s}`);return u},async writeFile(s,i,a,c,l){let u=Ko(l),d=new URLSearchParams({path:s,mtimeMs:String(Math.floor(a)||0)});u&&(d.set("baseSeq",String(u.baseSeq)),u.baseHash&&d.set("baseHash",u.baseHash));let h=await(await o(n(`/file?${d.toString()}`),{method:"PUT",body:new Uint8Array(i),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:c})).json();return{key:s,size:h.size,mtimeMs:h.mtimeMs,id:$a(h)}},async rm(s,i,a){let c=Ko(a),l=new URLSearchParams({path:s});c&&c.baseSeq>0&&(l.set("baseSeq",String(c.baseSeq)),c.baseHash&&l.set("baseHash",c.baseHash)),await o(n(`/file?${l.toString()}`),{method:"DELETE",signal:i})},async check(){try{return await o(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var jr="forsion-diagnostics",ja=50*1024*1024,Na=new Map;async function wf(t,e){let n=Na.get(e);if(n)return{id:n};let r=await Mn(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?(Na.set(e,o),{id:o}):{error:"penzor-auth-unverified"}}var Xo=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function Zo(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===jr)return{error:"penzor-bad-vault"};let s=await wf(n.cloudUrl,n.token);if("error"in s)return s;let i=n.token;return{remote:Nr({baseUrl:n.cloudUrl,vault:o,getToken:()=>i}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${s.id}|${o}`,maxFileBytes:ja}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as Sf}from"node:fs";import{access as vf,link as kf,lstat as Ef,mkdir as _f,open as Cf,readdir as xf,rename as Af,stat as qa,unlink as ts}from"node:fs/promises";import{request as Tf}from"node:http";import{request as If}from"node:https";import{homedir as Rf}from"node:os";import{basename as Wa,extname as Df,isAbsolute as Of,join as Nn}from"node:path";import{randomUUID as Lr}from"node:crypto";var $n=52428800;var Fa=["bytes","signed","text"],La=/^[A-Za-z0-9_-]{1,64}$/,Ua=/^[a-z0-9][a-z0-9-]{0,63}$/;function Fr(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 bf={".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 Ha(t){let e=t.lastIndexOf(".");return bf[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function za(t,e,n,r){let o=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",s=encodeURIComponent(n).replace(/['()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),i="";for(let[a,c]of Object.entries(e))i+=`--${t}\r
|
|
200
200
|
Content-Disposition: form-data; name="${a}"\r
|
|
201
201
|
\r
|
|
202
202
|
${c}\r
|
|
203
203
|
`;return i+=`--${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:i,tail:`\r
|
|
208
208
|
--${t}--\r
|
|
209
|
-
`}}function Zs(t,e){let n=t.filter(([a])=>e-a<=3e3);if(n.length<2)return 0;let[r,s]=n[0],[o,i]=n[n.length-1];return o>r?Math.max(0,(i-s)/(o-r)*1e3):0}function Qs(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 Of=3,to=6e4,Pf=200,Mf=Fa;function Va(t,e,n,r){let{head:s,tail:o}=za(t,e,n,r);return{head:Buffer.from(s,"utf8"),tail:Buffer.from(o,"utf8")}}function $f(t,e,n,r,s,o,i,a){return new Promise((c,l)=>{let u=new URL(t),d=(u.protocol==="https:"?Tf:Af)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+s+o.length)}},h=>{let m=[];h.on("data",y=>m.push(y)),h.on("end",()=>{let y=null;try{y=JSON.parse(Buffer.concat(m).toString("utf8"))}catch{}c({status:h.statusCode??0,body:y})}),h.on("error",l)}),g=()=>{d.destroy(new Error("aborted"))};if(a.aborted)return g();a.addEventListener("abort",g,{once:!0}),d.setTimeout(to,()=>d.destroy(new Error("timeout"))),d.on("error",h=>{a.removeEventListener("abort",g),l(h)}),(async()=>{try{d.write(n);let h=0;for await(let m of bf(r)){let y=m;if(h+=y.length,h>s)throw new Error("changed");d.write(y)||await new Promise(p=>d.once("drain",p)),i(h)}if(h!==s)throw new Error("changed");d.end(o)}catch(h){d.destroy(h)}})()})}function no(t,e={}){let n=e.downloadsDir??(()=>Nn(If(),"Downloads")),r=e.post??$f,s=e.now??Date.now,o=[],i=new Map,a=Promise.resolve(),c=async()=>{let w=await t.getCloud(),x=typeof t.accountId=="function"?t.accountId():null;return{...w,account:x||`${w.base}|${w.token}`}},l=w=>{let{account:x,attempt:C,relDir:D,abort:j,samples:P,dl:V,...Z}=w;return{...Z,speed:w.state==="active"?Zs(P,s()):0}},u=(w,x,C=null)=>{w.state=x,w.error=C,w.abort=null,w.finishedAt=s(),w.samples=[];let D=o.filter(j=>j.state==="done"||j.state==="canceled");for(let j of D.slice(0,Math.max(0,D.length-Pf)))o.splice(o.indexOf(j),1);d()};function d(){for(let w of["up","down"]){let x=o.filter(C=>C.kind===w&&C.state==="active").length;for(let C of o){if(x>=Of)break;if(C.kind!==w||C.state!=="queued")continue;x++,C.state="active",C.startedAt=s(),C.done=0,C.samples=[[s(),0]],C.abort=new AbortController;let D=++C.attempt,j=()=>C.attempt===D&&C.state==="active";(w==="up"?b(C,j):$(C,j)).catch(P=>{j()&&u(C,"failed",g(P))})}}}let g=w=>{let x=String(w?.message||w);return x==="changed"||x==="too_large"||x==="quota"||x==="account_changed"||x==="not_signed_in"||x.startsWith("http_")||x==="bad_response"||x==="gone"?x:"network"},h=(w,x)=>{w.done=x;let C=s(),D=w.samples[w.samples.length-1];for((!D||C-D[0]>=200)&&w.samples.push([C,x]);w.samples.length>2&&C-w.samples[0][0]>3500;)w.samples.shift()};async function m(w){let x=await c();if(x.account!==w.account)throw new Error("account_changed");if(!x.token)throw new Error("not_signed_in");return x}async function y(w,x,C,D){let j=gt(w,C);if(!j)throw new Error("bad_path");let P=await fetch(j,{method:D.method??"GET",headers:{Authorization:`Bearer ${x}`,...D.body!==void 0?{"Content-Type":"application/json"}:{},...D.projectSource?{"X-Project-Source":D.projectSource}:{}},body:D.body!==void 0?JSON.stringify(D.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:P.status,json:await P.json().catch(()=>null)}}function p(w,x,C){if(!w.relDir.length)return Promise.resolve(w.targetId);let D=i.get(w.batch);D||i.set(w.batch,D=new Map);let j=D,P=V=>{if(V===0)return Promise.resolve(w.targetId);let Z=w.relDir.slice(0,V).join("/"),Q=j.get(Z);return Q||(Q=P(V-1).then(async ee=>{let re=w.relDir[V-1],se=await y(x,C,"/files",{method:"POST",body:{type:"directory",parentId:ee,name:re},projectSource:w.projectSource});if(se.status===201&&typeof se.json?.id=="string")return se.json.id;if(se.status===409){let pe=await y(x,C,`/files${ee==="ROOT"?"":`?parentId=${encodeURIComponent(ee)}`}`,{projectSource:w.projectSource}),ie=Array.isArray(pe.json)?pe.json.find(xe=>xe?.fileType==="directory"&&xe?.name===re):null;if(ie?.id)return String(ie.id)}throw new Error(se.status===401?"not_signed_in":`http_${se.status}`)}),Q.catch(()=>j.delete(Z)),j.set(Z,Q)),Q};return P(w.relDir.length)}async function b(w,x){let{base:C,token:D}=await m(w),j=await qa(w.localPath).catch(()=>null);if(!j?.isFile())throw new Error("gone");if(j.size>52428800)throw new Error("too_large");w.size=j.size;let P=await p(w,C,D);if(!x())return;w.parentId=P;let V=gt(C,"/files/upload");if(!V)throw new Error("bad_path");let Z=`----penzor${Lr().replace(/-/g,"")}`,{head:Q,tail:ee}=Va(Z,{parentId:P,autoRename:"true"},w.name,Ha(w.name)),re=await r(V,{Authorization:`Bearer ${D}`,"Content-Type":`multipart/form-data; boundary=${Z}`,...w.projectSource?{"X-Project-Source":w.projectSource}:{}},Q,w.localPath,j.size,ee,se=>{x()&&h(w,se)},w.abort.signal);x()&&(re.status===201||re.status===200?(w.fileId=typeof re.body?.id=="string"?re.body.id:null,h(w,w.size),u(w,"done")):u(w,"failed",Qs(re.status,re.body)))}function v(w,x,C,D){let j=async()=>{let V=Rf(C),Z=V?C.slice(0,-V.length):C;for(let Q=0;Q<1e3;Q++){if(!D())throw new Error("aborted");let ee=Nn(x,Q===0?C:`${Z} (${Q})${V}`);try{await vf(w,ee)}catch(re){let se=re.code;if(se==="EEXIST")continue;if(se!=="EPERM"&&se!=="ENOTSUP"&&se!=="EOPNOTSUPP"&&se!=="ENOSYS"&&se!=="EXDEV")throw re;if(await Sf(ee).then(()=>!0,()=>!1))continue;await xf(w,ee)}if(!D())throw await eo(ee).catch(()=>{}),new Error("aborted");return await eo(w).catch(()=>{}),ee}throw new Error("too many duplicates")},P=a.then(j,j);return a=P.catch(()=>{}),P}async function $(w,x){let C=w.dl,{base:D,token:j}=await m(w);if(!x())return;let P=gt(D,C.path);if(!P)throw new Error("bad_path");let V=w.abort.signal,Z=C.subdir?Nn(n(),C.subdir):n();await Ef(Z,{recursive:!0});let Q=Nn(Z,`.${w.id}-${w.attempt}.penzor-part`),ee=await _f(Q,"wx"),re=!1;try{let se=new AbortController,pe=setTimeout(()=>se.abort(),to),ie=()=>{clearTimeout(pe),pe=setTimeout(()=>se.abort(),to)},xe=AbortSignal.any([V,se.signal]);try{let ye=await fetch(P,{headers:{Authorization:`Bearer ${j}`},signal:xe});if(!ye.ok)throw new Error(ye.status===401?"not_signed_in":`http_${ye.status}`);let Re=ye.body,$e=Number(ye.headers.get("content-length"))||w.size;if(C.mode!=="bytes"){let Ae=await ye.json().catch(()=>null);if(C.mode==="text"){if(typeof Ae?.content!="string")throw new Error("bad_response");let H=Buffer.from(Ae.content,"utf8");await ee.writeFile(H),w.size=H.length,h(w,H.length),Re=null}else{if(typeof Ae?.url!="string"||!/^https?:\/\//i.test(Ae.url))throw new Error("bad_response");let H=await fetch(Ae.url,{signal:xe});if(!H.ok)throw new Error(`http_${H.status}`);Re=H.body,$e=Number(H.headers.get("content-length"))||w.size}}if(Re){w.size=$e;let Ae=0;for await(let H of Re){ie();for(let Y=0;Y<H.length;){let{bytesWritten:_}=await ee.write(H,Y,H.length-Y);if(_<=0)throw new Error("short_write");Y+=_}if(Ae+=H.length,!x())throw new Error("aborted");h(w,Ae)}Ae>w.size&&(w.size=Ae)}}finally{clearTimeout(pe)}if(await ee.close(),!x()||(w.localPath=await v(Q,Z,C.name,x),re=!0,!x()))return;u(w,"done")}finally{re||(await ee.close().catch(()=>{}),await eo(Q).catch(()=>{}))}}let R=(w,x)=>{let C={...w,id:Lr(),attempt:0,done:0,state:x?"failed":"queued",error:x??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:x?s():null};return o.push(C),C};async function O(w){let x=[],C=async(D,j)=>{if(j.length>32)return!0;let P=await(j.length?kf(D):qa(D)).catch(()=>null);if(!P)return!0;if(P.isFile())return x.push({path:D,size:P.size,relDir:j}),x.length<=2e3;if(!P.isDirectory())return!0;let V=(await Cf(D).catch(()=>[])).filter(Z=>!Z.startsWith(".")).sort();for(let Z of V)if(!await C(Nn(D,Z),[...j,Wa(D)]))return!1;return!0};for(let D of w)if(!await C(D,[]))return"too_many";return x}return t.handle("penzor:device",w=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let x=$r();return{ok:!0,name:x?decodeURIComponent(x):null}}),t.handle("penzor:upload",async(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x??{},D=Array.isArray(C.paths)?C.paths.filter(ie=>typeof ie=="string"&&Df(ie)):[],j=typeof C.parentId=="string"&&La.test(C.parentId)?C.parentId:null,P=typeof C.projectSource=="string"&&Ua.test(C.projectSource)?C.projectSource:null;if(!D.length)return{ok:!1,error:"no_files"};if(!j||!P)return{ok:!1,error:"bad_target"};let{base:V,token:Z,account:Q}=await c();if(!Z)return{ok:!1,error:"not_signed_in"};let ee=await O(D);if(ee==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!ee.length)return{ok:!1,error:"no_files"};let re=ee.filter(ie=>ie.size<=52428800).reduce((ie,xe)=>ie+xe.size,0);try{let ie=await y(V,Z,"/storage/quota",{}),xe=Number(ie.json?.used),ye=Number(ie.json?.quota);if(ie.status===200&&ye>0&&xe+re>ye)return{ok:!1,error:"quota",short:xe+re-ye}}catch{}if((await c()).account!==Q)return{ok:!1,error:"account_changed"};let se=Lr(),pe=ee.map(ie=>R({kind:"up",name:Wa(ie.path),size:ie.size,projectSource:P,parentId:ie.relDir.length?null:j,targetId:j,fileId:null,localPath:ie.path,batch:se,account:Q,relDir:ie.relDir},ie.size>52428800?"too_large":void 0).id);return d(),{ok:!0,ids:pe,batch:se}}),t.handle("penzor:download",async(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x??{},D=Mf.includes(C.mode)?C.mode:null,j=Fr(C.name);if(!D)return{ok:!1,error:"bad_mode"};if(!j)return{ok:!1,error:"bad_name"};let{base:P,token:V,account:Z}=await c();if(typeof C.path!="string"||!gt(P,C.path))return{ok:!1,error:"bad_path"};if(!V)return{ok:!1,error:"not_signed_in"};let Q=C.subdir==null?null:Fr(C.subdir),ee=R({kind:"down",name:j,size:Math.max(0,Number(C.size)||0),localPath:null,batch:typeof C.batch=="string"&&C.batch.length<=64?C.batch:Lr(),account:Z,relDir:[],dl:{path:C.path,mode:D,name:j,subdir:Q}});return d(),{ok:!0,id:ee.id}}),t.handle("penzor:transfers",w=>t.isTrustedSender(w)?{ok:!0,items:o.map(l)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x??{},D=o.find(P=>P.id===C.id);if(!D)return{ok:!1,error:"not_found"};let j=()=>{D.abort?.abort(),D.abort=null,D.done=0,D.samples=[]};switch(C.op){case"pause":(D.state==="active"||D.state==="queued")&&(j(),D.state="paused",d());break;case"resume":D.state==="paused"&&(D.state="queued",d());break;case"cancel":(D.state==="active"||D.state==="queued"||D.state==="paused")&&(j(),u(D,"canceled"));break;case"retry":(D.state==="failed"||D.state==="canceled")&&(D.state="queued",D.error=null,D.finishedAt=null,D.done=0,d());break;case"dismiss":D.state!=="active"&&D.state!=="queued"&&o.splice(o.indexOf(D),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x?.which==="all";for(let D of[...o])(D.state==="done"||D.state==="canceled"||C&&D.state==="failed")&&o.splice(o.indexOf(D),1);return{ok:!0}}),t.addQuitGuard?.(w=>{let x=o.filter(C=>C.state==="active"||C.state==="queued"||C.state==="paused").length;return x?w==="zh"?{message:`\u8FD8\u6709 ${x} \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:x===1?"1 file hasn't finished transferring":`${x} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>o.map(l)}}import{readFileSync as Bf,writeFileSync as qf,mkdirSync as Wf,chmodSync as Vf,renameSync as Yf}from"node:fs";import{join as Gf}from"node:path";import{mkdirSync as Nf,readFileSync as jf,renameSync as Ff,unlinkSync as Lf,writeFileSync as Uf}from"node:fs";import{dirname as Hf,join as zf}from"node:path";import{randomUUID as Ya}from"node:crypto";var io=t=>zf(t,"content-sync","active-account.json"),ro=()=>Error("Invalid content sync account binding; original data was retained");function jn(t){try{let e=JSON.parse(jf(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 ro();return e}catch(e){if(e?.code==="ENOENT")return null;throw ro()}}function ao(t,e){Nf(Hf(t),{recursive:!0,mode:448});let n=t+".tmp-"+Ya();try{Uf(n,JSON.stringify(e),{flag:"wx",mode:384}),Ff(n,t)}finally{try{Lf(n)}catch{}}}var so=new WeakMap,oo=new WeakSet;function Ga(t,e){let n=so.get(t);return n||so.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function co(t){if(oo.has(t))throw ro()}function nn(t,e,n){if(!t.contentSync||e===n)return;let r=io(t.homeDir());try{let s=jn(r);ao(r,{version:1,account:s?.account??null,epoch:Ya(),pending:!0}),oo.delete(t)}catch(s){throw oo.add(t),s}finally{for(let s of so.get(t)??[])s()}}function Jf(t){let e=()=>Gf(t(),"auth-accounts.json");return{read:()=>Bf(e(),"utf8"),write:n=>{Wf(t(),{recursive:!0});let r=`${e()}.tmp`;qf(r,n,{encoding:"utf8",mode:384}),Vf(r,384),Yf(r,e())}}}var Ka=t=>qi(t,Jf(()=>t.homeDir())),Xa=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],lo=t=>Xa.every(e=>typeof t[e]=="function");function uo(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=Ka(t),s=0,o=()=>{let c=t.readCreds();return In(c.cloudUrl,c.token)},i=c=>Ne(c.cloudUrl??"",c.token??""),a=null;t.handle("auth:status",async c=>{if(!t.isTrustedSender(c))return n;let l=s,u=o(),{base:d}=await t.getCloud(),g=t.readCreds().token,h=g?await Mn(d,g):null,m=await t.accountBackendState(),{base:y}=await t.getCloud(),p=t.readCreds(),b=In(y,p.token)!==In(d,g),v=In(d,g);!b&&h?.status==="ok"&&h.user&&(a={key:v,user:h.user},r.rememberForsionAccount({...p,cloudUrl:d},h.user));let $=b?void 0:h?.status==="ok"?h.user:h?.status==="offline"&&a?.key===v?a.user:void 0;if(b)return{loggedIn:!!p.token,tokenValid:null,cloudUrl:y,accountId:Ne(y,p.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:p.token?"tangu-login":null,backendState:m};if(h?.status==="expired"){await t.accountTransition(async()=>{if(l!==s||o()!==u)return;let O=()=>{if(l!==s||o()!==u)throw Ja};try{await t.accountClear(O,()=>{nn(t,t.accountId?.()??null,null),t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++s,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),a=null})}catch(w){if(w!==Ja)throw w}});let R=t.readCreds();return{loggedIn:!!R.token,tokenValid:null,cloudUrl:R.cloudUrl||d,accountId:Ne(R.cloudUrl||d,R.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:R.token?"tangu-login":null,backendState:m}}return{loggedIn:!!g,tokenValid:h&&h.status==="ok"?!0:null,cloudUrl:d,accountId:Ne(d,g),username:$?.username||null,nickname:$?.nickname||null,avatar:$?.avatar||null,membershipTier:$?.membershipTier||null,tokenSource:g?"tangu-login":null,backendState:m}}),t.handle("auth:accounts",c=>t.isTrustedSender(c)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(c,l)=>{if(!t.isTrustedSender(c))return e;if(typeof l!="string")throw new Error("Invalid account.");let u=++s;return r.cancelForsionLogin(),t.accountTransition(async()=>{let d=r.savedForsionAccount(l);return await t.accountCommit(d,()=>{if(u!==s)throw new Error("Account switch cancelled.")},()=>{nn(t,t.accountId?.()??null,i(d)),r.rememberForsionAccount(d),a=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(c,l)=>{if(!t.isTrustedSender(c))return e;let u=++s;r.cancelForsionLogin();let{base:d}=await t.getCloud();if(u!==s)throw new Error("Sign-in cancelled.");let g=(l||d||"").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!==s)throw new Error("Sign-in cancelled.")},()=>{nn(t,t.accountId?.()??null,i(m)),r.rememberForsionAccount(m),a=null})))).cloudUrl}}),t.handle("auth:logout",async c=>t.isTrustedSender(c)?(++s,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:l}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{nn(t,t.accountId?.()??null,null),r.forgetForsionAccount(u),a=null,l&&u.token&&fetch(`${l}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${u.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:c,current:l})=>{try{nn(t,i(c),i(l))}catch{t.log("[content-sync] account transition could not be recorded; sync is stopped")}++s,r.cancelForsionLogin(),c.token&&!l.token&&r.forgetForsionAccount(c),a=null,r.rememberForsionAccount(l)}),t.setTokenRefresher(async c=>{let l=s,u=o(),d=t.readCreds().token;if(!_r(d))return;let{base:g}=await t.getCloud(),h=await Cr(g,d,c,`desktop/${t.appVersion()}`);if(!h){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}l!==s||o()!==u||(r.rememberForsionAccount({cloudUrl:g,token:h}),t.writeCreds({cloudUrl:g,token:h}),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 Ja=Symbol("stale-auth-intent");import{promises as ln}from"node:fs";import zt from"node:path";import{execFile as Cp}from"node:child_process";import xp from"node:os";var fo=null;function Za(t){fo=t}function Be(){if(!fo)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return fo}var je=()=>Be().accountId();function Fn(t=je()){return t?_e().sha256Hex(t):"signed-out"}var Ye=(t=je())=>Be().readConfig(t),mt=(t,e=je())=>Be().writeConfig(t,e),rn=(t,e=je())=>Be().updateConfig(t,e),xt=(t=je())=>Be().cloudVaultDir(t),Ur=t=>Be().isManagedCloudVault(t);function Kf(t,e){let n=Object.create(null);for(let o=0;o<e.length;o++){let i=e[o];n[i]?n[i].push(o):n[i]=[o]}let s=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let o=0;o<t.length;o++){let i=t[o],a=n[i]||[],c=0,l=s[0];for(let u of a){let d;for(d=c;d<s.length&&!(s[d].buffer2index<u&&(d===s.length-1||s[d+1].buffer2index>u));d++);if(d<s.length){let g={buffer1index:o,buffer2index:u,chain:s[d]};if(c===s.length?s.push(l):s[c]=l,c=d+1,l=g,c===s.length)break}}s[c]=l}return s[s.length-1]}function Qa(t,e){let n=Kf(t,e),r=[],s=t.length,o=e.length;for(let i=n;i!==null;i=i.chain){let a=s-i.buffer1index-1,c=o-i.buffer2index-1;s=i.buffer1index,o=i.buffer2index,(a||c)&&r.push({buffer1:[s+1,a],buffer1Content:t.slice(s+1,s+1+a),buffer2:[o+1,c],buffer2Content:e.slice(o+1,o+1+c)})}return r.reverse(),r}function Xf(t,e,n){let r=[];function s(c,l){r.push({ab:l,oStart:c.buffer1[0],oLength:c.buffer1[1],abStart:c.buffer2[0],abLength:c.buffer2[1]})}Qa(e,t).forEach(c=>s(c,"a")),Qa(e,n).forEach(c=>s(c,"b")),r.sort((c,l)=>c.oStart-l.oStart);let o=[],i=0;function a(c){c>i&&(o.push({stable:!0,buffer:"o",bufferStart:i,bufferLength:c-i,bufferContent:e.slice(i,c)}),i=c)}for(;r.length;){let c=r.shift(),l=c.oStart,u=c.oStart+c.oLength,d=[c];for(a(l);r.length;){let g=r[0],h=g.oStart;if(h>u)break;u=Math.max(u,h+g.oLength),d.push(r.shift())}if(d.length===1){if(c.abLength>0){let g=c.ab==="a"?t:n;o.push({stable:!0,buffer:c.ab,bufferStart:c.abStart,bufferLength:c.abLength,bufferContent:g.slice(c.abStart,c.abStart+c.abLength)})}}else{let g={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;d.length;){c=d.shift();let v=c.oStart,$=v+c.oLength,R=c.abStart,O=R+c.abLength,w=g[c.ab];w[0]=Math.min(R,w[0]),w[1]=Math.max(O,w[1]),w[2]=Math.min(v,w[2]),w[3]=Math.max($,w[3])}let h=g.a[0]+(l-g.a[2]),m=g.a[1]+(u-g.a[3]),y=g.b[0]+(l-g.b[2]),p=g.b[1]+(u-g.b[3]),b={stable:!1,aStart:h,aLength:m-h,aContent:t.slice(h,m),oStart:l,oLength:u-l,oContent:e.slice(l,u),bStart:y,bLength:p-y,bContent:n.slice(y,p)};o.push(b)}i=u}return a(e.length),o}function ec(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 o=[],i=Xf(t,e,n),a=[];function c(){a.length&&o.push({ok:a}),a=[]}function l(u,d){if(u.length!==d.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==d[g])return!1;return!0}return i.forEach(u=>{u.stable?a.push(...u.bufferContent):r.excludeFalseConflicts&&l(u.aContent,u.bContent)?a.push(...u.aContent):(c(),o.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),c(),o}function Hr(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),s=n<0?t:t.slice(n+1),o=s.lastIndexOf("."),i=o>0?s.slice(0,o):s,a=o>0?s.slice(o):"",c=u=>String(u).padStart(2,"0"),l=`${e.getFullYear()}-${c(e.getMonth()+1)}-${c(e.getDate())} ${c(e.getHours())}${c(e.getMinutes())}`;return`${r}${i} (conflict ${l})${a}`}function Zf(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),s=r?t.slice(0,n):t,o=r?t.slice(n):"";return`${s}-${e}${o}`}function Qf(t){let e=3735928559,n=1103547991;for(let s=0;s<t.length;s++){let o=t.charCodeAt(s);e=Math.imul(e^o,2654435761),n=Math.imul(n^o,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)}`}function zr(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?n.seq===e.seq?{kind:"pushDelete"}:{kind:"pull"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"conflict"};let r=t!==e.hash,s=n.seq!==e.seq;return!r&&!s?{kind:"none"}:r?s?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function tc(t,e,n){let r=ec(t.split(`
|
|
209
|
+
`}}function Qo(t,e){let n=t.filter(([a])=>e-a<=3e3);if(n.length<2)return 0;let[r,o]=n[0],[s,i]=n[n.length-1];return s>r?Math.max(0,(i-o)/(s-r)*1e3):0}function es(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 Pf=3,ns=6e4,Mf=200,$f=Fa;function Va(t,e,n,r){let{head:o,tail:s}=za(t,e,n,r);return{head:Buffer.from(o,"utf8"),tail:Buffer.from(s,"utf8")}}function Nf(t,e,n,r,o,s,i,a){return new Promise((c,l)=>{let u=new URL(t),d=(u.protocol==="https:"?If:Tf)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+o+s.length)}},h=>{let m=[];h.on("data",y=>m.push(y)),h.on("end",()=>{let y=null;try{y=JSON.parse(Buffer.concat(m).toString("utf8"))}catch{}c({status:h.statusCode??0,body:y})}),h.on("error",l)}),g=()=>{d.destroy(new Error("aborted"))};if(a.aborted)return g();a.addEventListener("abort",g,{once:!0}),d.setTimeout(ns,()=>d.destroy(new Error("timeout"))),d.on("error",h=>{a.removeEventListener("abort",g),l(h)}),(async()=>{try{d.write(n);let h=0;for await(let m of Sf(r)){let y=m;if(h+=y.length,h>o)throw new Error("changed");d.write(y)||await new Promise(p=>d.once("drain",p)),i(h)}if(h!==o)throw new Error("changed");d.end(s)}catch(h){d.destroy(h)}})()})}function rs(t,e={}){let n=e.downloadsDir??(()=>Nn(Rf(),"Downloads")),r=e.post??Nf,o=e.now??Date.now,s=[],i=new Map,a=Promise.resolve(),c=async()=>{let w=await t.getCloud(),x=typeof t.accountId=="function"?t.accountId():null;return{...w,account:x||`${w.base}|${w.token}`}},l=w=>{let{account:x,attempt:C,relDir:D,abort:F,samples:P,dl:V,...Z}=w;return{...Z,speed:w.state==="active"?Qo(P,o()):0}},u=(w,x,C=null)=>{w.state=x,w.error=C,w.abort=null,w.finishedAt=o(),w.samples=[];let D=s.filter(F=>F.state==="done"||F.state==="canceled");for(let F of D.slice(0,Math.max(0,D.length-Mf)))s.splice(s.indexOf(F),1);d()};function d(){for(let w of["up","down"]){let x=s.filter(C=>C.kind===w&&C.state==="active").length;for(let C of s){if(x>=Pf)break;if(C.kind!==w||C.state!=="queued")continue;x++,C.state="active",C.startedAt=o(),C.done=0,C.samples=[[o(),0]],C.abort=new AbortController;let D=++C.attempt,F=()=>C.attempt===D&&C.state==="active";(w==="up"?b(C,F):$(C,F)).catch(P=>{F()&&u(C,"failed",g(P))})}}}let g=w=>{let x=String(w?.message||w);return x==="changed"||x==="too_large"||x==="quota"||x==="account_changed"||x==="not_signed_in"||x.startsWith("http_")||x==="bad_response"||x==="gone"?x:"network"},h=(w,x)=>{w.done=x;let C=o(),D=w.samples[w.samples.length-1];for((!D||C-D[0]>=200)&&w.samples.push([C,x]);w.samples.length>2&&C-w.samples[0][0]>3500;)w.samples.shift()};async function m(w){let x=await c();if(x.account!==w.account)throw new Error("account_changed");if(!x.token)throw new Error("not_signed_in");return x}async function y(w,x,C,D){let F=yt(w,C);if(!F)throw new Error("bad_path");let P=await fetch(F,{method:D.method??"GET",headers:{Authorization:`Bearer ${x}`,...D.body!==void 0?{"Content-Type":"application/json"}:{},...D.projectSource?{"X-Project-Source":D.projectSource}:{}},body:D.body!==void 0?JSON.stringify(D.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:P.status,json:await P.json().catch(()=>null)}}function p(w,x,C){if(!w.relDir.length)return Promise.resolve(w.targetId);let D=i.get(w.batch);D||i.set(w.batch,D=new Map);let F=D,P=V=>{if(V===0)return Promise.resolve(w.targetId);let Z=w.relDir.slice(0,V).join("/"),Q=F.get(Z);return Q||(Q=P(V-1).then(async ee=>{let re=w.relDir[V-1],oe=await y(x,C,"/files",{method:"POST",body:{type:"directory",parentId:ee,name:re},projectSource:w.projectSource});if(oe.status===201&&typeof oe.json?.id=="string")return oe.json.id;if(oe.status===409){let pe=await y(x,C,`/files${ee==="ROOT"?"":`?parentId=${encodeURIComponent(ee)}`}`,{projectSource:w.projectSource}),ie=Array.isArray(pe.json)?pe.json.find(xe=>xe?.fileType==="directory"&&xe?.name===re):null;if(ie?.id)return String(ie.id)}throw new Error(oe.status===401?"not_signed_in":`http_${oe.status}`)}),Q.catch(()=>F.delete(Z)),F.set(Z,Q)),Q};return P(w.relDir.length)}async function b(w,x){let{base:C,token:D}=await m(w),F=await qa(w.localPath).catch(()=>null);if(!F?.isFile())throw new Error("gone");if(F.size>52428800)throw new Error("too_large");w.size=F.size;let P=await p(w,C,D);if(!x())return;w.parentId=P;let V=yt(C,"/files/upload");if(!V)throw new Error("bad_path");let Z=`----penzor${Lr().replace(/-/g,"")}`,{head:Q,tail:ee}=Va(Z,{parentId:P,autoRename:"true"},w.name,Ha(w.name)),re=await r(V,{Authorization:`Bearer ${D}`,"Content-Type":`multipart/form-data; boundary=${Z}`,...w.projectSource?{"X-Project-Source":w.projectSource}:{}},Q,w.localPath,F.size,ee,oe=>{x()&&h(w,oe)},w.abort.signal);x()&&(re.status===201||re.status===200?(w.fileId=typeof re.body?.id=="string"?re.body.id:null,h(w,w.size),u(w,"done")):u(w,"failed",es(re.status,re.body)))}function v(w,x,C,D){let F=async()=>{let V=Df(C),Z=V?C.slice(0,-V.length):C;for(let Q=0;Q<1e3;Q++){if(!D())throw new Error("aborted");let ee=Nn(x,Q===0?C:`${Z} (${Q})${V}`);try{await kf(w,ee)}catch(re){let oe=re.code;if(oe==="EEXIST")continue;if(oe!=="EPERM"&&oe!=="ENOTSUP"&&oe!=="EOPNOTSUPP"&&oe!=="ENOSYS"&&oe!=="EXDEV")throw re;if(await vf(ee).then(()=>!0,()=>!1))continue;await Af(w,ee)}if(!D())throw await ts(ee).catch(()=>{}),new Error("aborted");return await ts(w).catch(()=>{}),ee}throw new Error("too many duplicates")},P=a.then(F,F);return a=P.catch(()=>{}),P}async function $(w,x){let C=w.dl,{base:D,token:F}=await m(w);if(!x())return;let P=yt(D,C.path);if(!P)throw new Error("bad_path");let V=w.abort.signal,Z=C.subdir?Nn(n(),C.subdir):n();await _f(Z,{recursive:!0});let Q=Nn(Z,`.${w.id}-${w.attempt}.penzor-part`),ee=await Cf(Q,"wx"),re=!1;try{let oe=new AbortController,pe=setTimeout(()=>oe.abort(),ns),ie=()=>{clearTimeout(pe),pe=setTimeout(()=>oe.abort(),ns)},xe=AbortSignal.any([V,oe.signal]);try{let ye=await fetch(P,{headers:{Authorization:`Bearer ${F}`},signal:xe});if(!ye.ok)throw new Error(ye.status===401?"not_signed_in":`http_${ye.status}`);let Re=ye.body,$e=Number(ye.headers.get("content-length"))||w.size;if(C.mode!=="bytes"){let Ae=await ye.json().catch(()=>null);if(C.mode==="text"){if(typeof Ae?.content!="string")throw new Error("bad_response");let H=Buffer.from(Ae.content,"utf8");await ee.writeFile(H),w.size=H.length,h(w,H.length),Re=null}else{if(typeof Ae?.url!="string"||!/^https?:\/\//i.test(Ae.url))throw new Error("bad_response");let H=await fetch(Ae.url,{signal:xe});if(!H.ok)throw new Error(`http_${H.status}`);Re=H.body,$e=Number(H.headers.get("content-length"))||w.size}}if(Re){w.size=$e;let Ae=0;for await(let H of Re){ie();for(let Y=0;Y<H.length;){let{bytesWritten:E}=await ee.write(H,Y,H.length-Y);if(E<=0)throw new Error("short_write");Y+=E}if(Ae+=H.length,!x())throw new Error("aborted");h(w,Ae)}Ae>w.size&&(w.size=Ae)}}finally{clearTimeout(pe)}if(await ee.close(),!x()||(w.localPath=await v(Q,Z,C.name,x),re=!0,!x()))return;u(w,"done")}finally{re||(await ee.close().catch(()=>{}),await ts(Q).catch(()=>{}))}}let R=(w,x)=>{let C={...w,id:Lr(),attempt:0,done:0,state:x?"failed":"queued",error:x??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:x?o():null};return s.push(C),C};async function O(w){let x=[],C=async(D,F)=>{if(F.length>32)return!0;let P=await(F.length?Ef(D):qa(D)).catch(()=>null);if(!P)return!0;if(P.isFile())return x.push({path:D,size:P.size,relDir:F}),x.length<=2e3;if(!P.isDirectory())return!0;let V=(await xf(D).catch(()=>[])).filter(Z=>!Z.startsWith(".")).sort();for(let Z of V)if(!await C(Nn(D,Z),[...F,Wa(D)]))return!1;return!0};for(let D of w)if(!await C(D,[]))return"too_many";return x}return t.handle("penzor:device",w=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let x=$r();return{ok:!0,name:x?decodeURIComponent(x):null}}),t.handle("penzor:upload",async(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x??{},D=Array.isArray(C.paths)?C.paths.filter(ie=>typeof ie=="string"&&Of(ie)):[],F=typeof C.parentId=="string"&&La.test(C.parentId)?C.parentId:null,P=typeof C.projectSource=="string"&&Ua.test(C.projectSource)?C.projectSource:null;if(!D.length)return{ok:!1,error:"no_files"};if(!F||!P)return{ok:!1,error:"bad_target"};let{base:V,token:Z,account:Q}=await c();if(!Z)return{ok:!1,error:"not_signed_in"};let ee=await O(D);if(ee==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!ee.length)return{ok:!1,error:"no_files"};let re=ee.filter(ie=>ie.size<=52428800).reduce((ie,xe)=>ie+xe.size,0);try{let ie=await y(V,Z,"/storage/quota",{}),xe=Number(ie.json?.used),ye=Number(ie.json?.quota);if(ie.status===200&&ye>0&&xe+re>ye)return{ok:!1,error:"quota",short:xe+re-ye}}catch{}if((await c()).account!==Q)return{ok:!1,error:"account_changed"};let oe=Lr(),pe=ee.map(ie=>R({kind:"up",name:Wa(ie.path),size:ie.size,projectSource:P,parentId:ie.relDir.length?null:F,targetId:F,fileId:null,localPath:ie.path,batch:oe,account:Q,relDir:ie.relDir},ie.size>52428800?"too_large":void 0).id);return d(),{ok:!0,ids:pe,batch:oe}}),t.handle("penzor:download",async(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x??{},D=$f.includes(C.mode)?C.mode:null,F=Fr(C.name);if(!D)return{ok:!1,error:"bad_mode"};if(!F)return{ok:!1,error:"bad_name"};let{base:P,token:V,account:Z}=await c();if(typeof C.path!="string"||!yt(P,C.path))return{ok:!1,error:"bad_path"};if(!V)return{ok:!1,error:"not_signed_in"};let Q=C.subdir==null?null:Fr(C.subdir),ee=R({kind:"down",name:F,size:Math.max(0,Number(C.size)||0),localPath:null,batch:typeof C.batch=="string"&&C.batch.length<=64?C.batch:Lr(),account:Z,relDir:[],dl:{path:C.path,mode:D,name:F,subdir:Q}});return d(),{ok:!0,id:ee.id}}),t.handle("penzor:transfers",w=>t.isTrustedSender(w)?{ok:!0,items:s.map(l)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x??{},D=s.find(P=>P.id===C.id);if(!D)return{ok:!1,error:"not_found"};let F=()=>{D.abort?.abort(),D.abort=null,D.done=0,D.samples=[]};switch(C.op){case"pause":(D.state==="active"||D.state==="queued")&&(F(),D.state="paused",d());break;case"resume":D.state==="paused"&&(D.state="queued",d());break;case"cancel":(D.state==="active"||D.state==="queued"||D.state==="paused")&&(F(),u(D,"canceled"));break;case"retry":(D.state==="failed"||D.state==="canceled")&&(D.state="queued",D.error=null,D.finishedAt=null,D.done=0,d());break;case"dismiss":D.state!=="active"&&D.state!=="queued"&&s.splice(s.indexOf(D),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(w,x)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=x?.which==="all";for(let D of[...s])(D.state==="done"||D.state==="canceled"||C&&D.state==="failed")&&s.splice(s.indexOf(D),1);return{ok:!0}}),t.addQuitGuard?.(w=>{let x=s.filter(C=>C.state==="active"||C.state==="queued"||C.state==="paused").length;return x?w==="zh"?{message:`\u8FD8\u6709 ${x} \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:x===1?"1 file hasn't finished transferring":`${x} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>s.map(l)}}import{readFileSync as qf,writeFileSync as Wf,mkdirSync as Vf,chmodSync as Yf,renameSync as Gf}from"node:fs";import{join as Jf}from"node:path";import{mkdirSync as jf,readFileSync as Ff,renameSync as Lf,unlinkSync as Uf,writeFileSync as Hf}from"node:fs";import{dirname as zf,join as Bf}from"node:path";import{randomUUID as Ya}from"node:crypto";var as=t=>Bf(t,"content-sync","active-account.json"),os=()=>Error("Invalid content sync account binding; original data was retained");function jn(t){try{let e=JSON.parse(Ff(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 os();return e}catch(e){if(e?.code==="ENOENT")return null;throw os()}}function cs(t,e){jf(zf(t),{recursive:!0,mode:448});let n=t+".tmp-"+Ya();try{Hf(n,JSON.stringify(e),{flag:"wx",mode:384}),Lf(n,t)}finally{try{Uf(n)}catch{}}}var ss=new WeakMap,is=new WeakSet;function Ga(t,e){let n=ss.get(t);return n||ss.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function ls(t){if(is.has(t))throw os()}function nn(t,e,n){if(!t.contentSync||e===n)return;let r=as(t.homeDir());try{let o=jn(r);cs(r,{version:1,account:o?.account??null,epoch:Ya(),pending:!0}),is.delete(t)}catch(o){throw is.add(t),o}finally{for(let o of ss.get(t)??[])o()}}function Kf(t){let e=()=>Jf(t(),"auth-accounts.json");return{read:()=>qf(e(),"utf8"),write:n=>{Vf(t(),{recursive:!0});let r=`${e()}.tmp`;Wf(r,n,{encoding:"utf8",mode:384}),Yf(r,384),Gf(r,e())}}}var Ka=t=>qi(t,Kf(()=>t.homeDir())),Xa=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],us=t=>Xa.every(e=>typeof t[e]=="function");function ds(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=Ka(t),o=0,s=()=>{let c=t.readCreds();return In(c.cloudUrl,c.token)},i=c=>Ne(c.cloudUrl??"",c.token??""),a=null;t.handle("auth:status",async c=>{if(!t.isTrustedSender(c))return n;let l=o,u=s(),{base:d}=await t.getCloud(),g=t.readCreds().token,h=g?await Mn(d,g):null,m=await t.accountBackendState(),{base:y}=await t.getCloud(),p=t.readCreds(),b=In(y,p.token)!==In(d,g),v=In(d,g);!b&&h?.status==="ok"&&h.user&&(a={key:v,user:h.user},r.rememberForsionAccount({...p,cloudUrl:d},h.user));let $=b?void 0:h?.status==="ok"?h.user:h?.status==="offline"&&a?.key===v?a.user:void 0;if(b)return{loggedIn:!!p.token,tokenValid:null,cloudUrl:y,accountId:Ne(y,p.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:p.token?"tangu-login":null,backendState:m};if(h?.status==="expired"){await t.accountTransition(async()=>{if(l!==o||s()!==u)return;let O=()=>{if(l!==o||s()!==u)throw Ja};try{await t.accountClear(O,()=>{nn(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()),a=null})}catch(w){if(w!==Ja)throw w}});let R=t.readCreds();return{loggedIn:!!R.token,tokenValid:null,cloudUrl:R.cloudUrl||d,accountId:Ne(R.cloudUrl||d,R.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:R.token?"tangu-login":null,backendState:m}}return{loggedIn:!!g,tokenValid:h&&h.status==="ok"?!0:null,cloudUrl:d,accountId:Ne(d,g),username:$?.username||null,nickname:$?.nickname||null,avatar:$?.avatar||null,membershipTier:$?.membershipTier||null,tokenSource:g?"tangu-login":null,backendState:m}}),t.handle("auth:accounts",c=>t.isTrustedSender(c)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(c,l)=>{if(!t.isTrustedSender(c))return e;if(typeof l!="string")throw new Error("Invalid account.");let u=++o;return r.cancelForsionLogin(),t.accountTransition(async()=>{let d=r.savedForsionAccount(l);return await t.accountCommit(d,()=>{if(u!==o)throw new Error("Account switch cancelled.")},()=>{nn(t,t.accountId?.()??null,i(d)),r.rememberForsionAccount(d),a=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(c,l)=>{if(!t.isTrustedSender(c))return e;let u=++o;r.cancelForsionLogin();let{base:d}=await t.getCloud();if(u!==o)throw new Error("Sign-in cancelled.");let g=(l||d||"").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.")},()=>{nn(t,t.accountId?.()??null,i(m)),r.rememberForsionAccount(m),a=null})))).cloudUrl}}),t.handle("auth:logout",async c=>t.isTrustedSender(c)?(++o,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:l}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{nn(t,t.accountId?.()??null,null),r.forgetForsionAccount(u),a=null,l&&u.token&&fetch(`${l}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${u.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:c,current:l})=>{try{nn(t,i(c),i(l))}catch{t.log("[content-sync] account transition could not be recorded; sync is stopped")}++o,r.cancelForsionLogin(),c.token&&!l.token&&r.forgetForsionAccount(c),a=null,r.rememberForsionAccount(l)}),t.setTokenRefresher(async c=>{let l=o,u=s(),d=t.readCreds().token;if(!_r(d))return;let{base:g}=await t.getCloud(),h=await Cr(g,d,c,`desktop/${t.appVersion()}`);if(!h){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}l!==o||s()!==u||(r.rememberForsionAccount({cloudUrl:g,token:h}),t.writeCreds({cloudUrl:g,token:h}),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 Ja=Symbol("stale-auth-intent");import{promises as ln}from"node:fs";import zt from"node:path";import{execFile as xp}from"node:child_process";import Ap from"node:os";var fs=null;function Za(t){fs=t}function Be(){if(!fs)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return fs}var je=()=>Be().accountId();function Fn(t=je()){return t?_e().sha256Hex(t):"signed-out"}var Ye=(t=je())=>Be().readConfig(t),wt=(t,e=je())=>Be().writeConfig(t,e),rn=(t,e=je())=>Be().updateConfig(t,e),At=(t=je())=>Be().cloudVaultDir(t),Ur=t=>Be().isManagedCloudVault(t);function Xf(t,e){let n=Object.create(null);for(let s=0;s<e.length;s++){let i=e[s];n[i]?n[i].push(s):n[i]=[s]}let o=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let s=0;s<t.length;s++){let i=t[s],a=n[i]||[],c=0,l=o[0];for(let u of a){let d;for(d=c;d<o.length&&!(o[d].buffer2index<u&&(d===o.length-1||o[d+1].buffer2index>u));d++);if(d<o.length){let g={buffer1index:s,buffer2index:u,chain:o[d]};if(c===o.length?o.push(l):o[c]=l,c=d+1,l=g,c===o.length)break}}o[c]=l}return o[o.length-1]}function Qa(t,e){let n=Xf(t,e),r=[],o=t.length,s=e.length;for(let i=n;i!==null;i=i.chain){let a=o-i.buffer1index-1,c=s-i.buffer2index-1;o=i.buffer1index,s=i.buffer2index,(a||c)&&r.push({buffer1:[o+1,a],buffer1Content:t.slice(o+1,o+1+a),buffer2:[s+1,c],buffer2Content:e.slice(s+1,s+1+c)})}return r.reverse(),r}function Zf(t,e,n){let r=[];function o(c,l){r.push({ab:l,oStart:c.buffer1[0],oLength:c.buffer1[1],abStart:c.buffer2[0],abLength:c.buffer2[1]})}Qa(e,t).forEach(c=>o(c,"a")),Qa(e,n).forEach(c=>o(c,"b")),r.sort((c,l)=>c.oStart-l.oStart);let s=[],i=0;function a(c){c>i&&(s.push({stable:!0,buffer:"o",bufferStart:i,bufferLength:c-i,bufferContent:e.slice(i,c)}),i=c)}for(;r.length;){let c=r.shift(),l=c.oStart,u=c.oStart+c.oLength,d=[c];for(a(l);r.length;){let g=r[0],h=g.oStart;if(h>u)break;u=Math.max(u,h+g.oLength),d.push(r.shift())}if(d.length===1){if(c.abLength>0){let g=c.ab==="a"?t:n;s.push({stable:!0,buffer:c.ab,bufferStart:c.abStart,bufferLength:c.abLength,bufferContent:g.slice(c.abStart,c.abStart+c.abLength)})}}else{let g={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;d.length;){c=d.shift();let v=c.oStart,$=v+c.oLength,R=c.abStart,O=R+c.abLength,w=g[c.ab];w[0]=Math.min(R,w[0]),w[1]=Math.max(O,w[1]),w[2]=Math.min(v,w[2]),w[3]=Math.max($,w[3])}let h=g.a[0]+(l-g.a[2]),m=g.a[1]+(u-g.a[3]),y=g.b[0]+(l-g.b[2]),p=g.b[1]+(u-g.b[3]),b={stable:!1,aStart:h,aLength:m-h,aContent:t.slice(h,m),oStart:l,oLength:u-l,oContent:e.slice(l,u),bStart:y,bLength:p-y,bContent:n.slice(y,p)};s.push(b)}i=u}return a(e.length),s}function ec(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=[],i=Zf(t,e,n),a=[];function c(){a.length&&s.push({ok:a}),a=[]}function l(u,d){if(u.length!==d.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==d[g])return!1;return!0}return i.forEach(u=>{u.stable?a.push(...u.bufferContent):r.excludeFalseConflicts&&l(u.aContent,u.bContent)?a.push(...u.aContent):(c(),s.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),c(),s}function Hr(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("."),i=s>0?o.slice(0,s):o,a=s>0?o.slice(s):"",c=u=>String(u).padStart(2,"0"),l=`${e.getFullYear()}-${c(e.getMonth()+1)}-${c(e.getDate())} ${c(e.getHours())}${c(e.getMinutes())}`;return`${r}${i} (conflict ${l})${a}`}function Qf(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 ep(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)}`}function zr(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?n.seq===e.seq?{kind:"pushDelete"}:{kind:"pull"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"conflict"};let r=t!==e.hash,o=n.seq!==e.seq;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 tc(t,e,n){let r=ec(t.split(`
|
|
210
210
|
`),e.split(`
|
|
211
211
|
`),n.split(`
|
|
212
|
-
`),{excludeFalseConflicts:!0}),
|
|
213
|
-
`)}function
|
|
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 ps(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var nc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function rc(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function oc(t,e){if(t==="offline")return"errOffline";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 Br(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 qr(t){let e=null;return{error(n){n!==e&&(e=n,t?.(n))},ok(){e=null}}}var tp=/[\u0000-\u001f\u007f]/;function Tt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||tp.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function hs(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Tt(n):n.startsWith(`${e}/`)?Tt(n.slice(e.length+1)):null}function sc(t,e){return e===""?t:`${e}/${t}`}function Ln(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Ze(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var It=t=>t==="page"||t==="db";var np=1024,Ce=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},ic=t=>12e4+Math.ceil(t/256);function rp(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 ac(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=()=>t.getToken?.()??t.token,r=async(i,a)=>{let c=n();for(let l=0;;l++){let u={...a.headers,Authorization:`Bearer ${c}`},d=await fetch(i,{...a,headers:u});if(n(),d.status!==401||d.redirected)return d;let g=await d.text(),h=n();if(h===c||l>0)return new Response(g,{status:d.status,statusText:d.statusText,headers:d.headers});c=h}},o=async(i,a,c)=>{let l={Authorization:`Bearer ${t.token}`,...c?.headers};i!=="GET"&&(l["X-Amadeus-Client"]=t.clientId);let u;c?.json!==void 0?(l["Content-Type"]="application/json",u=JSON.stringify(c.json),u.length>=np&&(l["Content-Encoding"]="gzip",u=await zi(u))):c?.form&&(u=c.form);let d=await r(a,{method:i,headers:l,body:u,signal:rp(c?.timeoutMs??3e4,c?.signal)});if(!d.ok){let h=null;try{h=await d.json()}catch{}throw n(),new Ce(d.status,h,a)}let g=await d.json();return n(),g},s=i=>new URLSearchParams(i).toString();return{clientId:t.clientId,async listVaults(){return((await o("GET",`${e}/vaults`)).vaults??[]).map(a=>({id:String(a.id),name:String(a.name),lastChangeSeq:Number(a.lastChangeSeq??0)}))},async tree(i){let a=await o("GET",`${e}/vaults/${i}/tree`);if(!Array.isArray(a.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:a.folders??[],seq:Number(a.seq??0),maxFileBytes:Number.isInteger(a.maxFileBytes)&&a.maxFileBytes>0?a.maxFileBytes:void 0,entries:a.entries.map(c=>({path:String(c.path),kind:c.kind,seq:Number(c.seq??0),hash:c.hash??null,size:Number(c.size??0)}))}},async getFile(i,a){let c=await o("GET",`${e}/vaults/${i}/file?${s({path:a})}`);return{content:String(c.content??""),seq:Number(c.seq??0),hash:c.hash??null}},putFile(i,a,c,l,u=!1){return o("PUT",`${e}/vaults/${i}/file`,{json:{path:a,content:c,baseSeq:l,...u?{force:!0}:{}}})},async deleteFile(i,a,c,l){let u={path:a};c!==void 0&&(u.baseSeq=String(c)),await o("DELETE",`${e}/vaults/${i}/file?${s(u)}`,l?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(i,a,c){return o("POST",`${e}/vaults/${i}/move`,{json:{from:a,to:c}})},renameFolder(i,a,c){return o("POST",`${e}/vaults/${i}/folders/rename`,{json:{path:a,newName:c}})},moveFolder(i,a,c){return o("POST",`${e}/vaults/${i}/folders/move`,{json:{path:a,dest:c}})},async deleteFolder(i,a){await o("DELETE",`${e}/vaults/${i}/folders?${s({path:a})}`)},putBinary(i,a,c,l){let u=new FormData;return u.set("path",a),l?.ifAbsent&&u.set("ifAbsent","true"),l?.baseSeq!==void 0&&u.set("baseSeq",String(l.baseSeq)),u.set("file",new Blob([new Uint8Array(c)]),a.split("/").pop()||"file"),o("POST",`${e}/vaults/${i}/binary`,{form:u,timeoutMs:ic(c.length),signal:l?.signal})},async listVersions(i,a){return((await o("GET",`${e}/vaults/${i}/file/versions?${s({path:a})}`)).versions??[]).map(l=>({id:String(l.id),seq:Number(l.seq??0)}))},async getVersion(i,a){let c=await o("GET",`${e}/vaults/${i}/file/versions/${a}`);return String(c.content??"")},async getAsset(i,a,c){let l=new AbortController;c?.addEventListener("abort",()=>l.abort(c.reason),{once:!0});let u=()=>l.abort(new DOMException("Asset download timed out","TimeoutError")),d=setTimeout(u,12e4);try{let g=await r(`${e}/vaults/${i}/asset?${s({ref:a})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:l.signal});if(!g.ok)throw new Ce(g.redirected&&(g.status===401||g.status===403)?502:g.status,null,"asset:"+a);clearTimeout(d),d=setTimeout(u,ic(Number(g.headers.get("content-length"))||0));let h=new Uint8Array(await g.arrayBuffer());return n(),h}finally{clearTimeout(d)}},async changes(i,a){let c=await o("GET",`${e}/vaults/${i}/changes?${s({since:String(a)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function cc(t,e){let n=!1,r=0,o=null,s=null,i=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,a=l=>{if(n)return;o?.abort(),e.onDown(l);let u=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,s=setTimeout(()=>void c(),u)},c=async()=>{if(n)return;o=new AbortController;let l;try{if(l=await fetch(i(),{headers:{Authorization:`Bearer ${t.getToken?.()??t.token}`,Accept:"text/event-stream"},signal:o.signal}),n){await l.body?.cancel();return}t.getToken?.()}catch(p){a(p);return}if(!l.ok||!l.body){a(new Error(`sse http ${l.status}`));return}r=0,e.onOpen();let u=l.body.getReader(),d=new TextDecoder,g="",h="",m=[],y=()=>{if(t.getToken?.(),!m.length&&!h)return;let p=m.join(`
|
|
214
214
|
`),b=h||"message";h="",m=[];let v=null;try{v=p?JSON.parse(p):null}catch{return}b==="hello"?e.onHello(Number(v?.seq??0)):b==="change"?e.onChange(v):b==="reset"?e.onReset():b==="presence"?e.onPresence?.(v):b==="presence-roster"&&e.onPresenceRoster?.(v)};try{for(;;){let{done:p,value:b}=await u.read();if(p)break;for(g+=d.decode(b,{stream:!0});;){let v=g.indexOf(`
|
|
215
|
-
`);if(v<0)break;let $=g.slice(0,v).replace(/\r$/,"");if(g=g.slice(v+1),$==="")y();else{if($.startsWith(":"))continue;$.startsWith("event:")?h=$.slice(6).trim():$.startsWith("data:")&&m.push($.slice(5).replace(/^ /,""))}}}}catch(p){n||a(p);return}a(new Error("sse stream ended"))};return c(),{stop:()=>{n=!0,o&&clearTimeout(o),s?.abort()}}}var Un=t=>_e().path.join(Be().userDataDir(),Be().isDevMode()?`${t}.dev.json`:`${t}.json`),go=Un,sn=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wr=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Vr=t=>typeof t=="string"&&At(t)===t,lc=t=>typeof t=="string"&&t.length>0,rp=t=>sn(t)&&Wr(t.seq)&&lc(t.hash)&&Wr(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),sp=t=>sn(t)&&Vr(t.from)&&Vr(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||sn(t.hashes)&&Object.values(t.hashes).every(lc));async function mo(t){let e;try{e=await _e().fs.readFile(go(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(!sn(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Ut(n.rootIdentity)||!sn(n.files)||!Object.entries(n.files).every(([r,s])=>Vr(r)&&rp(s))||n.cursor!==void 0&&!Wr(n.cursor)||n.lastSyncAt!=null&&!Wr(n.lastSyncAt)||n.pending!==void 0&&(!sn(n.pending)||!Object.entries(n.pending).every(([r,s])=>Vr(r)&&(s==="local"||s==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(sp)))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(),s=null,o=()=>{if(!e)return r;let i=e,a=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let c=go(t),l=`${c}.tmp-${_e().tmpTag()}-${Date.now()}-0`;await _e().fs.writeFile(l,a,"utf8"),await _e().fs.rename(l,c),s=null}catch(c){e??=i,s=c}}),r};return{save(i){e=i,!n&&(n=setTimeout(()=>{n=null,o()},500))},async flush(i=!1){if(n&&(clearTimeout(n),n=null),await o(),i&&s)throw s}}}async function dc(t){try{await _e().fs.unlink(go(t))}catch{}}var op=5*1024*1024,ip=5*1024*1024,ap=3e4,cp=5e3,lp=5*6e4,up=2500,dp=3e3,fp=5,pp=256*1024,hp=5,fc=1024*1024,pc=200,gp=6e4,mp=50,yp=".sync-trash",It=t=>_e().sha256Hex(t);function Hn(t,e={localRoot:xt(),shadowName:`amadeus-sync-${Fn()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=f=>{let S=ho(f,"");if(!S)return null;for(let A of e.excludePrefixes??[])if(S===A.replace(/\/$/,"")||S.startsWith(A))return null;if(e.ignoreNames?.length&&S.split("/").some(A=>e.ignoreNames.includes(A)))return null;let k=e.serverDir?`${e.serverDir}/${S}`:S;return e.inScope&&!e.inScope(k,Ze(k))?null:k},r=f=>{let S;if(e.serverDir){if(!f.startsWith(`${e.serverDir}/`))return null;S=f.slice(e.serverDir.length+1)}else{for(let k of e.excludePrefixes??[])if(f.startsWith(k))return null;S=f}return S.split("/").some(k=>Ln(k)||!!e.ignoreNames?.includes(k))?null:S},s=(f,S)=>!e.inScope||e.inScope(f,S),o=e.accountId??je(),{fs:i,path:a,directoryIdentity:c}=_e(),l=f=>i.access(f).then(()=>!0,()=>!1),u=!1,d=0,g=Promise.resolve(),h=new Set,m="disabled",y=null,p=null,b=null,v=null,$=null,R=null,O=()=>{let f=t.loadCreds();if(!R||o!==je()||!f.token||f.cloudUrl?.replace(/\/+$/,"")!==R.cloudUrl.replace(/\/+$/,""))throw new Ce(401,{code:"ACCOUNT_CHANGED"},"sync-session");return f.token},w=null,x=0,C=new Map,D=null,j=uc(e.shadowName),P=new Map,V=!1,Z=!1,Q=[],ee=(f,S,k)=>{try{t.onHealth?.(f,S,k)}catch{}},re=qr(ee),se=0,pe=()=>{Z||ee("massDeleteGuard"),Z=!0},ie=()=>{p&&(p.pending=P.size?Object.fromEntries(P):void 0,j.save(p))},xe=()=>{Z=!1,Q.length=0},ye=()=>{if(Z)return!0;let f=Date.now();for(;Q.length&&f-Q[0]>gp;)Q.shift();return Q.length>=mp?(pe(),!0):!1},Re=[],$e=new Set,Ae=!1,H=null,Y=null,_=null,T=null,E=()=>{!u||T||(T=setTimeout(()=>{T=null,t.onStatus(Ft())},200))},I=(f,S)=>{let k=m;m=f,S!==void 0&&(y=S),q(k,f),E()},q=(f,S)=>{if(S==="syncing"&&f!=="syncing"&&(se=Date.now()),S==="idle"&&f==="syncing"&&(ee("cycles"),ee("cycleMsTotal",Math.max(0,Date.now()-se))),S==="idle"||S==="disabled"){re.ok();return}let k=sc(S,y);k&&re.error(k)},B=(f,S)=>{C.set(f,S),ee(rc(S),1,f)},M=(f,S=!1)=>{if(u){if(f.key){if($e.has(f.key))return;$e.add(f.key)}S?Re.unshift(f):Re.push(f),Se()}},L=new Map,J=f=>{if(!u)return;let S=(p?.files[f]?.size??0)>pp,k=(e.pushQuietMs??dp)*(S?hp:1),A=Date.now(),N=L.get(f);N&&clearTimeout(N.timer);let z=N?.since??A,W=Math.max(0,Math.min(k,z+k*fp-A)),F=setTimeout(()=>{L.delete(f),M({key:f,run:()=>Ee(f,!0)})},W);L.set(f,{timer:F,since:z}),E()},K=()=>{for(let{timer:f}of L.values())clearTimeout(f);L.clear()},X=f=>!(f instanceof Ce)||f.status>=500||f.status===0,te=f=>f instanceof Ce&&(f.status===401||f.status===403),de=(f,S)=>{B(f,S?.body?.code||`http ${S?.status}`),E()},Se=async()=>{if(!Ae){Ae=!0;try{for(;Re.length;){(m==="idle"||m==="starting")&&I("syncing");let f=Re.shift();f.key&&$e.delete(f.key);try{await f.run()}catch(S){if(!u)return;if(te(S)){Re.length=0,$e.clear(),Sr(),I("auth-required","login-expired");return}if(X(S)){M(f,!0),Sr(),I("offline",S?.message||"network error"),he();return}de(f.key??"(op)",S)}}u&&m==="syncing"&&(p&&(p.lastSyncAt=Date.now(),j.save(p)),I("idle",null))}finally{Ae=!1;for(let f of h)f();h.clear()}}},he=()=>{!u||H||(H=setTimeout(()=>{H=null,An()},ap))},ne=new Map,De=0,ge=null,jt=()=>!!Y||!!ge||!u,Ke=f=>f instanceof Ce&&f.status>=500||f?.name==="TimeoutError",vi=e.pushRetryMs??cp,Cn=(f,S)=>{(S||!ne.has(f))&&ne.set(f,S)},ki=(f,S,k)=>{B(f,S instanceof Ce?`http ${S.status}`:"timeout"),Cn(f,k),De=Math.min(De*2||vi,lp),Y=setTimeout(pr,De),E()},Ei=(f,S,k)=>{let A=new AbortController,N=S(A.signal).then(W=>()=>W,W=>()=>{throw W}),z={path:f,abort:A,after:[],settle:async()=>{let W=await N;if(ge===z){ge=null;try{await k(W)}catch(F){if(te(F)||X(F))throw F;de(f,F)}finally{for(let F of z.after)M(F);_i(f)}}}};ge=z,N.then(()=>M({run:z.settle}))},Jt=(f,S)=>{for(let[k,A]of[...ne])!A||!qe(k,f)||(ne.delete(k),C.delete(k),S!==null&&ne.set(S+k.slice(f.length),A));E()},pr=()=>{Y=null;let[f]=ne;if(f===void 0)return;let[S]=f;$e.delete(S),M({key:S,run:async()=>{if(ge?.path===S)return;let k=ne.get(S),A=!k&&ne.delete(S);(k||A)&&C.delete(S);try{k?await ot(S,k.seq):A&&await Ee(S,!0)}finally{A&&We(S)&&Cn(S),_i(S)}}})},_i=f=>{if(!jt())if(ne.has(f)){let S=ne.get(f);ne.delete(f),ne.set(f,S),Y=setTimeout(pr,De||vi)}else pr()},Oe=f=>{if(!w||!p)throw new Error("engine not bound");let S=r(f);if(S===null)throw new Error("path outside binding: "+f);let k=a.resolve(w,oc(S,p.folder)),A=a.relative(w,k);if(A.startsWith("..")||a.isAbsolute(A))throw new Error("path escapes vault: "+f);return k},hr=f=>({size:f,mtimeMs:-1}),Ci=async f=>{try{let S=await i.stat(f);return S.isFile()?{size:S.size,mtimeMs:Math.floor(S.mtimeMs)}:null}catch{return null}},Du=async f=>{if(!i.lstat||!w)return Ci(f);let S=a.relative(w,f).split(a.sep),k=w;for(let[A,N]of S.entries()){k=a.join(k,N);let z=await i.lstat(k).catch(W=>{if(W?.code==="ENOENT")return null;throw W});if(!z)return null;if(z.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(A===S.length-1&&z.isFile())return{size:z.size,mtimeMs:Math.floor(z.mtimeMs)};if(A===S.length-1||!z.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},Ou=0,xi=async(f,S,k,A)=>{await i.mkdir(a.dirname(f),{recursive:!0});let N=`${f}.tmp-${_e().tmpTag()}-${Date.now()}-${Ou++}`;await i.writeFile(N,S);let z=await Ci(N)??hr(As(S));if(!A())return await i.rm(N,{force:!0}),null;try{let W=_e().compareAndReplace;if(!W)throw new Error("Host does not support safe cloud download commits");return await W(N,f,k,A)?z:null}finally{await i.rm(N,{force:!0})}},Ai=async f=>{let S;try{S=await i.readdir(f,{withFileTypes:!0})}catch{return}for(let k of S)k.isDirectory()&&await Ai(a.join(f,k.name));try{await i.rmdir(f)}catch{}},kt=async f=>{let S=Oe(f),k=await Du(S);if(!await _t())throw Error("Cloud vault sync root is unavailable or changed");if(i.lstat&&!k)return null;let A;try{A=await i.readFile(S)}catch(z){if(z?.code!=="ENOENT")throw z;if(!await _t())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:Tt(Ze(f))?It(Ct(A)):It(A),size:k?.size??A.length,mtimeMs:k?.mtimeMs??-1,buf:A}},Et=async(f,S,k,A)=>{p&&(p.files[f]={seq:S,hash:k,size:A.size,mtimeMs:A.mtimeMs},j.save(p))},Xe=f=>{p&&f in p.files&&(delete p.files[f],j.save(p))},ot=async(f,S)=>{if(!v||!p||We(f))return;let k=ve,A=Ze(f);if(Tt(A)){let F;try{F=await v.getFile(p.vaultId,f),ee("downloads")}catch(G){if(G instanceof Ce&&G.status===404){await ks(f);return}throw G}await Ti(f,A,F.content,F.seq,F.hash??It(F.content),k);return}if(jt()){Cn(f,{seq:S}),E();return}let{vaultId:N}=p,z=v,W={seq:S};ne.set(f,W),Ei(f,F=>z.getAsset(N,f,F),async F=>{let G=ne.get(f)===W,U;try{U=F(),De=0,ee("downloads")}catch(oe){if(!G)return;if(ne.delete(f),oe instanceof Ce&&oe.status===404){B(f,"ASSET_404"),E();return}if(Ke(oe)){ki(f,oe,{seq:S});return}throw oe}G&&await Ti(f,A,U,S??0,It(U),k)}),E()},Ti=async(f,S,k,A,N,z)=>{if(!p)return;let W=async fe=>{await Et(f,A,N,fe),ne.get(f)&&(ne.delete(f),C.delete(f))},F=await kt(f);if(z!==ve||We(f))return;if(F&&F.hash===N){await W(F);return}let G=p.files[f];if(F&&G&&N===G.hash&&F.hash!==G.hash){await W(hr(G.size)),M({key:f,run:()=>Ee(f)});return}let U=F?It(F.buf):null;if(F&&(!G||F.hash!==G.hash)){if(G&&S==="page"&&typeof k=="string"&&await Pu(f,G,F,k,A,N,()=>z===ve&&!We(f))||z!==ve||We(f)||!await Mu(f,()=>z===ve&&!We(f)))return;U=null}let oe=await xi(Oe(f),k,U,()=>u&&z===ve&&!We(f));if(!oe){M({key:f,run:()=>Ee(f)});return}await W(oe)},Pu=async(f,S,k,A,N,z,W)=>{try{if(!v||!p||k.buf.length>fc||A.length>fc)return!1;let G=(await v.listVersions(p.vaultId,f)).find(fe=>fe.seq===S.seq);if(!G)return!1;let U=await v.getVersion(p.vaultId,G.id);if(It(U)!==S.hash)return!1;let oe=tc(Ct(k.buf),U,A);return oe===null?!1:await xi(Oe(f),oe,It(k.buf),()=>u&&W())?(await Et(f,N,z,hr(As(oe))),M({key:f,run:()=>Ee(f)}),!0):(M({key:f,run:()=>Ee(f)}),!0)}catch{return!1}},Mu=async(f,S)=>{let k=At(Hr(f,new Date));if(!k)return!0;let A=k.lastIndexOf("."),N=A>k.lastIndexOf("/"),z=N?k.slice(0,A):k,W=N?k.slice(A):"",F=k,G=_e().existsSync;if(G)for(let U=2;G(Oe(F));U++)F=`${z}-${U}${W}`;else for(let U=2;await l(Oe(F));U++)F=`${z}-${U}${W}`;if(!S())return!1;try{await i.rename(Oe(f),Oe(F))}catch(U){if(U?.code==="ENOENT")return!0;throw U}return x++,ee("conflicts"),M({key:F,run:()=>Ee(F)}),E(),!0},Ii=async f=>{if(!w)return;let S=Oe(f),k=r(f)??f,A=a.join(w,yp,new Date().toISOString().slice(0,10),...k.split("/")),N=await l(A)?`${A}.${Date.now()}`:A;try{await i.mkdir(a.dirname(N),{recursive:!0}),await i.rename(S,N)}catch(z){if(z?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${S}: ${z?.message??String(z)}`)}},ks=async f=>{if(!p)return;Jt(f,null);let S=await kt(f);if(We(f))return;let k=p.files[f]??null,A=zr(S?.hash??null,k,null);if(A.kind==="deleteLocal"){if(!V&&ye()){P.set(f,"local"),ie(),E();return}Q.push(Date.now()),await Ii(f),Xe(f)}else A.kind==="pushCreate"?(Xe(f),M({key:f,run:()=>Ee(f)})):Xe(f)},Ri=(f,S)=>{if(p){Jt(f,S);for(let k of Object.keys(p.files))if(k===f||k.startsWith(`${f}/`)){let A=S+k.slice(f.length);p.files[A]=p.files[k],delete p.files[k]}j.save(p)}},Di=async f=>{if(!v||!p||f.seq<=p.cursor||!await _t())return;if(f.origin.client&&v.clientId===f.origin.client){p.cursor=f.seq,j.save(p);return}let S=f.type==="structure"?"folder":f.type,k=N=>r(N)!==null&&s(N,S);if(!k(f.path)&&!(f.newPath&&k(f.newPath))){p.cursor=f.seq,j.save(p);return}let A=f.path;if(f.op!=="write"&&f.op!=="mkdir"){for(;ge&&(qe(ge.path,A)||f.newPath&&qe(ge.path,f.newPath));)await ge.settle();if(!u)return}switch(f.op){case"write":await ot(A,f.fileSeq);break;case"delete":await ks(A);break;case"move":{let N=f.newPath;if(!N)break;let z=p.files[A],W=await kt(A),F=!!ne.get(A);if(Jt(A,N),F&&Cn(N,{seq:f.fileSeq}),W&&z)try{await i.mkdir(a.dirname(Oe(N)),{recursive:!0}),await i.rename(Oe(A),Oe(N)),p.files[N]={...z,seq:F?z.seq:f.fileSeq??z.seq},delete p.files[A],j.save(p)}catch{await ot(N,f.fileSeq)}else Xe(A),await ot(N,f.fileSeq);break}case"mkdir":await i.mkdir(Oe(A),{recursive:!0});break;case"rename-folder":case"move-folder":{let N=f.newPath;if(!N)break;try{await i.mkdir(a.dirname(Oe(N)),{recursive:!0}),await i.rename(Oe(A),Oe(N))}catch{}Ri(A,N);break}case"delete-folder":{let N=`${A}/`;for(let z of Object.keys(p.files))(z===A||z.startsWith(N))&&await ks(z);Jt(A,null),await Ai(Oe(A));break}}if(p.cursor=f.seq,j.save(p),f.op==="move"||f.op==="rename-folder"||f.op==="move-folder"||f.op==="delete"||f.op==="delete-folder")try{await t.onRemoteApplied?.(f)}catch{}},$u=async(f,S,k)=>{let A=Number(S?.seq??0),N=S?.content??null;if(N!==null&&It(N)===k.hash){await Et(f,A,k.hash,k);return}if(N===null&&A===0){if(!p?.files[f]){B(f,S?.code||"EXISTS"),E();return}Xe(f),M({key:f,run:()=>Ee(f)});return}await ot(f,A)},gr=async(f,S)=>{if(!v||!p)return;let k=await kt(f);if(!k){M({key:f,run:()=>Ee(f)});return}if(k.size>op){B(f,"TOO_LARGE"),E();return}let A=Ct(k.buf);try{let N=await v.putFile(p.vaultId,f,A,S);ee("uploads"),C.delete(f),await Et(f,N.seq,N.hash??k.hash,k)}catch(N){if(N instanceof Ce&&N.status===409){await $u(f,N.body,k);return}throw N}},mr=async(f,S)=>{if(!v||!p)return;let k=await kt(f);if(!k){M({key:f,run:()=>Ee(f)});return}if(k.size>(D??ip)){B(f,"TOO_LARGE"),E();return}if(Cn(f),E(),jt())return;let{vaultId:A}=p,N=v;Ei(f,z=>N.putBinary(A,f,k.buf,{baseSeq:S,signal:z}),async z=>{if(p){ne.get(f)||ne.delete(f);try{let W=z();De=0,ee("uploads"),C.delete(f),await Et(f,W.seq,k.hash,k)}catch(W){if(Ke(W)){ki(f,W);return}if(!(W instanceof Ce)||W.status!==409)throw W;let F=Number(W.body?.seq??0),G=W.body?.hash??null;if(G!==null&&G===k.hash){await Et(f,F,k.hash,k);return}if(F===0){if(!p.files[f]){B(f,W.body?.code||"EXISTS"),E();return}Xe(f),M({key:f,run:()=>Ee(f)});return}await ot(f,F)}}})},Oi=async f=>{if(!v||!p||We(f))return;let S=ve,k=p.files[f];if(k){if(Tt(Ze(f)))try{let A=await v.getFile(p.vaultId,f);if(A.seq!==k.seq){await ot(f,A.seq);return}}catch(A){if(A instanceof Ce&&A.status===404){Xe(f);return}throw A}if(!(!await _t()||S!==ve||We(f))){try{await v.deleteFile(p.vaultId,f,k.seq,{confirmed:V})}catch(A){if(A instanceof Ce&&A.status===409){await ot(f,Number(A.body?.seq??0)||null);return}if(A instanceof Ce&&A.status===429&&A.body?.code==="MASS_DELETE_BLOCKED"){P.set(f,"remote"),pe(),ie(),E();return}throw A}Xe(f)}}},Es=f=>i.stat(f).catch(S=>{if(S?.code==="ENOENT")return null;throw S}),_s=f=>{let S=b??p?.rootIdentity,k=f!==null&&f.isDirectory();return k&&(!S||Ht(S,f))?!0:(I("error",`${k?"vault-changed":"vault-missing"}: ${w}`),he(),!1)},_t=async()=>!!w&&_s(await Es(w)),ve=0,yr=new Set,wr=new Map,He=f=>JSON.stringify([f.from,f.to]),qe=(f,S)=>f===S||f.startsWith(`${S}/`),We=f=>[...p?.moves??[],...yr].some(S=>qe(f,S.from)||qe(f,S.to)),ht=()=>!!(p?.moves?.length||yr.size),br=async f=>{if(!v||!p)return;let{from:S,to:k,kind:A}=f;if(r(S)===null||r(k)===null)throw new Error("Invalid queued cloud move");if(ge&&(qe(ge.path,S)||qe(ge.path,k))){ge.after.push({key:`move:${He(f)}`,run:()=>br(f)});return}f.hashes??=Object.fromEntries(Object.entries(p.files).filter(([F])=>qe(F,S)).map(([F,G])=>[F.slice(S.length),G.hash])),j.save(p),await j.flush(!0);let N,z=!1;try{if(A==="folder"){let F=a.posix.dirname(S)==="."?"":a.posix.dirname(S),G=a.posix.dirname(k)==="."?"":a.posix.dirname(k);F===G?await v.renameFolder(p.vaultId,S,a.posix.basename(k)):await v.moveFolder(p.vaultId,S,G)}else{let F=await v.move(p.vaultId,S,k);N=Number(F.seq)}}catch(F){if(!(F instanceof Ce)||F.status!==404)throw F;let G=await v.tree(p.vaultId);if(G.entries.some(fe=>qe(fe.path,S))||G.folders.some(fe=>qe(fe,S)))throw F;let oe=G.entries.find(fe=>fe.path===k);if(N=oe?.seq,z=!oe&&!G.entries.some(fe=>qe(fe.path,k))&&!G.folders.some(fe=>qe(fe,k)),!z){let fe=Object.entries(f.hashes);if(!(fe.length>0&&fe.every(([it,Xt])=>G.entries.some(Zt=>Zt.path===k+it&&Zt.hash===Xt))))throw new Ce(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(z){for(let F of Object.keys(p.files))qe(F,S)&&delete p.files[F];Jt(S,null)}else Ri(S,k),N!==void 0&&p.files[k]&&!ne.get(k)&&(p.files[k].seq=N);p.moves=(p.moves??[]).filter(F=>He(F)!==He(f)),j.save(p);try{await j.flush(!0)}catch(F){throw p.moves.unshift(f),j.save(p),F}let W=wr.get(He(f));wr.delete(He(f)),W?.(),We(k)||(A==="folder"?await Cs():await Ee(k))},Ee=async(f,S=!1)=>{if(!p||We(f))return;if(ge?.path===f){ge.after.push({key:f,run:()=>Ee(f,S)});return}if(!s(f,Ze(f))){Xe(f);return}if(!await _t())return;let k=await kt(f);if(We(f))return;let A=p.files[f]??null,N=zr(k?.hash??null,A,A?{seq:A.seq,hash:A.hash}:null);switch(N.kind){case"push":Tt(Ze(f))?await gr(f,N.baseSeq):await mr(f,N.baseSeq);break;case"pushCreate":Tt(Ze(f))?await gr(f,0):await mr(f,0);break;case"pushDelete":if(S){kr();break}if(!V&&(P.has(f)||ye())){P.set(f,"remote"),ie(),E();break}Q.push(Date.now()),await Oi(f);break;case"dropShadow":Xe(f);break;default:k&&A&&k.hash===A.hash&&k.mtimeMs>=0&&(A.size!==k.size||A.mtimeMs!==k.mtimeMs)&&await Et(f,A.seq,A.hash,k);break}},Pi=async()=>{let f=new Map;if(!w||!p)return f;let S=w,k=null,A=async N=>{if(k)return;let z;try{z=await i.readdir(N,{withFileTypes:!0})}catch(W){k=`${N}: ${W?.message??String(W)}`;return}for(let W of z){if(Ln(W.name)||W.isDirectory()&&e.ignoreNames?.includes(W.name))continue;let F=a.join(N,W.name);if(W.isDirectory())await A(F);else if(W.isFile()){let G=a.relative(S,F).split(a.sep).join("/"),U=n(G);if(!U)continue;try{let oe=await i.stat(F);if(!oe.isFile())continue;f.set(U,{size:oe.size,mtimeMs:Math.floor(oe.mtimeMs)})}catch(oe){if(oe?.code==="ENOENT")continue;k=`${F}: ${oe?.message??String(oe)}`;return}}}};return await A(S),k?(I("error",`scan-failed: ${k}`),he(),null):f},Cs=async()=>{let f=ve;if(ht()||f!==ve||!p||!await _t())return;let S=await Pi();if(!S||ht()||f!==ve)return;let k=!1;for(let[z,W]of[...P])(W==="remote"&&S.has(z)||W==="local"&&!S.has(z))&&(P.delete(z),k=!0);P.size||xe();for(let[z,W]of S){let F=p.files[z];F&&F.size===W.size&&F.mtimeMs===W.mtimeMs||M({key:z,run:()=>Ee(z)})}let A=Object.keys(p.files),N=A.filter(z=>!S.has(z));if(N.length&&!V&&(Z||po(N.length,A.length,pc))){pe();for(let z of N)P.set(z,"remote");ie(),E();return}k&&(ie(),E());for(let z of N)P.has(z)||M({key:z,run:()=>Ee(z)})},Kt=async()=>{if(ge){ge.after.push({run:Kt});return}let f=ve;if(ht()||f!==ve||!v||!p||!w||!await _t())return;let S=await v.tree(p.vaultId);if(S.maxFileBytes!==void 0&&S.maxFileBytes!==D&&(D=S.maxFileBytes,E()),ht()||f!==ve)return;let k=new Map;for(let U of S.entries)r(U.path)===null||!s(U.path,U.kind)||k.set(U.path,U);for(let[U,oe]of[...ne])oe&&!k.has(U)&&Jt(U,null);let A=await Pi();if(!A||ht()||f!==ve)return;let N=new Set([...k.keys(),...A.keys(),...Object.keys(p.files)]),z=Object.keys(p.files).length,W=[];for(let U of N){if(ht()||f!==ve)return;let oe=p.files[U]??null,fe=k.get(U)??null,Ue=A.get(U)??null,it=null,Xt=hr(Ue?.size??0);if(Ue)if(oe&&oe.size===Ue.size&&oe.mtimeMs===Ue.mtimeMs)it=oe.hash,Xt=Ue;else{let Zt=await kt(U);Zt&&(it=Zt.hash,Xt=Zt)}W.push({sp:U,d:zr(it,oe,fe?{seq:fe.seq,hash:fe.hash}:null),rSeq:fe?.seq??null,localHash:it,localStat:Xt})}if(ht()||f!==ve)return;let F=W.filter(U=>U.d.kind==="deleteLocal"||U.d.kind==="pushDelete").length,G=!V&&(Z||po(F,z,pc));G&&F&&pe(),P.clear();for(let{sp:U,d:oe,rSeq:fe,localHash:Ue,localStat:it}of W){if(ht()||f!==ve)return;if(G&&(oe.kind==="deleteLocal"||oe.kind==="pushDelete")){P.set(U,oe.kind==="deleteLocal"?"local":"remote");continue}if((oe.kind==="deleteLocal"||oe.kind==="pushDelete")&&((await kt(U))?.hash??null)!==Ue){M({key:U,run:()=>Ee(U)});continue}if(ht()||f!==ve)return;switch(oe.kind){case"adopt":await Et(U,fe,Ue,it);break;case"pull":await ot(U,fe);break;case"push":Tt(Ze(U))?await gr(U,oe.baseSeq):await mr(U,oe.baseSeq);break;case"pushCreate":Tt(Ze(U))?await gr(U,0):await mr(U,0);break;case"pushDelete":await Oi(U);break;case"deleteLocal":await Ii(U),Xe(U);break;case"conflict":await ot(U,fe);break;case"dropShadow":Xe(U);break;case"none":break}}V&&(V=!1,Q.length=0),P.size||xe(),ie(),G&&E();for(let U of S.folders)if(!(r(U)===null||!s(U,"folder")))try{await i.mkdir(Oe(U),{recursive:!0})}catch{}p.cursor=S.seq,p.lastSyncAt=Date.now(),j.save(p)},Nu=async()=>{if(!v||!p)return;let f=p.cursor,S=await v.changes(p.vaultId,f);if(S.changes.length===0&&S.seq>f||S.changes.length>0&&S.changes[0].seq!==f+1){await Kt();return}for(let A of S.changes)await Di(A)},xn=null,Mi=[],$i=()=>{xn&&Mi.push(xn.close()),xn=null},ju=()=>{if(!u||xn||!w)return;let f=_e();if(!f.watch)return;let S=k=>{if(!w)return;let A=a.relative(w,k);if(!A||A.startsWith(".."))return;let N=n(A);N&&J(N)};xn=f.watch(w,{depth:12,ignored:k=>{let A=a.basename(k);return Ln(A)||!!e.ignoreNames?.includes(A)}},{change:S,add:S,unlink:()=>kr(),unlinkDir:()=>kr()})},Sr=()=>{$?.stop(),$=null},Fu=()=>{if(!u||!v||!p||$)return;let f=R;f&&($=cc({baseUrl:f.cloudUrl,vaultId:p.vaultId,token:f.token,getToken:O},{getSince:()=>p?.cursor??0,onHello:S=>{p&&S>p.cursor&&M({run:Nu})},onChange:S=>{M({run:()=>Di(S)})},onReset:()=>{M({run:Kt})},onOpen:()=>{(m==="offline"||m==="starting")&&I("idle",null),M({run:Cs})},onDown:()=>{(m==="idle"||m==="syncing")&&I("offline")},onPresence:S=>t.onPresence?.(p?.vaultId??"",S),onPresenceRoster:S=>t.onPresenceRoster?.(p?.vaultId??"",S)}))},Lu=async()=>{let f=await Ye(o);if(f.cloudSync?.deviceId)return f.cloudSync.deviceId;let S=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await mt({cloudSync:{...f.cloudSync??{},deviceId:S}},o),S},Uu=async f=>{Sr(),$i(),b=null,Re.length=0,$e.clear(),P.clear(),V=!1,Z=!1,Q.length=0;let S=await Ye(o);if(f!==d)return;let k=S.cloudSync;if(k?.enabled===!1){w=null,v=null,I("disabled",null);return}if(!o||o!==je()){I("auth-required","not-logged-in");return}if(w=e.localRoot,e.requireRootExists){let W=await i.stat(w).then(F=>F.isDirectory()).catch(()=>!1);if(f!==d)return;if(!W){I("error",`vault-missing: ${w}`),he();return}}if(f!==d)return;let A=t.loadCreds();if(!A.cloudUrl||!A.token){v=null,I("auth-required","not-logged-in");return}I("starting",null);let N=k?.deviceId??await Lu();if(f!==d)return;let z=e.clientIdSuffix?`${N}#${e.clientIdSuffix}`:N;R={cloudUrl:A.cloudUrl,token:A.token},v=ac({baseUrl:A.cloudUrl,token:A.token,clientId:z,getToken:()=>{if(f!==d)throw new Ce(401,{code:"ACCOUNT_CHANGED"},"sync-session");return O()}});try{let W=e.vaultId==="first"?k?.vaultId:e.vaultId;if(!W){let U=await v.listVaults();if(f!==d)return;if(!U.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");W=U[0].id,await mt({cloudSync:{...k??{},vaultId:W}},o)}if(f!==d)return;let F=await mo(e.shadowName);if(f!==d||(p=F&&F.vaultRoot===w&&F.vaultId===W&&F.folder===""?F:{vaultRoot:w,folder:"",vaultId:W,cursor:0,lastSyncAt:null,files:{}},f!==d))return;for(let[U,oe]of Object.entries(p.pending??{}))P.set(U,oe);P.size&&(Z=!0);let G=await Es(w);if(f!==d||!G&&!e.requireRootExists&&!p.rootIdentity&&!Object.keys(p.files).length&&(await i.mkdir(w,{recursive:!0}),G=await Es(w),f!==d))return;if(!G?.isDirectory()){_s(G);return}if(typeof G.dev=="number"&&Number.isInteger(G.dev)&&G.dev>=0&&typeof G.ino=="number"&&Number.isInteger(G.ino)&&G.ino>0){let U=c?await c(w):{dev:G.dev,ino:G.ino,...G.birthtimeMs&&G.birthtimeMs>0?{birthtimeMs:G.birthtimeMs}:{}};if(f!==d)return;if(!Ut(U))throw Error("Invalid sync root identity; original state retained");if(!Ht(U,G)||p.rootIdentity&&!tn(p.rootIdentity,U)){I("error",`vault-changed: ${w}`),he();return}if(b=U,JSON.stringify(p.rootIdentity)!==JSON.stringify(U)&&(p.rootIdentity=U,j.save(p),await j.flush(!0)),f!==d||!await _t())return}else if(!_s(G))return;ju();for(let U of p.moves??[])M({key:`move:${He(U)}`,run:()=>br(U)});M({run:Kt}),M({run:async()=>{Fu()}})}catch(W){if(f!==d)return;te(W)?I("auth-required","login-expired"):(I("offline",W?.message||String(W)),he())}},Ni=()=>{u=!1,Sr(),$i(),Re.length=0,$e.clear(),K();for(let f of[H,Y,_,T])f&&clearTimeout(f);H=Y=_=T=null,ge?.abort.abort(),ge=null},ji=async()=>{Ae&&await new Promise(f=>h.add(f)),await Promise.all(Mi.splice(0)),await j.flush(),p=null,b=null,v=null,R=null,w=null,x=0,C.clear(),ne.clear(),De=0,D=null,P.clear(),V=!1,Z=!1,Q.length=0,m="disabled",y=null},Hu=()=>{Fi()},vr=null,An=()=>{vr?.(),vr=Be().onBeforeQuit(Hu);let f=++d;Ni();let S=g.catch(()=>{}).then(async()=>{await ji(),f===d&&(u=!0,await Uu(f))});return g=S,S},Fi=()=>{vr?.(),vr=null,++d,Ni();let f=g.catch(()=>{}).then(ji);return g=f,f},Ft=()=>({enabled:m!=="disabled",state:m==="idle"&&(L.size||ne.size)?"syncing":m,lastSyncAt:p?.lastSyncAt??null,pending:Re.length+L.size+ne.size,conflicts:x,skipped:[...C].map(([f,S])=>({path:f,reason:S})),error:y,pendingDeletions:P.size,maxFileBytes:D});return{getStatus:Ft,start(){An()},notifyLocal(f,S,k){if(!p||m==="disabled"||m==="auth-required")return;let A=n(f),N=k?n(k):null;if(S==="write"&&A){Ln(A.split("/").pop()||"")||J(A);return}if(S==="remove"){if(!A)return;let z=`${A}/`,W=!1;for(let F of Object.keys(p.files))(F===A||F.startsWith(z))&&(W=!0,M({key:F,run:()=>Ee(F)}));!W&&A&&M({key:A,run:()=>Ee(A)})}},holdLocalMove(f,S){let k=N=>e.serverDir?`${e.serverDir}/${N.replace(/\\/g,"/").normalize("NFC")}`:N.replace(/\\/g,"/").normalize("NFC"),A={from:k(f),to:k(S)};return++ve,yr.add(A),()=>{yr.delete(A)}},async notifyLocalMove(f,S,k,A){let N=n(f),z=n(S),W=p??await mo(e.shadowName),F=ho(f,""),G=F&&(e.serverDir?`${e.serverDir}/${F}`:F);if(!N&&z&&G&&W&&Object.keys(W.files).some(U=>U===G||U.startsWith(`${G}/`))&&(N=G),!N&&!z){k?.();return}if(N&&z){let U=p??W;if(!U){k?.();return}let oe=A??(Object.keys(U.files).some(Ue=>Ue.startsWith(`${N}/`))?"folder":"file"),fe={from:N,to:z,kind:oe};U.moves??=[],U.moves.some(Ue=>He(Ue)===He(fe))||(U.moves.push(fe),++ve),k&&wr.set(He(fe),k),j.save(U);try{await j.flush(!0)}catch(Ue){throw U.moves=U.moves.filter(it=>He(it)!==He(fe)),wr.delete(He(fe)),j.save(U),Ue}p===U&&u&&m!=="disabled"&&m!=="auth-required"&&M({key:`move:${He(fe)}`,run:()=>br(fe)});return}N&&this.notifyLocal(f,"remove"),z&&(M({key:z,run:()=>Ee(z)}),kr()),k?.()},async setEnabled(f){let S=await Ye(o);return await mt({cloudSync:{...S.cloudSync??{},enabled:f}},o),await An(),Ft()},async restart(){return await An(),Ft()},async syncNow(){if(C.clear(),m==="disabled"||m==="auth-required"||!v)await An();else{Y&&(clearTimeout(Y),pr());for(let f of p?.moves??[])M({key:`move:${He(f)}`,run:()=>br(f)});M({run:Kt})}return Ft()},confirmMassDeletions(){return P.size&&(V=!0,Z=!1,P.clear(),Q.length=0,ie(),M({run:Kt})),Ft()},stop:Fi};function kr(){u&&(_&&clearTimeout(_),_=setTimeout(()=>{_=null,M({run:Cs})},up))}}function yo(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 wo(t){return/\.md$/i.test(t)?yo(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function hc(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 wp=t=>_e().sha256Hex(t).slice(0,8),bp=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Yr="\u4E0E\u6211\u5171\u4EAB";function gc(t,e){let n=wp(`${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:`${Yr}/${bp(t.title)}-${n}`,serverDir:r,inScope:(s,o)=>e.some(i=>hc(i,s,o)),scopeKey:e.map(s=>s.root).join("\0")}}function mc(t){return gc(t,[yo(t.path),...(t.items??[]).map(wo)])}function yc(t){let e=t.map(mc),n=t.flatMap((s,o)=>{let i=e[o].serverDir?`${e[o].serverDir}/`:"";return(s.items??[]).filter(a=>!a.startsWith(i)).map(a=>gc({vaultId:s.vaultId,path:a,title:(a.split("/").pop()??a).replace(/\.md$/i,"")},[wo(a)]))}),r=new Map;for(let s of[...e,...n])r.has(s.key)||r.set(s.key,s);return[...r.values()]}var Sp=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 wc(t,e){let n=c=>c.normalize("NFC"),r=n(e.replace(/\\/g,"/")),s=t.find(c=>r.startsWith(`${n(c.localRelDir)}/`));if(!s)return null;let o=r.slice(n(s.localRelDir).length+1),i=Sp(s.serverDir?`${s.serverDir}/${o}`:o);if(!i||i===".."||i.startsWith("../"))return null;let a=[s,...t].find(c=>c.vaultId===s.vaultId&&(!c.serverDir||i.startsWith(`${c.serverDir}/`))&&c.inScope(i,Ze(i)));return a?`${a.localRelDir}/${a.serverDir?i.slice(a.serverDir.length+1):i}`:null}function bo(){let t=Be().readCreds(),e=Ne(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let d=Be().readCreds();if(n.signal.aborted||!e||Ne(d.cloudUrl??"",d.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return d},s=()=>{let d=r();if(!d.cloudUrl||!d.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return d.cloudUrl.replace(/\/+$/,"")},o=async(d,g,h)=>{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:d,headers:{Authorization:`Bearer ${m.token}`,...h!==void 0?{"Content-Type":"application/json"}:{}},body:h!==void 0?JSON.stringify(h):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!y.ok){let b=null;try{b=await y.json()}catch{}throw Object.assign(new Error(b?.detail||`http ${y.status}`),{status:y.status,code:b?.code})}let p=await y.json();return r(),p},i=null,a=async()=>(r(),i||(i=(await o("GET","/vaults")).vaults[0]?.id??"default",i)),c=()=>{try{let d=(r().token??"").split(".")[1],g=JSON.parse(Ct(Er(d)));return typeof g.userId=="string"?g.userId:null}catch{return null}},l=async()=>(await o("GET","/shared-with-me")).items.map(g=>{let h=mc(g),m=g.path.split("/").pop()??g.path;return{...g,localPath:`${h.localRelDir}/${m}`}}),u=null;return{stop:()=>n.abort(),call:o,ensureOwnVault:a,myUserId:c,sharedWithMe:l,linkBase:async()=>{if(r(),u)return u;try{u=((await o("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||s()}catch{u=s()}return u},async heartbeat(d,g){let h=(d??"").replace(/\\/g,"/"),m,y=null,p=g.find(b=>h.startsWith(`${b.localRelDir}/`));p?(m=p.vaultId,y=p.serverDir?`${p.serverDir}/${h.slice(p.localRelDir.length+1)}`:h.slice(p.localRelDir.length+1)):(m=await a(),y=h||null),await o("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:y})}}}import{promises as vc}from"node:fs";import vp from"node:path";var So=".forsion-vault.md",bc=t=>`${t}/${So}`;function Gr(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 Sc=t=>`---
|
|
215
|
+
`);if(v<0)break;let $=g.slice(0,v).replace(/\r$/,"");if(g=g.slice(v+1),$==="")y();else{if($.startsWith(":"))continue;$.startsWith("event:")?h=$.slice(6).trim():$.startsWith("data:")&&m.push($.slice(5).replace(/^ /,""))}}}}catch(p){n||a(p);return}a(new Error("sse stream ended"))};return c(),{stop:()=>{n=!0,s&&clearTimeout(s),o?.abort()}}}var Un=t=>_e().path.join(Be().userDataDir(),Be().isDevMode()?`${t}.dev.json`:`${t}.json`),gs=Un,on=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wr=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Vr=t=>typeof t=="string"&&Tt(t)===t,lc=t=>typeof t=="string"&&t.length>0,op=t=>on(t)&&Wr(t.seq)&&lc(t.hash)&&Wr(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),sp=t=>on(t)&&Vr(t.from)&&Vr(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||on(t.hashes)&&Object.values(t.hashes).every(lc));async function ms(t){let e;try{e=await _e().fs.readFile(gs(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(!on(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Ht(n.rootIdentity)||!on(n.files)||!Object.entries(n.files).every(([r,o])=>Vr(r)&&op(o))||n.cursor!==void 0&&!Wr(n.cursor)||n.lastSyncAt!=null&&!Wr(n.lastSyncAt)||n.pending!==void 0&&(!on(n.pending)||!Object.entries(n.pending).every(([r,o])=>Vr(r)&&(o==="local"||o==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(sp)))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 i=e,a=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let c=gs(t),l=`${c}.tmp-${_e().tmpTag()}-${Date.now()}-0`;await _e().fs.writeFile(l,a,"utf8"),await _e().fs.rename(l,c),o=null}catch(c){e??=i,o=c}}),r};return{save(i){e=i,!n&&(n=setTimeout(()=>{n=null,s()},500))},async flush(i=!1){if(n&&(clearTimeout(n),n=null),await s(),i&&o)throw o}}}async function dc(t){try{await _e().fs.unlink(gs(t))}catch{}}var ip=5*1024*1024,ap=5*1024*1024,cp=3e4,lp=5e3,up=5*6e4,dp=2500,fp=3e3,pp=5,hp=256*1024,gp=5,fc=1024*1024,pc=200,mp=6e4,yp=50,wp=".sync-trash",Rt=t=>_e().sha256Hex(t);function Hn(t,e={localRoot:At(),shadowName:`amadeus-sync-${Fn()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=f=>{let S=hs(f,"");if(!S)return null;for(let A of e.excludePrefixes??[])if(S===A.replace(/\/$/,"")||S.startsWith(A))return null;if(e.ignoreNames?.length&&S.split("/").some(A=>e.ignoreNames.includes(A)))return null;let k=e.serverDir?`${e.serverDir}/${S}`:S;return e.inScope&&!e.inScope(k,Ze(k))?null:k},r=f=>{let S;if(e.serverDir){if(!f.startsWith(`${e.serverDir}/`))return null;S=f.slice(e.serverDir.length+1)}else{for(let k of e.excludePrefixes??[])if(f.startsWith(k))return null;S=f}return S.split("/").some(k=>Ln(k)||!!e.ignoreNames?.includes(k))?null:S},o=(f,S)=>!e.inScope||e.inScope(f,S),s=e.accountId??je(),{fs:i,path:a,directoryIdentity:c}=_e(),l=f=>i.access(f).then(()=>!0,()=>!1),u=!1,d=0,g=Promise.resolve(),h=new Set,m="disabled",y=null,p=null,b=null,v=null,$=null,R=null,O=()=>{let f=t.loadCreds();if(!R||s!==je()||!f.token||f.cloudUrl?.replace(/\/+$/,"")!==R.cloudUrl.replace(/\/+$/,""))throw new Ce(401,{code:"ACCOUNT_CHANGED"},"sync-session");return f.token},w=null,x=0,C=new Map,D=null,F=uc(e.shadowName),P=new Map,V=!1,Z=!1,Q=[],ee=(f,S,k)=>{try{t.onHealth?.(f,S,k)}catch{}},re=qr(ee),oe=0,pe=()=>{Z||ee("massDeleteGuard"),Z=!0},ie=()=>{p&&(p.pending=P.size?Object.fromEntries(P):void 0,F.save(p))},xe=()=>{Z=!1,Q.length=0},ye=()=>{if(Z)return!0;let f=Date.now();for(;Q.length&&f-Q[0]>mp;)Q.shift();return Q.length>=yp?(pe(),!0):!1},Re=[],$e=new Set,Ae=!1,H=null,Y=null,E=null,T=null,_=()=>{!u||T||(T=setTimeout(()=>{T=null,t.onStatus(Lt())},200))},I=(f,S)=>{let k=m;m=f,S!==void 0&&(y=S),B(k,f),_()},B=(f,S)=>{if(S==="syncing"&&f!=="syncing"&&(oe=Date.now()),S==="idle"&&f==="syncing"&&(ee("cycles"),ee("cycleMsTotal",Math.max(0,Date.now()-oe))),S==="idle"||S==="disabled"){re.ok();return}let k=oc(S,y);k&&re.error(k)},q=(f,S)=>{C.set(f,S),ee(rc(S),1,f)},M=(f,S=!1)=>{if(u){if(f.key){if($e.has(f.key))return;$e.add(f.key)}S?Re.unshift(f):Re.push(f),Se()}},L=new Map,J=f=>{if(!u)return;let S=(p?.files[f]?.size??0)>hp,k=(e.pushQuietMs??fp)*(S?gp:1),A=Date.now(),N=L.get(f);N&&clearTimeout(N.timer);let z=N?.since??A,W=Math.max(0,Math.min(k,z+k*pp-A)),j=setTimeout(()=>{L.delete(f),M({key:f,run:()=>Ee(f,!0)})},W);L.set(f,{timer:j,since:z}),_()},K=()=>{for(let{timer:f}of L.values())clearTimeout(f);L.clear()},X=f=>!(f instanceof Ce)||f.status>=500||f.status===0,te=f=>f instanceof Ce&&(f.status===401||f.status===403),de=(f,S)=>{q(f,S?.body?.code||`http ${S?.status}`),_()},Se=async()=>{if(!Ae){Ae=!0;try{for(;Re.length;){(m==="idle"||m==="starting")&&I("syncing");let f=Re.shift();f.key&&$e.delete(f.key);try{await f.run()}catch(S){if(!u)return;if(te(S)){Re.length=0,$e.clear(),Sr(),I("auth-required","login-expired");return}if(X(S)){M(f,!0),Sr(),I("offline",S?.message||"network error"),he();return}de(f.key??"(op)",S)}}u&&m==="syncing"&&(p&&(p.lastSyncAt=Date.now(),F.save(p)),I("idle",null))}finally{Ae=!1;for(let f of h)f();h.clear()}}},he=()=>{!u||H||(H=setTimeout(()=>{H=null,An()},cp))},ne=new Map,De=0,ge=null,Ft=()=>!!Y||!!ge||!u,Ke=f=>f instanceof Ce&&f.status>=500||f?.name==="TimeoutError",vi=e.pushRetryMs??lp,Cn=(f,S)=>{(S||!ne.has(f))&&ne.set(f,S)},ki=(f,S,k)=>{q(f,S instanceof Ce?`http ${S.status}`:"timeout"),Cn(f,k),De=Math.min(De*2||vi,up),Y=setTimeout(pr,De),_()},Ei=(f,S,k)=>{let A=new AbortController,N=S(A.signal).then(W=>()=>W,W=>()=>{throw W}),z={path:f,abort:A,after:[],settle:async()=>{let W=await N;if(ge===z){ge=null;try{await k(W)}catch(j){if(te(j)||X(j))throw j;de(f,j)}finally{for(let j of z.after)M(j);_i(f)}}}};ge=z,N.then(()=>M({run:z.settle}))},Jt=(f,S)=>{for(let[k,A]of[...ne])!A||!qe(k,f)||(ne.delete(k),C.delete(k),S!==null&&ne.set(S+k.slice(f.length),A));_()},pr=()=>{Y=null;let[f]=ne;if(f===void 0)return;let[S]=f;$e.delete(S),M({key:S,run:async()=>{if(ge?.path===S)return;let k=ne.get(S),A=!k&&ne.delete(S);(k||A)&&C.delete(S);try{k?await it(S,k.seq):A&&await Ee(S,!0)}finally{A&&We(S)&&Cn(S),_i(S)}}})},_i=f=>{if(!Ft())if(ne.has(f)){let S=ne.get(f);ne.delete(f),ne.set(f,S),Y=setTimeout(pr,De||vi)}else pr()},Oe=f=>{if(!w||!p)throw new Error("engine not bound");let S=r(f);if(S===null)throw new Error("path outside binding: "+f);let k=a.resolve(w,sc(S,p.folder)),A=a.relative(w,k);if(A.startsWith("..")||a.isAbsolute(A))throw new Error("path escapes vault: "+f);return k},hr=f=>({size:f,mtimeMs:-1}),Ci=async f=>{try{let S=await i.stat(f);return S.isFile()?{size:S.size,mtimeMs:Math.floor(S.mtimeMs)}:null}catch{return null}},Du=async f=>{if(!i.lstat||!w)return Ci(f);let S=a.relative(w,f).split(a.sep),k=w;for(let[A,N]of S.entries()){k=a.join(k,N);let z=await i.lstat(k).catch(W=>{if(W?.code==="ENOENT")return null;throw W});if(!z)return null;if(z.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(A===S.length-1&&z.isFile())return{size:z.size,mtimeMs:Math.floor(z.mtimeMs)};if(A===S.length-1||!z.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},Ou=0,xi=async(f,S,k,A)=>{if(!await nt())throw Error("Cloud vault sync root is unavailable or changed");let N=w&&b?{path:w,identity:b}:void 0;await i.mkdir(a.dirname(f),{recursive:!0});let z=`${f}.tmp-${_e().tmpTag()}-${Date.now()}-${Ou++}`;await i.writeFile(z,S);let W=await Ci(z)??hr(To(S));try{if(!A())return null;let j=_e().compareAndReplace;if(!j)throw new Error("Host does not support safe cloud download commits");let G=await j(z,f,k,A,N);if(!G&&!await nt())throw Error("Cloud vault sync root is unavailable or changed");return G?W:null}finally{await nt()&&await i.rm(z,{force:!0})}},Ai=async f=>{let S;try{S=await i.readdir(f,{withFileTypes:!0})}catch{return}for(let k of S)k.isDirectory()&&await Ai(a.join(f,k.name));try{await i.rmdir(f)}catch{}},_t=async f=>{let S=Oe(f),k=await Du(S);if(!await nt())throw Error("Cloud vault sync root is unavailable or changed");if(i.lstat&&!k)return null;let A;try{A=await i.readFile(S)}catch(z){if(z?.code!=="ENOENT")throw z;if(!await nt())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:It(Ze(f))?Rt(xt(A)):Rt(A),size:k?.size??A.length,mtimeMs:k?.mtimeMs??-1,buf:A}},Ct=async(f,S,k,A)=>{p&&(p.files[f]={seq:S,hash:k,size:A.size,mtimeMs:A.mtimeMs},F.save(p))},Xe=f=>{p&&f in p.files&&(delete p.files[f],F.save(p))},it=async(f,S)=>{if(!v||!p||We(f))return;let k=ve,A=Ze(f);if(It(A)){let j;try{j=await v.getFile(p.vaultId,f),ee("downloads")}catch(G){if(G instanceof Ce&&G.status===404){await Eo(f);return}throw G}await Ti(f,A,j.content,j.seq,j.hash??Rt(j.content),k);return}if(Ft()){Cn(f,{seq:S}),_();return}let{vaultId:N}=p,z=v,W={seq:S};ne.set(f,W),Ei(f,j=>z.getAsset(N,f,j),async j=>{let G=ne.get(f)===W,U;try{U=j(),De=0,ee("downloads")}catch(se){if(!G)return;if(ne.delete(f),se instanceof Ce&&se.status===404){q(f,"ASSET_404"),_();return}if(Ke(se)){ki(f,se,{seq:S});return}throw se}G&&await Ti(f,A,U,S??0,Rt(U),k)}),_()},Ti=async(f,S,k,A,N,z)=>{if(!p)return;let W=async fe=>{await Ct(f,A,N,fe),ne.get(f)&&(ne.delete(f),C.delete(f))},j=await _t(f);if(z!==ve||We(f))return;if(j&&j.hash===N){await W(j);return}let G=p.files[f];if(j&&G&&N===G.hash&&j.hash!==G.hash){await W(hr(G.size)),M({key:f,run:()=>Ee(f)});return}let U=j?Rt(j.buf):null;if(j&&(!G||j.hash!==G.hash)){if(G&&S==="page"&&typeof k=="string"&&await Pu(f,G,j,k,A,N,()=>z===ve&&!We(f))||z!==ve||We(f)||!await Mu(f,()=>z===ve&&!We(f)))return;U=null}let se=await xi(Oe(f),k,U,()=>u&&z===ve&&!We(f));if(!se){M({key:f,run:()=>Ee(f)});return}await W(se)},Pu=async(f,S,k,A,N,z,W)=>{try{if(!v||!p||k.buf.length>fc||A.length>fc)return!1;let G=(await v.listVersions(p.vaultId,f)).find(fe=>fe.seq===S.seq);if(!G)return!1;let U=await v.getVersion(p.vaultId,G.id);if(Rt(U)!==S.hash)return!1;let se=tc(xt(k.buf),U,A);return se===null?!1:await xi(Oe(f),se,Rt(k.buf),()=>u&&W())?(await Ct(f,N,z,hr(To(se))),M({key:f,run:()=>Ee(f)}),!0):(M({key:f,run:()=>Ee(f)}),!0)}catch{return!1}},Mu=async(f,S)=>{let k=Tt(Hr(f,new Date));if(!k)return!0;let A=k.lastIndexOf("."),N=A>k.lastIndexOf("/"),z=N?k.slice(0,A):k,W=N?k.slice(A):"",j=k,G=_e().existsSync;if(G)for(let U=2;G(Oe(j));U++)j=`${z}-${U}${W}`;else for(let U=2;await l(Oe(j));U++)j=`${z}-${U}${W}`;if(!S())return!1;try{await i.rename(Oe(f),Oe(j))}catch(U){if(U?.code==="ENOENT")return!0;throw U}return x++,ee("conflicts"),M({key:j,run:()=>Ee(j)}),_(),!0},Ii=async f=>{if(!w)return;let S=Oe(f),k=r(f)??f,A=a.join(w,wp,new Date().toISOString().slice(0,10),...k.split("/")),N=await l(A)?`${A}.${Date.now()}`:A;try{await i.mkdir(a.dirname(N),{recursive:!0}),await i.rename(S,N)}catch(z){if(z?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${S}: ${z?.message??String(z)}`)}},Eo=async f=>{if(!p)return;Jt(f,null);let S=await _t(f);if(We(f))return;let k=p.files[f]??null,A=zr(S?.hash??null,k,null);if(A.kind==="deleteLocal"){if(!V&&ye()){P.set(f,"local"),ie(),_();return}Q.push(Date.now()),await Ii(f),Xe(f)}else A.kind==="pushCreate"?(Xe(f),M({key:f,run:()=>Ee(f)})):Xe(f)},Ri=(f,S)=>{if(p){Jt(f,S);for(let k of Object.keys(p.files))if(k===f||k.startsWith(`${f}/`)){let A=S+k.slice(f.length);p.files[A]=p.files[k],delete p.files[k]}F.save(p)}},Di=async f=>{if(!v||!p||f.seq<=p.cursor||!await nt())return;if(f.origin.client&&v.clientId===f.origin.client){p.cursor=f.seq,F.save(p);return}let S=f.type==="structure"?"folder":f.type,k=N=>r(N)!==null&&o(N,S);if(!k(f.path)&&!(f.newPath&&k(f.newPath))){p.cursor=f.seq,F.save(p);return}let A=f.path;if(f.op!=="write"&&f.op!=="mkdir"){for(;ge&&(qe(ge.path,A)||f.newPath&&qe(ge.path,f.newPath));)await ge.settle();if(!u)return}switch(f.op){case"write":await it(A,f.fileSeq);break;case"delete":await Eo(A);break;case"move":{let N=f.newPath;if(!N)break;let z=p.files[A],W=await _t(A),j=!!ne.get(A);if(Jt(A,N),j&&Cn(N,{seq:f.fileSeq}),W&&z)try{await i.mkdir(a.dirname(Oe(N)),{recursive:!0}),await i.rename(Oe(A),Oe(N)),p.files[N]={...z,seq:j?z.seq:f.fileSeq??z.seq},delete p.files[A],F.save(p)}catch{await it(N,f.fileSeq)}else Xe(A),await it(N,f.fileSeq);break}case"mkdir":await i.mkdir(Oe(A),{recursive:!0});break;case"rename-folder":case"move-folder":{let N=f.newPath;if(!N)break;try{await i.mkdir(a.dirname(Oe(N)),{recursive:!0}),await i.rename(Oe(A),Oe(N))}catch{}Ri(A,N);break}case"delete-folder":{let N=`${A}/`;for(let z of Object.keys(p.files))(z===A||z.startsWith(N))&&await Eo(z);Jt(A,null),await Ai(Oe(A));break}}if(p.cursor=f.seq,F.save(p),f.op==="move"||f.op==="rename-folder"||f.op==="move-folder"||f.op==="delete"||f.op==="delete-folder")try{await t.onRemoteApplied?.(f)}catch{}},$u=async(f,S,k)=>{let A=Number(S?.seq??0),N=S?.content??null;if(N!==null&&Rt(N)===k.hash){await Ct(f,A,k.hash,k);return}if(N===null&&A===0){if(!p?.files[f]){q(f,S?.code||"EXISTS"),_();return}Xe(f),M({key:f,run:()=>Ee(f)});return}await it(f,A)},gr=async(f,S)=>{if(!v||!p)return;let k=await _t(f);if(!k){M({key:f,run:()=>Ee(f)});return}if(k.size>ip){q(f,"TOO_LARGE"),_();return}let A=xt(k.buf);try{let N=await v.putFile(p.vaultId,f,A,S);ee("uploads"),C.delete(f),await Ct(f,N.seq,N.hash??k.hash,k)}catch(N){if(N instanceof Ce&&N.status===409){await $u(f,N.body,k);return}throw N}},mr=async(f,S)=>{if(!v||!p)return;let k=await _t(f);if(!k){M({key:f,run:()=>Ee(f)});return}if(k.size>(D??ap)){q(f,"TOO_LARGE"),_();return}if(Cn(f),_(),Ft())return;let{vaultId:A}=p,N=v;Ei(f,z=>N.putBinary(A,f,k.buf,{baseSeq:S,signal:z}),async z=>{if(p){ne.get(f)||ne.delete(f);try{let W=z();De=0,ee("uploads"),C.delete(f),await Ct(f,W.seq,k.hash,k)}catch(W){if(Ke(W)){ki(f,W);return}if(!(W instanceof Ce)||W.status!==409)throw W;let j=Number(W.body?.seq??0),G=W.body?.hash??null;if(G!==null&&G===k.hash){await Ct(f,j,k.hash,k);return}if(j===0){if(!p.files[f]){q(f,W.body?.code||"EXISTS"),_();return}Xe(f),M({key:f,run:()=>Ee(f)});return}await it(f,j)}}})},Oi=async f=>{if(!v||!p||We(f))return;let S=ve,k=p.files[f];if(k){if(It(Ze(f)))try{let A=await v.getFile(p.vaultId,f);if(A.seq!==k.seq){await it(f,A.seq);return}}catch(A){if(A instanceof Ce&&A.status===404){Xe(f);return}throw A}if(!(!await nt()||S!==ve||We(f))){try{await v.deleteFile(p.vaultId,f,k.seq,{confirmed:V})}catch(A){if(A instanceof Ce&&A.status===409){await it(f,Number(A.body?.seq??0)||null);return}if(A instanceof Ce&&A.status===429&&A.body?.code==="MASS_DELETE_BLOCKED"){P.set(f,"remote"),pe(),ie(),_();return}throw A}Xe(f)}}},_o=f=>i.stat(f).catch(S=>{if(S?.code==="ENOENT")return null;throw S}),Co=f=>{let S=b??p?.rootIdentity,k=f!==null&&f.isDirectory();return k&&(!S||ct(S,f))?!0:(I("error",`${k?"vault-changed":"vault-missing"}: ${w}`),he(),!1)},nt=async()=>!!w&&Co(await _o(w)),ve=0,yr=new Set,wr=new Map,He=f=>JSON.stringify([f.from,f.to]),qe=(f,S)=>f===S||f.startsWith(`${S}/`),We=f=>[...p?.moves??[],...yr].some(S=>qe(f,S.from)||qe(f,S.to)),mt=()=>!!(p?.moves?.length||yr.size),br=async f=>{if(!v||!p)return;let{from:S,to:k,kind:A}=f;if(r(S)===null||r(k)===null)throw new Error("Invalid queued cloud move");if(ge&&(qe(ge.path,S)||qe(ge.path,k))){ge.after.push({key:`move:${He(f)}`,run:()=>br(f)});return}f.hashes??=Object.fromEntries(Object.entries(p.files).filter(([j])=>qe(j,S)).map(([j,G])=>[j.slice(S.length),G.hash])),F.save(p),await F.flush(!0);let N,z=!1;try{if(A==="folder"){let j=a.posix.dirname(S)==="."?"":a.posix.dirname(S),G=a.posix.dirname(k)==="."?"":a.posix.dirname(k);j===G?await v.renameFolder(p.vaultId,S,a.posix.basename(k)):await v.moveFolder(p.vaultId,S,G)}else{let j=await v.move(p.vaultId,S,k);N=Number(j.seq)}}catch(j){if(!(j instanceof Ce)||j.status!==404)throw j;let G=await v.tree(p.vaultId);if(G.entries.some(fe=>qe(fe.path,S))||G.folders.some(fe=>qe(fe,S)))throw j;let se=G.entries.find(fe=>fe.path===k);if(N=se?.seq,z=!se&&!G.entries.some(fe=>qe(fe.path,k))&&!G.folders.some(fe=>qe(fe,k)),!z){let fe=Object.entries(f.hashes);if(!(fe.length>0&&fe.every(([at,Xt])=>G.entries.some(Zt=>Zt.path===k+at&&Zt.hash===Xt))))throw new Ce(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(z){for(let j of Object.keys(p.files))qe(j,S)&&delete p.files[j];Jt(S,null)}else Ri(S,k),N!==void 0&&p.files[k]&&!ne.get(k)&&(p.files[k].seq=N);p.moves=(p.moves??[]).filter(j=>He(j)!==He(f)),F.save(p);try{await F.flush(!0)}catch(j){throw p.moves.unshift(f),F.save(p),j}let W=wr.get(He(f));wr.delete(He(f)),W?.(),We(k)||(A==="folder"?await xo():await Ee(k))},Ee=async(f,S=!1)=>{if(!p||We(f))return;if(ge?.path===f){ge.after.push({key:f,run:()=>Ee(f,S)});return}if(!o(f,Ze(f))){Xe(f);return}if(!await nt())return;let k=await _t(f);if(We(f))return;let A=p.files[f]??null,N=zr(k?.hash??null,A,A?{seq:A.seq,hash:A.hash}:null);switch(N.kind){case"push":It(Ze(f))?await gr(f,N.baseSeq):await mr(f,N.baseSeq);break;case"pushCreate":It(Ze(f))?await gr(f,0):await mr(f,0);break;case"pushDelete":if(S){kr();break}if(!V&&(P.has(f)||ye())){P.set(f,"remote"),ie(),_();break}Q.push(Date.now()),await Oi(f);break;case"dropShadow":Xe(f);break;default:k&&A&&k.hash===A.hash&&k.mtimeMs>=0&&(A.size!==k.size||A.mtimeMs!==k.mtimeMs)&&await Ct(f,A.seq,A.hash,k);break}},Pi=async()=>{let f=new Map;if(!w||!p)return f;let S=w,k=null,A=async N=>{if(k)return;let z;try{z=await i.readdir(N,{withFileTypes:!0})}catch(W){k=`${N}: ${W?.message??String(W)}`;return}for(let W of z){if(Ln(W.name)||W.isDirectory()&&e.ignoreNames?.includes(W.name))continue;let j=a.join(N,W.name);if(W.isDirectory())await A(j);else if(W.isFile()){let G=a.relative(S,j).split(a.sep).join("/"),U=n(G);if(!U)continue;try{let se=await i.stat(j);if(!se.isFile())continue;f.set(U,{size:se.size,mtimeMs:Math.floor(se.mtimeMs)})}catch(se){if(se?.code==="ENOENT")continue;k=`${j}: ${se?.message??String(se)}`;return}}}};return await A(S),k?(I("error",`scan-failed: ${k}`),he(),null):f},xo=async()=>{let f=ve;if(mt()||f!==ve||!p||!await nt())return;let S=await Pi();if(!S||mt()||f!==ve)return;let k=!1;for(let[z,W]of[...P])(W==="remote"&&S.has(z)||W==="local"&&!S.has(z))&&(P.delete(z),k=!0);P.size||xe();for(let[z,W]of S){let j=p.files[z];j&&j.size===W.size&&j.mtimeMs===W.mtimeMs||M({key:z,run:()=>Ee(z)})}let A=Object.keys(p.files),N=A.filter(z=>!S.has(z));if(N.length&&!V&&(Z||ps(N.length,A.length,pc))){pe();for(let z of N)P.set(z,"remote");ie(),_();return}k&&(ie(),_());for(let z of N)P.has(z)||M({key:z,run:()=>Ee(z)})},Kt=async()=>{if(ge){ge.after.push({run:Kt});return}let f=ve;if(mt()||f!==ve||!v||!p||!w||!await nt())return;let S=await v.tree(p.vaultId);if(S.maxFileBytes!==void 0&&S.maxFileBytes!==D&&(D=S.maxFileBytes,_()),mt()||f!==ve)return;let k=new Map;for(let U of S.entries)r(U.path)===null||!o(U.path,U.kind)||k.set(U.path,U);for(let[U,se]of[...ne])se&&!k.has(U)&&Jt(U,null);let A=await Pi();if(!A||mt()||f!==ve)return;let N=new Set([...k.keys(),...A.keys(),...Object.keys(p.files)]),z=Object.keys(p.files).length,W=[];for(let U of N){if(mt()||f!==ve)return;let se=p.files[U]??null,fe=k.get(U)??null,Ue=A.get(U)??null,at=null,Xt=hr(Ue?.size??0);if(Ue)if(se&&se.size===Ue.size&&se.mtimeMs===Ue.mtimeMs)at=se.hash,Xt=Ue;else{let Zt=await _t(U);Zt&&(at=Zt.hash,Xt=Zt)}W.push({sp:U,d:zr(at,se,fe?{seq:fe.seq,hash:fe.hash}:null),rSeq:fe?.seq??null,localHash:at,localStat:Xt})}if(mt()||f!==ve)return;let j=W.filter(U=>U.d.kind==="deleteLocal"||U.d.kind==="pushDelete").length,G=!V&&(Z||ps(j,z,pc));G&&j&&pe(),P.clear();for(let{sp:U,d:se,rSeq:fe,localHash:Ue,localStat:at}of W){if(mt()||f!==ve)return;if(G&&(se.kind==="deleteLocal"||se.kind==="pushDelete")){P.set(U,se.kind==="deleteLocal"?"local":"remote");continue}if((se.kind==="deleteLocal"||se.kind==="pushDelete")&&((await _t(U))?.hash??null)!==Ue){M({key:U,run:()=>Ee(U)});continue}if(mt()||f!==ve)return;switch(se.kind){case"adopt":await Ct(U,fe,Ue,at);break;case"pull":await it(U,fe);break;case"push":It(Ze(U))?await gr(U,se.baseSeq):await mr(U,se.baseSeq);break;case"pushCreate":It(Ze(U))?await gr(U,0):await mr(U,0);break;case"pushDelete":await Oi(U);break;case"deleteLocal":await Ii(U),Xe(U);break;case"conflict":await it(U,fe);break;case"dropShadow":Xe(U);break;case"none":break}}V&&(V=!1,Q.length=0),P.size||xe(),ie(),G&&_();for(let U of S.folders)if(!(r(U)===null||!o(U,"folder")))try{await i.mkdir(Oe(U),{recursive:!0})}catch{}p.cursor=S.seq,p.lastSyncAt=Date.now(),F.save(p)},Nu=async()=>{if(!v||!p)return;let f=p.cursor,S=await v.changes(p.vaultId,f);if(S.changes.length===0&&S.seq>f||S.changes.length>0&&S.changes[0].seq!==f+1){await Kt();return}for(let A of S.changes)await Di(A)},xn=null,Mi=[],$i=()=>{xn&&Mi.push(xn.close()),xn=null},ju=()=>{if(!u||xn||!w)return;let f=_e();if(!f.watch)return;let S=k=>{if(!w)return;let A=a.relative(w,k);if(!A||A.startsWith(".."))return;let N=n(A);N&&J(N)};xn=f.watch(w,{depth:12,ignored:k=>{let A=a.basename(k);return Ln(A)||!!e.ignoreNames?.includes(A)}},{change:S,add:S,unlink:()=>kr(),unlinkDir:()=>kr()})},Sr=()=>{$?.stop(),$=null},Fu=()=>{if(!u||!v||!p||$)return;let f=R;f&&($=cc({baseUrl:f.cloudUrl,vaultId:p.vaultId,token:f.token,getToken:O},{getSince:()=>p?.cursor??0,onHello:S=>{p&&S>p.cursor&&M({run:Nu})},onChange:S=>{M({run:()=>Di(S)})},onReset:()=>{M({run:Kt})},onOpen:()=>{(m==="offline"||m==="starting")&&I("idle",null),M({run:xo})},onDown:()=>{(m==="idle"||m==="syncing")&&I("offline")},onPresence:S=>t.onPresence?.(p?.vaultId??"",S),onPresenceRoster:S=>t.onPresenceRoster?.(p?.vaultId??"",S)}))},Lu=async()=>{let f=await Ye(s);if(f.cloudSync?.deviceId)return f.cloudSync.deviceId;let S=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await wt({cloudSync:{...f.cloudSync??{},deviceId:S}},s),S},Uu=async f=>{Sr(),$i(),b=null,Re.length=0,$e.clear(),P.clear(),V=!1,Z=!1,Q.length=0;let S=await Ye(s);if(f!==d)return;let k=S.cloudSync;if(k?.enabled===!1){w=null,v=null,I("disabled",null);return}if(!s||s!==je()){I("auth-required","not-logged-in");return}if(w=e.localRoot,e.requireRootExists){let W=await i.stat(w).then(j=>j.isDirectory()).catch(()=>!1);if(f!==d)return;if(!W){I("error",`vault-missing: ${w}`),he();return}}if(f!==d)return;let A=t.loadCreds();if(!A.cloudUrl||!A.token){v=null,I("auth-required","not-logged-in");return}I("starting",null);let N=k?.deviceId??await Lu();if(f!==d)return;let z=e.clientIdSuffix?`${N}#${e.clientIdSuffix}`:N;R={cloudUrl:A.cloudUrl,token:A.token},v=ac({baseUrl:A.cloudUrl,token:A.token,clientId:z,getToken:()=>{if(f!==d)throw new Ce(401,{code:"ACCOUNT_CHANGED"},"sync-session");return O()}});try{let W=e.vaultId==="first"?k?.vaultId:e.vaultId;if(!W){let U=await v.listVaults();if(f!==d)return;if(!U.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");W=U[0].id,await wt({cloudSync:{...k??{},vaultId:W}},s)}if(f!==d)return;let j=await ms(e.shadowName);if(f!==d||(p=j&&j.vaultRoot===w&&j.vaultId===W&&j.folder===""?j:{vaultRoot:w,folder:"",vaultId:W,cursor:0,lastSyncAt:null,files:{}},f!==d))return;for(let[U,se]of Object.entries(p.pending??{}))P.set(U,se);P.size&&(Z=!0);let G=await _o(w);if(f!==d||!G&&!e.requireRootExists&&!p.rootIdentity&&!Object.keys(p.files).length&&(await i.mkdir(w,{recursive:!0}),G=await _o(w),f!==d))return;if(!G?.isDirectory()){Co(G);return}if(typeof G.dev=="number"&&Number.isInteger(G.dev)&&G.dev>=0&&typeof G.ino=="number"&&Number.isInteger(G.ino)&&G.ino>0){let U=c?await c(w):{dev:G.dev,ino:G.ino,...G.birthtimeMs&&G.birthtimeMs>0?{birthtimeMs:G.birthtimeMs}:{}};if(f!==d)return;if(!Ht(U))throw Error("Invalid sync root identity; original state retained");if(!ct(U,G)||p.rootIdentity&&!tn(p.rootIdentity,U)){I("error",`vault-changed: ${w}`),he();return}if(b=U,JSON.stringify(p.rootIdentity)!==JSON.stringify(U)&&(p.rootIdentity=U,F.save(p),await F.flush(!0)),f!==d||!await nt())return}else if(!Co(G))return;ju();for(let U of p.moves??[])M({key:`move:${He(U)}`,run:()=>br(U)});M({run:Kt}),M({run:async()=>{Fu()}})}catch(W){if(f!==d)return;te(W)?I("auth-required","login-expired"):(I("offline",W?.message||String(W)),he())}},Ni=()=>{u=!1,Sr(),$i(),Re.length=0,$e.clear(),K();for(let f of[H,Y,E,T])f&&clearTimeout(f);H=Y=E=T=null,ge?.abort.abort(),ge=null},ji=async()=>{Ae&&await new Promise(f=>h.add(f)),await Promise.all(Mi.splice(0)),await F.flush(),p=null,b=null,v=null,R=null,w=null,x=0,C.clear(),ne.clear(),De=0,D=null,P.clear(),V=!1,Z=!1,Q.length=0,m="disabled",y=null},Hu=()=>{Fi()},vr=null,An=()=>{vr?.(),vr=Be().onBeforeQuit(Hu);let f=++d;Ni();let S=g.catch(()=>{}).then(async()=>{await ji(),f===d&&(u=!0,await Uu(f))});return g=S,S},Fi=()=>{vr?.(),vr=null,++d,Ni();let f=g.catch(()=>{}).then(ji);return g=f,f},Lt=()=>({enabled:m!=="disabled",state:m==="idle"&&(L.size||ne.size)?"syncing":m,lastSyncAt:p?.lastSyncAt??null,pending:Re.length+L.size+ne.size,conflicts:x,skipped:[...C].map(([f,S])=>({path:f,reason:S})),error:y,pendingDeletions:P.size,maxFileBytes:D});return{getStatus:Lt,start(){An()},notifyLocal(f,S,k){if(!p||m==="disabled"||m==="auth-required")return;let A=n(f),N=k?n(k):null;if(S==="write"&&A){Ln(A.split("/").pop()||"")||J(A);return}if(S==="remove"){if(!A)return;let z=`${A}/`,W=!1;for(let j of Object.keys(p.files))(j===A||j.startsWith(z))&&(W=!0,M({key:j,run:()=>Ee(j)}));!W&&A&&M({key:A,run:()=>Ee(A)})}},holdLocalMove(f,S){let k=N=>e.serverDir?`${e.serverDir}/${N.replace(/\\/g,"/").normalize("NFC")}`:N.replace(/\\/g,"/").normalize("NFC"),A={from:k(f),to:k(S)};return++ve,yr.add(A),()=>{yr.delete(A)}},async notifyLocalMove(f,S,k,A){let N=n(f),z=n(S),W=p??await ms(e.shadowName),j=hs(f,""),G=j&&(e.serverDir?`${e.serverDir}/${j}`:j);if(!N&&z&&G&&W&&Object.keys(W.files).some(U=>U===G||U.startsWith(`${G}/`))&&(N=G),!N&&!z){k?.();return}if(N&&z){let U=p??W;if(!U){k?.();return}let se=A??(Object.keys(U.files).some(Ue=>Ue.startsWith(`${N}/`))?"folder":"file"),fe={from:N,to:z,kind:se};U.moves??=[],U.moves.some(Ue=>He(Ue)===He(fe))||(U.moves.push(fe),++ve),k&&wr.set(He(fe),k),F.save(U);try{await F.flush(!0)}catch(Ue){throw U.moves=U.moves.filter(at=>He(at)!==He(fe)),wr.delete(He(fe)),F.save(U),Ue}p===U&&u&&m!=="disabled"&&m!=="auth-required"&&M({key:`move:${He(fe)}`,run:()=>br(fe)});return}N&&this.notifyLocal(f,"remove"),z&&(M({key:z,run:()=>Ee(z)}),kr()),k?.()},async setEnabled(f){let S=await Ye(s);return await wt({cloudSync:{...S.cloudSync??{},enabled:f}},s),await An(),Lt()},async restart(){return await An(),Lt()},async syncNow(){if(C.clear(),m==="disabled"||m==="auth-required"||!v)await An();else{Y&&(clearTimeout(Y),pr());for(let f of p?.moves??[])M({key:`move:${He(f)}`,run:()=>br(f)});M({run:Kt})}return Lt()},confirmMassDeletions(){return P.size&&(V=!0,Z=!1,P.clear(),Q.length=0,ie(),M({run:Kt})),Lt()},stop:Fi};function kr(){u&&(E&&clearTimeout(E),E=setTimeout(()=>{E=null,M({run:xo})},dp))}}function ys(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 ws(t){return/\.md$/i.test(t)?ys(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function hc(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 bp=t=>_e().sha256Hex(t).slice(0,8),Sp=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Yr="\u4E0E\u6211\u5171\u4EAB";function gc(t,e){let n=bp(`${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:`${Yr}/${Sp(t.title)}-${n}`,serverDir:r,inScope:(o,s)=>e.some(i=>hc(i,o,s)),scopeKey:e.map(o=>o.root).join("\0")}}function mc(t){return gc(t,[ys(t.path),...(t.items??[]).map(ws)])}function yc(t){let e=t.map(mc),n=t.flatMap((o,s)=>{let i=e[s].serverDir?`${e[s].serverDir}/`:"";return(o.items??[]).filter(a=>!a.startsWith(i)).map(a=>gc({vaultId:o.vaultId,path:a,title:(a.split("/").pop()??a).replace(/\.md$/i,"")},[ws(a)]))}),r=new Map;for(let o of[...e,...n])r.has(o.key)||r.set(o.key,o);return[...r.values()]}var vp=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 wc(t,e){let n=c=>c.normalize("NFC"),r=n(e.replace(/\\/g,"/")),o=t.find(c=>r.startsWith(`${n(c.localRelDir)}/`));if(!o)return null;let s=r.slice(n(o.localRelDir).length+1),i=vp(o.serverDir?`${o.serverDir}/${s}`:s);if(!i||i===".."||i.startsWith("../"))return null;let a=[o,...t].find(c=>c.vaultId===o.vaultId&&(!c.serverDir||i.startsWith(`${c.serverDir}/`))&&c.inScope(i,Ze(i)));return a?`${a.localRelDir}/${a.serverDir?i.slice(a.serverDir.length+1):i}`:null}function bs(){let t=Be().readCreds(),e=Ne(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let d=Be().readCreds();if(n.signal.aborted||!e||Ne(d.cloudUrl??"",d.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return d},o=()=>{let d=r();if(!d.cloudUrl||!d.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return d.cloudUrl.replace(/\/+$/,"")},s=async(d,g,h)=>{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:d,headers:{Authorization:`Bearer ${m.token}`,...h!==void 0?{"Content-Type":"application/json"}:{}},body:h!==void 0?JSON.stringify(h):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!y.ok){let b=null;try{b=await y.json()}catch{}throw Object.assign(new Error(b?.detail||`http ${y.status}`),{status:y.status,code:b?.code})}let p=await y.json();return r(),p},i=null,a=async()=>(r(),i||(i=(await s("GET","/vaults")).vaults[0]?.id??"default",i)),c=()=>{try{let d=(r().token??"").split(".")[1],g=JSON.parse(xt(Er(d)));return typeof g.userId=="string"?g.userId:null}catch{return null}},l=async()=>(await s("GET","/shared-with-me")).items.map(g=>{let h=mc(g),m=g.path.split("/").pop()??g.path;return{...g,localPath:`${h.localRelDir}/${m}`}}),u=null;return{stop:()=>n.abort(),call:s,ensureOwnVault:a,myUserId:c,sharedWithMe:l,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(d,g){let h=(d??"").replace(/\\/g,"/"),m,y=null,p=g.find(b=>h.startsWith(`${b.localRelDir}/`));p?(m=p.vaultId,y=p.serverDir?`${p.serverDir}/${h.slice(p.localRelDir.length+1)}`:h.slice(p.localRelDir.length+1)):(m=await a(),y=h||null),await s("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:y})}}}import{promises as vc}from"node:fs";import kp from"node:path";var Ss=".forsion-vault.md",bc=t=>`${t}/${Ss}`;function Gr(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 Sc=t=>`---
|
|
216
216
|
devices: ${JSON.stringify(t.map(e=>({id:e.id,name:e.name,...e.since?{since:e.since}:{}})))}
|
|
217
217
|
---
|
|
218
|
-
`;var Ge=t=>t.replace(/\\/g,"/").normalize("NFC");function vo(t){let e=Ge(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function on(t,e,n){let r=Ge(n);if(!r)return!1;if(t.some(s=>Ge(s.path)===r))return!0;for(let s of e??[]){let o=Ge(s);if(!o)continue;let i=`${o.replace(/\.md$/i,"")}.fd`;if(r===o||r.startsWith(`${o}/`)||r===i||r.startsWith(`${i}/`))return!1}return t.some(s=>{let o=vo(s);return!!o&&r.startsWith(o)})}function ko(t,e,n){let r=Ge(t),s=Ge(e);return r===s?Ge(n):r.startsWith(`${s}/`)?Ge(n)+r.slice(s.length):null}function zn(t,e,n){let r=!1,s=t.map(o=>{let i=ko(o,e,n);return i===null?o:(r=!0,i)});return{changed:r,next:s}}async function kc(t){let e=await vc.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let s of e){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=await vc.readFile(vp.join(t,s.name,So),"utf8").catch(()=>null);if(o===null)continue;n.push(s.name);let i=Gr(o);i?.length&&(r[s.name]=i)}return{names:n.sort(),devices:r}}var Te={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",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 Jr=t=>_e().sha256Hex(t).slice(0,8);function Ec(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Rt(t,e=[]){let n=[],r=[];for(let s of t){let o=Ge(s.path);if(!o)continue;r.push(o);let i=vo(s);i&&n.push(i)}return{entries:t,exclude:e,prefixes:n,paths:r}}function _c(t,e){let n=Ec(Ge(e));if(!n)return!1;if(on(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let s of t.paths)if(s.startsWith(r))return!0;for(let s of t.prefixes)if(s.startsWith(r))return!0;return!1}function Bn(t,e,n){let r=!1,s=t.map(o=>{let i=ko(o.path,e,n);return i===null?o:(r=!0,{...o,path:i})});return{changed:r,next:s}}function Cc(t,e,n,r){if(e==="delete"||e==="delete-folder"){let s=Ge(n),o=t.filter(i=>{let a=Ge(i.path);return!(a===s||e==="delete-folder"&&a.startsWith(`${s}/`))});return{changed:o.length!==t.length,next:o}}return r?Bn(t,n,r):{changed:!1,next:t}}function Eo(t,e){let n=At(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Yr?`\u300C${Yr}\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 kp,promises as xc}from"node:fs";async function Ac(t,e){try{await xc.copyFile(Un(t),Un(e),kp.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await xc.unlink(Un(t)).catch(()=>{}),!0}var Ep=/^\d{4}-\d{2}-\d{2}$/,Tc=["vault","content"],Ic=new Set(nc),_p=40,an=t=>new Date(t).toISOString().slice(0,10),Wn=t=>typeof t=="string"&&Ep.test(t),Rc=!1,Qe=Object.create(null),cn=!1,_o=()=>Date.now(),qn=new Set,Kr="";function rt(t,e,n=1,r){try{if(!Rc||!Ic.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let s=an(_o());if(r!==void 0){s!==Kr&&(qn.clear(),Kr=s);let a=`${t}\0${e}\0${r}`;if(qn.has(a))return;qn.add(a)}let o=Qe[s]??={},i=o[t]??={};i[e]=(i[e]??0)+Math.round(n),cn=!0}catch{}}function Co(t){Rc=t}function Dc(t){if(Qe=Object.create(null),qn.clear(),Kr="",cn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!Wn(e)||!n||typeof n!="object"))for(let r of Tc){let s=n[r];if(!s||typeof s!="object")continue;let o={};for(let[i,a]of Object.entries(s))Ic.has(i)&&typeof a=="number"&&Number.isFinite(a)&&a>0&&(o[i]=Math.round(a));Object.keys(o).length&&((Qe[e]??={})[r]=o)}}}function Oc(){let t=an(_o()-_p*864e5),e={};for(let n of Object.keys(Qe).sort()){if(n<t){delete Qe[n];continue}e[n]=JSON.parse(JSON.stringify(Qe[n]))}return e}var Pc=()=>cn,Mc=()=>{cn=!1};function $c(t,e){let n=[];for(let r of Object.keys(Qe).sort())if(!(r<=t||r>e))for(let s of Tc){let o=Qe[r][s];o&&Object.keys(o).length&&n.push({day:r,system:s,counts:{...o}})}return n}function xo(t){for(let e of Object.keys(Qe))e<=t&&(delete Qe[e],cn=!0)}function Nc(){Object.keys(Qe).length&&(cn=!0),Qe=Object.create(null),qn.clear(),Kr=""}function jc(t){_o=t}var Fc=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],Ao=t=>Fc.every(e=>typeof t[e]=="function"),Ap=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function To(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Te.get,()=>e?e.get():Ap()),t.handle(Te.setEnabled,(r,s)=>n().setEnabled(s)),t.handle(Te.syncNow,()=>n().syncNow()),t.handle(Te.confirmDeletions,()=>n().confirmDeletions()),t.handle(Te.entryGet,()=>n().entryGet()),t.handle(Te.otherSideDbs,()=>n().otherSideDbs()),t.handle(Te.entryEnable,(r,s)=>n().entryEnable(s)),t.handle(Te.entryDisable,(r,s)=>n().entryDisable(s)),t.handle(Te.entryMark,(r,s,o)=>n().entryMark(s,o)),t.handle(Te.entryClosure,(r,s,o)=>n().entryClosure(s,o)),t.handle(Te.collabCall,(r,s,o)=>n().collabCall(s,o)),t.handle(Te.switchSide,(r,s)=>n().switchSide(r.sender.id,s)),t.setAmadeusSyncFactory(r=>{Za(r);let s=Lc(r);return e=s.handlers,s.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function Lc(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,s=!1,o=bo(),i=new Map,a=()=>{let _=Date.now();for(let[T,E]of i)_-E.at>7e4&&i.delete(T);e(Te.presence,[...i.values()])},l={loadCreds:()=>t.readCreds(),onHealth:(_,T,E)=>rt("vault",_,T,E),onStatus:_=>e(Te.status,{..._,pendingDeletions:xe(),side:p()?"cloud":"local"}),onPresence:(_,T)=>{let E=T;E?.userId&&(i.set(E.userId,{userId:E.userId,username:String(E.username??"user"),page:E.page??null,at:Number(E.at)||Date.now()}),a())},onPresenceRoster:(_,T)=>{if(Array.isArray(T)){for(let E of T){let I=E;I?.userId&&i.set(I.userId,{userId:I.userId,username:String(I.username??"user"),page:I.page??null,at:Number(I.at)||Date.now()})}a()}}},u=()=>{let _=r;return{...l,onStatus:T=>{_===r&&l.onStatus(T)},onPresence:(T,E)=>{_===r&&l.onPresence(T,E)},onPresenceRoster:(T,E)=>{_===r&&l.onPresenceRoster(T,E)}}},d=Hn(u()),g=new Map,h=[],m=0,y=async()=>{if(!s||!je())return;let _=r,T=++m,E=o,I;try{I=await E.sharedWithMe()}catch{return}if(_!==r||!s||T!==m)return;let q=yc(I);h=q;let B=new Map(q.map(M=>[M.key,M.scopeKey]));for(let[M,L]of g)if(B.get(M)!==L.plan.scopeKey){if(await L.engine.stop(),_!==r)return;g.delete(M)}for(let M of q){if(g.has(M.key))continue;let L=Hn(u(),{localRoot:zt.join(xt(),...M.localRelDir.split("/")),shadowName:`amadeus-sync-${Fn()}-share-${M.key}`,vaultId:M.vaultId,serverDir:M.serverDir,inScope:M.inScope});g.set(M.key,{engine:L,plan:M}),L.start()}},p=()=>n()===xt(),b=(_,T=_.base)=>{_.base=T;let E=[T,..._.pendingMoves];_.scope.current=Rt(E.flatMap(I=>I.entries),E.flatMap(I=>I.exclude))},v=new Map,$=new Set,R=new Set,O=null,w=()=>O??=new Promise(_=>{let T=()=>xp.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return _(T());Cp("scutil",["--get","ComputerName"],{timeout:1500},(E,I)=>_(!E&&String(I).trim()||T()))}),x=async()=>{let _=(await Ye()).cloudSync?.deviceId;return _?{id:_,name:await w()}:null},C=new Map,D=(_,T,E)=>{let I=r,q=(C.get(_)??Promise.resolve()).catch(()=>{}).then(async()=>{I!==r||E&&!await E()||I!==r||await j(_,T,I)});return C.set(_,q),q.finally(()=>{C.get(_)===q&&C.delete(_)}).catch(()=>{}),q},j=async(_,T,E)=>{let I=o,q=encodeURIComponent(await I.ensureOwnVault()),B=bc(_);for(let M=0;M<3;M++){let L=null;try{L=await I.call("GET",`/vaults/${q}/file?path=${encodeURIComponent(B)}`)}catch(K){if(K?.status!==404)throw K}let J=T(!!L,L?Gr(L.content):null);if(J===void 0||E!==r)return;try{if(J===null){L&&await I.call("DELETE",`/vaults/${q}/file?path=${encodeURIComponent(B)}&baseSeq=${L.seq}`);return}await I.call("PUT",`/vaults/${q}/file`,{path:B,content:Sc(J),baseSeq:L?.seq??0});return}catch(K){if(K?.status!==409)throw K}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},P=async _=>!!(await Ye()).entrySync?.some(T=>T.cloudName===_&&T.entries.length>0),V=(_,T)=>D(_,(E,I)=>{let q=I?.find(M=>M.id===T.id);if(q&&q.name===T.name)return;let B=q?.since??new Date().toISOString().slice(0,10);return[...(I??[]).filter(M=>M.id!==T.id),{...T,since:B}]},()=>P(_)),Z=(_,T)=>D(_,(E,I)=>{if(!E||!I?.some(B=>B.id===T))return;let q=I.filter(B=>B.id!==T);return q.length?q:null},async()=>!await P(_)),Q=()=>{e(Te.entryChange)},ee=async(_,T)=>{let E=v.get(_);if(!E)return;let I=M=>M&&M.startsWith(`${E.cloudName}/`)?M.slice(E.cloudName.length+1):null,q=I(T.path);if(!q)return;let B=!1;await rn(M=>{if(v.get(_)!==E)return!1;let L=(M.entrySync??[]).find(de=>de.vaultRoot===_);if(!L)return!1;let J=T.op,K=I(T.newPath),X=Cc(L.entries,J,q,K),te=K?zn(L.exclude??[],q,K):{changed:!1,next:L.exclude??[]};if(!X.changed&&!te.changed)return!1;B=!0,L.entries=X.next,te.changed&&(L.exclude=te.next),b(E,Rt(L.entries,L.exclude??[]))}),B&&v.get(_)===E&&Q()},re=_=>{let T=r;return{...u(),onStatus:E=>{T===r&&e(Te.status,{...E,pendingDeletions:xe(),side:"local",binding:_})},onRemoteApplied:async E=>{T===r&&await ee(_,E)}}},se=async()=>{let _=je();if(!s||!_)return;let T=r,E=o,I=Fn(_);await t.adoptLegacyCloudState(_,Ac);let q=await Ye(_),B=q.entrySync??[];if(T!==r||!s||_!==je())return;let M=new Map(B.map(L=>[L.vaultRoot,L]));for(let[L,J]of v){let K=M.get(L);if(!(K&&K.cloudName===J.cloudName)&&(await J.engine.stop(),T!==r||(v.delete(L),K&&await dc(`amadeus-sync-${I}-entry-${Jr(L)}`),T!==r)))return}for(let L of B){let J=v.get(L.vaultRoot);if(J){b(J,Rt(L.entries,L.exclude??[]));continue}let K={current:Rt(L.entries,L.exclude??[])},X=L.cloudName,te=Hn(re(L.vaultRoot),{accountId:_,localRoot:L.vaultRoot,shadowName:`amadeus-sync-${I}-entry-${Jr(L.vaultRoot)}`,vaultId:"first",serverDir:X,clientIdSuffix:`entry-${Jr(L.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:de=>de===X?!0:de.startsWith(`${X}/`)?_c(K.current,de.slice(X.length+1)):!1});v.set(L.vaultRoot,{engine:te,scope:K,cloudName:X,base:K.current,pendingMoves:new Set}),te.start()}if(q.cloudSync?.enabled!==!1)for(let L of B){let J=L.entries.length>0,K=J?$:R;K.has(L.cloudName)||((J?R:$).delete(L.cloudName),(async()=>{try{let X=await x();if(!X||T!==r||(await(J?V(L.cloudName,X):Z(L.cloudName,X.id)),T!==r))return;K.add(L.cloudName),(J?R:$).delete(L.cloudName)}catch{}})())}},pe=async(_,T,E,I,q)=>{let B=T.replace(/\\/g,"/").normalize("NFC"),M=E.replace(/\\/g,"/").normalize("NFC"),L=!1,J,K,X,te=q??"file";try{await rn(async de=>{if(v.get(_)!==I)return!1;let Se=(de.entrySync??[]).find(Ke=>Ke.vaultRoot===_);if(!Se)return!1;let he=Bn(Se.entries,B,M),ne=zn(Se.exclude??[],B,M),De=on(Se.entries,Se.exclude,B);!q&&await ln.stat(zt.join(_,...M.split("/"))).then(Ke=>Ke.isDirectory(),()=>!1)&&(te="folder");let ge=te==="folder"?"folder":/\.md$/i.test(M)?"page":"asset";De&&!on(he.next,ne.next,M)&&(he.next.push({path:M,kind:ge}),he.changed=!0),L=he.changed||ne.changed;let jt=Se.entries.filter(Ke=>Bn([Ke],B,M).changed);return De&&!jt.some(Ke=>Ke.path===B)&&jt.push({path:B,kind:ge}),J=Rt(jt,(Se.exclude??[]).filter(Ke=>zn([Ke],B,M).changed)),K=I.base,I.pendingMoves.add(J),Se.entries=he.next,Se.exclude=ne.next,X=Rt(Se.entries,Se.exclude),b(I,X),L})}catch(de){throw J&&I.pendingMoves.delete(J),b(I,I.base===X&&K?K:I.base),de}try{J&&await I.engine.notifyLocalMove(B,M,()=>{I.pendingMoves.delete(J),b(I)},te)}catch(de){throw J&&I.pendingMoves.delete(J),await rn(Se=>{let he=Se.entrySync?.find(ne=>ne.vaultRoot===_);if(!he)return!1;he.entries=Bn(he.entries,M,B).next,he.exclude=zn(he.exclude??[],M,B).next,b(I,Rt(he.entries,he.exclude))}),de}L&&v.get(_)===I&&Q()},ie=_=>{let T=_.replace(/\\/g,"/");for(let{engine:E,plan:I}of g.values())if(T.startsWith(`${I.localRelDir}/`))return{engine:E,rel:T.slice(I.localRelDir.length+1)};return{engine:d,rel:T}};t.setMutationHooks((_,T)=>{if(p()){let E=ie(_);E.engine.notifyLocal(E.rel,T);return}v.get(n()??"")?.engine.notifyLocal(_,T)},(_,T,E)=>{if(p()){let B=ie(_),M=ie(T);if(B.engine===M.engine)return B.engine.notifyLocalMove(B.rel,M.rel,void 0,E);B.engine.notifyLocal(B.rel,"remove"),M.engine.notifyLocal(M.rel,"write");return}let I=n()??"",q=v.get(I);if(q)return pe(I,_,T,q,E)},(_,T)=>{if(p()){let E=ie(_),I=ie(T),q=[E.engine.holdLocalMove(E.rel,I.rel)];return E.engine!==I.engine&&q.push(I.engine.holdLocalMove(E.rel,I.rel)),()=>{for(let B of q)B()}}return v.get(n()??"")?.engine.holdLocalMove(_,T)});let xe=()=>{let _=d.getStatus().pendingDeletions;for(let{engine:T}of g.values())_+=T.getStatus().pendingDeletions;for(let{engine:T}of v.values())_+=T.getStatus().pendingDeletions;return _},ye=_=>({..._,pendingDeletions:xe(),side:p()?"cloud":"local"}),Re=()=>{if(!s)return Promise.resolve(d.getStatus());y();for(let{engine:_}of g.values())_.syncNow();for(let{engine:_}of v.values())_.syncNow();return d.syncNow()},$e=async()=>{++r,s=!1,o.stop();let _=[d.stop(),...[...g.values()].map(({engine:E})=>E.stop()),...[...v.values()].map(({engine:E})=>E.stop())];g.clear(),v.clear(),h=[],$.clear(),R.clear(),i.clear(),a(),await Promise.all(_),await t.awaitPendingVaultWrites();let T=n();if(T&&Ur(T)){let E=await Ye(),I=E.localVault&&!Ur(E.localVault)?E.localVault:zt.join(t.workspaceDir(),"Amadeus");await ln.mkdir(I,{recursive:!0}),await mt({lastVault:I,localVault:I,lastPage:void 0}),await t.activateRoot(I,!1)}Q()};return{handlers:{get:()=>ye(d.getStatus()),setEnabled:async _=>{if(!s)throw new Error("Cloud account is changing");let T=r;return await d.setEnabled(_),T!==r?d.getStatus():(await Promise.all([...g.values(),...v.values()].map(({engine:E})=>E.restart())),ye(d.getStatus()))},syncNow:()=>Re(),confirmDeletions:()=>{for(let{engine:_}of g.values())_.confirmMassDeletions();for(let{engine:_}of v.values())_.confirmMassDeletions();return ye(d.confirmMassDeletions())},entryGet:async()=>{let _=await Ye(),T=xt(),E=await kc(T);return{vaults:_.entrySync??[],activeRoot:n(),cloudRoot:T,mirrorVaults:E.names,mirrorVaultDevices:E.devices,deviceId:_.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let _=n();if(!_)return null;let T=xt(),E=await Ye(),I=_===T?E.localVault&&E.localVault!==T?E.localVault:null:T;if(!I)return null;let q=[],B=500,M=async(L,J)=>{if(q.length>=B)return;let K;try{K=await ln.readdir(L,{withFileTypes:!0})}catch{return}for(let X of K){if(q.length>=B)break;if(X.name.startsWith(".")||X.isSymbolicLink())continue;let te=J?`${J}/${X.name}`:X.name;if(X.isDirectory())await M(zt.join(L,X.name),te);else if(X.isFile()&&/\.db$/i.test(X.name))try{q.push({rel:te,source:await ln.readFile(zt.join(L,X.name),"utf8")})}catch{}}};return await M(I,""),{root:I,vaultName:I===T?"\u4E91\u7AEF":zt.basename(I),dbs:q}},entryEnable:async _=>{let T=r,E=o;if(!s||!je())return{error:"Sign in to enable cloud sync"};let I=n();if(!I||p())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let q=await Ye(),B=q.entrySync??[],M=B.find(L=>L.vaultRoot===I);if(!M){let L=(_.cloudName??zt.basename(I)).normalize("NFC").trim(),J=Eo(L,B.map(K=>K.cloudName));if(J)return{error:J};if(!_.merge)try{let K=await E.ensureOwnVault(),X=await E.call("GET",`/vaults/${encodeURIComponent(K)}/tree`);if((X.folders??[]).some(de=>de===L||de.startsWith(`${L}/`))||(X.entries??[]).some(de=>de.path===L||de.path.startsWith(`${L}/`)))return{conflict:L}}catch(K){return{error:K?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}M={vaultRoot:I,cloudName:L,entries:[]},B.push(M)}return T!==r||!s?{error:"Cloud account changed; retry from the current account"}:(await rn(L=>{if(T!==r||!s)return!1;let J=L.entrySync??[],K=J.find(ne=>ne.vaultRoot===I);if(!K){let ne=Eo(M.cloudName,J.map(De=>De.cloudName));if(ne)throw new Error(ne);K={vaultRoot:I,cloudName:M.cloudName,entries:[]},J.push(K)}let X=ne=>String(ne??"").replace(/\\/g,"/").normalize("NFC"),te=new Set;for(let ne of _.entries??[]){let De=X(ne.path);De&&(te.add(De),!K.entries.some(ge=>ge.path===De)&&K.entries.push({path:De,kind:ne.kind==="folder"||ne.kind==="asset"?ne.kind:"page"}))}let de=(_.exclude??[]).map(X).filter(Boolean),Se=new Set([...te,...(_.include??[]).map(X).filter(Boolean)]);K.exclude=[...new Set([...(K.exclude??[]).filter(ne=>!Se.has(ne)),...de])];let he=new Set(de);K.entries=K.entries.filter(ne=>!he.has(ne.path)),L.entrySync=J,M=K},q.cloudAccountId),T!==r?{error:"Cloud account changed; retry from the current account"}:(await se(),v.get(I)?.engine.syncNow(),Q(),{ok:!0,cloudName:M.cloudName}))},entryDisable:async _=>{let T=n(),E=!1,I=r;return await rn(q=>{if(I!==r||!s)return!1;let B=(q.entrySync??[]).find(J=>J.vaultRoot===T);if(!T||!B)return!1;let M=String(_??"").replace(/\\/g,"/").normalize("NFC"),L=B.entries.length;if(B.entries=B.entries.filter(J=>J.path!==M),on(B.entries,B.exclude,M))B.exclude=[...new Set([...B.exclude??[],M])];else if(B.entries.length===L)return!1;E=!0}),!E||I!==r?{ok:!1}:(await se(),Q(),{ok:!0})},entryMark:async(_,T)=>{let E=String(_??"").normalize("NFC");if(!E||E.includes("/")||E.startsWith("."))return{error:"invalid name"};if(!s||!je())return{error:"Sign in first"};try{await D(E,I=>T?I?void 0:[]:I?null:void 0)}catch(I){return{error:I?.message||String(I)}}return d.syncNow(),{ok:!0}},entryClosure:(_,T)=>t.relatedClosure(String(_??""),T==="folder"?"folder":"page"),collabCall:async(_,T)=>{let E=o,I=async()=>E.ensureOwnVault(),q=M=>String((T??[])[M]??""),B=M=>(T??[])[M]??{};switch(_){case"listVaults":return(await E.call("GET","/vaults")).vaults;case"activeVaultId":return I();case"pageShare":return E.call("GET",`/vaults/${encodeURIComponent(await I())}/page-shares?path=${encodeURIComponent(q(0))}`);case"relatedItems":return E.call("GET",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(q(0))}/related`);case"setShareItem":return E.call("POST",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(q(0))}/items`,{path:q(1),included:(T??[])[2]===!0});case"createPageShare":return E.call("POST",`/vaults/${encodeURIComponent(await I())}/page-shares`,{path:q(0),...B(1)});case"updatePageShare":return E.call("PATCH",`/vaults/${encodeURIComponent(q(2)||await I())}/page-shares/${encodeURIComponent(q(0))}`,B(1));case"revokePageShare":return E.call("DELETE",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(q(0))}`);case"setParticipantRole":return E.call("PATCH",`/vaults/${encodeURIComponent(q(3)||await I())}/page-shares/${encodeURIComponent(q(0))}/members/${encodeURIComponent(q(1))}`,{role:q(2)});case"removeParticipant":return E.call("DELETE",`/vaults/${encodeURIComponent(q(2)||await I())}/page-shares/${encodeURIComponent(q(0))}/members/${encodeURIComponent(q(1))}`);case"sharedWithMe":{let M=await E.sharedWithMe();return y(),M}case"leaveShare":{let M=E.myUserId();if(!M)throw new Error("\u672A\u767B\u5F55");let L=await E.call("DELETE",`/vaults/${encodeURIComponent(q(1)||await I())}/page-shares/${encodeURIComponent(q(0))}/members/${encodeURIComponent(M)}`);return y(),L}case"publishes":return E.call("GET",`/vaults/${encodeURIComponent(await I())}/shares`);case"listAllShares":{let M=(await E.call("GET","/vaults")).vaults||[],L=E.myUserId(),J=[],K=[];for(let X of M){try{let te=await E.call("GET",`/vaults/${encodeURIComponent(X.id)}/shares`);for(let de of te.shares||[])J.push({...de,vaultId:X.id,vaultName:X.name||""})}catch(te){t.log(`[connect] listAllShares publishes vault ${X.id} failed: ${te?.message}`)}try{let te=await E.call("GET",`/vaults/${encodeURIComponent(X.id)}/page-shares?expired=1`),de=te?.shares||te?.pageShares||(Array.isArray(te)?te:[]);for(let Se of de){let he=Se.created_by??Se.createdBy;(!L||!he||he===L)&&K.push({...Se,vaultId:X.id,vaultName:X.name||""})}}catch(te){t.log(`[connect] listAllShares pageShares vault ${X.id} failed: ${te?.message}`)}}return{publishes:J,pageShares:K,linkBase:await E.linkBase()}}case"createPublish":{let M=await E.call("POST",`/vaults/${encodeURIComponent(await I())}/shares`,{mode:q(0),path:q(1)});return{...M,url:`${await E.linkBase()}/share/${M.token}`}}case"revokePublish":return E.call("DELETE",`/vaults/${encodeURIComponent(await I())}/shares/${encodeURIComponent(q(0))}`);case"revokePublishIn":return E.call("DELETE",`/vaults/${encodeURIComponent(q(0))}/shares/${encodeURIComponent(q(1))}`);case"revokePageShareIn":return E.call("DELETE",`/vaults/${encodeURIComponent(q(0))}/page-shares/${encodeURIComponent(q(1))}`);case"myUserId":return E.myUserId();case"linkBase":return E.linkBase();case"heartbeat":return E.heartbeat((T??[])[0]??null,h);default:throw new Error(`unknown collab fn: ${_}`)}},switchSide:async(_,T)=>{let E=await Ye();if(T==="cloud"){if(!s||!je())throw new Error("Sign in to open cloud notes");let B=xt();await ln.mkdir(B,{recursive:!0}),E.lastVault&&!Ur(E.lastVault)&&await mt({localVault:E.lastVault}),await mt({lastVault:B});let M=await t.activateRoot(B,!1);return t.bindRenderer(_,B),{...M,side:"cloud"}}let I=E.localVault&&await ln.stat(E.localVault).then(B=>B.isDirectory()).catch(()=>!1)?E.localVault:null;if(!I){let B=await t.ensureDefaultVault();return t.bindRenderer(_,B.root),{...B,side:"local"}}await mt({lastVault:I});let q=await t.activateRoot(I,!1);return t.bindRenderer(_,I),{...q,side:"local"}}},instance:{start:()=>{s=!0,d.start(),y(),se()},stopAllSync:$e,restartAllSync:async()=>{await $e(),o=bo(),d=Hn(u()),s=!0,await Promise.all([d.restart(),y(),se()]),Q(),e(Te.status,ye(d.getStatus()))},resolveSharedAsset:_=>wc(h,_)}}}import{hostname as Tp}from"node:os";var Ip=256*1024;function Uc(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>Ip}var Io=45e3,Rp=3e3,Dp=16*1024,Op=6e4,Xr=t=>`${t.replace(/\/+$/,"")}/api`,Vn=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??Op}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(s,e);function s(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,s()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,s=()=>r.abort();e.signal.addEventListener("abort",s,{once:!0}),this.conn=r;try{let{cloudUrl:o,token:i}=this.deps.getCreds();if(!i)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let a=this.deps.getPairing();if(!a){if(a=await this.register(o,i,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(a),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${a.unitId}`)}let c=this.deps.getLanUrl();this.hubCaps=new Set;let l=this.deps.readIdleMs??Io,u=l?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(l/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},l):null,d;try{d=await this.hubFetch(`${Xr(o)}/units/${a.unitId}/channel`,{headers:{Authorization:`Bearer ${i}`,"X-Unit-Secret":a.secret,...c?{"X-Unit-Lan-Url":c}:{}},signal:r.signal})}finally{u&&clearTimeout(u)}if(d.status===403||d.status===404){let g=Number(d.headers.get("content-length"))>Dp,h=setTimeout(()=>r.abort(),g?0:Rp),m=await d.json().then(y=>y?.code,()=>null);throw clearTimeout(h),m==="UNIT_NOT_FOUND"||m==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${d.status} ${m}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${d.status} (not a hub verdict; keeping pairing and retrying)`)}if(!d.ok||!d.body)throw new Error(`channel HTTP ${d.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(d.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(o){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(o?.message||o),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",s),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 s=this.deps.readIdleMs??Io,o=s?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(s/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},s):null;try{let i=await this.hubFetch(`${Xr(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Tp(),platform:process.platform}),signal:r.signal});if(!i.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${i.status}`);let a=await i.json();if(!a.unitId||!a.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:a.unitId,secret:a.secret}}finally{o&&clearTimeout(o)}}async consume(e,n){let r=e.getReader(),s=new TextDecoder,o="",i=this.deps.readIdleMs??Io,a=null,c=()=>{i&&(a&&clearTimeout(a),a=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(i/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(()=>{})},i))};c();try{for(;;){let{done:l,value:u}=await r.read();if(l||n.signal.aborted)return;c(),o=this.parseFrames(o+s.decode(u,{stream:!0}),n)}}finally{a&&clearTimeout(a)}}parseFrames(e,n){let r=e,s;for(;(s=r.indexOf(`
|
|
218
|
+
`;var Ge=t=>t.replace(/\\/g,"/").normalize("NFC");function vs(t){let e=Ge(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function sn(t,e,n){let r=Ge(n);if(!r)return!1;if(t.some(o=>Ge(o.path)===r))return!0;for(let o of e??[]){let s=Ge(o);if(!s)continue;let i=`${s.replace(/\.md$/i,"")}.fd`;if(r===s||r.startsWith(`${s}/`)||r===i||r.startsWith(`${i}/`))return!1}return t.some(o=>{let s=vs(o);return!!s&&r.startsWith(s)})}function ks(t,e,n){let r=Ge(t),o=Ge(e);return r===o?Ge(n):r.startsWith(`${o}/`)?Ge(n)+r.slice(o.length):null}function zn(t,e,n){let r=!1,o=t.map(s=>{let i=ks(s,e,n);return i===null?s:(r=!0,i)});return{changed:r,next:o}}async function kc(t){let e=await vc.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 vc.readFile(kp.join(t,o.name,Ss),"utf8").catch(()=>null);if(s===null)continue;n.push(o.name);let i=Gr(s);i?.length&&(r[o.name]=i)}return{names:n.sort(),devices:r}}var Te={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",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 Jr=t=>_e().sha256Hex(t).slice(0,8);function Ec(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Dt(t,e=[]){let n=[],r=[];for(let o of t){let s=Ge(o.path);if(!s)continue;r.push(s);let i=vs(o);i&&n.push(i)}return{entries:t,exclude:e,prefixes:n,paths:r}}function _c(t,e){let n=Ec(Ge(e));if(!n)return!1;if(sn(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 Bn(t,e,n){let r=!1,o=t.map(s=>{let i=ks(s.path,e,n);return i===null?s:(r=!0,{...s,path:i})});return{changed:r,next:o}}function Cc(t,e,n,r){if(e==="delete"||e==="delete-folder"){let o=Ge(n),s=t.filter(i=>{let a=Ge(i.path);return!(a===o||e==="delete-folder"&&a.startsWith(`${o}/`))});return{changed:s.length!==t.length,next:s}}return r?Bn(t,n,r):{changed:!1,next:t}}function Es(t,e){let n=Tt(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Yr?`\u300C${Yr}\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 Ep,promises as xc}from"node:fs";async function Ac(t,e){try{await xc.copyFile(Un(t),Un(e),Ep.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await xc.unlink(Un(t)).catch(()=>{}),!0}var _p=/^\d{4}-\d{2}-\d{2}$/,Tc=["vault","content"],Ic=new Set(nc),Cp=40,an=t=>new Date(t).toISOString().slice(0,10),Wn=t=>typeof t=="string"&&_p.test(t),Rc=!1,Qe=Object.create(null),cn=!1,_s=()=>Date.now(),qn=new Set,Kr="";function ot(t,e,n=1,r){try{if(!Rc||!Ic.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let o=an(_s());if(r!==void 0){o!==Kr&&(qn.clear(),Kr=o);let a=`${t}\0${e}\0${r}`;if(qn.has(a))return;qn.add(a)}let s=Qe[o]??={},i=s[t]??={};i[e]=(i[e]??0)+Math.round(n),cn=!0}catch{}}function Cs(t){Rc=t}function Dc(t){if(Qe=Object.create(null),qn.clear(),Kr="",cn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!Wn(e)||!n||typeof n!="object"))for(let r of Tc){let o=n[r];if(!o||typeof o!="object")continue;let s={};for(let[i,a]of Object.entries(o))Ic.has(i)&&typeof a=="number"&&Number.isFinite(a)&&a>0&&(s[i]=Math.round(a));Object.keys(s).length&&((Qe[e]??={})[r]=s)}}}function Oc(){let t=an(_s()-Cp*864e5),e={};for(let n of Object.keys(Qe).sort()){if(n<t){delete Qe[n];continue}e[n]=JSON.parse(JSON.stringify(Qe[n]))}return e}var Pc=()=>cn,Mc=()=>{cn=!1};function $c(t,e){let n=[];for(let r of Object.keys(Qe).sort())if(!(r<=t||r>e))for(let o of Tc){let s=Qe[r][o];s&&Object.keys(s).length&&n.push({day:r,system:o,counts:{...s}})}return n}function xs(t){for(let e of Object.keys(Qe))e<=t&&(delete Qe[e],cn=!0)}function Nc(){Object.keys(Qe).length&&(cn=!0),Qe=Object.create(null),qn.clear(),Kr=""}function jc(t){_s=t}var Fc=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],As=t=>Fc.every(e=>typeof t[e]=="function"),Tp=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function Ts(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Te.get,()=>e?e.get():Tp()),t.handle(Te.setEnabled,(r,o)=>n().setEnabled(o)),t.handle(Te.syncNow,()=>n().syncNow()),t.handle(Te.confirmDeletions,()=>n().confirmDeletions()),t.handle(Te.entryGet,()=>n().entryGet()),t.handle(Te.otherSideDbs,()=>n().otherSideDbs()),t.handle(Te.entryEnable,(r,o)=>n().entryEnable(o)),t.handle(Te.entryDisable,(r,o)=>n().entryDisable(o)),t.handle(Te.entryMark,(r,o,s)=>n().entryMark(o,s)),t.handle(Te.entryClosure,(r,o,s)=>n().entryClosure(o,s)),t.handle(Te.collabCall,(r,o,s)=>n().collabCall(o,s)),t.handle(Te.switchSide,(r,o)=>n().switchSide(r.sender.id,o)),t.setAmadeusSyncFactory(r=>{Za(r);let o=Lc(r);return e=o.handlers,o.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function Lc(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,o=!1,s=bs(),i=new Map,a=()=>{let E=Date.now();for(let[T,_]of i)E-_.at>7e4&&i.delete(T);e(Te.presence,[...i.values()])},l={loadCreds:()=>t.readCreds(),onHealth:(E,T,_)=>ot("vault",E,T,_),onStatus:E=>e(Te.status,{...E,pendingDeletions:xe(),side:p()?"cloud":"local"}),onPresence:(E,T)=>{let _=T;_?.userId&&(i.set(_.userId,{userId:_.userId,username:String(_.username??"user"),page:_.page??null,at:Number(_.at)||Date.now()}),a())},onPresenceRoster:(E,T)=>{if(Array.isArray(T)){for(let _ of T){let I=_;I?.userId&&i.set(I.userId,{userId:I.userId,username:String(I.username??"user"),page:I.page??null,at:Number(I.at)||Date.now()})}a()}}},u=()=>{let E=r;return{...l,onStatus:T=>{E===r&&l.onStatus(T)},onPresence:(T,_)=>{E===r&&l.onPresence(T,_)},onPresenceRoster:(T,_)=>{E===r&&l.onPresenceRoster(T,_)}}},d=Hn(u()),g=new Map,h=[],m=0,y=async()=>{if(!o||!je())return;let E=r,T=++m,_=s,I;try{I=await _.sharedWithMe()}catch{return}if(E!==r||!o||T!==m)return;let B=yc(I);h=B;let q=new Map(B.map(M=>[M.key,M.scopeKey]));for(let[M,L]of g)if(q.get(M)!==L.plan.scopeKey){if(await L.engine.stop(),E!==r)return;g.delete(M)}for(let M of B){if(g.has(M.key))continue;let L=Hn(u(),{localRoot:zt.join(At(),...M.localRelDir.split("/")),shadowName:`amadeus-sync-${Fn()}-share-${M.key}`,vaultId:M.vaultId,serverDir:M.serverDir,inScope:M.inScope});g.set(M.key,{engine:L,plan:M}),L.start()}},p=()=>n()===At(),b=(E,T=E.base)=>{E.base=T;let _=[T,...E.pendingMoves];E.scope.current=Dt(_.flatMap(I=>I.entries),_.flatMap(I=>I.exclude))},v=new Map,$=new Set,R=new Set,O=null,w=()=>O??=new Promise(E=>{let T=()=>Ap.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return E(T());xp("scutil",["--get","ComputerName"],{timeout:1500},(_,I)=>E(!_&&String(I).trim()||T()))}),x=async()=>{let E=(await Ye()).cloudSync?.deviceId;return E?{id:E,name:await w()}:null},C=new Map,D=(E,T,_)=>{let I=r,B=(C.get(E)??Promise.resolve()).catch(()=>{}).then(async()=>{I!==r||_&&!await _()||I!==r||await F(E,T,I)});return C.set(E,B),B.finally(()=>{C.get(E)===B&&C.delete(E)}).catch(()=>{}),B},F=async(E,T,_)=>{let I=s,B=encodeURIComponent(await I.ensureOwnVault()),q=bc(E);for(let M=0;M<3;M++){let L=null;try{L=await I.call("GET",`/vaults/${B}/file?path=${encodeURIComponent(q)}`)}catch(K){if(K?.status!==404)throw K}let J=T(!!L,L?Gr(L.content):null);if(J===void 0||_!==r)return;try{if(J===null){L&&await I.call("DELETE",`/vaults/${B}/file?path=${encodeURIComponent(q)}&baseSeq=${L.seq}`);return}await I.call("PUT",`/vaults/${B}/file`,{path:q,content:Sc(J),baseSeq:L?.seq??0});return}catch(K){if(K?.status!==409)throw K}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},P=async E=>!!(await Ye()).entrySync?.some(T=>T.cloudName===E&&T.entries.length>0),V=(E,T)=>D(E,(_,I)=>{let B=I?.find(M=>M.id===T.id);if(B&&B.name===T.name)return;let q=B?.since??new Date().toISOString().slice(0,10);return[...(I??[]).filter(M=>M.id!==T.id),{...T,since:q}]},()=>P(E)),Z=(E,T)=>D(E,(_,I)=>{if(!_||!I?.some(q=>q.id===T))return;let B=I.filter(q=>q.id!==T);return B.length?B:null},async()=>!await P(E)),Q=()=>{e(Te.entryChange)},ee=async(E,T)=>{let _=v.get(E);if(!_)return;let I=M=>M&&M.startsWith(`${_.cloudName}/`)?M.slice(_.cloudName.length+1):null,B=I(T.path);if(!B)return;let q=!1;await rn(M=>{if(v.get(E)!==_)return!1;let L=(M.entrySync??[]).find(de=>de.vaultRoot===E);if(!L)return!1;let J=T.op,K=I(T.newPath),X=Cc(L.entries,J,B,K),te=K?zn(L.exclude??[],B,K):{changed:!1,next:L.exclude??[]};if(!X.changed&&!te.changed)return!1;q=!0,L.entries=X.next,te.changed&&(L.exclude=te.next),b(_,Dt(L.entries,L.exclude??[]))}),q&&v.get(E)===_&&Q()},re=E=>{let T=r;return{...u(),onStatus:_=>{T===r&&e(Te.status,{..._,pendingDeletions:xe(),side:"local",binding:E})},onRemoteApplied:async _=>{T===r&&await ee(E,_)}}},oe=async()=>{let E=je();if(!o||!E)return;let T=r,_=s,I=Fn(E);await t.adoptLegacyCloudState(E,Ac);let B=await Ye(E),q=B.entrySync??[];if(T!==r||!o||E!==je())return;let M=new Map(q.map(L=>[L.vaultRoot,L]));for(let[L,J]of v){let K=M.get(L);if(!(K&&K.cloudName===J.cloudName)&&(await J.engine.stop(),T!==r||(v.delete(L),K&&await dc(`amadeus-sync-${I}-entry-${Jr(L)}`),T!==r)))return}for(let L of q){let J=v.get(L.vaultRoot);if(J){b(J,Dt(L.entries,L.exclude??[]));continue}let K={current:Dt(L.entries,L.exclude??[])},X=L.cloudName,te=Hn(re(L.vaultRoot),{accountId:E,localRoot:L.vaultRoot,shadowName:`amadeus-sync-${I}-entry-${Jr(L.vaultRoot)}`,vaultId:"first",serverDir:X,clientIdSuffix:`entry-${Jr(L.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:de=>de===X?!0:de.startsWith(`${X}/`)?_c(K.current,de.slice(X.length+1)):!1});v.set(L.vaultRoot,{engine:te,scope:K,cloudName:X,base:K.current,pendingMoves:new Set}),te.start()}if(B.cloudSync?.enabled!==!1)for(let L of q){let J=L.entries.length>0,K=J?$:R;K.has(L.cloudName)||((J?R:$).delete(L.cloudName),(async()=>{try{let X=await x();if(!X||T!==r||(await(J?V(L.cloudName,X):Z(L.cloudName,X.id)),T!==r))return;K.add(L.cloudName),(J?R:$).delete(L.cloudName)}catch{}})())}},pe=async(E,T,_,I,B)=>{let q=T.replace(/\\/g,"/").normalize("NFC"),M=_.replace(/\\/g,"/").normalize("NFC"),L=!1,J,K,X,te=B??"file";try{await rn(async de=>{if(v.get(E)!==I)return!1;let Se=(de.entrySync??[]).find(Ke=>Ke.vaultRoot===E);if(!Se)return!1;let he=Bn(Se.entries,q,M),ne=zn(Se.exclude??[],q,M),De=sn(Se.entries,Se.exclude,q);!B&&await ln.stat(zt.join(E,...M.split("/"))).then(Ke=>Ke.isDirectory(),()=>!1)&&(te="folder");let ge=te==="folder"?"folder":/\.md$/i.test(M)?"page":"asset";De&&!sn(he.next,ne.next,M)&&(he.next.push({path:M,kind:ge}),he.changed=!0),L=he.changed||ne.changed;let Ft=Se.entries.filter(Ke=>Bn([Ke],q,M).changed);return De&&!Ft.some(Ke=>Ke.path===q)&&Ft.push({path:q,kind:ge}),J=Dt(Ft,(Se.exclude??[]).filter(Ke=>zn([Ke],q,M).changed)),K=I.base,I.pendingMoves.add(J),Se.entries=he.next,Se.exclude=ne.next,X=Dt(Se.entries,Se.exclude),b(I,X),L})}catch(de){throw J&&I.pendingMoves.delete(J),b(I,I.base===X&&K?K:I.base),de}try{J&&await I.engine.notifyLocalMove(q,M,()=>{I.pendingMoves.delete(J),b(I)},te)}catch(de){throw J&&I.pendingMoves.delete(J),await rn(Se=>{let he=Se.entrySync?.find(ne=>ne.vaultRoot===E);if(!he)return!1;he.entries=Bn(he.entries,M,q).next,he.exclude=zn(he.exclude??[],M,q).next,b(I,Dt(he.entries,he.exclude))}),de}L&&v.get(E)===I&&Q()},ie=E=>{let T=E.replace(/\\/g,"/");for(let{engine:_,plan:I}of g.values())if(T.startsWith(`${I.localRelDir}/`))return{engine:_,rel:T.slice(I.localRelDir.length+1)};return{engine:d,rel:T}};t.setMutationHooks((E,T)=>{if(p()){let _=ie(E);_.engine.notifyLocal(_.rel,T);return}v.get(n()??"")?.engine.notifyLocal(E,T)},(E,T,_)=>{if(p()){let q=ie(E),M=ie(T);if(q.engine===M.engine)return q.engine.notifyLocalMove(q.rel,M.rel,void 0,_);q.engine.notifyLocal(q.rel,"remove"),M.engine.notifyLocal(M.rel,"write");return}let I=n()??"",B=v.get(I);if(B)return pe(I,E,T,B,_)},(E,T)=>{if(p()){let _=ie(E),I=ie(T),B=[_.engine.holdLocalMove(_.rel,I.rel)];return _.engine!==I.engine&&B.push(I.engine.holdLocalMove(_.rel,I.rel)),()=>{for(let q of B)q()}}return v.get(n()??"")?.engine.holdLocalMove(E,T)});let xe=()=>{let E=d.getStatus().pendingDeletions;for(let{engine:T}of g.values())E+=T.getStatus().pendingDeletions;for(let{engine:T}of v.values())E+=T.getStatus().pendingDeletions;return E},ye=E=>({...E,pendingDeletions:xe(),side:p()?"cloud":"local"}),Re=()=>{if(!o)return Promise.resolve(d.getStatus());y();for(let{engine:E}of g.values())E.syncNow();for(let{engine:E}of v.values())E.syncNow();return d.syncNow()},$e=async()=>{let E=++r;o=!1,s.stop();let T=[d.stop(),...[...g.values()].map(({engine:I})=>I.stop()),...[...v.values()].map(({engine:I})=>I.stop())];if(g.clear(),v.clear(),h=[],$.clear(),R.clear(),i.clear(),a(),await Promise.all(T),await t.awaitPendingVaultWrites(),E!==r)return;let _=n();if(_&&Ur(_)){let I=await Ye();if(E!==r)return;let B=I.localVault&&!Ur(I.localVault)?I.localVault:zt.join(t.workspaceDir(),"Amadeus");if(await ln.mkdir(B,{recursive:!0}),E!==r||(await wt({lastVault:B,localVault:B,lastPage:void 0}),E!==r))return;await t.activateRoot(B,!1)}E===r&&Q()};return{handlers:{get:()=>ye(d.getStatus()),setEnabled:async E=>{if(!o)throw new Error("Cloud account is changing");let T=r;return await d.setEnabled(E),T!==r?d.getStatus():(await Promise.all([...g.values(),...v.values()].map(({engine:_})=>_.restart())),ye(d.getStatus()))},syncNow:()=>Re(),confirmDeletions:()=>{for(let{engine:E}of g.values())E.confirmMassDeletions();for(let{engine:E}of v.values())E.confirmMassDeletions();return ye(d.confirmMassDeletions())},entryGet:async()=>{let E=await Ye(),T=At(),_=await kc(T);return{vaults:E.entrySync??[],activeRoot:n(),cloudRoot:T,mirrorVaults:_.names,mirrorVaultDevices:_.devices,deviceId:E.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let E=n();if(!E)return null;let T=At(),_=await Ye(),I=E===T?_.localVault&&_.localVault!==T?_.localVault:null:T;if(!I)return null;let B=[],q=500,M=async(L,J)=>{if(B.length>=q)return;let K;try{K=await ln.readdir(L,{withFileTypes:!0})}catch{return}for(let X of K){if(B.length>=q)break;if(X.name.startsWith(".")||X.isSymbolicLink())continue;let te=J?`${J}/${X.name}`:X.name;if(X.isDirectory())await M(zt.join(L,X.name),te);else if(X.isFile()&&/\.db$/i.test(X.name))try{B.push({rel:te,source:await ln.readFile(zt.join(L,X.name),"utf8")})}catch{}}};return await M(I,""),{root:I,vaultName:I===T?"\u4E91\u7AEF":zt.basename(I),dbs:B}},entryEnable:async E=>{let T=r,_=s;if(!o||!je())return{error:"Sign in to enable cloud sync"};let I=n();if(!I||p())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let B=await Ye(),q=B.entrySync??[],M=q.find(L=>L.vaultRoot===I);if(!M){let L=(E.cloudName??zt.basename(I)).normalize("NFC").trim(),J=Es(L,q.map(K=>K.cloudName));if(J)return{error:J};if(!E.merge)try{let K=await _.ensureOwnVault(),X=await _.call("GET",`/vaults/${encodeURIComponent(K)}/tree`);if((X.folders??[]).some(de=>de===L||de.startsWith(`${L}/`))||(X.entries??[]).some(de=>de.path===L||de.path.startsWith(`${L}/`)))return{conflict:L}}catch(K){return{error:K?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}M={vaultRoot:I,cloudName:L,entries:[]},q.push(M)}return T!==r||!o?{error:"Cloud account changed; retry from the current account"}:(await rn(L=>{if(T!==r||!o)return!1;let J=L.entrySync??[],K=J.find(ne=>ne.vaultRoot===I);if(!K){let ne=Es(M.cloudName,J.map(De=>De.cloudName));if(ne)throw new Error(ne);K={vaultRoot:I,cloudName:M.cloudName,entries:[]},J.push(K)}let X=ne=>String(ne??"").replace(/\\/g,"/").normalize("NFC"),te=new Set;for(let ne of E.entries??[]){let De=X(ne.path);De&&(te.add(De),!K.entries.some(ge=>ge.path===De)&&K.entries.push({path:De,kind:ne.kind==="folder"||ne.kind==="asset"?ne.kind:"page"}))}let de=(E.exclude??[]).map(X).filter(Boolean),Se=new Set([...te,...(E.include??[]).map(X).filter(Boolean)]);K.exclude=[...new Set([...(K.exclude??[]).filter(ne=>!Se.has(ne)),...de])];let he=new Set(de);K.entries=K.entries.filter(ne=>!he.has(ne.path)),L.entrySync=J,M=K},B.cloudAccountId),T!==r?{error:"Cloud account changed; retry from the current account"}:(await oe(),v.get(I)?.engine.syncNow(),Q(),{ok:!0,cloudName:M.cloudName}))},entryDisable:async E=>{let T=n(),_=!1,I=r;return await rn(B=>{if(I!==r||!o)return!1;let q=(B.entrySync??[]).find(J=>J.vaultRoot===T);if(!T||!q)return!1;let M=String(E??"").replace(/\\/g,"/").normalize("NFC"),L=q.entries.length;if(q.entries=q.entries.filter(J=>J.path!==M),sn(q.entries,q.exclude,M))q.exclude=[...new Set([...q.exclude??[],M])];else if(q.entries.length===L)return!1;_=!0}),!_||I!==r?{ok:!1}:(await oe(),Q(),{ok:!0})},entryMark:async(E,T)=>{let _=String(E??"").normalize("NFC");if(!_||_.includes("/")||_.startsWith("."))return{error:"invalid name"};if(!o||!je())return{error:"Sign in first"};try{await D(_,I=>T?I?void 0:[]:I?null:void 0)}catch(I){return{error:I?.message||String(I)}}return d.syncNow(),{ok:!0}},entryClosure:(E,T)=>t.relatedClosure(String(E??""),T==="folder"?"folder":"page"),collabCall:async(E,T)=>{let _=s,I=async()=>_.ensureOwnVault(),B=M=>String((T??[])[M]??""),q=M=>(T??[])[M]??{};switch(E){case"listVaults":return(await _.call("GET","/vaults")).vaults;case"activeVaultId":return I();case"pageShare":return _.call("GET",`/vaults/${encodeURIComponent(await I())}/page-shares?path=${encodeURIComponent(B(0))}`);case"relatedItems":return _.call("GET",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(B(0))}/related`);case"setShareItem":return _.call("POST",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(B(0))}/items`,{path:B(1),included:(T??[])[2]===!0});case"createPageShare":return _.call("POST",`/vaults/${encodeURIComponent(await I())}/page-shares`,{path:B(0),...q(1)});case"updatePageShare":return _.call("PATCH",`/vaults/${encodeURIComponent(B(2)||await I())}/page-shares/${encodeURIComponent(B(0))}`,q(1));case"revokePageShare":return _.call("DELETE",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(B(0))}`);case"setParticipantRole":return _.call("PATCH",`/vaults/${encodeURIComponent(B(3)||await I())}/page-shares/${encodeURIComponent(B(0))}/members/${encodeURIComponent(B(1))}`,{role:B(2)});case"removeParticipant":return _.call("DELETE",`/vaults/${encodeURIComponent(B(2)||await I())}/page-shares/${encodeURIComponent(B(0))}/members/${encodeURIComponent(B(1))}`);case"sharedWithMe":{let M=await _.sharedWithMe();return y(),M}case"leaveShare":{let M=_.myUserId();if(!M)throw new Error("\u672A\u767B\u5F55");let L=await _.call("DELETE",`/vaults/${encodeURIComponent(B(1)||await I())}/page-shares/${encodeURIComponent(B(0))}/members/${encodeURIComponent(M)}`);return y(),L}case"publishes":return _.call("GET",`/vaults/${encodeURIComponent(await I())}/shares`);case"listAllShares":{let M=(await _.call("GET","/vaults")).vaults||[],L=_.myUserId(),J=[],K=[];for(let X of M){try{let te=await _.call("GET",`/vaults/${encodeURIComponent(X.id)}/shares`);for(let de of te.shares||[])J.push({...de,vaultId:X.id,vaultName:X.name||""})}catch(te){t.log(`[connect] listAllShares publishes vault ${X.id} failed: ${te?.message}`)}try{let te=await _.call("GET",`/vaults/${encodeURIComponent(X.id)}/page-shares?expired=1`),de=te?.shares||te?.pageShares||(Array.isArray(te)?te:[]);for(let Se of de){let he=Se.created_by??Se.createdBy;(!L||!he||he===L)&&K.push({...Se,vaultId:X.id,vaultName:X.name||""})}}catch(te){t.log(`[connect] listAllShares pageShares vault ${X.id} failed: ${te?.message}`)}}return{publishes:J,pageShares:K,linkBase:await _.linkBase()}}case"createPublish":{let M=await _.call("POST",`/vaults/${encodeURIComponent(await I())}/shares`,{mode:B(0),path:B(1)});return{...M,url:`${await _.linkBase()}/share/${M.token}`}}case"revokePublish":return _.call("DELETE",`/vaults/${encodeURIComponent(await I())}/shares/${encodeURIComponent(B(0))}`);case"revokePublishIn":return _.call("DELETE",`/vaults/${encodeURIComponent(B(0))}/shares/${encodeURIComponent(B(1))}`);case"revokePageShareIn":return _.call("DELETE",`/vaults/${encodeURIComponent(B(0))}/page-shares/${encodeURIComponent(B(1))}`);case"myUserId":return _.myUserId();case"linkBase":return _.linkBase();case"heartbeat":return _.heartbeat((T??[])[0]??null,h);default:throw new Error(`unknown collab fn: ${E}`)}},switchSide:async(E,T)=>{let _=await Ye();if(T==="cloud"){if(!o||!je())throw new Error("Sign in to open cloud notes");let q=At();await ln.mkdir(q,{recursive:!0}),_.lastVault&&!Ur(_.lastVault)&&await wt({localVault:_.lastVault}),await wt({lastVault:q});let M=await t.activateRoot(q,!1);return t.bindRenderer(E,q),{...M,side:"cloud"}}let I=_.localVault&&await ln.stat(_.localVault).then(q=>q.isDirectory()).catch(()=>!1)?_.localVault:null;if(!I){let q=await t.ensureDefaultVault();return t.bindRenderer(E,q.root),{...q,side:"local"}}await wt({lastVault:I});let B=await t.activateRoot(I,!1);return t.bindRenderer(E,I),{...B,side:"local"}}},instance:{start:()=>{o=!0,d.start(),y(),oe()},stopAllSync:$e,restartAllSync:async()=>{let E=$e(),T=r;await E,T===r&&(s=bs(),d=Hn(u()),o=!0,await Promise.all([d.restart(),y(),oe()]),T===r&&(Q(),e(Te.status,ye(d.getStatus()))))},resolveSharedAsset:E=>wc(h,E)}}}import{hostname as Ip}from"node:os";var Rp=256*1024;function Uc(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>Rp}var Is=45e3,Dp=3e3,Op=16*1024,Pp=6e4,Xr=t=>`${t.replace(/\/+$/,"")}/api`,Vn=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??Pp}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:i}=this.deps.getCreds();if(!i)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let a=this.deps.getPairing();if(!a){if(a=await this.register(s,i,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(a),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${a.unitId}`)}let c=this.deps.getLanUrl();this.hubCaps=new Set;let l=this.deps.readIdleMs??Is,u=l?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(l/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},l):null,d;try{d=await this.hubFetch(`${Xr(s)}/units/${a.unitId}/channel`,{headers:{Authorization:`Bearer ${i}`,"X-Unit-Secret":a.secret,...c?{"X-Unit-Lan-Url":c}:{}},signal:r.signal})}finally{u&&clearTimeout(u)}if(d.status===403||d.status===404){let g=Number(d.headers.get("content-length"))>Op,h=setTimeout(()=>r.abort(),g?0:Dp),m=await d.json().then(y=>y?.code,()=>null);throw clearTimeout(h),m==="UNIT_NOT_FOUND"||m==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${d.status} ${m}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${d.status} (not a hub verdict; keeping pairing and retrying)`)}if(!d.ok||!d.body)throw new Error(`channel HTTP ${d.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(d.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(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??Is,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 i=await this.hubFetch(`${Xr(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Ip(),platform:process.platform}),signal:r.signal});if(!i.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${i.status}`);let a=await i.json();if(!a.unitId||!a.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:a.unitId,secret:a.secret}}finally{s&&clearTimeout(s)}}async consume(e,n){let r=e.getReader(),o=new TextDecoder,s="",i=this.deps.readIdleMs??Is,a=null,c=()=>{i&&(a&&clearTimeout(a),a=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(i/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(()=>{})},i))};c();try{for(;;){let{done:l,value:u}=await r.read();if(l||n.signal.aborted)return;c(),s=this.parseFrames(s+o.decode(u,{stream:!0}),n)}}finally{a&&clearTimeout(a)}}parseFrames(e,n){let r=e,o;for(;(o=r.indexOf(`
|
|
219
219
|
|
|
220
|
-
`))>=0;){let
|
|
221
|
-
`).find(c=>c.startsWith("data: "))?.slice(6);try{let c=JSON.parse(a||"{}").caps;this.hubCaps=new Set(Array.isArray(c)?c.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!
|
|
222
|
-
`).find(a=>a.startsWith("data: "))?.slice(6);if(i)try{let a=JSON.parse(i);this.dispatch(a,n).catch(c=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${c?.message||c}`))}catch{}}return r}async dispatch(e,n){let r=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let
|
|
223
|
-
`,i===e&&(
|
|
224
|
-
`))}return
|
|
220
|
+
`))>=0;){let s=r.slice(0,o);if(r=r.slice(o+2),s.includes("event: ready")){let a=s.split(`
|
|
221
|
+
`).find(c=>c.startsWith("data: "))?.slice(6);try{let c=JSON.parse(a||"{}").caps;this.hubCaps=new Set(Array.isArray(c)?c.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!s.includes("event: dispatch"))continue;let i=s.split(`
|
|
222
|
+
`).find(a=>a.startsWith("data: "))?.slice(6);if(i)try{let a=JSON.parse(i);this.dispatch(a,n).catch(c=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${c?.message||c}`))}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})),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 i=s.headers.get("content-type")||"",a={};for(let u of["content-security-policy","x-content-type-options"]){let d=s.headers.get(u);d&&(a[u]=d)}let c=i||"application/octet-stream";s.body&&Uc(i,s.headers.get("content-length"),{hasSecHeaders:Object.keys(a).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,s,n,c,a):await this.respond(e.id,s.status,c,Buffer.from(await s.arrayBuffer()),a,n.signal)}async respond(e,n,r,o,s,i){if(i?.aborted)return;let{cloudUrl:a,token:c}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let u=this.requestTimeoutMs*2,d=[...u?[AbortSignal.timeout(u)]:[],...i?[i]:[]],g=d.length>1?AbortSignal.any(d):d[0];await this.hubFetch(`${Xr(a)}/units/${l.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"X-Unit-Secret":l.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":r,...s},bodyB64:o.toString("base64")}),...g?{signal:g}:{}}).then(h=>{h.body?.cancel().catch(()=>{})}).catch(h=>{i?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${h?.name==="TimeoutError"?`${Math.round(u/1e3)}s \u672A\u5B8C\u6210`:h?.message||h}`)})}async streamBack(e,n,r,o,s){let{cloudUrl:i,token:a}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let l=s?.["content-security-policy"],u=s?.["x-content-type-options"],d=`${Xr(i)}/units/${c.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(o)}`+(l?`&csp=${encodeURIComponent(l)}`:"")+(u?`&xcto=${encodeURIComponent(u)}`:""),g=n.body;if(!g)return;let h=g.getReader(),m=0,y=this.requestTimeoutMs,p=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,b=new ReadableStream({async pull(v){++m===2&&p&&clearTimeout(p);let{done:$,value:R}=await h.read();$?v.close():v.enqueue(R)},cancel(v){return h.cancel(v)}},{highWaterMark:0});try{await this.hubFetch(d,{method:"POST",headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":c.secret,"Content-Type":"application/octet-stream"},body:b,signal:r.signal,duplex:"half"})}catch(v){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${v?.message||v}`);try{await h.cancel()}catch{}}finally{p&&clearTimeout(p)}}};var Yn=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()}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(a){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${a?.message||a}`);return}if(e===this.lastSent)return;let n=this.d.getPairing(),r;try{r=this.d.getCreds()}catch{return}if(!n||!r.token||!r.cloudUrl)return;let o=this.gen;this.inflight=!0;let s=new AbortController,i=setTimeout(()=>s.abort(),this.d.timeoutMs??1e4);try{let a=`${r.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(n.unitId)}/caps`,c=await(this.d.hubFetch??fetch)(a,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"X-Unit-Secret":n.secret,"Content-Type":"application/json"},body:JSON.stringify({engine:e,tools:[]}),signal:s.signal});try{await c.text()}catch{}if(o!==this.gen)return;c.ok?(this.lastSent=e,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}`)):c.status===404||c.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${c.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):c.status===400||c.status===401||c.status===403?this.warned.has(c.status)||(this.warned.add(c.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${c.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${c.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(a){o===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${s.signal.aborted?"\u8D85\u65F6":a?.message||a}`)}finally{clearTimeout(i),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var Hc=["setUnitHubFactory"],Rs=t=>Hc.every(e=>typeof t[e]=="function");function zc(t){let e=new Yn({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),log:r=>t.log(r)}),n=new Vn({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()}}function Ds(t){let e=async(n,r,o)=>{let{base:s,token:i}=await t.getCloud();if(!i)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let a=await fetch(`${s}/api${r}`,{method:n,headers:{Authorization:`Bearer ${i}`,...o!==void 0?{"Content-Type":"application/json"}:{}},body:o!==void 0?JSON.stringify(o):void 0});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}};t.handle("units:list",()=>e("GET","/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(zc),t.log("[forsion-extend] unit hub registered")}import{createHash as Qp}from"node:crypto";import{constants as fl,mkdirSync as eh,readFileSync as th,renameSync as nh,writeFileSync as rh}from"node:fs";import{lstat as vt,open as xl,readFile as oh,readdir as Al,statfs as sh}from"node:fs/promises";import{cpus as ih,freemem as ah,homedir as pl,hostname as Tl,release as ch,totalmem as lh}from"node:os";import{basename as Il,join as le}from"node:path";var Mp=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Gn=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(Mp);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 $p(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Np(t,e,n){let r=t.split(/\r\n|\n|\r/g),o="",s=(Math.log10(e+1)|0)+1;for(let i=e-1;i<=e+1;i++){let a=r[i-1];a&&(o+=i.toString().padEnd(s," "),o+=": ",o+=a,o+=`
|
|
223
|
+
`,i===e&&(o+=" ".repeat(s+n+2),o+=`^
|
|
224
|
+
`))}return o}var ae=class extends Error{line;column;codeblock;constructor(e,n){let[r,o]=$p(n.toml,n.ptr),s=Np(n.toml,r,o);super(`Invalid TOML document: ${e}
|
|
225
225
|
|
|
226
|
-
${
|
|
226
|
+
${s}`,n),this.line=r,this.column=o,this.codeblock=s}};var jp=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Fp=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Lp=/^[+-]?0[0-9_]/;function Zr(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 i="",a=e,c=0;for(let l=e;l<t.length;l++)if(n=t[l],
|
|
228
|
+
`&&(e+=2));let i="",a=e,c=0;for(let l=e;l<t.length;l++)if(n=t[l],s&&(n===`
|
|
229
229
|
`||n==="\r"&&t[l+1]===`
|
|
230
|
-
`))c=c&&3;else{if(n<" "&&n!==" "||n==="\x7F")throw new ae("control characters are not allowed in strings",{toml:t,ptr:l});if((!c||c===3)&&n===r&&(!
|
|
231
|
-
`;else if(n==="f")i+="\f";else if(n==="r")i+="\r";else if(n==="e")i+="\x1B";else if(n==='"')i+='"';else if(n==="\\")i+="\\";else throw new ae("unrecognized escape sequence",{toml:t,ptr:l});a=l+1,c=0}else if(n!==" "&&n!==" "){if(c===2)throw new ae("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:a});c=!
|
|
230
|
+
`))c=c&&3;else{if(n<" "&&n!==" "||n==="\x7F")throw new ae("control characters are not allowed in strings",{toml:t,ptr:l});if((!c||c===3)&&n===r&&(!s||t[l+1]===r&&t[l+2]===r))return s&&(t[l+3]===r&&l++,t[l+3]===r&&l++),[c?i:i+t.slice(a,l),l+(s?3:1)];if(!c)!o&&n==="\\"&&(i+=t.slice(a,a=l),c=1);else if(c===1)if(n==="x"||n==="u"||n==="U"){let u=0,d=n==="x"?2:n==="u"?4:8;for(let g=0;g<d;g++,l++){let h=t.charCodeAt(l+1),m=h>=48&&h<=57?h-48:h>=65&&h<=70?h-65+10:h>=97&&h<=102?h-97+10:-1;if(m<0)throw new ae("invalid non-hex character in unicode escape",{toml:t,ptr:l+1});u=u<<4|m}if(u<0||u>1114111||u>=55296&&u<=57343)throw new ae("invalid unicode escape",{toml:t,ptr:l});i+=String.fromCodePoint(u),a=l+1,c=0}else if(n===" "||n===" ")c=2;else{if(n==="b")i+="\b";else if(n==="t")i+=" ";else if(n==="n")i+=`
|
|
231
|
+
`;else if(n==="f")i+="\f";else if(n==="r")i+="\r";else if(n==="e")i+="\x1B";else if(n==='"')i+='"';else if(n==="\\")i+="\\";else throw new ae("unrecognized escape sequence",{toml:t,ptr:l});a=l+1,c=0}else if(n!==" "&&n!==" "){if(c===2)throw new ae("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:a});c=!o&&n==="\\"?1:0,a=l}}throw new ae("unfinished string",{toml:t,ptr:e})}function Bc(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=jp.test(t);if(o||Fp.test(t)){if(Lp.test(t))throw new ae("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let i=+t;if(isNaN(i))throw new ae("invalid number",{toml:e,ptr:n});if(o){if((o=!Number.isSafeInteger(i))&&!r)throw new ae("integer value cannot be represented losslessly",{toml:e,ptr:n});(o||r===!0)&&(i=BigInt(t))}return i}let s=new Gn(t);if(!s.isValid())throw new ae("invalid value",{toml:e,ptr:n});return s}function Qr(t,e=0,n=t.length){let r=t.indexOf(`
|
|
232
232
|
`,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function un(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 ae("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function
|
|
235
|
-
`||
|
|
236
|
-
`);)e++;if(r||
|
|
237
|
-
`||i==="\r"&&t[
|
|
238
|
-
`))return
|
|
239
|
-
`&&t[l]!=="\r")throw new ae("unexpected character encountered",{toml:t,ptr:l});t[l]===","&&l++}return[c,l]}let i=qc(t,e,",",n),a=
|
|
240
|
-
`&&i!=="\r"){let a,c=
|
|
241
|
-
`&&
|
|
242
|
-
`&&t[a]!=="\r")throw new ae("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=at(t,a)}return r}var rs=14,Hp=1440*6e4,zp=12e4,Bp=15e3,Oo=1792*1024,qp=7,yt=t=>t.toISOString().slice(0,10),ct=t=>Date.parse(yt(t))-(qp-1)*Hp,Gc=["sessions","activity"],ns=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Po(t,e,n){let r=t?.day===yt(n)?t:void 0;return Object.fromEntries(Gc.map(s=>[s,ns(r?.[s])??Math.min(Math.max(ns(e[s])??0,ct(n)),n.getTime())]))}function Mo(t,e,n,r,s,o){let i=e?.day===yt(r)?e:void 0,a={sent:{...t},file:{day:yt(r)}};for(let c of Gc){let l=c in s&&!o.includes(c)&&!(`${c}Error`in s),u=ns(i?.[c]);l?(a.file[c]=n[c],a.sent[c]=r.getTime()):u!==void 0&&(a.sent[c]=Math.min(ns(t[c])??u,u))}return a}function Jc(t,e=[]){let n={...t},r=Tn(JSON.stringify(n));for(let s of["activity","sessions","memory","runs","engine"]){if(r.length<=Oo)break;s in n&&(delete n[s],e.push(s),r=Tn(JSON.stringify({...n,truncated:e})))}return r.length>Oo?null:r}async function $o(t,e,n,r=new Date){let s=AbortSignal.timeout(zp);await t.writeFile(`${e}/${yt(r)}.json`,n,r.getTime(),s);try{let o=yt(new Date(r.getTime()-rs*24*60*6e4));for(let i of await t.walk(s)){let a=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(i.key);a&&a[1]===e&&a[2]<o&&await t.rm(i.key,s)}}catch{}}var No={mode:"scheduled",intervalHours:24,requestedAt:0};function Kn(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:No.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function jo(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Bp)});return e.status===404?{...No}:e.ok?Kn(await e.json()):null}catch{return null}}var Xc=["merge","cloud","local"],Zc={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Dt(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 Wp(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 Ot(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,s=new Set,o=n.rules.map(i=>{let a=Dt(i.source,!0),c=Wp(i.target);if(typeof i.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(i.id)||s.has(i.id)||r.has(a))throw Error("Duplicate or invalid sync rule");return s.add(i.id),r.add(a),{id:i.id,source:a,target:c,...i.sourceId&&/^[a-f0-9-]{36}$/i.test(i.sourceId)?{sourceId:i.sourceId}:{}}});return{version:1,revision:e,enabled:n.enabled,rules:o}}function dn(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 lt={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"},ss=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,Kc=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Fo=(t,e,n)=>{let r=Kc(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(s=>s.id!==n&&Kc(s.name)===r)?"taken":null:null},Qc=["Amadeus","agents","human","Plugins"];var wt=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var Xn=/^[a-z0-9][a-z0-9-]{0,63}$/,os=new Set(["muse"]),Zn=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&Xn.test(e[1])?e[1]:null},Vp=t=>[...os].some(e=>Lo(t,`agents/${e}`));function el(t){let e=t.split(/^\s*\[/m)[0]??"",n=o=>{let i=new RegExp(`^[ \\t]*${o}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(i?.[1]!=null?i[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):i?.[2])?.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,80)||void 0},r=n("name"),s=n("name_en");return{...r?{name:r}:{},...s?{nameEn:s}:{}}}var fn=(t,e)=>dn(e,t)?.target??"off",Lo=(t,e)=>t===e||t.startsWith(e+"/"),Yp=t=>wt.some(e=>Lo(t,e.path)),Uo=t=>t.some(e=>e.id==="default")?is():"default",tl=(t,e)=>t.enabled?fn(t.rules,e):"off";function nl(t,e,n){n==="off"&&(t=t.filter(o=>e?!o.source.startsWith(e+"/"):!o.source||Yp(o.source)));let r=t.find(o=>o.source===e),s=t.filter(o=>o!==r);return e&&fn(s,e)===n?s:r?t.map(o=>o===r?{...o,target:n}:o):[...t,{id:e?is():Uo(t),source:e,target:n}]}function pn(t,e,n,r=!1){if(Vp(e))return t;let s=t.rules;if(!t.enabled){let o=s.find(a=>!a.source),i=e?s.filter(a=>a.source&&Lo(a.source,e)):[];s=[{id:o?.id??Uo(i),source:"",target:"off"},...i],e!=="agents"&&(s=Ho(s,"agents","off"))}if(!e)for(let o of wt)s.some(i=>i.source===o.path)||(s=[...s,{id:is(),source:o.path,target:fn(s,o.path)}]);return rl({...t,rules:nl(s,e,n)},r)}function rl(t,e=!1){let n=r=>fn(t.rules,r)!=="off";return{...t,enabled:wt.some(r=>n(r.path))||t.rules.some(r=>r.source&&r.target!=="off")||e&&n("")}}function sl(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:Uo(t.rules),source:"",target:"default"},...t.rules];for(let n of wt)n.id!=="agents"&&fn(e,n.path)==="off"&&(e=nl(e,n.path,"default"));return e=Ho(e,"agents","off"),{...t,enabled:!0,rules:e}}function Ho(t,e,n){let r=t.find(s=>s.source===e);return r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:is(),source:e,target:n}]}function ol(t,e){let n=t;for(let r of new Set(e))Xn.test(r)&&!os.has(r)&&(n=pn(n,`agents/${r}`,"default"));return n}function il(t){let e=fn(t.rules,"agents")!=="off"||t.rules.some(s=>s.source.startsWith("agents/")&&s.target!=="off"),n=t.rules.some(s=>s.source.startsWith("agents/"));if(!e&&!n)return null;let r=Ho(t.rules.filter(s=>!s.source.startsWith("agents/")),"agents","off");return t.enabled?rl({...t,rules:r},!0):{...t,rules:r}}var Gp=0,is=()=>`rule-${Date.now().toString(36)}-${(Gp++).toString(36)}`;var al=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var Jp=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function cl(t,e=[]){let n=t;for(let r of[...e].filter(s=>s&&s.length>=2).sort((s,o)=>o.length-s.length))n=n.split(r).join("[path]");return n.replace(/^(Duplicate folder sync identity|Concurrent (?:folder|file) rename): [\s\S]*$/,"$1: [path]")}var Qn=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||Jp.test(e))return;this.count("errors"),/^File exceeds \d+ MB/.test(e)&&this.count("tooLarge");let s=this.errors[this.errors.length-1];if(s&&s.text===e){s.n++,s.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(s=>typeof s=="string"&&s);!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 s={at:r.at,ms:Math.max(0,n-r.at),completed:e,counts:r.counts};this.last=s,this.totals.runs++,e&&this.totals.completedRuns++,!e||Object.keys(r.counts).length?(this.runs.push(s),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]}:{}}))}}},ll=null;function ul(t){ll=t}function dl(){try{return ll?.()??null}catch{return null}}var lh=(t,e=[])=>{let n=Jc(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},Rl=60*6e4,uh=2*6e4,dh=10*6e4,hl=Rl,fh=4*1024*1024,ph=256*1024,gl=["user","teamwork","discussion","delegate"],hh=/^(?:New remarks in the team chat:|You are activated now \()/,Dl={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Bo=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,Ol=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,s)=>Bo.test(s)||e&&!/\s/.test(s)?n:`${r}[path]${r}`),Pl=t=>Ol(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>Bo.test(e)?e:"[path]"),nr=4e3,cs=(t,e)=>typeof t=="string"&&t?dt(Pl(ft(t.slice(0,nr))),e):void 0,gh={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},mh=64*1024,zo=500,yh={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},wh=256*1024,ml=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],bh=["description","developer_instructions"],Sh=["memory","harness","project_memory","human","dream","log_appended"],vh=["homeDir","readCreds","accountId","appVersion"],qo=t=>vh.every(e=>typeof t[e]=="function"),yl=pl().length>3?pl():null;function ft(t){return typeof t=="string"?(yl?t.split(yl).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(ft):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]":ft(n)])):t}var kh=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ce=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,Eh=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function hn(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,[s,o]]of Object.entries(t).slice(0,100).entries())n[Eh(s,r)]=kh.test(s)&&ce(o,80)!==void 0?o:hn(o,e+1);return n}var _h={"":/^(?: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)$/},wl={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},Ch=/^(?:apps|enabled_skill_ids)$/,bl=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function xh(t){try{let e=ts(t),n=[],r=[],s=8192,o=(c,l)=>s<=0?!1:(s-=l.length+1,c.push(l),!0),i=(c,l,u)=>{let d=_h[c].test(l)?l:`[key:${l.length}]`,g=wl[c].test(l),h;return typeof u=="boolean"||typeof u=="number"?h=String(u):g&&typeof u=="string"&&!/[\r\n]/.test(u)&&JSON.stringify(u).length<=120?h=JSON.stringify(u):g&&u instanceof Date?h=u.toISOString():c===""&&Ch.test(l)&&Array.isArray(u)&&u.every(m=>typeof m=="string"&&!/[\r\n]/.test(m))&&JSON.stringify(u).length<=2e3&&(h=`[${u.map(m=>JSON.stringify(m)).join(", ")}]`),`${d} = ${h??`"[text:${typeof u=="string"?u.length:JSON.stringify(u).length}]"`}`},a=(c,l,u)=>{if(o(r,l)){for(let[d,g]of Object.entries(u))if(!o(r,i(c,d,g)))return}};for(let[c,l]of Object.entries(e)){let u=c!==""&&Object.hasOwn(wl,c);if(u&&bl(l))a(c,`[${c}]`,l);else if(u&&Array.isArray(l)&&l.length>0&&l.every(bl))for(let d of l)a(c,`[[${c}]]`,d);else o(n,i("",c,l));if(s<=0)break}return[...n,...r].join(`
|
|
243
|
-
`)}catch{return`[unparsed:${t.length}]`}}var Ml=async t=>{try{return(await
|
|
244
|
-
`)+1):i}finally{await n.close()}}function
|
|
234
|
+
`)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new ae("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function lt(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=un(t,e)}return e}function qc(t,e,n,r,o=!1){if(!r)return e=Qr(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let i=t[s];if(i==="#")s=Qr(t,s);else{if(i===n)return s+1;if(i===r||o&&(i===`
|
|
237
|
+
`||i==="\r"&&t[s+1]===`
|
|
238
|
+
`))return s}}throw new ae("cannot find end of structure",{toml:t,ptr:e})}function Up(t,e,n){let r=t.slice(e,n),o=r.indexOf("#");return o>-1&&(un(t,o),r=r.slice(0,o)),[r.trimEnd(),o]}function Jn(t,e,n,r,o){if(r===0)throw new ae("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let s=t[e];if(s==="["||s==="{"){let[c,l]=s==="["?Vc(t,e,r,o):Wc(t,e,r,o);if(n){if(l=lt(t,l),t[l]===",")l++;else if(t[l]!==n)throw new ae("expected comma or end of structure",{toml:t,ptr:l})}return[c,l]}if(s==='"'||s==="'"){let[c,l]=Zr(t,e);if(n){if(l=lt(t,l),t[l]&&t[l]!==","&&t[l]!==n&&t[l]!==`
|
|
239
|
+
`&&t[l]!=="\r")throw new ae("unexpected character encountered",{toml:t,ptr:l});t[l]===","&&l++}return[c,l]}let i=qc(t,e,",",n),a=Up(t,e,i-(t[i-1]===","?1:0));if(!a[0])throw new ae("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&a[1]>-1&&(i=lt(t,e+a[1]),t[i]===","&&i++),[Bc(a[0],t,e,o),i]}var Hp=/^[a-zA-Z0-9-_]+[ \t]*$/;function eo(t,e,n="="){let r=e-1,o=[],s=t.indexOf(n,e);if(s<0)throw new ae("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let i=t[e=++r];if(i!==" "&&i!==" ")if(i==='"'||i==="'"){if(i===t[e+1]&&i===t[e+2])throw new ae("multiline strings are not allowed in keys",{toml:t,ptr:e});let[a,c]=Zr(t,e);r=t.indexOf(".",c);let l=t.slice(c,r<0||r>s?s:r),u=Qr(l);if(u>-1)throw new ae("newlines are not allowed in keys",{toml:t,ptr:e+r+u});if(l.trimStart())throw new ae("found extra tokens after the string part",{toml:t,ptr:c});if(s<c&&(s=t.indexOf(n,c),s<0))throw new ae("incomplete key-value: cannot find end of key",{toml:t,ptr:e});o.push(a)}else{r=t.indexOf(".",e);let a=t.slice(e,r<0||r>s?s:r);if(!Hp.test(a))throw new ae("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});o.push(a.trimEnd())}}while(r+1&&r<s);return[o,lt(t,s+1,!0,!0)]}function Wc(t,e,n,r){let o={},s=new Set,i;for(e++;(i=t[e++])!=="}"&&i;){if(i===",")throw new ae("expected value, found comma",{toml:t,ptr:e-1});if(i==="#")e=un(t,e);else if(i!==" "&&i!==" "&&i!==`
|
|
240
|
+
`&&i!=="\r"){let a,c=o,l=!1,[u,d]=eo(t,e-1);for(let m=0;m<u.length;m++){if(m&&(c=l?c[a]:c[a]={}),a=u[m],(l=Object.hasOwn(c,a))&&(typeof c[a]!="object"||s.has(c[a])))throw new ae("trying to redefine an already defined value",{toml:t,ptr:e});!l&&a==="__proto__"&&Object.defineProperty(c,a,{enumerable:!0,configurable:!0,writable:!0})}if(l)throw new ae("trying to redefine an already defined value",{toml:t,ptr:e});let[g,h]=Jn(t,d,"}",n-1,r);s.add(g),c[a]=g,e=h}}if(!i)throw new ae("unfinished table encountered",{toml:t,ptr:e});return[o,e]}function Vc(t,e,n,r){let o=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new ae("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=un(t,e);else if(s!==" "&&s!==" "&&s!==`
|
|
241
|
+
`&&s!=="\r"){let i=Jn(t,e-1,"]",n-1,r);o.push(i[0]),e=i[1]}}if(!s)throw new ae("unfinished array encountered",{toml:t,ptr:e});return[o,e]}function Yc(t,e,n,r){let o=e,s=n,i,a=!1,c;for(let l=0;l<t.length;l++){if(l){if(o=a?o[i]:o[i]={},s=(c=s[i]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let u=o.length-1;o=o[u],s=s[u].c}}if(i=t[l],(a=Object.hasOwn(o,i))&&s[i]?.t===0&&s[i]?.d)return null;a||(i==="__proto__"&&(Object.defineProperty(o,i,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,i,{enumerable:!0,configurable:!0,writable:!0})),s[i]={t:l<t.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=s[i],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=!0,o[i]=[]),o[i].push(o={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)o=a?o[i]:o[i]={};else if(r===0&&a)return null;return[i,o,c.c]}function to(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},o={},s=r,i=o;for(let a=lt(t,0);a<t.length;){if(t[a]==="["){let c=t[++a]==="[",l=eo(t,a+=+c,"]");if(c){if(t[l[1]-1]!=="]")throw new ae("expected end of table declaration",{toml:t,ptr:l[1]-1});l[1]++}let u=Yc(l[0],r,o,c?2:1);if(!u)throw new ae("trying to redefine an already defined table or value",{toml:t,ptr:a});i=u[2],s=u[1],a=l[1]}else{let c=eo(t,a),l=Yc(c[0],s,i,0);if(!l)throw new ae("trying to redefine an already defined table or value",{toml:t,ptr:a});let u=Jn(t,c[1],void 0,e,n);l[1][l[0]]=u[0],a=u[1]}if(a=lt(t,a,!0),t[a]&&t[a]!==`
|
|
242
|
+
`&&t[a]!=="\r")throw new ae("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=lt(t,a)}return r}var ro=14,zp=1440*6e4,Bp=12e4,qp=15e3,Os=1792*1024,Wp=7,bt=t=>t.toISOString().slice(0,10),ut=t=>Date.parse(bt(t))-(Wp-1)*zp,Gc=["sessions","activity"],no=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Ps(t,e,n){let r=t?.day===bt(n)?t:void 0;return Object.fromEntries(Gc.map(o=>[o,no(r?.[o])??Math.min(Math.max(no(e[o])??0,ut(n)),n.getTime())]))}function Ms(t,e,n,r,o,s){let i=e?.day===bt(r)?e:void 0,a={sent:{...t},file:{day:bt(r)}};for(let c of Gc){let l=c in o&&!s.includes(c)&&!(`${c}Error`in o),u=no(i?.[c]);l?(a.file[c]=n[c],a.sent[c]=r.getTime()):u!==void 0&&(a.sent[c]=Math.min(no(t[c])??u,u))}return a}function Jc(t,e=[]){let n={...t},r=Tn(JSON.stringify(n));for(let o of["activity","sessions","memory","runs","engine"]){if(r.length<=Os)break;o in n&&(delete n[o],e.push(o),r=Tn(JSON.stringify({...n,truncated:e})))}return r.length>Os?null:r}async function $s(t,e,n,r=new Date){let o=AbortSignal.timeout(Bp);await t.writeFile(`${e}/${bt(r)}.json`,n,r.getTime(),o);try{let s=bt(new Date(r.getTime()-ro*24*60*6e4));for(let i of await t.walk(o)){let a=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(i.key);a&&a[1]===e&&a[2]<s&&await t.rm(i.key,o)}}catch{}}var Ns={mode:"scheduled",intervalHours:24,requestedAt:0};function Kn(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:Ns.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function js(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(qp)});return e.status===404?{...Ns}:e.ok?Kn(await e.json()):null}catch{return null}}var Xc=["merge","cloud","local"],Zc={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Ot(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 Vp(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 Pt(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(i=>{let a=Ot(i.source,!0),c=Vp(i.target);if(typeof i.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(i.id)||o.has(i.id)||r.has(a))throw Error("Duplicate or invalid sync rule");return o.add(i.id),r.add(a),{id:i.id,source:a,target:c,...i.sourceId&&/^[a-f0-9-]{36}$/i.test(i.sourceId)?{sourceId:i.sourceId}:{}}});return{version:1,revision:e,enabled:n.enabled,rules:s}}function dn(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 dt={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"},oo=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,Kc=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Fs=(t,e,n)=>{let r=Kc(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(o=>o.id!==n&&Kc(o.name)===r)?"taken":null:null},Qc=["Amadeus","agents","human","Plugins"];var St=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var Xn=/^[a-z0-9][a-z0-9-]{0,63}$/,so=new Set(["muse"]),Zn=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&Xn.test(e[1])?e[1]:null},Yp=t=>[...so].some(e=>Ls(t,`agents/${e}`));function el(t){let e=t.split(/^\s*\[/m)[0]??"",n=s=>{let i=new RegExp(`^[ \\t]*${s}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(i?.[1]!=null?i[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):i?.[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 fn=(t,e)=>dn(e,t)?.target??"off",Ls=(t,e)=>t===e||t.startsWith(e+"/"),Gp=t=>St.some(e=>Ls(t,e.path)),Us=t=>t.some(e=>e.id==="default")?io():"default",tl=(t,e)=>t.enabled?fn(t.rules,e):"off";function nl(t,e,n){n==="off"&&(t=t.filter(s=>e?!s.source.startsWith(e+"/"):!s.source||Gp(s.source)));let r=t.find(s=>s.source===e),o=t.filter(s=>s!==r);return e&&fn(o,e)===n?o:r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:e?io():Us(t),source:e,target:n}]}function pn(t,e,n,r=!1){if(Yp(e))return t;let o=t.rules;if(!t.enabled){let s=o.find(a=>!a.source),i=e?o.filter(a=>a.source&&Ls(a.source,e)):[];o=[{id:s?.id??Us(i),source:"",target:"off"},...i],e!=="agents"&&(o=Hs(o,"agents","off"))}if(!e)for(let s of St)o.some(i=>i.source===s.path)||(o=[...o,{id:io(),source:s.path,target:fn(o,s.path)}]);return rl({...t,rules:nl(o,e,n)},r)}function rl(t,e=!1){let n=r=>fn(t.rules,r)!=="off";return{...t,enabled:St.some(r=>n(r.path))||t.rules.some(r=>r.source&&r.target!=="off")||e&&n("")}}function ol(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:Us(t.rules),source:"",target:"default"},...t.rules];for(let n of St)n.id!=="agents"&&fn(e,n.path)==="off"&&(e=nl(e,n.path,"default"));return e=Hs(e,"agents","off"),{...t,enabled:!0,rules:e}}function Hs(t,e,n){let r=t.find(o=>o.source===e);return r?t.map(o=>o===r?{...o,target:n}:o):[...t,{id:io(),source:e,target:n}]}function sl(t,e){let n=t;for(let r of new Set(e))Xn.test(r)&&!so.has(r)&&(n=pn(n,`agents/${r}`,"default"));return n}function il(t){let e=fn(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=Hs(t.rules.filter(o=>!o.source.startsWith("agents/")),"agents","off");return t.enabled?rl({...t,rules:r},!0):{...t,rules:r}}var Jp=0,io=()=>`rule-${Date.now().toString(36)}-${(Jp++).toString(36)}`;var al=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var Kp=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function cl(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 Qn=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||Kp.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]}:{}}))}}},ll=null;function ul(t){ll=t}function dl(){try{return ll?.()??null}catch{return null}}var uh=(t,e=[])=>{let n=Jc(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},Rl=60*6e4,dh=2*6e4,fh=10*6e4,hl=Rl,ph=4*1024*1024,hh=256*1024,gl=["user","teamwork","discussion","delegate"],gh=/^(?:New remarks in the team chat:|You are activated now \()/,Dl={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Bs=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,Ol=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,o)=>Bs.test(o)||e&&!/\s/.test(o)?n:`${r}[path]${r}`),Pl=t=>Ol(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>Bs.test(e)?e:"[path]"),nr=4e3,co=(t,e)=>typeof t=="string"&&t?pt(Pl(ht(t.slice(0,nr))),e):void 0,mh={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},yh=64*1024,zs=500,wh={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},bh=256*1024,ml=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],Sh=["description","developer_instructions"],vh=["memory","harness","project_memory","human","dream","log_appended"],kh=["homeDir","readCreds","accountId","appVersion"],qs=t=>kh.every(e=>typeof t[e]=="function"),yl=pl().length>3?pl():null;function ht(t){return typeof t=="string"?(yl?t.split(yl).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(ht):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]":ht(n)])):t}var Eh=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ce=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,_h=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function hn(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[_h(o,r)]=Eh.test(o)&&ce(s,80)!==void 0?s:hn(s,e+1);return n}var Ch={"":/^(?: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)$/},wl={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},xh=/^(?:apps|enabled_skill_ids)$/,bl=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Ah(t){try{let e=to(t),n=[],r=[],o=8192,s=(c,l)=>o<=0?!1:(o-=l.length+1,c.push(l),!0),i=(c,l,u)=>{let d=Ch[c].test(l)?l:`[key:${l.length}]`,g=wl[c].test(l),h;return typeof u=="boolean"||typeof u=="number"?h=String(u):g&&typeof u=="string"&&!/[\r\n]/.test(u)&&JSON.stringify(u).length<=120?h=JSON.stringify(u):g&&u instanceof Date?h=u.toISOString():c===""&&xh.test(l)&&Array.isArray(u)&&u.every(m=>typeof m=="string"&&!/[\r\n]/.test(m))&&JSON.stringify(u).length<=2e3&&(h=`[${u.map(m=>JSON.stringify(m)).join(", ")}]`),`${d} = ${h??`"[text:${typeof u=="string"?u.length:JSON.stringify(u).length}]"`}`},a=(c,l,u)=>{if(s(r,l)){for(let[d,g]of Object.entries(u))if(!s(r,i(c,d,g)))return}};for(let[c,l]of Object.entries(e)){let u=c!==""&&Object.hasOwn(wl,c);if(u&&bl(l))a(c,`[${c}]`,l);else if(u&&Array.isArray(l)&&l.length>0&&l.every(bl))for(let d of l)a(c,`[[${c}]]`,d);else s(n,i("",c,l));if(o<=0)break}return[...n,...r].join(`
|
|
243
|
+
`)}catch{return`[unparsed:${t.length}]`}}var Ml=async t=>{try{return(await vt(t)).isFile()?await oh(t,"utf8"):null}catch{return null}},tr=t=>vt(t).then(e=>e.isDirectory(),()=>!1),gn=async t=>{try{return JSON.parse(await Ml(t)??"null")}catch{return null}},ft=async(t,e=200)=>{try{return(await Al(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function Th(t,e){if(!(await vt(t)).isFile())return"";let n=await xl(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 i=s.toString("utf8");return o>0?i.slice(i.indexOf(`
|
|
244
|
+
`)+1):i}finally{await n.close()}}function Ih(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:ce(t.cloud?.defaultModel)??null,models:hn(t.models),tts:hn(t.tts),asr:hn(t.asr),specialAgents:hn(t.specialAgents),pluginSettings:hn(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:ce(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(r=>ce(r)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,r])=>({name:ce(n,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(t.channels).map(([n,r])=>({name:ce(n,64)??"[name]",enabled:r?.enabled===!0}))}}var Rh=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function Sl(t){let e=[];for(let n of await ft(t,100)){let r=le(t,n);if(!await tr(r))continue;let o=await Ml(le(r,"config.toml"));e.push({id:n,config:o===null?null:Ah(o).slice(0,4096),files:(await ft(r,400)).filter(s=>Rh.has(s))})}return e}async function vl(t){let e=[];for(let n of await ft(t,300)){let r=await gn(le(t,n,"manifest.json"));r&&e.push({id:ce(r.id)??n,version:ce(r.version,40)??null,name:ce(r.nameEn)??ce(r.name)??null})}return e}var Bt=t=>String(t?.code||t?.message||t).slice(0,120);async function Dh(t,e,n,r=hh){let o=g=>String(g).padStart(2,"0"),s=g=>{let h=new Date(g);return`${h.getFullYear()}${o(h.getMonth()+1)}${o(h.getDate())}${o(h.getHours())}${o(h.getMinutes())}`},i=g=>`${g.slice(0,4)}-${g.slice(4,6)}-${g.slice(6,8)}.log`,a=s(n),c=s(e.getTime()),l=[],u=r,d=!1;try{let g=(await Al(t)).filter(h=>/^\d{4}-\d{2}-\d{2}\.log$/.test(h)&&h>=i(a)&&h<=i(c)).sort().reverse();for(let h of g){if(d)break;let y=(await Th(le(t,h),ph).catch(b=>{if(b?.code==="ENOENT")return"";throw b})).split(`
|
|
245
245
|
`).filter(b=>/^\d{12} /.test(b)&&b.slice(0,12)>=a&&b.slice(0,12)<c),p=y.length;for(;p>0&&Buffer.byteLength(y[p-1])+1<=u;)u-=Buffer.byteLength(y[--p])+1;p>0&&(d=!0),p<y.length&&l.push({date:h.slice(0,10),log:y.slice(p).join(`
|
|
246
|
-
`)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:Bt(g)}}return{activity:l.reverse(),...d?{activityTruncated:!0}:{}}}var
|
|
246
|
+
`)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:Bt(g)}}return{activity:l.reverse(),...d?{activityTruncated:!0}:{}}}var pt=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},kl=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},mn=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function Oh(t,e,n=Dl,r=ut(e)){let o=le(t,"tangu","state.db"),s=await vt(o).then(a=>a.isFile(),a=>a?.code==="ENOENT"?!1:Bt(a));if(s!==!0)return s===!1?{sessions:[]}:{sessions:[],sessionsError:s};let i;try{let{DatabaseSync:a}=await import("node:sqlite");i=new a(o,{readOnly:!0}),i.exec("PRAGMA busy_timeout = 1500");let l="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",u=[mn(r),mn(e.getTime()),ut(e)],d=i.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
248
|
WHERE s.kind IN (${gl.map(()=>"?").join(", ")}) AND ${l} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...gl,...u,n.sessions+1),g=i.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 ${l} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),h=[],m=0,y=d.length>n.sessions;for(let p of d.slice(0,n.sessions)){let b=g.all(p.id,...u,n.messages+1),v=b.length>n.messages,$=[],R=0;for(let x of b.slice(0,n.messages)){let C=kl(x.tool_calls),D=p.kind==="teamwork"&&x.role==="user"&&
|
|
249
|
+
FROM chat_messages m WHERE m.session_id = ? AND ${l} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),h=[],m=0,y=d.length>n.sessions;for(let p of d.slice(0,n.sessions)){let b=g.all(p.id,...u,n.messages+1),v=b.length>n.messages,$=[],R=0;for(let x of b.slice(0,n.messages)){let C=kl(x.tool_calls),D=p.kind==="teamwork"&&x.role==="user"&&gh.test(String(x.content??"")),F={role:ce(x.role,16)??null,at:Number(x.timestamp)||null,agent:ce(x.agent_slug,64),model:ce(x.model_id,128),error:x.is_error?!0:void 0,text:D?void 0:pt(x.content,n.textChars),relayChars:D?String(x.content??"").length:void 0,reasoning:pt(x.reasoning,n.textChars),tools:C.length?C.map(V=>ce(V?.function?.name??V?.name,80)??"?"):void 0,toolArgChars:C.length?C.reduce((V,Z)=>V+String(Z?.function?.arguments??"").length,0):void 0,toolResultChars:Number(x.tool_result_chars)||void 0,attachments:kl(x.attachments).length||void 0},P=Buffer.byteLength(JSON.stringify(F));if(R+P>n.sessionBytes){v=!0;break}R+=P,$.push(F)}let O={id:ce(p.id,64)??null,kind:ce(p.kind,16)??null,parent:ce(p.parent_session_id,64),app:ce(p.app_id,50)??null,title:pt(p.title,200)??null,model:ce(p.model_id,128)??null,project:pt(p.project_name,120),archived:p.archived?!0:void 0,createdAt:ce(p.created_at,40)??null,updatedAt:ce(p.updated_at,40)??null,messages:$.reverse(),...v?{olderMessagesDropped:!0}:{}},w=Buffer.byteLength(JSON.stringify(O));if(m+w>n.totalBytes){y=!0;break}m+=w,h.push(O)}return{sessions:h,...y?{sessionsTruncated:!0}:{}}}catch(a){return{sessions:[],sessionsError:Bt(a)}}finally{try{i?.close()}catch{}}}async function Ph(t,e,n=mh){let r=le(t,"tangu","state.db"),o=await vt(r).then(i=>i.isFile(),i=>i?.code==="ENOENT"?!1:Bt(i));if(o!==!0)return o===!1?{runs:[]}:{runs:[],runsError:o};let s;try{let{DatabaseSync:i}=await import("node:sqlite");s=new i(r,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let c=s.prepare(`SELECT r.id, r.session_id, r.app_id, r.status, r.current_step, r.model_id, substr(r.error, 1, ${nr}) 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(mn(
|
|
251
|
+
WHERE r.updated_at >= ? AND r.updated_at < ? ORDER BY r.updated_at DESC, r.id LIMIT ?`).all(mn(ut(e)),mn(e.getTime()),n.runs+1),l=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
254
|
json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${nr}) 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,d=y=>y||void 0,g=[],h=0,m=c.length>n.runs;for(let y of c.slice(0,n.runs)){let p={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},b=new Map,v=[],$=0,R=l.all(y.id,n.events+1),O=R.length>n.events;for(let C of R.slice(0,n.events))if(C.type==="usage")p.llmCalls++,p.prompt+=u(C.prompt),p.completion+=u(C.completion),p.cached+=u(C.cached),p.reasoning+=u(C.reasoning),p.llmMs+=u(C.llm_ms),p.ttftMaxMs=Math.max(p.ttftMaxMs,u(C.ttft_ms)),p.requestMaxBytes=Math.max(p.requestMaxBytes,u(C.request_bytes));else if(C.type==="tool_result"){let D=ce(C.name,80)??"?",
|
|
256
|
-
`),...
|
|
257
|
-
WHERE created_at >= ? AND created_at < ? AND (${
|
|
258
|
-
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(mn(ct(e)),mn(e.getTime()),n.activity+1);p.length>n.activity&&(i.truncated=!0);for(let b of p.slice(0,n.activity))if(!c(i.activity,{at:ce(b.created_at,40)??null,agent:ce(b.agent,64)??null,action:ce(b.action,64)??null,detail:typeof b.detail=="string"&&b.detail?dt(ft(b.detail),n.detailChars):void 0,session:ce(b.session_ref,64)}))break}catch(m){i.activityError=Bt(m)}finally{try{h?.close()}catch{}}}for(let h of await ut(le(r,"project-memory"),100)){let m=le(r,"project-memory",h);if(!await tr(m))continue;let y=await er(le(m,"MEMORY.md"),n.fileChars),p=await Cl(m);if(!y&&!p)continue;let b=(await gn(le(m,"PROJECT.json")))?.project;if(!c(i.projects,{id:ce(h,64)??null,name:typeof b=="string"?ce(Il(b.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:p,memory:y}))break}for(let h of await ut(le(r,"teams"),100)){if(!await tr(le(r,"teams",h)))continue;let m=await er(le(r,"teams",h,"TEAM.md"),n.fileChars);if(m&&!c(i.teams,{id:h,files:{"TEAM.md":m}}))break}let g=[];for(let h of await ut(le(r,"agents"),100)){let m=le(r,"agents",h);await tr(m)&&g.push({id:h,dir:m,at:Math.max(0,...await Promise.all([...ml,".memory-state.json"].map(y=>s(le(m,y)))))})}for(let{id:h,dir:m,at:y}of g.sort((p,b)=>b.at-p.at||p.id.localeCompare(b.id))){let p={};for(let O of ml){let w=await er(le(m,O),n.fileChars);w&&(p[O]=w)}let b=[];if(await tr(le(m,"LOG")))for(let O of(await ut(le(m,"LOG"),400)).filter(w=>/^\d{4}-\d{2}-\d{2}\.md$/.test(w)&&w.slice(0,10)>=o&&w.slice(0,10)<=yt(e))){let w=await er(le(m,"LOG",O),n.logChars);w&&b.push({date:O.slice(0,10),text:w})}let v=(await gn(le(m,".memory-dream.json")))?.last,$=await Cl(m),R=await qh(m,n.fileChars);!Object.keys(p).length&&!b.length&&!$&&!R||c(i.agents,{id:h,updatedAt:y?new Date(y).toISOString():null,config:R,state:$,dream:v&&typeof v=="object"?{state:ce(v.state,32),startedAt:ce(v.startedAt,40),finishedAt:ce(v.finishedAt,40),calls:typeof v.calls=="number"?v.calls:void 0,detail:typeof v.detail=="string"?dt(ft(v.detail),n.detailChars):void 0}:void 0,files:Object.keys(p).length?p:void 0,log:b.length?b:void 0})}return i}async function jl(t){let e=(await gn(le(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Zp("sha256").update(Tl()).digest("hex").slice(0,8)}`}async function Vh(t){let{home:e}=t,n=le(e,"tangu"),r=t.now??new Date,s=i=>t.since?.[i]??ct(r),o=Mh(t.engineLogs);return ft({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:ah(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:Il(e),cloudUrl:t.cloudUrl},device:{id:await jl(e),name:Tl()},system:await Ph(e),config:Th(await gn(le(e,"config.json"))),agents:await Sl(le(n,"agents")),teams:await Sl(le(n,"teams")),plugins:{desktop:await vl(le(e,"plugins")),engine:await vl(le(n,"plugins"))},inventory:{skills:await ut(le(n,"skills")),spaces:await ut(le(e,"spaces")),themes:await ut(le(e,"themes"))},...t.activity?{...await Rh(le(e,"activity"),r,s("activity")),activitySince:new Date(s("activity")).toISOString()}:{},...t.sessions?{...await Dh(e,r,Dl,s("sessions")),sessionsSince:new Date(s("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await Wh(e,r)}:{},...await Oh(e,r),runsSince:new Date(ct(r)).toISOString(),...o?{engine:o}:{},sync:{content:Hh(t.contentSync),legacy:zh(t.engineLogs)}})}function Fl(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(R=>Nr({baseUrl:R.cloudUrl,vault:jr,getToken:()=>R.token})),s=e.policyFor??jo,o=()=>le(t.homeDir(),"extend-diagnostics.json"),i=()=>{let R=O=>O&&typeof O=="object"?O:{};try{let O=JSON.parse(eh(o(),"utf8"));return{accounts:R(O?.accounts),sent:R(O?.sent)}}catch{return{accounts:{},sent:{}}}},a=()=>i().accounts,c=(R,O,w)=>{let x=i();x.accounts[R]={...x.accounts[R],...O},Object.assign(x.sent,w),Qp(t.homeDir(),{recursive:!0});let C=`${o()}.${process.pid}.tmp`;nh(C,JSON.stringify(x,null,2),{encoding:"utf8",mode:384}),th(C,o())},l=()=>{let R=t.readCreds();return R.token&&R.cloudUrl?t.accountId():null},u=()=>{let R=l(),O=R?a()[R]??{}:{},w=Kn(O.policy);return{signedIn:!!R,enabled:O.enabled===!0,activity:O.activity!==!1,sessions:O.sessions??O.enabled!==!0,memory:O.memory??O.enabled!==!0,lastUploadAt:O.lastUploadAt??null,lastError:O.lastError??null,retainDays:rs,mode:w.mode,intervalHours:w.intervalHours}},d=()=>{try{return El(t)?t.diagnosticLogs():null}catch{return null}},g=null,h=new Map,m=async()=>{let R=l();if(!R)return!1;if(g)return g.id===R?g.done:(await g.done,m());let O={...t.readCreds()},w=n(),x=i(),C=x.accounts[R],D=O.cloudUrl.replace(/\/+$/,""),j=Po(C?.file,x.sent[D]??{},w),P=(async()=>{try{let V=await Vh({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:O.cloudUrl,activity:C?.activity!==!1,sessions:C?.sessions===!0,now:w,since:j,engineLogs:d(),contentSync:dl(),memory:()=>{let pe=l()===R?a()[R]:void 0;return pe?.enabled===!0&&pe.memory===!0}}),Z=await jl(t.homeDir()),Q=a()[R];if(l()!==R||Q?.enabled!==!0)return!1;if(Q.activity===!1)for(let pe of["activity","activityTruncated","activityError","activitySince"])delete V[pe];if(Q.sessions!==!0)for(let pe of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete V[pe];Q.memory!==!0&&delete V.memory;let ee=[],re=lh(V,ee);if(!re)throw new Error("snapshot too large");await $o(r(O),Z,re,w),h.delete(R);let se=Mo(i().sent[D]??{},C?.file,j,w,V,ee);return c(R,{lastUploadAt:n().getTime(),lastError:void 0,file:se.file},{[D]:se.sent}),t.log(`[forsion-extend] diagnostics uploaded (${re.length} bytes)`),!0}catch(V){h.set(R,n().getTime());let Z=String(V?.message||V).slice(0,300);try{c(R,{lastError:Z})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${Z}`),!1}finally{g=null}})();return g={id:R,done:P},P},y=async()=>{try{let R=l();if(!R||a()[R]?.enabled!==!0)return;let O=await s({...t.readCreds()}),w=l()===R?a()[R]:void 0;if(w?.enabled!==!0)return;O&&(O.mode!==w.policy?.mode||O.intervalHours!==w.policy?.intervalHours)&&c(R,{policy:{mode:O.mode,intervalHours:O.intervalHours}}),O&&w.requestSeen===void 0&&c(R,{requestSeen:O.requestedAt});let x=O??{...Kn(w.policy),requestedAt:0},C=x.requestedAt>(w.requestSeen??x.requestedAt),D=w.lastUploadAt??0,j=!D||x.mode==="scheduled"&&n().getTime()-D>=x.intervalHours*Rl;if(!C&&!j||n().getTime()-(h.get(R)??-hl)<hl)return;await m()&&C&&c(R,{requestSeen:x.requestedAt})}catch(R){t.log(`[forsion-extend] diagnostics tick failed: ${String(R?.message||R)}`)}},p=Promise.resolve(),b={ok:!1,error:"untrusted"};t.handle("diagnostics:get",R=>t.isTrustedSender(R)?u():b),t.handle("diagnostics:set",(R,O)=>{if(!t.isTrustedSender(R))return b;let w=l();if(!w)return u();let x={};typeof O?.enabled=="boolean"&&(x.enabled=O.enabled),x.enabled&&(x.requestSeen=void 0),typeof O?.activity=="boolean"&&(x.activity=O.activity),typeof O?.sessions=="boolean"&&(x.sessions=O.sessions),typeof O?.memory=="boolean"&&(x.memory=O.memory);let C=a()[w];for(let D of["sessions","memory"])x[D]!==void 0||C?.[D]!==void 0||(C?.enabled===!0?x[D]=!1:x.enabled&&(x[D]=!0));return c(w,x),x.enabled&&(h.delete(w),p=Promise.all([p,y()]).then(()=>{})),u()}),t.handle("diagnostics:uploadNow",async R=>t.isTrustedSender(R)?(u().enabled&&await m(),u()):b);let v=setTimeout(()=>void y(),uh),$=setInterval(()=>void y(),dh);return v.unref?.(),$.unref?.(),t.log(`[forsion-extend] diagnostics registered${El(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(v),clearInterval($)},{tick:y,settled:()=>p})}import{randomUUID as Jl}from"node:crypto";import{appendFileSync as sg,existsSync as og,mkdirSync as Xo,readFileSync as Kl,renameSync as Xl,rmSync as Zo,statSync as ig,writeFileSync as Zl}from"node:fs";import{lstat as nu}from"node:fs/promises";import{homedir as ag,release as cg}from"node:os";import{join as wn}from"node:path";var rr={$comment:"\u5E2E\u52A9\u6539\u8FDB Forsion(\u533F\u540D\u9065\u6D4B)\u4E8B\u4EF6\u767D\u540D\u5355 v2(v1 \u539F\u6837\u4FDD\u7559,v2 \u53EA\u52A0\u4E8B\u4EF6\u4E0E\u5B57\u6BB5;\u5951\u7EA6\u89C1\u540C\u76EE\u5F55 contract.md \xA76\u2013\xA714)\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:2,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"]},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","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"]}},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"}},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"}}}};var Gh=rr.events,Jh=rr.envelope,Yo=rr.limits,Hl=rr.version,Kh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Xh=/^[A-Za-z0-9._:/@+-]+$/,zl=t=>typeof t=="string"&&Kh.test(t),Ll=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Zh=[[/\/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]"]],Bl=t=>Zh.reduce((e,[n,r])=>e.replace(n,r),t);function Ul(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(Ll,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=Bl(r),(r.length>e?r.slice(0,e):r).replace(Ll,"\uFFFD")}var Qh=/^pr-[a-f0-9]{48}$/,eg=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,tg=t=>Qh.test(t)||eg.test(t)||Bl(t)===t;function ng(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function Vo(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 zl(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&&Xh.test(e)&&tg(e)?e:void 0;case"text":return typeof e=="string"&&e?Ul(e,t.max,n):void 0;case"stack":{let r=ng(e);return r?Ul(r,t.max,n):void 0}}}function qt(t,e){let n=typeof t?.event=="string"?Gh[t.event]:void 0;if(!n)return null;let r={},s=t.props&&typeof t.props=="object"?t.props:{};for(let[i,a]of Object.entries(n)){let c=Vo(a,s[i],e);c!==void 0&&(r[i]=c)}let o=Vo({type:"iso-time"},t.ts);return{event:t.event,ts:o??new Date().toISOString(),...zl(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function ql(t){let e={};for(let[n,r]of Object.entries(Jh)){if(n==="installId")continue;let s=Vo(r,t[n]);e[n]=typeof s=="string"?s:null}return e}function Wl(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":/\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 Vl(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function Go(t){return t?/^pr-/.test(t)?"forsion":/^codex\//.test(t)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(t)?"local":"byok":"other"}var rg=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function Yl(t){if(typeof t!="string"||!t)return;let e=Go(t);if(e==="forsion"||e==="codex")return t;let n=t.slice(t.lastIndexOf("/")+1);return rg.test(n)?n:void 0}function Jo(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function Ko(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}function Gl(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var lg=10*6e4,ug=6e4,dg=50,Ql=1024*1024,fg=168*36e5,eu=15e3,pg=200,hg=2e3,Qo=7,gg=5e3,tu=864e5,mg=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts"]),ei={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},yg=new Set(["custom-ask","escalate","mode","protected","control","always"]),wg=new Set(["readonly","auto-edit","full-auto","custom"]),ru=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),ti=t=>({at:ru(t),id:"~"}),yn=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function bg(t,e,n,r){let s=wn(t,"tangu","state.db");if(!await nu(s).then(i=>i.isFile(),()=>!1))return{events:[],cursor:e};let o;try{let{DatabaseSync:i}=await import("node:sqlite");o=new i(s,{readOnly:!0}),o.exec("PRAGMA busy_timeout = 1500");let a=o.prepare(`SELECT r.id, r.status, r.current_step, r.model_id, substr(r.error, 1, 2000) AS error, r.created_at, r.updated_at, s.kind
|
|
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,d=y=>y||void 0,g=[],h=0,m=c.length>n.runs;for(let y of c.slice(0,n.runs)){let p={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},b=new Map,v=[],$=0,R=l.all(y.id,n.events+1),O=R.length>n.events;for(let C of R.slice(0,n.events))if(C.type==="usage")p.llmCalls++,p.prompt+=u(C.prompt),p.completion+=u(C.completion),p.cached+=u(C.cached),p.reasoning+=u(C.reasoning),p.llmMs+=u(C.llm_ms),p.ttftMaxMs=Math.max(p.ttftMaxMs,u(C.ttft_ms)),p.requestMaxBytes=Math.max(p.requestMaxBytes,u(C.request_bytes));else if(C.type==="tool_result"){let D=ce(C.name,80)??"?",F=b.get(D)??(b.size<n.tools?{name:D,n:0,ms:0,maxMs:0}:void 0);if(!F){O=!0;continue}b.set(D,F),F.n++,C.failed&&(F.errors=(F.errors??0)+1),F.ms+=u(C.ms),F.maxMs=Math.max(F.maxMs,u(C.ms))}else if(C.type==="error"){let D=co(C.error,n.errorChars);D&&!v.includes(D)&&v.length<3&&v.push(D)}else C.phase==="llm_retry"&&$++;let w={id:ce(y.id,64)??null,session:ce(y.session_id,64)??null,kind:ce(y.kind,16),app:ce(y.app_id,50),model:ce(y.model_id,128),status:ce(y.status,16)??null,error:co(y.error,n.errorChars),createdAt:ce(y.created_at,40)??null,updatedAt:ce(y.updated_at,40)??null,steps:d(u(y.current_step)),tokens:d(u(y.tokens_total)),retries:d($),...Object.fromEntries(Object.entries(p).map(([C,D])=>[C,d(D)])),errors:v.length?v:void 0,tools:b.size?[...b.values()]:void 0,partial:O||void 0},x=Buffer.byteLength(JSON.stringify(w));if(h+x>n.totalBytes){m=!0;break}h+=x,g.push(w)}return{runs:g,...m?{runsTruncated:!0}:{}}}catch(i){return{runs:[],runsError:Bt(i)}}finally{try{s?.close()}catch{}}}async function Mh(t){let e=o=>Math.round(o/1048576),n=o=>vt(o).then(s=>s.isFile()?s.size:0,()=>0),r=le(t,"tangu","state.db");return{cpus:ih().length,memTotalMB:e(lh()),memFreeMB:e(ah()),diskFreeMB:await sh(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 El=t=>typeof t.diagnosticLogs=="function";function $h(t,e=yh){let n=t?.engine;if(!n||typeof n!="object")return null;let r=(Array.isArray(n.lines)?n.lines:[]).filter(c=>typeof c=="string"&&!!c),o=r.map(c=>co(c,zs)??""),s=o.some((c,l)=>c.length>zs||r[l].length>nr),i=o.length,a=e;for(;i>0&&Buffer.byteLength(o[i-1])+1<=a;)a-=Buffer.byteLength(o[--i])+1;return i>0&&(s=!0),{state:ce(n.state,32)??null,lastError:co(n.lastError,zs)??null,log:o.slice(i).join(`
|
|
256
|
+
`),...s?{logTruncated:!0}:{}}}var Ws={errors:20,errorChars:300,agents:100},Nh=t=>Pl(Ol(t,!1).replace(/[^\s"'`<>()[\]{},;]*\/[^\s"'`<>()[\]{},;]*/g,e=>Bs.test(e)?e:"[path]")),jh=(t,e=[],n=Ws.errorChars)=>pt(Nh(cl(ht(t),e.map(r=>ht(r)))),n)??"",Fe=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?Math.round(t):0,ao=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?new Date(t).toISOString():null,$l=t=>{let e=t&&typeof t=="object"?t:{};return Object.fromEntries(al.flatMap(n=>Fe(e[n])?[[n,Fe(e[n])]]:[]))},_l=t=>{let e=t;return e&&typeof e=="object"?{at:ao(e.at),ms:Fe(e.ms),completed:e.completed===!0,...$l(e.counts)}:null},Fh=Object.fromEntries(St.map(t=>[t.path,t.id])),Lh=new Set(["idle","scanning","syncing","paused"]),Uh=new Set(["queued","active","done","failed","paused","conflict"]);function Hh(t,e){let n=(Array.isArray(t)?t:[]).filter(a=>!!a&&typeof a.source=="string"&&typeof a.target=="string"),r=a=>a===void 0?null:a==="default"?"shared":a==="off"?"off":e&&a===`device-${e}`?"device":/^device-/.test(a)?"other-device":"unknown",o={other:r(n.find(a=>a.source==="")?.target)};for(let a of St)o[a.id]=r(dn(a.path,n)?.target);let s={},i={};for(let a of n){if(a.source===""||Fh[a.source])continue;let c=Zn(a.source);if(c&&Object.keys(s).length<Ws.agents)s[c]=r(a.target);else if(!c){let l=r(a.target)??"unknown";i[l]=(i[l]??0)+1}}return{...o,agentRules:s,folderRules:i,count:n.length}}function zh(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(([i,a])=>Uh.has(i)&&Fe(a)).map(([i,a])=>[i,Fe(a)])):{},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"&&Lh.has(e.phase)?e.phase:null,revision:Fe(e.revision),rules:Hh(e.rules,n),backlog:r?{jobs:o,blocked:Fe(r.blocked),pendingUploads:Fe(r.pendingUploads),unconfirmed:Fe(r.unconfirmed),trash:Fe(r.trash),awaitingBytes:Fe(r.awaitingBytes),dirty:Fe(r.dirty)}:null,archive:e.archive==="running"||e.archive==="done"?e.archive:null,since:ao(e.since),lastRun:_l(e.lastRun),runs:(Array.isArray(e.runs)?e.runs:[]).slice(-20).map(_l).filter(Boolean),totals:{runs:Fe(s.runs),completedRuns:Fe(s.completedRuns),idleRuns:Fe(s.idleRuns),...$l(s)},errors:(Array.isArray(e.errors)?e.errors:[]).slice(-Ws.errors).flatMap(i=>{if(!i||typeof i!="object"||typeof i.text!="string"||!i.text)return[];let a=Array.isArray(i.paths)?i.paths.filter(c=>typeof c=="string"):[];return[{first:ao(i.first),at:ao(i.at),n:Fe(i.n)||1,kind:Br(i.text)??"other",text:jh(i.text,a)}]})}}function Bh(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 qh(t,e=Sh){let n;try{n=to(t)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof n[r]=="string"&&n[r]?[[r,n[r]]]:[]))}async function Nl(t,e=bh){try{if(!(await vt(t)).isFile())return null;let n=await xl(t,fl.O_RDONLY|(fl.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 er=async(t,e)=>{let n=await Nl(t);return n?pt(ht(n),e):void 0};async function Wh(t,e){let n=await Nl(le(t,"config.toml")),r=Object.entries(n?qh(n):{}).map(([o,s])=>[o,pt(ht(s),e)??""]);return r.length?Object.fromEntries(r):void 0}async function Cl(t){let e=await gn(le(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 Vh(t,e,n=wh){let r=le(t,"tangu"),o=h=>vt(h).then(m=>m.isFile()?m.mtimeMs:0,()=>0),s=bt(new Date(ut(e))),i={agents:[],teams:[],projects:[],activity:[]},a=n.totalBytes,c=(h,m)=>{let y=Buffer.byteLength(JSON.stringify(m))+1;return y>a?(i.truncated=!0,!1):(a-=y,h.push(m),!0)},l=await er(le(r,"USER.md"),n.fileChars);l&&c([],l)&&(i.user=l);let u=le(r,"state.db"),d=await vt(u).then(h=>h.isFile(),h=>h?.code==="ENOENT"?!1:Bt(h));if(typeof d=="string")i.activityError=d;else if(d){let h;try{let{DatabaseSync:m}=await import("node:sqlite");h=new m(u,{readOnly:!0}),h.exec("PRAGMA busy_timeout = 1500");let p=h.prepare(`SELECT agent, action, substr(detail, 1, ${nr}) AS detail, session_ref, created_at FROM special_agent_log
|
|
257
|
+
WHERE created_at >= ? AND created_at < ? AND (${vh.map(b=>`action GLOB '${b}*'`).join(" OR ")})
|
|
258
|
+
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(mn(ut(e)),mn(e.getTime()),n.activity+1);p.length>n.activity&&(i.truncated=!0);for(let b of p.slice(0,n.activity))if(!c(i.activity,{at:ce(b.created_at,40)??null,agent:ce(b.agent,64)??null,action:ce(b.action,64)??null,detail:typeof b.detail=="string"&&b.detail?pt(ht(b.detail),n.detailChars):void 0,session:ce(b.session_ref,64)}))break}catch(m){i.activityError=Bt(m)}finally{try{h?.close()}catch{}}}for(let h of await ft(le(r,"project-memory"),100)){let m=le(r,"project-memory",h);if(!await tr(m))continue;let y=await er(le(m,"MEMORY.md"),n.fileChars),p=await Cl(m);if(!y&&!p)continue;let b=(await gn(le(m,"PROJECT.json")))?.project;if(!c(i.projects,{id:ce(h,64)??null,name:typeof b=="string"?ce(Il(b.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:p,memory:y}))break}for(let h of await ft(le(r,"teams"),100)){if(!await tr(le(r,"teams",h)))continue;let m=await er(le(r,"teams",h,"TEAM.md"),n.fileChars);if(m&&!c(i.teams,{id:h,files:{"TEAM.md":m}}))break}let g=[];for(let h of await ft(le(r,"agents"),100)){let m=le(r,"agents",h);await tr(m)&&g.push({id:h,dir:m,at:Math.max(0,...await Promise.all([...ml,".memory-state.json"].map(y=>o(le(m,y)))))})}for(let{id:h,dir:m,at:y}of g.sort((p,b)=>b.at-p.at||p.id.localeCompare(b.id))){let p={};for(let O of ml){let w=await er(le(m,O),n.fileChars);w&&(p[O]=w)}let b=[];if(await tr(le(m,"LOG")))for(let O of(await ft(le(m,"LOG"),400)).filter(w=>/^\d{4}-\d{2}-\d{2}\.md$/.test(w)&&w.slice(0,10)>=s&&w.slice(0,10)<=bt(e))){let w=await er(le(m,"LOG",O),n.logChars);w&&b.push({date:O.slice(0,10),text:w})}let v=(await gn(le(m,".memory-dream.json")))?.last,$=await Cl(m),R=await Wh(m,n.fileChars);!Object.keys(p).length&&!b.length&&!$&&!R||c(i.agents,{id:h,updatedAt:y?new Date(y).toISOString():null,config:R,state:$,dream:v&&typeof v=="object"?{state:ce(v.state,32),startedAt:ce(v.startedAt,40),finishedAt:ce(v.finishedAt,40),calls:typeof v.calls=="number"?v.calls:void 0,detail:typeof v.detail=="string"?pt(ht(v.detail),n.detailChars):void 0}:void 0,files:Object.keys(p).length?p:void 0,log:b.length?b:void 0})}return i}async function jl(t){let e=(await gn(le(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Qp("sha256").update(Tl()).digest("hex").slice(0,8)}`}async function Yh(t){let{home:e}=t,n=le(e,"tangu"),r=t.now??new Date,o=i=>t.since?.[i]??ut(r),s=$h(t.engineLogs);return ht({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:ch(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:Il(e),cloudUrl:t.cloudUrl},device:{id:await jl(e),name:Tl()},system:await Mh(e),config:Ih(await gn(le(e,"config.json"))),agents:await Sl(le(n,"agents")),teams:await Sl(le(n,"teams")),plugins:{desktop:await vl(le(e,"plugins")),engine:await vl(le(n,"plugins"))},inventory:{skills:await ft(le(n,"skills")),spaces:await ft(le(e,"spaces")),themes:await ft(le(e,"themes"))},...t.activity?{...await Dh(le(e,"activity"),r,o("activity")),activitySince:new Date(o("activity")).toISOString()}:{},...t.sessions?{...await Oh(e,r,Dl,o("sessions")),sessionsSince:new Date(o("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await Vh(e,r)}:{},...await Ph(e,r),runsSince:new Date(ut(r)).toISOString(),...s?{engine:s}:{},sync:{content:zh(t.contentSync),legacy:Bh(t.engineLogs)}})}function Fl(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(R=>Nr({baseUrl:R.cloudUrl,vault:jr,getToken:()=>R.token})),o=e.policyFor??js,s=()=>le(t.homeDir(),"extend-diagnostics.json"),i=()=>{let R=O=>O&&typeof O=="object"?O:{};try{let O=JSON.parse(th(s(),"utf8"));return{accounts:R(O?.accounts),sent:R(O?.sent)}}catch{return{accounts:{},sent:{}}}},a=()=>i().accounts,c=(R,O,w)=>{let x=i();x.accounts[R]={...x.accounts[R],...O},Object.assign(x.sent,w),eh(t.homeDir(),{recursive:!0});let C=`${s()}.${process.pid}.tmp`;rh(C,JSON.stringify(x,null,2),{encoding:"utf8",mode:384}),nh(C,s())},l=()=>{let R=t.readCreds();return R.token&&R.cloudUrl?t.accountId():null},u=()=>{let R=l(),O=R?a()[R]??{}:{},w=Kn(O.policy);return{signedIn:!!R,enabled:O.enabled===!0,activity:O.activity!==!1,sessions:O.sessions??O.enabled!==!0,memory:O.memory??O.enabled!==!0,lastUploadAt:O.lastUploadAt??null,lastError:O.lastError??null,retainDays:ro,mode:w.mode,intervalHours:w.intervalHours}},d=()=>{try{return El(t)?t.diagnosticLogs():null}catch{return null}},g=null,h=new Map,m=async()=>{let R=l();if(!R)return!1;if(g)return g.id===R?g.done:(await g.done,m());let O={...t.readCreds()},w=n(),x=i(),C=x.accounts[R],D=O.cloudUrl.replace(/\/+$/,""),F=Ps(C?.file,x.sent[D]??{},w),P=(async()=>{try{let V=await Yh({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:O.cloudUrl,activity:C?.activity!==!1,sessions:C?.sessions===!0,now:w,since:F,engineLogs:d(),contentSync:dl(),memory:()=>{let pe=l()===R?a()[R]:void 0;return pe?.enabled===!0&&pe.memory===!0}}),Z=await jl(t.homeDir()),Q=a()[R];if(l()!==R||Q?.enabled!==!0)return!1;if(Q.activity===!1)for(let pe of["activity","activityTruncated","activityError","activitySince"])delete V[pe];if(Q.sessions!==!0)for(let pe of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete V[pe];Q.memory!==!0&&delete V.memory;let ee=[],re=uh(V,ee);if(!re)throw new Error("snapshot too large");await $s(r(O),Z,re,w),h.delete(R);let oe=Ms(i().sent[D]??{},C?.file,F,w,V,ee);return c(R,{lastUploadAt:n().getTime(),lastError:void 0,file:oe.file},{[D]:oe.sent}),t.log(`[forsion-extend] diagnostics uploaded (${re.length} bytes)`),!0}catch(V){h.set(R,n().getTime());let Z=String(V?.message||V).slice(0,300);try{c(R,{lastError:Z})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${Z}`),!1}finally{g=null}})();return g={id:R,done:P},P},y=async()=>{try{let R=l();if(!R||a()[R]?.enabled!==!0)return;let O=await o({...t.readCreds()}),w=l()===R?a()[R]:void 0;if(w?.enabled!==!0)return;O&&(O.mode!==w.policy?.mode||O.intervalHours!==w.policy?.intervalHours)&&c(R,{policy:{mode:O.mode,intervalHours:O.intervalHours}}),O&&w.requestSeen===void 0&&c(R,{requestSeen:O.requestedAt});let x=O??{...Kn(w.policy),requestedAt:0},C=x.requestedAt>(w.requestSeen??x.requestedAt),D=w.lastUploadAt??0,F=!D||x.mode==="scheduled"&&n().getTime()-D>=x.intervalHours*Rl;if(!C&&!F||n().getTime()-(h.get(R)??-hl)<hl)return;await m()&&C&&c(R,{requestSeen:x.requestedAt})}catch(R){t.log(`[forsion-extend] diagnostics tick failed: ${String(R?.message||R)}`)}},p=Promise.resolve(),b={ok:!1,error:"untrusted"};t.handle("diagnostics:get",R=>t.isTrustedSender(R)?u():b),t.handle("diagnostics:set",(R,O)=>{if(!t.isTrustedSender(R))return b;let w=l();if(!w)return u();let x={};typeof O?.enabled=="boolean"&&(x.enabled=O.enabled),x.enabled&&(x.requestSeen=void 0),typeof O?.activity=="boolean"&&(x.activity=O.activity),typeof O?.sessions=="boolean"&&(x.sessions=O.sessions),typeof O?.memory=="boolean"&&(x.memory=O.memory);let C=a()[w];for(let D of["sessions","memory"])x[D]!==void 0||C?.[D]!==void 0||(C?.enabled===!0?x[D]=!1:x.enabled&&(x[D]=!0));return c(w,x),x.enabled&&(h.delete(w),p=Promise.all([p,y()]).then(()=>{})),u()}),t.handle("diagnostics:uploadNow",async R=>t.isTrustedSender(R)?(u().enabled&&await m(),u()):b);let v=setTimeout(()=>void y(),dh),$=setInterval(()=>void y(),fh);return v.unref?.(),$.unref?.(),t.log(`[forsion-extend] diagnostics registered${El(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(v),clearInterval($)},{tick:y,settled:()=>p})}import{randomUUID as Jl}from"node:crypto";import{appendFileSync as sg,existsSync as ig,mkdirSync as Xs,readFileSync as Kl,renameSync as Xl,rmSync as Zs,statSync as ag,writeFileSync as Zl}from"node:fs";import{lstat as nu}from"node:fs/promises";import{homedir as cg,release as lg}from"node:os";import{join as wn}from"node:path";var rr={$comment:"\u5E2E\u52A9\u6539\u8FDB Forsion(\u533F\u540D\u9065\u6D4B)\u4E8B\u4EF6\u767D\u540D\u5355 v2(v1 \u539F\u6837\u4FDD\u7559,v2 \u53EA\u52A0\u4E8B\u4EF6\u4E0E\u5B57\u6BB5;\u5951\u7EA6\u89C1\u540C\u76EE\u5F55 contract.md \xA76\u2013\xA714)\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:2,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"]},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","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"]}},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"}},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"}}}};var Jh=rr.events,Kh=rr.envelope,Ys=rr.limits,Hl=rr.version,Xh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Zh=/^[A-Za-z0-9._:/@+-]+$/,zl=t=>typeof t=="string"&&Xh.test(t),Ll=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Qh=[[/\/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]"]],Bl=t=>Qh.reduce((e,[n,r])=>e.replace(n,r),t);function Ul(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(Ll,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=Bl(r),(r.length>e?r.slice(0,e):r).replace(Ll,"\uFFFD")}var eg=/^pr-[a-f0-9]{48}$/,tg=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ng=t=>eg.test(t)||tg.test(t)||Bl(t)===t;function rg(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function Vs(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 zl(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&&Zh.test(e)&&ng(e)?e:void 0;case"text":return typeof e=="string"&&e?Ul(e,t.max,n):void 0;case"stack":{let r=rg(e);return r?Ul(r,t.max,n):void 0}}}function qt(t,e){let n=typeof t?.event=="string"?Jh[t.event]:void 0;if(!n)return null;let r={},o=t.props&&typeof t.props=="object"?t.props:{};for(let[i,a]of Object.entries(n)){let c=Vs(a,o[i],e);c!==void 0&&(r[i]=c)}let s=Vs({type:"iso-time"},t.ts);return{event:t.event,ts:s??new Date().toISOString(),...zl(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function ql(t){let e={};for(let[n,r]of Object.entries(Kh)){if(n==="installId")continue;let o=Vs(r,t[n]);e[n]=typeof o=="string"?o:null}return e}function Wl(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":/\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 Vl(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function Gs(t){return t?/^pr-/.test(t)?"forsion":/^codex\//.test(t)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(t)?"local":"byok":"other"}var og=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function Yl(t){if(typeof t!="string"||!t)return;let e=Gs(t);if(e==="forsion"||e==="codex")return t;let n=t.slice(t.lastIndexOf("/")+1);return og.test(n)?n:void 0}function Js(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function Ks(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}function Gl(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var ug=10*6e4,dg=6e4,fg=50,Ql=1024*1024,pg=168*36e5,eu=15e3,hg=200,gg=2e3,Qs=7,mg=5e3,tu=864e5,yg=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts"]),ei={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},wg=new Set(["custom-ask","escalate","mode","protected","control","always"]),bg=new Set(["readonly","auto-edit","full-auto","custom"]),ru=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),ti=t=>({at:ru(t),id:"~"}),yn=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function Sg(t,e,n,r){let o=wn(t,"tangu","state.db");if(!await nu(o).then(i=>i.isFile(),()=>!1))return{events:[],cursor:e};let s;try{let{DatabaseSync:i}=await import("node:sqlite");s=new i(o,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let a=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",hg),c=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,
|
|
@@ -267,22 +267,22 @@ ${o}`,n),this.line=r,this.column=s,this.codeblock=o}};var Np=/^((0x[0-9a-fA-F](_
|
|
|
267
267
|
json_extract(e.payload, '$.action') AS action, json_extract(e.payload, '$.by.via') AS via, e.created_at AS at
|
|
268
268
|
FROM agent_run_events e
|
|
269
269
|
WHERE e.run_id = ? AND e.type IN ('usage', 'tool_call', 'tool_result', 'status', 'approval_request', 'approval_result') AND json_valid(e.payload)
|
|
270
|
-
ORDER BY e.seq LIMIT ?`),l=y=>`(SELECT total(json_extract(s.value, '$.tokens')) FROM json_each(e.payload, '$.sections') s WHERE json_extract(s.value, '$.k') = '${y}')`,u=
|
|
270
|
+
ORDER BY e.seq LIMIT ?`),l=y=>`(SELECT total(json_extract(s.value, '$.tokens')) FROM json_each(e.payload, '$.sections') s WHERE json_extract(s.value, '$.k') = '${y}')`,u=s.prepare(`SELECT json_extract(e.payload, '$.telemetry.agentRole') AS agentRole, json_extract(e.payload, '$.telemetry.recallEntries') AS recallEntries,
|
|
271
271
|
json_extract(e.payload, '$.telemetry.recallHistory') AS recallHistory, json_extract(e.payload, '$.telemetry.recallTruncated') AS recallTruncated,
|
|
272
272
|
json_type(e.payload, '$.sections') AS sectionsType,
|
|
273
273
|
${l("memory")} AS memoryTokens, ${l("human")} AS humanTokens,
|
|
274
274
|
${l("profile")} AS profileTokens, ${l("project")} AS projectTokens
|
|
275
275
|
FROM agent_run_events e
|
|
276
276
|
WHERE e.run_id = ? AND e.type = 'status' AND json_valid(e.payload) AND json_extract(e.payload, '$.phase') = 'context_info'
|
|
277
|
-
ORDER BY e.seq LIMIT 1`),d=y=>typeof y=="number"&&Number.isFinite(y)&&y>0?y:0,g=y=>typeof y=="string"&&y?y:void 0,h=[],m=e;for(let y of a){m={at:String(y.updated_at),id:String(y.id)};let p={llmCalls:0,tokensIn:0,tokensOut:0,tokensCached:0,retries:0},b=new Map,v=new Map,$=[],R=new Map;for(let P of c.all(y.id,
|
|
277
|
+
ORDER BY e.seq LIMIT 1`),d=y=>typeof y=="number"&&Number.isFinite(y)&&y>0?y:0,g=y=>typeof y=="string"&&y?y:void 0,h=[],m=e;for(let y of a){m={at:String(y.updated_at),id:String(y.id)};let p={llmCalls:0,tokensIn:0,tokensOut:0,tokensCached:0,retries:0},b=new Map,v=new Map,$=[],R=new Map;for(let P of c.all(y.id,gg))if(P.type==="usage")p.llmCalls++,p.tokensIn+=d(P.prompt),p.tokensOut+=d(P.completion),p.tokensCached+=d(P.cached);else if(P.type==="tool_call"||P.type==="tool_result"){if(typeof P.id=="string"&&P.source!=null&&v.set(P.id,P.source),P.type!=="tool_result"||typeof P.name!="string")continue;let V=P.source??(typeof P.id=="string"?v.get(P.id):void 0),Z=Ks(P.name,V),Q=Js(V),ee=`${Z}\0${Q}`,re=b.get(ee)??{tool:Z,toolSource:Q,calls:0,failures:0,totalMs:0,maxMs:0};b.set(ee,re),re.calls++,P.failed&&re.failures++,re.totalMs+=d(P.ms),re.maxMs=Math.max(re.maxMs,d(P.ms))}else if(P.type==="approval_request")$.push({approvalId:g(P.approvalId),name:g(P.name),toolCallId:g(P.toolCallId),reasonKind:wg.has(P.reasonKind)?P.reasonKind:"other",mode:bg.has(P.reasonMode)?P.reasonMode:"other",at:yn(P.at)});else if(P.type==="approval_result"){let V=g(P.approvalId);V&&!R.has(V)&&R.set(V,{action:g(P.action),via:g(P.via),at:yn(P.at)})}else P.phase==="llm_retry"&&p.retries++;let O=u.all(y.id)[0],w=Vl(y.status),x=yn(y.updated_at)-yn(y.created_at),C=new Date(Number.isNaN(yn(y.updated_at))?Date.now():yn(y.updated_at)).toISOString(),D=qt({event:"agent_run",ts:C,sessionId:n,props:{modelId:Yl(y.model_id),providerKind:Gs(y.model_id),mode:Gl(y.kind),steps:d(y.current_step),...p,durationMs:Number.isFinite(x)&&x>=0?x:void 0,outcome:w,errorClass:w==="done"?void 0:Wl(y.error,y.status),...O?{agentRole:O.agentRole,recallEntries:O.recallEntries,recallHistory:O.recallHistory,recallTruncated:O.recallTruncated===1?!0:O.recallTruncated===0?!1:void 0,...O.sectionsType==="array"?{memoryTokens:O.memoryTokens,humanTokens:O.humanTokens,profileTokens:O.profileTokens,projectTokens:O.projectTokens}:{}}:{}}});D&&h.push(D);for(let P of b.values()){let V=qt({event:"tool_call",ts:C,sessionId:n,props:{...P,runOutcome:w}});V&&V.props.tool&&h.push(V)}let F=new Map;for(let P of $){if(!P.name)continue;let V=P.toolCallId?v.get(P.toolCallId):void 0,Z=V==null?P.name.startsWith("mcp__")?"mcp":void 0:Ks(P.name,V),Q=Js(V),ee=`${Z??""}\0${Q}\0${P.reasonKind}\0${P.mode}`,re=F.get(ee)??{tool:Z,toolSource:Q,reasonKind:P.reasonKind,mode:P.mode,asked:0,approved:0,rejected:0,expired:0,decideSecTotal:0,remoteAnswers:0};F.set(ee,re),re.asked++;let oe=P.approvalId?R.get(P.approvalId):void 0;if(!oe){re.expired++;continue}oe.action==="approve"||oe.action==="approve_always"?re.approved++:oe.action==="reject"&&re.rejected++;let pe=Math.round((oe.at-P.at)/1e3);Number.isFinite(pe)&&pe>0&&(re.decideSecTotal+=pe),oe.via&&oe.via!=="local"&&re.remoteAnswers++}for(let P of F.values()){let V=qt({event:"approval",ts:C,sessionId:n,props:P});V&&(V.props.tool||P.tool===void 0)&&h.push(V)}}return{events:h,cursor:m}}catch{return{events:[],cursor:e}}finally{try{s?.close()}catch{}}}async function vg(t,e,n){let r=wn(t,"tangu","state.db"),o=await nu(r).then(i=>i.isFile(),i=>i?.code==="ENOENT"||i?.code==="ENOTDIR"?!1:null);if(o===null)return null;if(!o)return{days:[],complete:!0};let s;try{let{DatabaseSync:i}=await import("node:sqlite");if(s=new i(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 a=Object.keys(ei),c=s.prepare(`SELECT DISTINCT day FROM telemetry_ledger
|
|
278
278
|
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 (${a.map(()=>"?").join(", ")})
|
|
279
|
-
ORDER BY day LIMIT ?`).all(e,n,...a,
|
|
280
|
-
`).filter(Boolean)}catch{return[]}},v=()=>b(a()).flatMap(H=>{try{return[JSON.parse(H)]}catch{return[]}}),$=(H,Y)=>{if(
|
|
279
|
+
ORDER BY day LIMIT ?`).all(e,n,...a,Qs+1),l=s.prepare("SELECT event, dim, field, n FROM telemetry_ledger WHERE day = ? ORDER BY event, dim, field LIMIT ?"),u=[];for(let{day:d}of c.slice(0,Qs)){if(!Wn(d))continue;let g=new Map;for(let m of l.all(d,mg)){if(typeof m.event!="string"||!Object.hasOwn(ei,m.event))continue;let y=ei[m.event],p=typeof m.dim=="string"?m.dim:"";if((y?!p:p!=="")||typeof m.field!="string"||typeof m.n!="number")continue;let b=`${m.event}\0${p}`,v=g.get(b)??{event:m.event,dimKey:y,dim:p,fields:new Map};g.set(b,v),v.fields.set(m.field,(v.fields.get(m.field)??0)+m.n)}let h=[];for(let m of g.values()){let y=qt({event:m.event,ts:`${d}T23:59:59.000Z`,props:{...Object.fromEntries(m.fields),day:d,...m.dimKey?{[m.dimKey]:m.dim}:{}}});!y||y.props.day!==d||m.dimKey&&y.props[m.dimKey]===void 0||Object.keys(y.props).some(p=>p!=="day"&&p!==m.dimKey)&&h.push(y)}u.push({day:d,events:h})}return{days:u,complete:c.length<=Qs}}catch{return null}finally{try{s?.close()}catch{}}}var kg=(t,e,n)=>qt({event:"sync_health",ts:`${t}T23:59:59.000Z`,props:{...n,system:e,day:t}}),Eg=t=>["darwin","win32","linux"].includes(t)?t:"other",_g=t=>["arm64","x64","ia32"].includes(t)?t:"other",Cg=()=>/^zh\b/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en";function ou(t,e={}){let n=e.now??(()=>new Date),r=e.fetch??fetch,o=()=>t.homeDir(),s=()=>wn(o(),"extend-telemetry.json"),i=()=>wn(o(),"telemetry"),a=()=>wn(i(),"queue.jsonl"),c=()=>wn(i(),"sent.jsonl"),l=t.telemetry,u=()=>an(n().getTime()-tu);jc(()=>n().getTime());let d=()=>g()??{},g=()=>{let H;try{H=Kl(s(),"utf8")}catch(Y){return Y?.code==="ENOENT"?{}:null}try{let Y=JSON.parse(H);return Y&&typeof Y=="object"&&!Array.isArray(Y)?Y:null}catch{return null}},h=(H,Y=d())=>{let E={...Y,...H};Xs(o(),{recursive:!0});let T=`${s()}.${process.pid}.tmp`;return Zl(T,JSON.stringify(E,null,2),{encoding:"utf8",mode:384}),Xl(T,s()),E},m=()=>d().installId??h({installId:Jl()}).installId,y=()=>{try{return!!t.readCreds().token}catch{return!1}},p=(H=d())=>H.enabled!==!1&&H.noticeSeen===!0&&l?.packaged===!0&&y(),b=H=>{try{return Kl(H,"utf8").split(`
|
|
280
|
+
`).filter(Boolean)}catch{return[]}},v=()=>b(a()).flatMap(H=>{try{return[JSON.parse(H)]}catch{return[]}}),$=(H,Y)=>{if(Xs(i(),{recursive:!0}),!Y.length){Zs(H,{force:!0});return}let E=`${H}.${process.pid}.tmp`;Zl(E,Y.map(T=>JSON.stringify(T)).join(`
|
|
281
281
|
`)+`
|
|
282
|
-
`,{encoding:"utf8",mode:384}),Xl(
|
|
282
|
+
`,{encoding:"utf8",mode:384}),Xl(E,H)},R=0,O=()=>{R++,Zs(a(),{force:!0}),Zs(c(),{force:!0}),Nc()},w=()=>{let H=n().getTime(),Y=b(c()).flatMap(T=>{try{return[JSON.parse(T)]}catch{return[]}}),E=Y.filter(T=>H-T.at<pg);return E.length!==Y.length&&$(c(),E),E},x=0,C=!1,D=0,F=()=>{let H=g();if(!H)return Cs(!1),!1;let Y=p(H);return Y&&H.closed?h({closed:void 0,cursor:ti(n().getTime()),ledgerCursor:u()},H):Y&&!Wn(H.ledgerCursor)?h({ledgerCursor:u()},H):!Y&&!H.closed&&(x++,h({closed:!0},H)),Cs(Y),Y},P=()=>{let H=g();if(!H){t.log("[forsion-extend] telemetry state unreadable; skipping the signed-in migration");return}if(H.signedInGate)return;let Y={signedInGate:1};!y()&&H.enabled===void 0&&H.noticeSeen===!0&&(Y.enabled=!1,Y.syncHealth=void 0,x++,O(),t.log("[forsion-extend] telemetry turned off: not signed in (sending now needs a Forsion account)")),h(Y,H)},V=H=>{if(!(!H.length||!p())){Xs(i(),{recursive:!0}),sg(a(),H.map(Y=>JSON.stringify(Y)).join(`
|
|
283
283
|
`)+`
|
|
284
|
-
`,{encoding:"utf8",mode:384});try{if(ig(a()).size>Ql){let Y=v(),_=Y.length,T=0;for(;_>0&&T+Buffer.byteLength(JSON.stringify(Y[_-1]))+1<=Ql/2;)T+=Buffer.byteLength(JSON.stringify(Y[--_]))+1;$(a(),Y.slice(_))}}catch{}v().length>=dg&&re()}},Z=()=>{let H=d();return{available:!!l,enabled:H.enabled!==!1,noticeSeen:H.noticeSeen===!0,signedIn:y(),active:p(H),packaged:l?.packaged===!0,installId:m(),queued:og(a())?v().length:0,lastSentAt:H.lastSentAt??null,lastError:H.lastError??null}},Q=()=>ql({app:"desktop",appVersion:t.appVersion(),coreVersion:l?.coreVersion()??void 0,channel:l?.channel(),os:kg(process.platform),osVersion:cg(),arch:Eg(process.arch),locale:_g()}),ee=null,re=()=>{if(ee)return ee;if(C||n().getTime()<D)return Promise.resolve();let H=x,Y=R,_=(async()=>{try{for(let T=0;T<5;T++){let E=v();if(!E.length)return;let I=m(),q={v:Hl,installId:I,...Q()},B=[],M=Buffer.byteLength(JSON.stringify({...q,events:[]}));for(let te of E){let de=Buffer.byteLength(JSON.stringify(te))+1;if(B.length>=Yo.maxEvents||M+de>Yo.maxBatchBytes)break;B.push(te),M+=de}if(!B.length){$(a(),E.slice(1));continue}let{base:L}=await t.getCloud(),J={...q,events:B};if(!j()||H!==x)return;let K=await r(`${L.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(J),signal:AbortSignal.timeout(eu)}).catch(te=>({ok:!1,status:0,error:String(te?.message||te)})),X=K.status;if(X>=200&&X<300||X===400||X===413){let te=new Set(B.map(de=>JSON.stringify(de)));$(a(),v().filter(de=>!te.has(JSON.stringify(de))))}if(X>=200&&X<300){let te=n().getTime();Y===R&&$(c(),[...w(),{at:te,body:J}]),h({lastSentAt:te,lastError:void 0});continue}if(X!==400&&X!==413){let te=Number(K.headers?.get?.("retry-after"));D=n().getTime()+(Number.isFinite(te)&&te>0?Math.min(te,3600)*1e3:5*6e4)}h({lastError:X?`HTTP ${X}`:String(K.error??"network error").slice(0,200)});return}}catch(T){try{h({lastError:String(T?.message||T).slice(0,200)})}catch{}}})();return ee=_,_.finally(()=>{ee===_&&(ee=null)}),_},se=async()=>{try{if(w(),!j())return;let H=d(),Y=x,_=H.cursor??ti(n().getTime()),T=await bg(s(),_,l?.sessionId,ru(n().getTime()));if(!j()||Y!==x)return;V(T.events),T.cursor!==_&&h({cursor:T.cursor}),await pe(Y),await re()}catch(H){t.log(`[forsion-extend] telemetry tick failed: ${String(H?.message||H)}`)}},pe=async H=>{let Y=n().getTime(),_=an(Y),T=an(Y-tu),E=d().ledgerCursor;if(Wn(E)||(E=T,h({ledgerCursor:E})),xo(E),E>=T){ie();return}let I=await Sg(s(),E,_);if(!(!j()||H!==x)){if(I){let q=I.complete?T:I.days[I.days.length-1]?.day??E;if(q>E){let B=$c(E,q),M=[...new Set([...I.days.map(J=>J.day),...B.map(J=>J.day)])].filter(J=>J>E&&J<=q).sort(),L=[];for(let J of M){L.push(...I.days.find(K=>K.day===J)?.events??[]);for(let K of B)if(K.day===J){let X=vg(J,K.system,K.counts);X&&L.push(X)}}V(L),h({ledgerCursor:q}),xo(q)}}ie()}},ie=()=>{if(!Pc())return;let H=g();if(!H)return;let Y=Oc();h({syncHealth:Object.keys(Y).length?Y:void 0},H),Mc()},xe=l?.subscribe(H=>{try{if(!mg.has(H?.event)||!j())return;let Y=qt({...H,sessionId:l.sessionId},ag());Y&&V([Y])}catch(Y){t.log(`[forsion-extend] telemetry event dropped: ${String(Y?.message||Y)}`)}}),ye={ok:!1,error:"untrusted"};t.handle("telemetry:get",H=>t.isTrustedSender(H)?(j(),Z()):ye),t.handle("telemetry:set",(H,Y)=>{if(!t.isTrustedSender(H))return ye;let _=d(),T={};typeof Y?.enabled=="boolean"&&(T.enabled=Y.enabled),Y?.noticeSeen===!0&&(T.noticeSeen=!0);let E={..._,...T};return!p(_)&&p(E)&&(T.cursor=ti(n().getTime()),T.ledgerCursor=u()),p(_)&&!p(E)&&x++,T.enabled===!1&&(T.syncHealth=void 0),h(T),T.enabled===!1&&O(),j(),Z()}),t.handle("telemetry:sent",H=>t.isTrustedSender(H)?{batches:w()}:ye),t.handle("telemetry:delete",async H=>{if(!t.isTrustedSender(H))return ye;C=!0,x++;try{await ee?.catch(()=>{});let Y=m(),{base:_}=await t.getCloud(),E=(await r(`${_.replace(/\/+$/,"")}/api/telemetry/install/${Y}`,{method:"DELETE",signal:AbortSignal.timeout(eu)}).catch(I=>({ok:!1,status:0,error:String(I?.message||I)}))).status;return E>=200&&E<300?(O(),h({installId:Jl(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),Z()):{ok:!1,error:E?`HTTP ${E}`:"network error"}}finally{C=!1}});try{Dc(d().syncHealth),P(),j()}catch(H){t.log(`[forsion-extend] telemetry startup check failed: ${String(H?.message||H)}`)}let Re=t.addFlushHook?.(H=>{if(H!=="blur")try{ie()}catch{}}),$e=setTimeout(()=>void se(),ug),Ae=setInterval(()=>void se(),lg);return $e.unref?.(),Ae.unref?.(),t.log(`[forsion-extend] telemetry registered (${l?l.packaged?"packaged":"dev build: never sends":"host has no telemetry seam: never sends"})`),Object.assign(()=>{clearTimeout($e),clearInterval(Ae),xe?.(),Re?.()},{tick:se,flush:re})}import{readFileSync as kn,lstatSync as Qg,renameSync as em,linkSync as tm,unlinkSync as fi,readdirSync as nm,rmdirSync as rm,writeFileSync as sm,mkdirSync as om,copyFileSync as im,constants as am}from"node:fs";import{readFile as ir,writeFile as ar,mkdir as pi,rename as vs,readdir as cr,lstat as St,stat as hi,unlink as lr}from"node:fs/promises";import{join as Ie,dirname as Yt,relative as ur,sep as En}from"node:path";import{hostname as gi}from"node:os";import{randomUUID as tt}from"node:crypto";import{isUtf8 as mi}from"node:buffer";import{Readable as _u}from"node:stream";var Cg=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],xg=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],sr=".memory-tombstones.json",iu=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),ou=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),Ag=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,Tg=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function Ig(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===sr)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:Cg.includes(t)||iu(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&Ag(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var Rg=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),Dg=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,Og=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function ls(t){let e=t.slice(t.lastIndexOf("/")+1);return Dg.test(e)||Og.test(e)}function au(t,e,n=1){let r=t.lastIndexOf("/"),s=r<0?"":t.slice(0,r+1),o=r<0?t:t.slice(r+1),i=o.lastIndexOf("."),a=i>0?o.slice(0,i):o,c=i>0?o.slice(i):"",l=d=>String(d).padStart(2,"0"),u=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}${n>1?` ${n}`:""}`;return`${s}${a} (conflict ${u})${c}`}function ni(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(ls(t))return!1;if(n){let l=t.slice(6);return e==="folder"?ou(l):xg.includes(l)||iu(l)}let s=t.slice(7),o=s.indexOf("/"),i=o<0?s:s.slice(0,o),a=o<0?"":s.slice(o+1);if(!Tg(i)||Rg(i))return!1;if(e==="file")return Ig(a);if(a===""||a==="LOG"||ou(a))return!0;let c=a.split("/");return c[0]==="Library"&&c.every(l=>l&&!l.startsWith(".")&&!l.endsWith(".")&&!l.endsWith(" "))}import{isAbsolute as Pg}from"node:path";var et=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),pt=t=>typeof t=="string",si=t=>pt(t)&&t.length>0,Pt=t=>typeof t=="boolean",Wt=t=>typeof t=="number"&&Number.isFinite(t),bn=t=>Wt(t)&&Number.isSafeInteger(t)&&t>=0,cu=t=>Wt(t)&&Number.isInteger(t)&&t>=0,lu=t=>bn(t)&&t>0,Sn=t=>pt(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),ps=t=>pt(t)&&/^[a-f0-9]{64}$/.test(t),uu=t=>pt(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),ds=(t,e)=>pt(t)&&e.includes(t),be=(t,e)=>t===void 0||e(t),du=(t,e,n)=>e.every(r=>be(t[r],n)),fu=t=>pt(t)&&!t.includes("\0")&&Pg(t);function Mt(t,e=!1){try{return Dt(t,e),!0}catch{return!1}}var pu=t=>Mt(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,hu=t=>t===""||Sn(t);function fs(t,e){let n=t.indexOf(":");return n>0&&Sn(e)&&t.slice(n+1)===e&&uu(t.slice(0,n))}function Mg(t,e){return et(e)&&fs(t,e.id)&&Mt(e.path)&&si(e.version)&&ps(e.hash)&&du(e,["base","inode","stat"],pt)&&be(e.statAt,Wt)&&be(e.memoryDeleted,Pt)}function $g(t,e){return et(e)&&fs(t,e.localId)&&Sn(e.id)&&Mt(e.path)&&lu(e.revision)&&hu(e.parentId)&&pu(e.name)}function Ng(t){return et(t)&&Sn(t.id)&&Mt(t.path)&&uu(t.target)&&ds(t.direction,["upload","download","merge","rename","delete"])&&ds(t.state,["queued","active","done","failed","paused","conflict"])&&bn(t.done)&&(t.size===null||bn(t.size))&&Wt(t.at)&&be(t.error,pt)&&be(t.finishedAt,Wt)}function jg(t){return et(t)&&Mt(t.path)&&ps(t.hash)&&pt(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&be(t.parentId,Sn)&&be(t.stageRoot,fu)&&be(t.stageIdentity,Ut)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&cu(t.stageDev)&&cu(t.stageIno))}function Fg(t){return et(t)&&Mt(t.prefix,!0)&&fu(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Ut(t))}function Lg(t){return et(t)&&ds(t.state,["running","done"])&&Pt(t.seen)&&du(t,["name","folderId","shelfId","shelfName"],pt)&&be(t.files,bn)&&be(t.at,Wt)&&be(t.rewritten,Pt)}var us=(t,e)=>et(t)&&Object.entries(t).every(([n,r])=>e(n,r)),ri=(t,e)=>Array.isArray(t)&&t.every(e);function gu(t){if(!et(t)||!et(t.config)||!bn(t.config.revision)||!Pt(t.owned)||!Pt(t.paused)||!us(t.files,Mg)||!us(t.folders,$g)||!ri(t.jobs,Ng)||!be(t.accountReview,Pt)||!be(t.agentArchive,Lg)||!be(t.roots,e=>ri(e,Fg))||!be(t.trash,e=>ri(e,jg))||!be(t.unconfirmed,e=>us(e,(n,r)=>fs(n,n.slice(-36))&&ps(r)))||!be(t.pendingUploads,e=>us(e,(n,r)=>et(r)&&fs(n,r.id)&&Mt(r.path))))throw Error("Invalid content sync state; original data was retained");Ot(t.config,t.config.revision)}function Ug(t){return et(t)&&Sn(t.id)&&hu(t.parentId)&&pu(t.name)&&Mt(t.path)&&ds(t.kind,["file","folder"])&&lu(t.revision)&&Pt(t.deleted)&&be(t.busy,Pt)&&be(t.version,si)&&be(t.hash,ps)&&be(t.size,bn)&&be(t.mtime,Wt)&&t.version===void 0==(t.hash===void 0)}function hs(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!et(t)||t.schemaVersion!==1||t.namespace!==e||!si(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,s=new Set;for(let o of t.nodes){if(!Ug(o)||r.has(o.id)||!o.deleted&&s.has(o.path))throw n();r.set(o.id,o),o.deleted||s.add(o.path)}for(let o of r.values()){let i=o.parentId?r.get(o.parentId):void 0;if(o.parentId&&(!i||i.kind!=="folder"||i.deleted&&!o.deleted)||o.path!==(i?i.path+"/"+o.name:o.name))throw n()}}import{constants as mu,lstatSync as Vt,readdirSync as Hg,readFileSync as zg,renameSync as gs,unlinkSync as Bg,linkSync as qg,mkdirSync as ys,realpathSync as oi,rmdirSync as Wg}from"node:fs";import{open as yu,lstat as ii,readdir as Vg,realpath as wu,readFile as ai,writeFile as Yg,mkdir as bu,unlink as Gg}from"node:fs/promises";import{join as $t,dirname as ms,relative as ci,sep as ws}from"node:path";import{randomUUID as Su,createHash as Jg}from"node:crypto";var or=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,bs=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),vu=".forsion-sync-id.json",Kg=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),Xg=t=>!Kg.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),ke=t=>Jg("sha256").update(t).digest("hex");function ku(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 Je(t,e,n=!1){if(n){if(e.split("/").some(a=>a===".."||a==="."||!a)||e.startsWith("/")||e.includes("\\"))throw Error("Invalid internal content path")}else Dt(e,!0);ku(e);let r=await wu(t),s=$t(r,...e.split("/").filter(Boolean)),o=ci(r,s);if(o===".."||o.startsWith(".."+ws))throw Error("Content path escapes root");let i=r;for(let a of o.split(ws).filter(Boolean)){i=$t(i,a);try{if((await ii(i)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(c){if(c.code!=="ENOENT")throw c}}return s}function st(t,e,n=!1){if(n||Dt(e,!0),ku(e),e.split("/").some(o=>o===".."||o===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let s=oi(t);for(let o of e.split("/").filter(Boolean)){s=$t(s,o);try{if(Vt(s).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(i){if(i.code!=="ENOENT")throw i}}return s}async function Ss(t){let e=new Map,n=t.filter(s=>s.prefix).map(s=>s.prefix),r=[];for(let s of t)try{r.push({...s,root:await wu(s.root)})}catch(o){if(o.code!=="ENOENT")throw o}if(new Set(r.map(s=>s.root)).size!==r.length)throw Error("Managed roots refer to the same directory; choose a separate vault folder");for(let s of r){let o=s.root;if(!(await ii(o)).isDirectory())throw Error(`Sync root is not a directory: ${s.prefix||"Forsion"}`);let i=async(a,c)=>{let l=await ii(a);if(!l.isSymbolicLink()&&!(a!==o&&r.some(u=>u!==s&&u.root===a))&&!(c&&s.prefix===""&&n.some(u=>c===u||c.startsWith(u+"/")))){if(c){Dt(c);let u;if(l.isDirectory())try{let d=JSON.parse(await ai($t(a,vu),"utf8"));/^[a-f0-9-]{36}$/i.test(d.id)&&(u=d.id)}catch(d){if(d.code!=="ENOENT"&&!(d instanceof SyntaxError))throw d}e.set(c,{path:c,physical:a,root:o,kind:l.isDirectory()?"folder":"file",localId:u,...bs(l),size:l.isFile()?l.size:0})}if(l.isDirectory())for(let u of await Vg(a,{withFileTypes:!0}))!Xg(u.name)||!u.isDirectory()&&!u.isFile()||await i($t(a,u.name),c?`${c}/${u.name}`:u.name)}};await i(o,s.prefix)}return[...e.values()].sort((s,o)=>s.path.split("/").length-o.path.split("/").length||s.path.localeCompare(o.path))}async function li(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await Je(t.root,ci(t.root,$t(t.physical,vu)).split(ws).join("/"),!0),n=Su();try{let r=await yu(e,"wx",384);try{await r.writeFile(JSON.stringify({version:1,id:n})+`
|
|
285
|
-
`)}finally{await r.close()}return t.localId=n,n}catch(r){if(r.code!=="EEXIST")throw r;let s=JSON.parse(await ai(e,"utf8"));if(!/^[a-f0-9-]{36}$/i.test(s.id))throw Error("Invalid folder sync identity");return t.localId=s.id,s.id}}async function vn(t){let e=await Je(t.root,ci(t.root,t.physical).split(ws).join("/")),n=await yu(e,mu.O_RDONLY|(mu.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 Le(t,e){Dt(e);let n=[...t].sort((r,s)=>s.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 ui(t,e,n,r,s=async(o,i)=>i()){let o=Le(t,e);await bu(o.root,{recursive:!0});let i=await Je(o.root,o.relative),a=await ai(i).catch(l=>{if(l.code==="ENOENT")return null;throw l});if((a?ke(a):null)!==r)throw Error("Local file changed during download");let c=$t(o.root,`.forsion-sync-${Su()}.tmp`);try{await Yg(c,n,{flag:"wx",mode:384}),await Je(o.root,o.relative),await s(i,()=>{st(o.root,o.relative),ys(ms(i),{recursive:!0}),st(o.root,o.relative);let l=null;try{l=zg(i)}catch(u){if(u.code!=="ENOENT")throw u}if((l?ke(l):null)!==r)throw Error("Local file changed during download");gs(c,i)})}finally{await Gg(c).catch(()=>{})}}async function Eu(t,e,n=async(r,s)=>s()){let r=Le(t,e);await bu(r.root,{recursive:!0});let s=await Je(r.root,r.relative);await n([s],()=>{st(r.root,r.relative),ys(s,{recursive:!0})})}async function di(t,e,n,r=async(s,o)=>o()){let s=Le(t,e),o=Le(t,n);if(s.root!==o.root)throw Error("Folder move crosses a managed source");let i=await Je(s.root,s.relative),a=await Je(o.root,o.relative);await r([i,a],()=>{if(st(s.root,s.relative),st(o.root,o.relative),Zg(a)){let l=Vt(i),u=Vt(a),d=oi(ms(i));if((l.dev===u.dev&&l.ino===u.ino&&d===oi(ms(a))?Hg(d).filter(m=>{let y=Vt($t(d,m));return y.dev===l.dev&&y.ino===l.ino}):[]).length!==1)throw Error("Local rename destination exists");gs(i,a);return}ys(ms(a),{recursive:!0});let c=Vt(i);if(c.isDirectory()){if(process.platform==="win32"){gs(i,a);return}ys(a,{mode:448});try{gs(i,a)}catch(l){try{Wg(a)}catch{}throw l}}else{qg(i,a);let l=Vt(i);if(l.ino!==c.ino||l.dev!==c.dev)throw Error("Source changed during rename");Bg(i)}})}function Zg(t){try{return Vt(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Cu=(t,e)=>t.length===e.length&&t.every(n=>e.some(r=>n.prefix===r.prefix&&n.root===r.root&&(n.dev===void 0||tn(n,r)))),cm=()=>({config:structuredClone(Zc),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),_n=50*1024*1024,lm=10*6e4,xu=1024*1024,Pe=(t,e)=>`${t}:${e}`,vt=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",Gt=t=>t.slice(t.lastIndexOf("/")+1),dr=ke(""),yi=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),Nt=t=>t.split("/").length,Me=t=>t instanceof Error?t.message:String(t),um={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},wi=t=>t.file.replace(/\.json$/,".bases"),Iu=5e3,dm=3e4,Au=3e4,fm=3e3,fr=10*6e4,bi=t=>/^(agents|human)\//.test(t)?dm:Iu,pm=t=>Math.max(t.mtime,t.ctime);function Ru(t){if(!t.contentSync)return;let e=new Si(t);for(let[n,r]of Object.entries({[lt.get]:s=>e.snapshot(s),[lt.preview]:s=>e.preview(s),[lt.apply]:(s,o)=>e.apply(typeof s=="string"?s:"",o),[lt.run]:()=>e.kick(),[lt.pause]:s=>e.pause(s===!0),[lt.retry]:()=>e.kick(),[lt.rename]:s=>e.rename(s),[lt.setup]:s=>e.setup(s),[lt.archiveSeen]:()=>e.archiveSeen()}))t.handle(n,async(s,...o)=>{if(!t.isTrustedSender(s))return{ok:!1,error:"untrusted"};try{return{ok:!0,value:await r(...o)}}catch(i){return{ok:!1,error:Me(i)}}});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)),ul(()=>e.stats()),e.start()}var Si=class{session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;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 Qn;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=qr((e,n,r)=>rt("content",e,n,r));httpStatus=0;closed=!1;runFinished=Promise.resolve();archiving=null;archiveRetry={account:"",at:0};resolving=!1;awaitingBytes=new Map;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=Ga(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{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()+fr}};return this.archiving??=(async()=>{try{let r=this.host.readCreds();if(!r.token)return;let s=await fetch(r.cloudUrl.replace(/\/+$/,"")+"/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()}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(6e4)])});if(this.guard(e),!s.ok){n();return}let o=await s.json();if(this.guard(e),o.state!=="done"&&o.state!=="running"){n();return}let i=e.stored.agentArchive,a=o.archive;i?.rewritten||this.turnAgentsOff(e);let c={rewritten:!0,seen:i?.seen??!1,state:o.state};o.state==="done"&&(a?.folderId?Object.assign(c,{folderId:a.folderId,name:a.name??void 0,shelfId:a.shelfId??void 0,shelfName:a.shelfName??void 0,files:a.files??0,at:a.at??Date.now()}):c.seen=!0),e.stored.agentArchive=c,await this.persist(e)}catch(r){if(Me(r)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${Me(r)}`)}finally{this.archiving=null}})()}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=il(n);if(!r)return;e.stored.config=Ot(r,n.revision+1);let s=o=>o==="agents"||o.startsWith("agents/");for(let[o,i]of Object.entries(e.stored.files))s(i.path)&&(delete e.stored.files[o],delete e.stored.unconfirmed?.[o]);for(let[o,i]of Object.entries(e.stored.folders))s(i.path)&&delete e.stored.folders[o];for(let[o,i]of Object.entries(e.stored.pendingUploads??{}))s(i.path)&&delete e.stored.pendingUploads[o];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=jn(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(co(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 pi(Yt(e.file),{recursive:!0,mode:448});let s=e.file+".tmp-"+tt();try{await ar(s,r,{mode:384,flag:"wx"}),this.guard(e,!1),await vs(s,e.file),e.persisted=r}finally{await lr(s).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 co(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=Ie(this.host.homeDir(),"content-sync"),s=Ie(r,ke(e)+".json"),o=cm();try{let d=JSON.parse(await ir(s,"utf8"));gu(d),o={...o,...d,config:Ot(d.config,d.config.revision)},o.jobs=Array.isArray(d.jobs)?d.jobs.slice(-200):[]}catch(d){if(d.code!=="ENOENT")throw Error("Invalid content sync state; original data was retained")}let i,a=Ie(this.host.homeDir(),"content-sync-device.json"),c=async()=>{let d=JSON.parse(await ir(a,"utf8"));if(typeof d?.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(d.id))throw Error("Invalid device sync ID");return d};try{i=await c()}catch(d){if(d.code!=="ENOENT")throw d;i={id:tt()},await pi(Yt(a),{recursive:!0});try{await ar(a,JSON.stringify(i),{flag:"wx",mode:384})}catch(g){if(g.code!=="EEXIST")throw g;i=await c()}}if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=i.id,this.customName=typeof i.name=="string"?i.name:"";let l=await this.host.contentSync.roots();if(this.host.accountId()!==e)throw Error("account_changed");let u={account:e,generation:n,file:s,stored:o,roots:l,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map};return this.session=u,await this.bindAccount(u),await this.recoverTrash(u),this.guard(u),o.owned&&await this.accountWrite(u,d=>this.host.contentSync.claim(!0,d)),this.setSources(await this.scan(u,l).catch(d=>(this.error=Me(d),[]))),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=Yt(e.file),r=io(this.host.homeDir()),s=ke(e.account),o=jn(r),i=!o?.account&&(await cr(n).catch(c=>{if(c.code==="ENOENT")return[];throw c})).some(c=>/^[a-f0-9]{64}\.json$/.test(c)&&c!==s+".json"),a=o?.pending&&(e.stored.owned||e.stored.config.revision>0);if((o?.account&&o.account!==s||i||a)&&(e.stored.accountReview=!0,e.stored.owned=!0,e.stored.config.enabled&&(e.stored.config={...e.stored.config,enabled:!1,revision:e.stored.config.revision+1}),await this.persist(e)),o?.account!==s||o.pending){this.guard(e,!1);let c=jn(r);if(c?.account!==o?.account||c?.epoch!==o?.epoch||c?.pending!==o?.pending)throw Error("account_changed");ao(r,{version:1,account:s,...o?.epoch?{epoch:o.epoch}:{}})}e.binding={file:r,account:s,epoch:o?.epoch},this.guard(e,!1)}async rootIdentity(e,n){let r=e.rootIdentities.get(n);if(r){let o=await hi(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!o.isDirectory()||!Ht(r,o))throw Error("Sync root changed; preview before rebinding");return r}let s=await Pn(n).catch(o=>{throw o.code==="ENOENT"?Error("Sync root unavailable: "+n):o});return this.guard(e),e.rootIdentities.set(n,s),s}async scan(e,n=e.roots){let r=!1;for(let s of e.stored.roots??[]){let o=n.find(a=>a.prefix===s.prefix);if(!o||o.root!==s.root)throw Error("content_roots_changed_preview_required");let i=await this.rootIdentity(e,s.root);if(s.dev!==void 0&&!tn(s,i))throw Error("Sync root changed; preview before rebinding");if(s.dev!==void 0&&s.dev!==i.dev){let a=String(s.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(a)&&Le(n,c.path).root===s.root&&(c.inode=String(i.dev)+":"+c.inode.slice(a.length),delete c.stat,delete c.statAt)}JSON.stringify(s)!==JSON.stringify({...s,...i})&&(Object.assign(s,i),r=!0)}return r&&await this.persist(e),Ss(n)}async write(e,n,r,s){this.guard(e),await ui(e.roots,n,r,s,(o,i)=>this.lock(e,o,i)),await this.recordRoots(e)}async recordRoots(e){this.guard(e);let n=!1;for(let r of e.roots){if(e.stored.roots?.some(o=>o.prefix===r.prefix&&o.root===r.root))continue;await hi(r.root).catch(o=>{if(o.code==="ENOENT")return null;throw o})&&((e.stored.roots??=[]).push({...r,...await this.rootIdentity(e,r.root)}),n=!0)}n&&await this.persist(e)}lock(e,n,r,s=!1){let o=()=>{if(this.guard(e),e.stored.paused&&!s)throw Error("paused");r(),this.wroteLocal=!0};return this.host.contentSync.withWriteLock?.(n,o)??Promise.resolve().then(o)}async previewScan(e,n){for(let r of e.stored.roots??[])n.some(s=>s.prefix===r.prefix&&s.root===r.root)&&await St(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return Ss(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Us(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 s=this.logical(e,r),o=Date.now();if(s){let i=this.dirty.get(s);i?i.last=o:this.dirty.set(s,{first:o,last:o})}this.schedule(s?void 0:o+Iu)}))}logical(e,n){let r=null;for(let i of e.roots)(n===i.root||n.startsWith(i.root+En))&&(!r||i.root.length>r.root.length)&&(r=i);if(!r)return null;let s=ur(r.root,n).split(En).join("/");return(r.prefix?s?`${r.prefix}/${s}`:r.prefix:s)||null}dueAt(e,n){return n.last<=this.flushAt?0:Math.min(n.last+bi(e),n.first+Au)}schedule(e){let n=e??1/0;for(let[r,s]of this.dirty)n=Math.min(n,this.dueAt(r,s));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()}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()),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 s=this.flushRequest;if(await this.run(),s===this.flushRequest)return}}finally{this.flushing=null,this.quitting=!1,this.flushAt=this.flushThrough}})()}async request(e,n,r="",s="GET",o,i,a){this.guard(e);let c=this.host.readCreds();if(!c.token)throw Error("not_signed_in");let l=c.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(n)}${r}`,u={Authorization:`Bearer ${c.token}`,"X-Content-Device":this.deviceId,...a},d;if(o instanceof Buffer){u["Content-Type"]="application/octet-stream",u["Content-Length"]=String(o.length);let m=async function*(){for(let y=0;y<o.length;y+=64*1024)e.abort.signal.throwIfAborted(),yield o.subarray(y,y+64*1024),i?.(Math.min(o.length,y+64*1024))};d=_u.from(m())}else o!==void 0&&(u["Content-Type"]="application/json",d=JSON.stringify(o));let g={method:s,headers:u,body:d,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...o instanceof Buffer?{duplex:"half"}:{}},h=await fetch(l,g);if(this.guard(e),!h.ok&&!(h.status===304&&a?.["If-None-Match"])){this.httpStatus=h.status;let m=await h.json().catch(()=>({}));throw Object.assign(new Error(typeof m.detail=="string"?m.detail:`content_http_${h.status}`),{status:h.status})}return s==="DELETE"&&this.tally("deletesSent"),h}async json(e,n,r="",s="GET",o){let i=await(await this.request(e,n,r,s,o)).json();return this.guard(e),i}async manifests(e,n){let r=new Map;for(let o of new Set(n.rules.filter(i=>i.target!=="off").map(i=>i.target))){let i=JSON.parse(await this.manifestText(e,o));hs(i,o),r.set(o,i)}let s=[r.get("default"),r.get(`device-${this.deviceId}`)].filter(Boolean);return s.length&&(this.cloudAgents=[...new Set(s.flatMap(o=>o.nodes.filter(i=>!i.deleted&&i.kind==="file").map(i=>/^agents\/([^/]+)\/config\.toml$/.exec(i.path)?.[1]).filter(i=>!!i&&Xn.test(i))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),s=r&&Date.now()-r.at<fr?r:void 0,o=await this.request(e,n,"","GET",void 0,void 0,s?{"If-None-Match":s.etag}:void 0);if(o.status===304)return await o.body?.cancel(),s?s.text:(e.manifests.delete(n),this.manifestText(e,n));let i=await o.text();this.guard(e),hs(JSON.parse(i),n);let a=o.headers.get("etag");return a?e.manifests.set(n,{etag:a,text:i,at:Date.now()}):e.manifests.delete(n),i}route(e,n,r="file"){if(ls(e)||ni(e,r)===!1)return null;let s=dn(e,n.rules);return s&&s.target!=="off"?s.target:null}effective(e,n){let r=new Map(n.filter(s=>s.localId).map(s=>[s.localId,s.path]));return{...e,rules:e.rules.map(s=>s.sourceId&&r.has(s.sourceId)?{...s,source:r.get(s.sourceId)}:s)}}deviceName(){return this.customName||ss(gi())}setSources(e){let n=new Map,r={files:0,size:0};for(let o of e)o.kind==="folder"&&n.set(o.path,{size:0,files:0});for(let o of e)if(o.kind==="file"){Qc.some(i=>o.path.startsWith(i+"/"))||(r.files++,r.size+=o.size);for(let i=vt(o.path);i;i=vt(i)){let a=n.get(i);a&&(a.size+=o.size,a.files++)}}let s=new Map(e.filter(o=>o.kind==="file"&&/^agents\/[^/]+\/config\.toml$/.test(o.path)).map(o=>[o.path.slice(0,-12),o]));this.others=r,this.sources=[...n].sort(([o],[i])=>Nt(o)-Nt(i)||(o<i?-1:1)).slice(0,2e3).map(([o,i])=>({path:o,kind:"folder",size:i.size,files:i.files,...Zn(o)&&s.has(o)?{agent:!0}:{}})),this.sourcesAt=Date.now(),this.readAgentNames(s)}async readAgentNames(e){for(let n of this.agentNames.keys())e.has(n)||this.agentNames.delete(n);for(let[n,r]of e){let s=`${r.mtime}:${r.size}`;if(!(this.agentNames.get(n)?.key===s||r.size>256*1024))try{this.agentNames.set(n,{key:s,...el((await vn(r)).toString("utf8"))})}catch{this.agentNames.set(n,{key:s})}}}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(),s=n||ss(gi()),o=Fo(s,this.devices,this.deviceId);if(o)throw Error(o==="taken"?"device_name_taken":o==="reserved"?"device_name_reserved":"device_name_invalid");return await this.json(r,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:s,unique:!0}),await this.saveName(n),await this.register(r,!0),this.deviceName()}async saveName(e){let n=Ie(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+tt();try{await ar(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await vs(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<fr){r-this.devicesAt>=fr&&await this.refreshDevices(e);return}let s=(a,c)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:a,...c?{unique:!0}:{}}),o=async()=>(await this.json(e,"devices")).devices,i=a=>/device_name_(taken|reserved|invalid)/.test(Me(a));try{await s(this.deviceName(),!0)}catch(a){if(!i(a))throw a;let c=!1;if(!this.customName){let l=ss(gi());for(let u=0;u<5&&!c;u++){let d=await o(),g=null;for(let h=2;h<100&&!g;h++){let m=`${l} ${h}`;Fo(m,d,this.deviceId)||(g=m)}if(!g)break;try{await s(g,!0),await this.saveName(g),c=!0}catch(h){if(!i(h))throw h}}}c||await s(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=Ie(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let a=JSON.parse(await ir(e,"utf8"));Array.isArray(a?.devices)&&(n=a.devices)}catch{}let r=new Map(n.filter(a=>a&&typeof a.id=="string").map(a=>[a.id,a])),s=this.devices.map(a=>{let c=r.get(a.id),l=[...Array.isArray(c?.aliases)?c.aliases:[],...c&&typeof c.name=="string"&&c.name!==a.name?[c.name]:[]],u=l.filter((d,g)=>typeof d=="string"&&d!==a.name&&l.lastIndexOf(d)===g).slice(-5);return{id:a.id,name:a.name,...u.length?{aliases:u}:{}}}),o=JSON.stringify({devices:s});if(o===this.cachedDevices)return;let i=e+".tmp-"+tt();try{await ar(i,o,{mode:384,flag:"wx"}),await vs(i,e),this.cachedDevices=o}catch(a){this.error=Me(a)}finally{await lr(i).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 s=pn(sl(n.stored.config),"","off");for(let a of wt)a.id!=="agents"&&r[a.id]===!1&&(s=pn(s,a.path,"off"));let o=new Set(this.sources.filter(a=>a.agent).map(a=>a.path.slice(7))),i=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(a=>typeof a=="string"&&o.has(a)):[];return this.preview(ol(s,i))}async snapshot(e){(e==="zh"||e==="en")&&(this.uiLocale=e);let n=await this.getSession();return!n.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(n).then(r=>{this.session===n&&this.setSources(r)},()=>{})),Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(n).catch(()=>{})),{available:!0,account:ke(n.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(n.stored.config),running:this.running,paused:n.stored.paused,phase:this.phase,jobs:structuredClone(n.stored.jobs),devices:this.devices,sources:this.sources.map(r=>{let s=r.agent&&this.agentNames.get(r.path);return s?{...r,...s.name?{name:s.name}:{},...s.nameEn?{nameEn:s.nameEn}:{}}:r}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...n.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...n.stored.agentArchive?{agentArchive:(({rewritten:r,...s})=>s)(n.stored.agentArchive)}:{}}}stats(){let e=this.host.accountId(),n=e&&this.session?.account===e?this.session:null,r=n?.stored,s={},o=e&&e===this.logAccount?this.runLog.snapshot():new Qn().snapshot();for(let i of r?.jobs??[])s[i.state]=(s[i.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(i=>({source:i.source,target:i.target})),backlog:r?{jobs:s,blocked:[...this.blocked.values()].reduce((i,a)=>i+a.length,0),pendingUploads:Object.keys(r.pendingUploads??{}).length,unconfirmed:Object.keys(r.unconfirmed??{}).length,trash:r.trash?.length??0,awaitingBytes:this.awaitingBytes.size,dirty:this.dirty.size}:null,archive:r?.agentArchive?.state??null,...o}}async preview(e){let n=await this.getSession();if(e?.revision!==n.stored.config.revision)throw Error("config_changed");let s=Ot(e,n.stored.config.revision+1),o=await this.host.contentSync.roots();this.guard(n);let i=await this.previewScan(n,o),a=this.effective(s,i);if(n.stored.agentArchive?.state==="running"&&i.some(b=>b.kind==="file"&&b.path.startsWith("agents/")&&this.route(b.path,a)))throw Error("agent_archive_running");let c=await this.manifests(n,a);this.guard(n),this.setSources(i);let l=0,u=0,d=0,g=0,h=new Map;for(let b of i.filter(v=>v.kind==="file")){let v=this.route(b.path,a);if(!v)continue;let $=c.get(v)?.nodes.find(O=>!O.deleted&&O.kind==="file"&&O.path===b.path);if(b.size>_n){l++,g+=b.size;continue}let R=ke(await vn(b));this.guard(n),h.set(b.path,R),R!==$?.hash&&(l++,g+=b.size,$?.version&&d++)}let m=s.enabled?this.agentAsks(n,i,a,c,h):[];for(let[b,v]of c)for(let $ of v.nodes)!$.deleted&&$.kind==="file"&&$.version&&this.route($.path,a)===b&&!i.some(R=>R.path===$.path)&&u++;let y=this.signature(i,c,o),p={token:tt(),config:a,upload:s.enabled?l:0,download:s.enabled?u:0,conflicts:s.enabled?d:0,bytes:s.enabled?g:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,...m.length?{agentAsks:m}:{}};return this.previewValue={value:p,account:n.account,signature:y},p}signature(e,n,r){return ke(JSON.stringify([r,e.map(s=>[s.path,s.size,s.mtime,s.inode]),[...n].map(([s,o])=>[s,o.nodes.map(i=>[i.id,i.revision,i.version,i.deleted])])]))}async apply(e,n){let r=this.serial,s;this.serial=new Promise(o=>{s=o}),await r;try{let o=await this.getSession(),i=this.previewValue;if(!i||i.value.token!==e||i.account!==o.account||i.value.expiresAt<Date.now()||i.value.config.revision!==o.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let a=i.value.agentAsks??[],c=hm(n);this.resolving=!0;try{let l=await this.host.contentSync.roots(),u=await this.previewScan(o,l),d=await this.manifests(o,i.value.config);if(this.signature(u,d,l)!==i.signature)throw Error("preview_changed");let g=[];for(let p of l)await hi(p.root).catch(v=>{if(v.code==="ENOENT")return null;throw v})&&g.push({...p,...await Pn(p.root)});let h=structuredClone(i.value.config);for(let p of h.rules){let b=u.find(v=>v.kind==="folder"&&v.path===p.source);b&&(p.sourceId=await li(b))}let m=a.length?Ot(a.reduce((p,b)=>pn(p,`agents/${b.slug}`,"off"),h),h.revision):h;if(this.guard(o),this.previewValue!==i||i.value.config.revision!==o.stored.config.revision+1)throw Error("preview_expired");let y=structuredClone(o.stored);o.stored.config=m,o.stored.owned=!0,o.stored.paused=!1,delete o.stored.unconfirmed;for(let[p,b]of Object.entries(o.stored.files))(y.config.enabled!==o.stored.config.enabled||!Cu(y.roots??g,g)||this.route(b.path,y.config)!==this.route(b.path,o.stored.config))&&delete o.stored.files[p];for(let[p,b]of Object.entries(o.stored.folders))(y.config.enabled!==o.stored.config.enabled||!Cu(y.roots??g,g)||this.route(b.path,y.config,"folder")!==this.route(b.path,o.stored.config,"folder"))&&delete o.stored.folders[p];o.stored.roots=g,o.rootIdentities=new Map(g.map(p=>[p.root,p])),await this.persist(o);try{await this.accountWrite(o,p=>this.host.contentSync.claim(!0,p))}catch(p){throw o.stored=y,await this.persist(o),await this.accountWrite(o,b=>this.host.contentSync.claim(y.owned,b)).catch(()=>{}),p}if(this.previewValue=null,o.roots=l,await this.watchRoots(o),a.length)try{await this.resolveAsks(o,a,c,h)}catch(p){throw this.fault(Me(p)),p}o.stored.accountReview&&(delete o.stored.accountReview,await this.persist(o))}finally{this.resolving=!1}}finally{s()}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,s,o){let i=e.stored.jobs.findLast(c=>c.path===n&&c.target===r&&c.direction===s&&["failed","paused","queued"].includes(c.state));if(i)return Object.assign(i,{state:"active",done:0,size:o,at:Date.now(),error:void 0,finishedAt:void 0}),i;let a={id:tt(),path:n,target:r,direction:s,state:"active",done:0,size:o,at:Date.now()};return e.stored.jobs.push(a),e.stored.jobs=e.stored.jobs.slice(-200),a}done(e){e.state="done",e.done=e.size??e.done,e.finishedAt=Date.now()}async operation(e,n,r,s,o,i){if(this.guard(e),e.stored.paused)throw Error("paused");let a=this.job(e,n,r,s,o);try{let c=await i(a);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(a),s==="upload"?rt("content","uploads"):s==="download"&&rt("content","downloads");let l=um[s];return l&&this.tally(l),c}catch(c){throw a.state=e.stored.paused?"paused":"failed",a.error=Me(c),a.finishedAt=Date.now(),c}}async run(){if(this.running||this.closed||this.resolving)return;this.running=!0;let e;this.runFinished=new Promise(a=>{e=a});let n=Date.now();this.wroteLocal=!1;let r=new Set,s,o=!1,i=!1;try{if(s=await this.getSession(),this.runAccount=s.account,s.stored.accountReview){this.error="content_account_changed_preview_required";return}if(await this.archiveStep(s),!s.stored.config.enabled||s.stored.paused)return;s.abort.signal.aborted&&(s.abort=new AbortController),this.blocked.clear(),this.phase="scanning",this.error=void 0,o=!0,this.httpStatus=0,this.live()&&this.runLog.begin(n);let a=await this.host.contentSync.roots();this.guard(s),s.roots=a,await this.host.contentSync.agentFiles?.prepare().catch(p=>{this.error=Me(p)}),this.guard(s);let c=await this.scan(s,a);await this.recordRoots(s);let l=this.effective(s.stored.config,c),u=await this.manifests(s,l);this.guard(s),await this.register(s),this.openJobs=new Set(s.stored.jobs.filter(p=>["failed","paused","active"].includes(p.state)&&["upload","download","merge"].includes(p.direction)).map(p=>p.target+"\0"+p.path)),await this.folders(s,l,c,u),await this.recordRoots(s),await this.fileRenames(s,l,c,u),c=await this.scan(s,a),l=this.effective(l,c),s.stored.config=l,this.setSources(c),this.phase="syncing";let d=p=>p.endsWith("/"+sr),g=new Set,h=new Set,m=p=>p.startsWith("agents/")?p.slice(0,p.lastIndexOf("/")+1):null,y=p=>p.endsWith("/MEMORY.md")&&h.has(m(p)??"");for(let[p,b]of u)for(let v of b.nodes.filter($=>$.kind==="file"&&!$.busy&&d($.path))){if(this.guard(s),s.stored.paused)throw Error("paused");if(!(this.route(v.path,l)!==p||c.some($=>$.path===v.path))){if(this.isBlocked(p,v.path)){h.add(m(v.path)??"");continue}g.add(v.id);try{await this.missing(s,v,p,c,l)}catch($){this.error=Me($),h.add(m(v.path)??"")}}}for(let p of c.filter(b=>b.kind==="file").sort((b,v)=>+!d(b.path)-+!d(v.path))){if(this.guard(s),s.stored.paused)throw Error("paused");let b=this.route(p.path,l);if(!(!b||y(p.path))){if(this.isBlocked(b,p.path)){d(p.path)&&h.add(m(p.path)??"");continue}try{await this.file(s,l,p,b,u.get(b))==="held"&&r.add(p.path)}catch(v){this.error=Me(v),d(p.path)&&h.add(m(p.path)??"")}}}for(let[p,b]of u)for(let v of b.nodes.filter($=>$.kind==="file"&&!$.busy&&!g.has($.id))){if(this.guard(s),s.stored.paused)throw Error("paused");if(!(this.isBlocked(p,v.path)||this.route(v.path,l)!==p||c.some($=>$.path===v.path)||y(v.path))){if(this.holdGone(v.path)){r.add(v.path);continue}try{await this.missing(s,v,p,c,l)}catch($){this.error=Me($)}}}await this.cleanupFolders(s,l,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(s).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=fr)&&(await this.accountWrite(s,p=>this.host.contentSync.changed(p)),this.changedAt=Date.now()),this.guard(s),await this.persist(s),await this.pruneBases(s),i=!0}catch(a){this.error=Me(a)}finally{this.phase=s?.stored.paused?"paused":"idle",o&&(this.noteHealth(n,i),this.live()&&this.runLog.end(i));for(let[a,c]of this.dirty)!r.has(a)&&c.last<n&&this.dirty.delete(a);s&&this.host.accountId()===s.account&&(await this.persist(s).catch(()=>{}),!this.closed&&s.abort.signal.aborted&&!s.stored.paused&&s.stored.config.enabled&&(s.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&&(rt("content","cycles"),rt("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?Br(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<bi(e)&&r-n.first<Au}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=Me(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(Me(r),[n])}async folders(e,n,r,s){let o=r.filter(a=>a.kind==="folder"),i=new Map;for(let a of o)if(a.localId){if(i.has(a.localId))throw Error(`Duplicate folder sync identity: ${a.path}`);i.set(a.localId,a.path)}for(let[a,c]of s){for(let l of c.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,d)=>Nt(u.path)-Nt(d.path)))if(!this.isBlocked(a,l.path))try{let u=Object.entries(e.stored.folders).find(([g,h])=>g.startsWith(a+":")&&h.id===l.id)?.[1],d=(u?o.find(g=>g.localId===u.localId):null)??o.find(g=>g.path===l.path);if(u&&d&&l.path!==u.path&&d.path!==u.path&&l.path!==d.path)throw Error(`Concurrent folder rename: ${d.path}`);if(u&&d&&l.path!==u.path&&d.path===u.path){if(this.route(d.path,n,"folder")!==a)continue;if(this.route(l.path,n,"folder")!==a)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,d.path,a,"rename",null,()=>di(e.roots,d.path,l.path,(h,m)=>this.lock(e,h,m)));let g=d.path;for(let h of r)if(h.path===g||h.path.startsWith(g+"/")){let m=h.path;h.path=l.path+m.slice(g.length);let y=Le(e.roots,h.path);h.physical=Ie(y.root,y.relative)}for(let[h,m]of Object.entries(e.stored.files))h.startsWith(a+":")&&m.path.startsWith(u.path+"/")&&(m.path=l.path+m.path.slice(u.path.length));for(let h of n.rules)(h.source===u.path||h.source.startsWith(u.path+"/"))&&(h.source=l.path+h.source.slice(u.path.length))}if(!d&&this.route(l.path,n,"folder")===a&&!u){await Eu(e.roots,l.path,(h,m)=>this.lock(e,h,m));let g=(await this.scan(e)).find(h=>h.path===l.path);g&&(r.push(g),o.push(g))}}catch(u){this.block(a,l.path,u),this.tally("folderConflicts");let d=Object.entries(e.stored.folders).find(([g,h])=>g.startsWith(a+":")&&h.id===l.id)?.[1];d&&this.block(a,d.path,u)}for(let l of o.sort((u,d)=>Nt(u.path)-Nt(d.path)))if(!this.isBlocked(a,l.path))try{let u=this.route(l.path,n,"folder"),d=n.rules.some(b=>b.target===a&&b.source.startsWith(l.path+"/"));if(u!==a&&!d||ni(l.path,"folder")===!1)continue;let g=await li(l),h=e.stored.folders[Pe(a,g)],m=h?c.nodes.find(b=>b.id===h.id):c.nodes.find(b=>b.path===l.path&&!b.deleted);if(m?.deleted){if(h){let b=!1;for(let v of r.filter($=>$.kind==="file"&&$.path.startsWith(l.path+"/")&&this.route($.path,n)===a)){let $=Object.entries(e.stored.files).find(([R,O])=>R.startsWith(a+":")&&O.path===v.path)?.[1];if(!$){b=!0;break}if(!this.sameAsShadow($,v)){let R=ke(await vn(v));if(R!==$.hash&&!($.memoryDeleted&&yi(v.path)&&R===dr)){b=!0;break}}}if(!b)continue}m=void 0}let y=vt(l.path),p=y?c.nodes.find(b=>b.path===y&&b.kind==="folder"&&!b.deleted)?.id:"";if(y&&!p)throw Error("Cloud parent is unavailable");if(!m)m=await this.json(e,a,"/nodes","POST",{id:h?tt():g,parentId:p,name:Gt(l.path),kind:"folder"}),c.nodes.push(m);else if(h&&m.path!==l.path){if(m.revision!==h.revision)throw Error(`Concurrent folder rename: ${l.path}`);let b=m.path,v=await this.operation(e,l.path,a,"rename",null,()=>this.json(e,a,`/nodes/${m.id}`,"PATCH",{parentId:p,name:Gt(l.path),revision:m.revision}));for(let $ of c.nodes)$.path.startsWith(b+"/")&&($.path=l.path+$.path.slice(b.length));Object.assign(m,v);for(let[$,R]of Object.entries(e.stored.files))$.startsWith(a+":")&&R.path.startsWith(b+"/")&&(R.path=l.path+R.path.slice(b.length))}e.stored.folders[Pe(a,g)]={id:m.id,localId:g,path:l.path,revision:m.revision,parentId:m.parentId,name:m.name}}catch(u){this.block(a,l.path,u);let d=l.localId?e.stored.folders[Pe(a,l.localId)]:void 0;d&&this.block(a,d.path,u),rt("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,l.path,a,"rename",null);g.state="conflict",g.error=Me(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let s=await this.scan(e);for(let[o,i]of r)for(let a of i.nodes.filter(c=>c.kind==="folder"&&!c.busy).sort((c,l)=>Nt(l.path)-Nt(c.path))){if(this.isBlocked(o,a.path)||this.route(a.path,n,"folder")!==o)continue;let c=Object.entries(e.stored.folders).find(([u,d])=>u.startsWith(o+":")&&d.id===a.id);if(!c)continue;let l=s.find(u=>u.path===a.path&&u.kind==="folder");if(a.deleted&&l){if(s.some(d=>d.path.startsWith(a.path+"/"))||(await cr(l.physical)).some(d=>d!==".forsion-sync-id.json"))continue;await this.operation(e,a.path,o,"delete",null,()=>this.lock(e,l.physical,()=>{st(l.root,ur(l.root,l.physical).split(En).join("/"));let d=nm(l.physical);if(d.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let g=Ie(l.physical,".forsion-sync-id.json"),h=d.length?kn(g):null;h&&fi(g);try{rm(l.physical)}catch(m){if(h)try{sm(g,h,{flag:"wx",mode:384})}catch{}throw m}})),this.tally("deletesLocal"),delete e.stored.folders[c[0]]}else if(!a.deleted&&!l){if(!await this.absent(e,a.path)||i.nodes.some(u=>u.parentId===a.id&&!u.deleted))continue;await this.operation(e,a.path,o,"delete",null,()=>this.json(e,o,`/nodes/${a.id}`,"DELETE",{revision:a.revision,version:null})),a.deleted=!0,delete e.stored.folders[c[0]]}}}async download(e,n,r,s){if(n.size!==void 0&&n.size>_n)throw Error("File exceeds 50 MB content limit");let o=await this.request(e,r,`/nodes/${n.id}/content`),i=[],a=0;if(o.body){let l=o.body.getReader();for(;;){let u=await l.read();if(u.done)break;if(this.guard(e),a+=u.value.length,a>_n)throw await l.cancel(),Error("Content too large");i.push(u.value),s.done=a}}let c=Buffer.concat(i);if(n.hash&&ke(c)!==n.hash)throw Error("Cloud file changed during download");return c}async fileRenames(e,n,r,s){for(let[o,i]of s)for(let a of i.nodes.filter(c=>c.kind==="file"&&!c.deleted&&!c.busy)){let c=e.stored.files[Pe(o,a.id)];if(!c||c.path===a.path)continue;let l=r.find(u=>u.kind==="file"&&u.path===c.path);if(!(!l||this.route(l.path,n)!==o))try{if(this.route(a.path,n)!==o)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,l.path,o,"rename",null,()=>di(e.roots,l.path,a.path,(u,d)=>this.lock(e,u,d))),c.path=a.path}catch(u){this.block(o,l.path,u),this.block(o,a.path,u)}}}async upload(e,n,r,s,o){if(s.length>_n)throw Error("File exceeds 50 MB content limit");this.guard(e);let i=this.host.readCreds(),a=_u.from((async function*(){for(let l=0;l<s.length;l+=64*1024)e.abort.signal.throwIfAborted(),yield s.subarray(l,l+64*1024),o.done=Math.min(s.length,l+64*1024)})()),c=await fetch(i.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(r)}/nodes/${n.id}/content`,{method:"PUT",headers:{Authorization:`Bearer ${i.token}`,"X-Content-Device":this.deviceId,"Content-Type":"application/octet-stream","Content-Length":String(s.length),"X-Content-Version":n.version??"create"},body:a,duplex:"half",signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)])});if(this.guard(e),!c.ok){let l=await c.json().catch(()=>({}));throw Error(l.detail??`content_http_${c.status}`)}return await c.json()}async shadow(e,n,r,s,o,i){let a=Pe(n,r.id),c=ke(s),l=mi(s);l&&s.length>=xu&&await this.keepBase(e,c,s);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[a],delete e.stored.unconfirmed?.[a],e.stored.files[a]={id:r.id,path:r.path,version:r.version,hash:c,...l&&s.length<xu?{base:s.toString("utf8")}:{},...i?{inode:i.inode,stat:i.key,statAt:i.at}:o?{inode:o.inode}:{}}}async seen(e,n,r){let s=Le(e.roots,n),o=await St(Ie(s.root,...s.relative.split("/"))).catch(()=>null);if(!o?.isFile())return;let i=bs(o);return{key:or(i),at:r,inode:i.inode}}sameAsShadow(e,n){return!this.dirty.has(n.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===or(n)&&pm(n)<=e.statAt-fm}unchanged(e,n,r,s,o){let i=Pe(n,r.id);return this.sameAsShadow(s,o)&&s.id===r.id&&s.path===o.path&&!r.busy&&!r.deleted&&r.version===s.version&&r.hash===s.hash&&!e.stored.unconfirmed?.[i]&&!e.stored.pendingUploads?.[i]&&!this.openJobs.has(n+"\0"+o.path)}hold(e,n){if(e.path.endsWith("/"+sr)||n?.stat===or(e))return!1;let r=e.mtime,s=Date.now(),o=this.dirty.get(e.path);if(Math.floor(r)<=this.flushAt)return!1;if(o)o.last=Math.max(o.last,r);else{if(s-r>=bi(e.path))return!1;o={first:Math.min(s,r),last:r},this.dirty.set(e.path,o)}return this.dueAt(e.path,o)>s}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 s=wi(e),o=Ie(s,n);if(await St(o).then(()=>!0,()=>!1))return;await pi(s,{recursive:!0,mode:448});let i=o+".tmp-"+tt();try{await ar(i,r,{mode:384,flag:"wx"}),await vs(i,o)}finally{await lr(i).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await ir(Ie(wi(e),n.hash)).catch(s=>{if(s.code==="ENOENT")return null;throw s});return r&&ke(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(s=>s.hash)),r=wi(e);for(let s of await cr(r).catch(()=>[]))n.has(s)||await lr(Ie(r,s)).catch(()=>{})}async file(e,n,r,s,o){if(r.size>_n){rt("content","skippedTooLarge",1,r.path),await this.operation(e,r.path,s,"upload",r.size,async()=>{throw Error("File exceeds 50 MB content limit")});return}let i=o.nodes.find(b=>b.kind==="file"&&!b.deleted&&b.path===r.path);if(!i){let b=Object.entries(e.stored.files).find(([v,$])=>v.startsWith(s+":")&&$.inode===r.inode&&$.path!==r.path)?.[1];if(b){let v=Le(e.roots,b.path),$=await St(Ie(v.root,v.relative)).then(async O=>bs(O).inode!==r.inode||vt(b.path)!==vt(r.path)?!0:(await cr(Yt(r.physical))).includes(Gt(b.path)),O=>O.code==="ENOENT"?!1:Promise.reject(O)),R=o.nodes.find(O=>O.id===b.id&&!O.deleted);if(!$&&R)try{if(R.path!==b.path)throw Error(`Concurrent file rename: ${r.path}`);let O=vt(r.path),w=O?o.nodes.find(C=>C.path===O&&C.kind==="folder"&&!C.deleted)?.id:"";if(O&&!w)throw Error("Rename parent unavailable");let x=await this.operation(e,r.path,s,"rename",null,()=>this.json(e,s,`/nodes/${R.id}`,"PATCH",{name:Gt(r.path),parentId:w,revision:R.revision}));Object.assign(R,x),b.path=r.path,i=R}catch(O){for(let w of new Set([b.path,R.path,r.path]))this.block(s,w,O);throw O}}}let a=i?e.stored.files[Pe(s,i.id)]:Object.entries(e.stored.files).find(([b,v])=>b.startsWith(s+":")&&v.path===r.path)?.[1];if(!a&&i?.version&&s==="default"&&(a=await this.legacyBaseline(r.path,i)),i&&a&&this.unchanged(e,s,i,a,r))return;if(this.hold(r,a))return"held";let c=Date.now(),l=await vn(r),u=ke(l),d={key:or(r),at:c,inode:r.inode};if(this.guard(e),this.settled(r.path,c),!i){if((a?o.nodes.find(x=>x.id===a.id&&x.deleted):null)&&a&&(a.hash===u||a.memoryDeleted&&yi(r.path)&&u===dr)){yi(r.path)?await this.clearDeletedMemory(e,s,r,a,l,u):(await this.operation(e,r.path,s,"delete",r.size,()=>this.trashFile(e,r,u)),this.tally("deletesLocal"),delete e.stored.files[Pe(s,a.id)]);return}let v=vt(r.path),$=v?o.nodes.find(x=>x.path===v&&!x.deleted&&x.kind==="folder")?.id:"";if(v&&!$)throw Error("Parent folder is unavailable");let R=Object.entries(e.stored.pendingUploads??{}).find(([x,C])=>x.startsWith(s+":")&&C.path===r.path&&!o.nodes.some(D=>D.id===C.id))?.[1];for(let[x,C]of Object.entries(e.stored.pendingUploads??{}))x.startsWith(s+":")&&C.path===r.path&&o.nodes.some(D=>D.id===C.id&&D.deleted)&&delete e.stored.pendingUploads[x];let O=R?.id??tt(),w=Pe(s,O);(e.stored.pendingUploads??={})[w]={id:O,path:r.path},await this.persist(e),i=await this.json(e,s,"/nodes","POST",{id:O,parentId:$,name:Gt(r.path),kind:"file"}),i.id!==O&&delete e.stored.pendingUploads[w],o.nodes.push(i),a=void 0}if(i.busy)return;let g=Pe(s,i.id);if(i.version&&this.awaitingBytes.delete(g),i.hash===u){await this.shadow(e,s,i,l,r,d);return}if(i.hash&&e.stored.unconfirmed?.[g]===i.hash&&(await this.shadow(e,s,i,await this.operation(e,r.path,s,"download",i.size??null,b=>this.download(e,i,s,b)),r),a=e.stored.files[g]),!i.version&&a&&a.hash===u&&!e.stored.pendingUploads?.[g]){let b=this.awaitingBytes.get(g)??Date.now();if(this.awaitingBytes.set(g,b),Date.now()-b<lm)return}if(this.awaitingBytes.delete(g),!i.version||a&&i.version===a.version){(e.stored.unconfirmed??={})[g]=u,await this.persist(e);let b=await this.operation(e,r.path,s,"upload",l.length,v=>this.upload(e,i,s,l,v));Object.assign(i,b),await this.shadow(e,s,i,l,r,d);return}let h=await this.operation(e,r.path,s,"download",i.size??null,b=>this.download(e,i,s,b)),m=h,y=!1;if(!a||a.hash!==u){let b=l.toString("utf8"),v=h.toString("utf8"),$=a?await this.readBase(e,a):null,R=Buffer.from(b).equals(l)&&Buffer.from(v).equals(h)?this.host.contentSync.merge(r.path,b,$,v):null;if(R?(m=Buffer.from(R.content),y=R.conflict):y=!0,y){await this.preserveConflict(e,r.path,l)&&(rt("content","conflicts"),this.tally("conflictCopies"));let O=this.job(e,r.path,s,"merge",l.length);O.state="conflict",O.error="Both versions preserved",O.finishedAt=Date.now()}if(!m.equals(h)){let O=await this.operation(e,r.path,s,"merge",m.length,w=>this.upload(e,i,s,m,w));Object.assign(i,O)}}let p=Date.now();await this.write(e,r.path,m,u),await this.shadow(e,s,i,m,r,await this.seen(e,r.path,p))}async preserveConflict(e,n,r){let s=Le(e.roots,n),o=await Je(s.root,s.relative),i=Gt(n),a=ke(r);for(let c of await cr(Yt(o))){if(c.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==i||!ls(c))continue;let l=vt(n)?vt(n)+"/"+c:c,u=Le(e.roots,l),d=await Je(u.root,u.relative),g=await St(d);if(g.isFile()&&g.size===r.length&&ke(await ir(d))===a)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 s=1;;s++){let o=au(n,r,s),i=Le(e.roots,o);if(!await St(Ie(i.root,...i.relative.split("/"))).then(()=>!0,a=>a.code==="ENOENT"?!1:Promise.reject(a)))return o}}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,s,o){let i=[],a=c=>c.length?Math.max(...c):null;for(let c of n){let l=c.kind==="folder"?Zn(c.path):null;if(!l||os.has(l))continue;let u=`agents/${l}/`,d=this.route(u+"config.toml",r);if(!d||Object.entries(e.stored.files).some(([p,b])=>p.startsWith(d+":")&&b.path.startsWith(u)))continue;let g=(s.get(d)?.nodes??[]).filter(p=>!p.deleted&&p.kind==="file"&&p.version&&p.path.startsWith(u)&&this.route(p.path,r)===d),h=n.filter(p=>p.kind==="file"&&p.path.startsWith(u)&&this.route(p.path,r)===d);if(!g.length||!h.length)continue;let m=new Map(g.map(p=>[p.path,p])),y=h.filter(p=>{let b=m.get(p.path);return!!b&&o.get(p.path)!==b.hash}).length;!y&&h.length===g.length&&h.every(p=>m.has(p.path))||i.push({slug:l,namespace:d,cloudFiles:g.length,localFiles:h.length,differ:y,cloudMtime:a(g.map(p=>p.mtime??0)),localMtime:a(h.map(p=>p.mtime))})}return i}async resolveAsks(e,n,r,s){for(let o of n){try{await this.resolveAsk(e,o,r[o.slug]??"merge",s)}catch(l){throw this.dropShadows(e,o.namespace,`agents/${o.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Me(l)}`)}let i=`agents/${o.slug}`,a=s.rules.find(l=>l.source===i),c=pn(e.stored.config,i,tl(s,i));a&&(c={...c,rules:c.rules.map(l=>l.source===i?{...a,target:l.target}:l)}),e.stored.config=Ot(c,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,s){let o=n.namespace,i=`agents/${n.slug}/`;if(this.dropShadows(e,o,i),r==="local"){await this.archiveAgent(e,o,n.slug),await this.persist(e);return}let a=await this.json(e,o);this.guard(e),hs(a,o);let c=new Map(a.nodes.filter(h=>!h.deleted&&!h.busy&&h.kind==="file"&&h.version&&h.path.startsWith(i)&&this.route(h.path,s)===o).map(h=>[h.path,h])),l=h=>h.endsWith("/"+sr),u=async(h,m,y)=>{let p=Date.now();return await this.write(e,h,m,y),this.seen(e,h,p)};for(let[h,m]of c){if(!l(h))continue;let y=Le(e.roots,h);if(Tu(Ie(y.root,y.relative)))continue;let p=await this.operation(e,h,o,"download",m.size??null,b=>this.download(e,m,o,b));await this.shadow(e,o,m,p,void 0,await u(h,p,null))}let d=(await this.scan(e)).filter(h=>h.kind==="file"&&h.path.startsWith(i)&&this.route(h.path,s)===o&&h.size<=_n).sort((h,m)=>+!l(h.path)-+!l(m.path)),g=await this.removedDir(e,n.slug);for(let h of d){this.guard(e);let m=await vn(h),y=ke(m),p=c.get(h.path),b=h.path.slice(i.length);if(p&&p.hash===y){await this.shadow(e,o,p,m,h);continue}if(r==="cloud"){if(await this.keep(e,`${g}/${b}`,m),p){let w=await this.operation(e,h.path,o,"download",p.size??null,x=>this.download(e,p,o,x));await this.shadow(e,o,p,w,h,await u(h.path,w,y))}else b==="MEMORY.md"?await this.write(e,h.path,Buffer.alloc(0),y):await this.removeLocal(e,h,y);continue}if(!p)continue;let v=await this.operation(e,h.path,o,"download",p.size??null,w=>this.download(e,p,o,w)),$=o==="default"?await this.legacyBaseline(h.path,p):void 0;if($?.hash===y){await this.shadow(e,o,p,v,h,await u(h.path,v,y));continue}let R=$?await this.readBase(e,$):null,O=mi(m)&&mi(v)?this.host.contentSync.merge(h.path,m.toString("utf8"),R,v.toString("utf8")):null;if(O&&!O.conflict){let w=Buffer.from(O.content);w.equals(m)||await this.write(e,h.path,w,y),await this.shadow(e,o,p,v)}else(p.mtime??0)>h.mtime?(await this.keep(e,`${g}/${b}`,m),await this.shadow(e,o,p,v,h,await u(h.path,v,y))):(await this.keep(e,`${g}/${b}`,v),await this.shadow(e,o,p,v))}await this.persist(e)}dropShadows(e,n,r){for(let[s,o]of Object.entries(e.stored.files))s.startsWith(n+":")&&o.path.startsWith(r)&&(delete e.stored.files[s],delete e.stored.unconfirmed?.[s])}async removedDir(e,n,r="agents"){let s=new Date,o=a=>String(a).padStart(2,"0"),i=`${s.getFullYear()}-${o(s.getMonth()+1)}-${o(s.getDate())} ${o(s.getHours())}${o(s.getMinutes())}`;for(let a=1;;a++){let c=`${r}/.removed/${n} ${i}${a>1?` ${a}`:""}`,l=Le(e.roots,c);if(!await St(Ie(l.root,...l.relative.split("/"))).then(()=>!0,u=>u.code==="ENOENT"?!1:Promise.reject(u)))return c}}async keep(e,n,r){this.guard(e),await ui(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(st(n.root,ur(n.root,n.physical).split(En).join("/")),ke(kn(n.physical))!==r)throw Error("Local file changed before replacing");fi(n.physical)})}async archiveAgent(e,n,r){let s=this.host.readCreds();if(!s.token)throw Error("not_signed_in");let o=await fetch(s.cloudUrl.replace(/\/+$/,"")+"/api/remotesync/agent-archive/agent",{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({namespace:n,slug:r,opId:tt(),locale:this.locale()}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)])});this.guard(e);let i=await o.json().catch(()=>({}));if(this.guard(e),!o.ok||i?.state!=="done")throw Error(typeof i?.detail=="string"?i.detail:`agent_archive_http_${o.status}`)}async absent(e,n){this.guard(e);let r=Le(e.roots,n),s=await Je(r.root,r.relative);try{return await St(s),!1}catch(o){if(o.code==="ENOENT")return!0;throw o}}async missing(e,n,r,s,o){let i=e.stored.files[Pe(r,n.id)],a=e.stored.pendingUploads?.[Pe(r,n.id)];if(n.deleted){i&&delete e.stored.files[Pe(r,n.id)],a&&delete e.stored.pendingUploads[Pe(r,n.id)];return}if(n.busy||i?.inode&&this.blocked.has(r)&&s.some(u=>u.kind==="file"&&u.inode===i.inode&&this.isBlocked(r,u.path)&&this.route(u.path,o)===r))return;if(!n.version){a&&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[Pe(r,n.id)],n.deleted=!0);return}if(i&&i.version===n.version){if(!await this.absent(e,n.path))return;await this.operation(e,n.path,r,"delete",n.size??null,()=>this.json(e,r,`/nodes/${n.id}`,"DELETE",{revision:n.revision,version:n.version})),delete e.stored.files[Pe(r,n.id)],n.deleted=!0;return}let c=await this.operation(e,n.path,r,"download",n.size??null,u=>this.download(e,n,r,u)),l=Date.now();await this.write(e,n.path,c,null),await this.shadow(e,r,n,c,void 0,await this.seen(e,n.path,l))}async recoverTrash(e){for(let n of[...e.stored.trash??[]]){if(n.parentId){let l=(await Ss(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);l&&(n.path=l.path+"/"+Gt(n.path))}let r=Le(e.roots,n.path),s=await Je(r.root,r.relative);if(!/^\.forsion-sync-trash-[a-f0-9-]+$/.test(n.stage))throw Error("Invalid sync recovery journal");let o=n.stageRoot??r.root,i=await this.rootIdentity(e,o),a=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(a&&!tn(a,i))throw Error("Sync recovery root changed; journal retained");let c=Ie(o,n.stage);await St(c).then(()=>!0,l=>l.code==="ENOENT"?!1:Promise.reject(l))&&await this.lock(e,s,()=>{if(st(o,n.stage,!0),ke(kn(c))!==n.hash)throw Error("Sync recovery content changed");st(r.root,r.relative),om(Yt(s),{recursive:!0});let l=Tu(s)?s+` (sync recovery ${tt().slice(0,8)})`:s;try{tm(c,l)}catch(u){if(u.code!=="EXDEV")throw u;if(im(c,l,am.COPYFILE_EXCL),ke(kn(l))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}fi(c)},!0),e.stored.trash=e.stored.trash.filter(l=>l!==n)}}async clearDeletedMemory(e,n,r,s,o,i){s.memoryDeleted&&s.hash===dr&&i===dr||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!s.memoryDeleted&&o.length){let l=r.path==="human/MEMORY.md",u=await this.removedDir(e,l?"memory":r.path.split("/")[1],l?"human":"agents");await this.keep(e,`${u}/MEMORY.md`,o)}s.memoryDeleted=!0,await this.persist(e);let a=Date.now();o.length&&await this.write(e,r.path,Buffer.alloc(0),i);let c=await this.seen(e,r.path,a);e.stored.files[Pe(n,s.id)]={...s,hash:dr,base:"",stat:void 0,statAt:void 0,...c?{inode:c.inode,stat:c.key,statAt:c.at}:{}}}),this.tally("deletesLocal"))}async trashFile(e,n,r){this.guard(e);let s=await Je(n.root,ur(n.root,n.physical).split(En).join("/")),o={path:n.path,stage:".forsion-sync-trash-"+tt(),hash:r},i=Ie(n.root,o.stage),a=await this.rootIdentity(e,n.root);o.stageRoot=n.root,o.stageDev=a.dev,o.stageIno=a.ino,o.stageIdentity=a;try{let c=JSON.parse(kn(Ie(Yt(s),".forsion-sync-id.json"),"utf8")).id;/^[a-f0-9-]{36}$/i.test(c)&&(o.parentId=c)}catch{}(e.stored.trash??=[]).push(o),await this.persist(e);try{await this.lock(e,s,()=>{if(st(n.root,ur(n.root,s).split(En).join("/")),ke(kn(s))!==r)throw Error("Local file changed before deletion");em(s,i)}),await this.host.contentSync.trash(i),e.stored.trash=e.stored.trash.filter(c=>c!==o)}catch(c){throw this.host.accountId()===e.account&&!e.abort.signal.aborted&&await this.recoverTrash(e),c}}};function hm(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))Xn.test(n)&&Xc.includes(r)&&(e[n]=r);return e}function Tu(t){try{return Qg(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}Li(va);function QS(t){Sa(t.contentSync?.withWriteLock?.bind(t.contentSync)),Ji(t),no(t),Ru(t),t.log("[forsion-extend] cloud account handlers registered"),Ys(t)?Gs(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Ks(t)?Xs(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),lo(t)?uo(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),Ao(t)?To(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),Ro(t)?Do(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),qo(t)?Fl(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),qo(t)&&su(t)}export{Xa as ACCOUNT_SEAM,Fc as AMADEUS_SEAM,Vs as CONNECT_MAX_FILES,_a as CONNECT_MAX_FILE_BYTES,Ca as CONNECT_MAX_TOTAL_BYTES,jr as DIAGNOSTICS_VAULT,Ma as FORSION_CONNECT_LOCAL_SDK,Gi as PAY_PERIODS,Yi as PAY_TABS,ja as PENZOR_MAX_FILE,Te as SYNC_IPC,Hc as UNIT_SEAM,$n as UPLOAD_MAX_FILE,Yn as UnitCapsReporter,Vn as UnitHost,ze as cloudJson,Aa as collectProjectFiles,Hr as conflictCopyPath,Zf as conflictCopyVariant,Oa as connectMetaOf,Ka as createAccountCloud,Lc as createAmadeusCloud,Nr as createPenzorRemote,zc as createUnitHub,$r as deviceHeader,Js as expectedPartsOf,Ne as forsionAccountId,Cr as forsionRefreshToken,Mn as forsionWhoami,lo as hasAccountHost,Ao as hasAmadeusHost,Ys as hasConnectHost,Ks as hasRemoteSyncHost,Ro as hasUnitHost,Pa as makePreviewProxy,Va as multipartFrame,Ia as readConnectMeta,uo as registerAccount,To as registerAmadeus,QS as registerCloud,Gs as registerConnect,Xs as registerPenzor,no as registerPenzorTransfers,Do as registerUnit,Fr as safeDownloadName,Da as scanSdkUsage,_r as shouldRefreshToken,Zs as speedOf,Uc as streamWorthy,Ec as stripConflictSuffix,Qf as textFingerprint,Is as tokenAgeMs,Bi as tokenRemainingMs,Qs as uploadError,Ra as writeConnectMeta};
|
|
284
|
+
`,{encoding:"utf8",mode:384});try{if(ag(a()).size>Ql){let Y=v(),E=Y.length,T=0;for(;E>0&&T+Buffer.byteLength(JSON.stringify(Y[E-1]))+1<=Ql/2;)T+=Buffer.byteLength(JSON.stringify(Y[--E]))+1;$(a(),Y.slice(E))}}catch{}v().length>=fg&&re()}},Z=()=>{let H=d();return{available:!!l,enabled:H.enabled!==!1,noticeSeen:H.noticeSeen===!0,signedIn:y(),active:p(H),packaged:l?.packaged===!0,installId:m(),queued:ig(a())?v().length:0,lastSentAt:H.lastSentAt??null,lastError:H.lastError??null}},Q=()=>ql({app:"desktop",appVersion:t.appVersion(),coreVersion:l?.coreVersion()??void 0,channel:l?.channel(),os:Eg(process.platform),osVersion:lg(),arch:_g(process.arch),locale:Cg()}),ee=null,re=()=>{if(ee)return ee;if(C||n().getTime()<D)return Promise.resolve();let H=x,Y=R,E=(async()=>{try{for(let T=0;T<5;T++){let _=v();if(!_.length)return;let I=m(),B={v:Hl,installId:I,...Q()},q=[],M=Buffer.byteLength(JSON.stringify({...B,events:[]}));for(let te of _){let de=Buffer.byteLength(JSON.stringify(te))+1;if(q.length>=Ys.maxEvents||M+de>Ys.maxBatchBytes)break;q.push(te),M+=de}if(!q.length){$(a(),_.slice(1));continue}let{base:L}=await t.getCloud(),J={...B,events:q};if(!F()||H!==x)return;let K=await r(`${L.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(J),signal:AbortSignal.timeout(eu)}).catch(te=>({ok:!1,status:0,error:String(te?.message||te)})),X=K.status;if(X>=200&&X<300||X===400||X===413){let te=new Set(q.map(de=>JSON.stringify(de)));$(a(),v().filter(de=>!te.has(JSON.stringify(de))))}if(X>=200&&X<300){let te=n().getTime();Y===R&&$(c(),[...w(),{at:te,body:J}]),h({lastSentAt:te,lastError:void 0});continue}if(X!==400&&X!==413){let te=Number(K.headers?.get?.("retry-after"));D=n().getTime()+(Number.isFinite(te)&&te>0?Math.min(te,3600)*1e3:5*6e4)}h({lastError:X?`HTTP ${X}`:String(K.error??"network error").slice(0,200)});return}}catch(T){try{h({lastError:String(T?.message||T).slice(0,200)})}catch{}}})();return ee=E,E.finally(()=>{ee===E&&(ee=null)}),E},oe=async()=>{try{if(w(),!F())return;let H=d(),Y=x,E=H.cursor??ti(n().getTime()),T=await Sg(o(),E,l?.sessionId,ru(n().getTime()));if(!F()||Y!==x)return;V(T.events),T.cursor!==E&&h({cursor:T.cursor}),await pe(Y),await re()}catch(H){t.log(`[forsion-extend] telemetry tick failed: ${String(H?.message||H)}`)}},pe=async H=>{let Y=n().getTime(),E=an(Y),T=an(Y-tu),_=d().ledgerCursor;if(Wn(_)||(_=T,h({ledgerCursor:_})),xs(_),_>=T){ie();return}let I=await vg(o(),_,E);if(!(!F()||H!==x)){if(I){let B=I.complete?T:I.days[I.days.length-1]?.day??_;if(B>_){let q=$c(_,B),M=[...new Set([...I.days.map(J=>J.day),...q.map(J=>J.day)])].filter(J=>J>_&&J<=B).sort(),L=[];for(let J of M){L.push(...I.days.find(K=>K.day===J)?.events??[]);for(let K of q)if(K.day===J){let X=kg(J,K.system,K.counts);X&&L.push(X)}}V(L),h({ledgerCursor:B}),xs(B)}}ie()}},ie=()=>{if(!Pc())return;let H=g();if(!H)return;let Y=Oc();h({syncHealth:Object.keys(Y).length?Y:void 0},H),Mc()},xe=l?.subscribe(H=>{try{if(!yg.has(H?.event)||!F())return;let Y=qt({...H,sessionId:l.sessionId},cg());Y&&V([Y])}catch(Y){t.log(`[forsion-extend] telemetry event dropped: ${String(Y?.message||Y)}`)}}),ye={ok:!1,error:"untrusted"};t.handle("telemetry:get",H=>t.isTrustedSender(H)?(F(),Z()):ye),t.handle("telemetry:set",(H,Y)=>{if(!t.isTrustedSender(H))return ye;let E=d(),T={};typeof Y?.enabled=="boolean"&&(T.enabled=Y.enabled),Y?.noticeSeen===!0&&(T.noticeSeen=!0);let _={...E,...T};return!p(E)&&p(_)&&(T.cursor=ti(n().getTime()),T.ledgerCursor=u()),p(E)&&!p(_)&&x++,T.enabled===!1&&(T.syncHealth=void 0),h(T),T.enabled===!1&&O(),F(),Z()}),t.handle("telemetry:sent",H=>t.isTrustedSender(H)?{batches:w()}:ye),t.handle("telemetry:delete",async H=>{if(!t.isTrustedSender(H))return ye;C=!0,x++;try{await ee?.catch(()=>{});let Y=m(),{base:E}=await t.getCloud(),_=(await r(`${E.replace(/\/+$/,"")}/api/telemetry/install/${Y}`,{method:"DELETE",signal:AbortSignal.timeout(eu)}).catch(I=>({ok:!1,status:0,error:String(I?.message||I)}))).status;return _>=200&&_<300?(O(),h({installId:Jl(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),Z()):{ok:!1,error:_?`HTTP ${_}`:"network error"}}finally{C=!1}});try{Dc(d().syncHealth),P(),F()}catch(H){t.log(`[forsion-extend] telemetry startup check failed: ${String(H?.message||H)}`)}let Re=t.addFlushHook?.(H=>{if(H!=="blur")try{ie()}catch{}}),$e=setTimeout(()=>void oe(),dg),Ae=setInterval(()=>void oe(),ug);return $e.unref?.(),Ae.unref?.(),t.log(`[forsion-extend] telemetry registered (${l?l.packaged?"packaged":"dev build: never sends":"host has no telemetry seam: never sends"})`),Object.assign(()=>{clearTimeout($e),clearInterval(Ae),xe?.(),Re?.()},{tick:oe,flush:re})}import{readFileSync as kn,lstatSync as em,statSync as tm,renameSync as nm,linkSync as rm,unlinkSync as fi,readdirSync as om,rmdirSync as sm,writeFileSync as im,mkdirSync as am,copyFileSync as cm,constants as lm}from"node:fs";import{readFile as ir,writeFile as ar,mkdir as pi,rename as ko,readdir as cr,lstat as kt,stat as hi,unlink as lr}from"node:fs/promises";import{join as Ie,dirname as Yt,relative as ur,sep as En}from"node:path";import{hostname as gi}from"node:os";import{randomUUID as tt}from"node:crypto";import{isUtf8 as mi}from"node:buffer";import{Readable as _u}from"node:stream";var xg=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],Ag=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],or=".memory-tombstones.json",iu=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),su=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),Tg=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,Ig=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function Rg(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:xg.includes(t)||iu(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&Tg(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var Dg=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),Og=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,Pg=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function lo(t){let e=t.slice(t.lastIndexOf("/")+1);return Og.test(e)||Pg.test(e)}function au(t,e,n=1){let r=t.lastIndexOf("/"),o=r<0?"":t.slice(0,r+1),s=r<0?t:t.slice(r+1),i=s.lastIndexOf("."),a=i>0?s.slice(0,i):s,c=i>0?s.slice(i):"",l=d=>String(d).padStart(2,"0"),u=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}${n>1?` ${n}`:""}`;return`${o}${a} (conflict ${u})${c}`}function ni(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(lo(t))return!1;if(n){let l=t.slice(6);return e==="folder"?su(l):Ag.includes(l)||iu(l)}let o=t.slice(7),s=o.indexOf("/"),i=s<0?o:o.slice(0,s),a=s<0?"":o.slice(s+1);if(!Ig(i)||Dg(i))return!1;if(e==="file")return Rg(a);if(a===""||a==="LOG"||su(a))return!0;let c=a.split("/");return c[0]==="Library"&&c.every(l=>l&&!l.startsWith(".")&&!l.endsWith(".")&&!l.endsWith(" "))}import{isAbsolute as Mg}from"node:path";var et=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),gt=t=>typeof t=="string",oi=t=>gt(t)&&t.length>0,Mt=t=>typeof t=="boolean",Wt=t=>typeof t=="number"&&Number.isFinite(t),bn=t=>Wt(t)&&Number.isSafeInteger(t)&&t>=0,cu=t=>Wt(t)&&Number.isInteger(t)&&t>=0,lu=t=>bn(t)&&t>0,Sn=t=>gt(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),ho=t=>gt(t)&&/^[a-f0-9]{64}$/.test(t),uu=t=>gt(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),fo=(t,e)=>gt(t)&&e.includes(t),be=(t,e)=>t===void 0||e(t),du=(t,e,n)=>e.every(r=>be(t[r],n)),fu=t=>gt(t)&&!t.includes("\0")&&Mg(t);function $t(t,e=!1){try{return Ot(t,e),!0}catch{return!1}}var pu=t=>$t(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,hu=t=>t===""||Sn(t);function po(t,e){let n=t.indexOf(":");return n>0&&Sn(e)&&t.slice(n+1)===e&&uu(t.slice(0,n))}function $g(t,e){return et(e)&&po(t,e.id)&&$t(e.path)&&oi(e.version)&&ho(e.hash)&&du(e,["base","inode","stat"],gt)&&be(e.statAt,Wt)&&be(e.memoryDeleted,Mt)}function Ng(t,e){return et(e)&&po(t,e.localId)&&Sn(e.id)&&$t(e.path)&&lu(e.revision)&&hu(e.parentId)&&pu(e.name)}function jg(t){return et(t)&&Sn(t.id)&&$t(t.path)&&uu(t.target)&&fo(t.direction,["upload","download","merge","rename","delete"])&&fo(t.state,["queued","active","done","failed","paused","conflict"])&&bn(t.done)&&(t.size===null||bn(t.size))&&Wt(t.at)&&be(t.error,gt)&&be(t.finishedAt,Wt)}function Fg(t){return et(t)&&$t(t.path)&&ho(t.hash)&>(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&be(t.parentId,Sn)&&be(t.stageRoot,fu)&&be(t.stageIdentity,Ht)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&cu(t.stageDev)&&cu(t.stageIno))}function Lg(t){return et(t)&&$t(t.prefix,!0)&&fu(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Ht(t))}function Ug(t){return et(t)&&fo(t.state,["running","done"])&&Mt(t.seen)&&du(t,["name","folderId","shelfId","shelfName"],gt)&&be(t.files,bn)&&be(t.at,Wt)&&be(t.rewritten,Mt)}var uo=(t,e)=>et(t)&&Object.entries(t).every(([n,r])=>e(n,r)),ri=(t,e)=>Array.isArray(t)&&t.every(e);function gu(t){if(!et(t)||!et(t.config)||!bn(t.config.revision)||!Mt(t.owned)||!Mt(t.paused)||!uo(t.files,$g)||!uo(t.folders,Ng)||!ri(t.jobs,jg)||!be(t.accountReview,Mt)||!be(t.agentArchive,Ug)||!be(t.roots,e=>ri(e,Lg))||!be(t.trash,e=>ri(e,Fg))||!be(t.unconfirmed,e=>uo(e,(n,r)=>po(n,n.slice(-36))&&ho(r)))||!be(t.pendingUploads,e=>uo(e,(n,r)=>et(r)&&po(n,r.id)&&$t(r.path))))throw Error("Invalid content sync state; original data was retained");Pt(t.config,t.config.revision)}function Hg(t){return et(t)&&Sn(t.id)&&hu(t.parentId)&&pu(t.name)&&$t(t.path)&&fo(t.kind,["file","folder"])&&lu(t.revision)&&Mt(t.deleted)&&be(t.busy,Mt)&&be(t.version,oi)&&be(t.hash,ho)&&be(t.size,bn)&&be(t.mtime,Wt)&&t.version===void 0==(t.hash===void 0)}function go(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!et(t)||t.schemaVersion!==1||t.namespace!==e||!oi(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,o=new Set;for(let s of t.nodes){if(!Hg(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 i=s.parentId?r.get(s.parentId):void 0;if(s.parentId&&(!i||i.kind!=="folder"||i.deleted&&!s.deleted)||s.path!==(i?i.path+"/"+s.name:s.name))throw n()}}import{constants as mu,lstatSync as Vt,readdirSync as zg,readFileSync as Bg,renameSync as mo,unlinkSync as qg,linkSync as Wg,mkdirSync as wo,realpathSync as si,rmdirSync as Vg}from"node:fs";import{open as yu,lstat as ii,readdir as Yg,realpath as wu,readFile as ai,writeFile as Gg,mkdir as bu,unlink as Jg}from"node:fs/promises";import{join as Nt,dirname as yo,relative as ci,sep as bo}from"node:path";import{randomUUID as Su,createHash as Kg}from"node:crypto";var sr=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,So=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),vu=".forsion-sync-id.json",Xg=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),Zg=t=>!Xg.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),ke=t=>Kg("sha256").update(t).digest("hex");function ku(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 Je(t,e,n=!1){if(n){if(e.split("/").some(a=>a===".."||a==="."||!a)||e.startsWith("/")||e.includes("\\"))throw Error("Invalid internal content path")}else Ot(e,!0);ku(e);let r=await wu(t),o=Nt(r,...e.split("/").filter(Boolean)),s=ci(r,o);if(s===".."||s.startsWith(".."+bo))throw Error("Content path escapes root");let i=r;for(let a of s.split(bo).filter(Boolean)){i=Nt(i,a);try{if((await ii(i)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(c){if(c.code!=="ENOENT")throw c}}return o}function st(t,e,n=!1){if(n||Ot(e,!0),ku(e),e.split("/").some(s=>s===".."||s===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let o=si(t);for(let s of e.split("/").filter(Boolean)){o=Nt(o,s);try{if(Vt(o).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(i){if(i.code!=="ENOENT")throw i}}return o}async function vo(t){let e=new Map,n=t.filter(o=>o.prefix).map(o=>o.prefix),r=[];for(let o of t)try{r.push({...o,root:await wu(o.root)})}catch(s){if(s.code!=="ENOENT")throw s}if(new Set(r.map(o=>o.root)).size!==r.length)throw Error("Managed roots refer to the same directory; choose a separate vault folder");for(let o of r){let s=o.root;if(!(await ii(s)).isDirectory())throw Error(`Sync root is not a directory: ${o.prefix||"Forsion"}`);let i=async(a,c)=>{let l=await ii(a);if(!l.isSymbolicLink()&&!(a!==s&&r.some(u=>u!==o&&u.root===a))&&!(c&&o.prefix===""&&n.some(u=>c===u||c.startsWith(u+"/")))){if(c){Ot(c);let u;if(l.isDirectory())try{let d=JSON.parse(await ai(Nt(a,vu),"utf8"));/^[a-f0-9-]{36}$/i.test(d.id)&&(u=d.id)}catch(d){if(d.code!=="ENOENT"&&!(d instanceof SyntaxError))throw d}e.set(c,{path:c,physical:a,root:s,kind:l.isDirectory()?"folder":"file",localId:u,...So(l),size:l.isFile()?l.size:0})}if(l.isDirectory())for(let u of await Yg(a,{withFileTypes:!0}))!Zg(u.name)||!u.isDirectory()&&!u.isFile()||await i(Nt(a,u.name),c?`${c}/${u.name}`:u.name)}};await i(s,o.prefix)}return[...e.values()].sort((o,s)=>o.path.split("/").length-s.path.split("/").length||o.path.localeCompare(s.path))}async function li(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await Je(t.root,ci(t.root,Nt(t.physical,vu)).split(bo).join("/"),!0),n=Su();try{let r=await yu(e,"wx",384);try{await r.writeFile(JSON.stringify({version:1,id:n})+`
|
|
285
|
+
`)}finally{await r.close()}return t.localId=n,n}catch(r){if(r.code!=="EEXIST")throw r;let o=JSON.parse(await ai(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 vn(t){let e=await Je(t.root,ci(t.root,t.physical).split(bo).join("/")),n=await yu(e,mu.O_RDONLY|(mu.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 Le(t,e){Ot(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 ui(t,e,n,r,o=async(s,i)=>i()){let s=Le(t,e);await bu(s.root,{recursive:!0});let i=await Je(s.root,s.relative),a=await ai(i).catch(l=>{if(l.code==="ENOENT")return null;throw l});if((a?ke(a):null)!==r)throw Error("Local file changed during download");let c=Nt(s.root,`.forsion-sync-${Su()}.tmp`);try{await Gg(c,n,{flag:"wx",mode:384}),await Je(s.root,s.relative),await o(i,()=>{st(s.root,s.relative),wo(yo(i),{recursive:!0}),st(s.root,s.relative);let l=null;try{l=Bg(i)}catch(u){if(u.code!=="ENOENT")throw u}if((l?ke(l):null)!==r)throw Error("Local file changed during download");mo(c,i)})}finally{await Jg(c).catch(()=>{})}}async function Eu(t,e,n=async(r,o)=>o()){let r=Le(t,e);await bu(r.root,{recursive:!0});let o=await Je(r.root,r.relative);await n([o],()=>{st(r.root,r.relative),wo(o,{recursive:!0})})}async function di(t,e,n,r=async(o,s)=>s()){let o=Le(t,e),s=Le(t,n);if(o.root!==s.root)throw Error("Folder move crosses a managed source");let i=await Je(o.root,o.relative),a=await Je(s.root,s.relative);await r([i,a],()=>{if(st(o.root,o.relative),st(s.root,s.relative),Qg(a)){let l=Vt(i),u=Vt(a),d=si(yo(i));if((l.dev===u.dev&&l.ino===u.ino&&d===si(yo(a))?zg(d).filter(m=>{let y=Vt(Nt(d,m));return y.dev===l.dev&&y.ino===l.ino}):[]).length!==1)throw Error("Local rename destination exists");mo(i,a);return}wo(yo(a),{recursive:!0});let c=Vt(i);if(c.isDirectory()){if(process.platform==="win32"){mo(i,a);return}wo(a,{mode:448});try{mo(i,a)}catch(l){try{Vg(a)}catch{}throw l}}else{Wg(i,a);let l=Vt(i);if(l.ino!==c.ino||l.dev!==c.dev)throw Error("Source changed during rename");qg(i)}})}function Qg(t){try{return Vt(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Cu=(t,e)=>t.length===e.length&&t.every(n=>e.some(r=>n.prefix===r.prefix&&n.root===r.root&&(n.dev===void 0||tn(n,r)))),um=()=>({config:structuredClone(Zc),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),_n=50*1024*1024,dm=10*6e4,xu=1024*1024,Pe=(t,e)=>`${t}:${e}`,Et=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",Gt=t=>t.slice(t.lastIndexOf("/")+1),dr=ke(""),yi=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),jt=t=>t.split("/").length,Me=t=>t instanceof Error?t.message:String(t),fm={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},wi=t=>t.file.replace(/\.json$/,".bases"),Iu=5e3,pm=3e4,Au=3e4,hm=3e3,fr=10*6e4,bi=t=>/^(agents|human)\//.test(t)?pm:Iu,gm=t=>Math.max(t.mtime,t.ctime);function Ru(t){if(!t.contentSync)return;let e=new Si(t);for(let[n,r]of Object.entries({[dt.get]:o=>e.snapshot(o),[dt.preview]:o=>e.preview(o),[dt.apply]:(o,s)=>e.apply(typeof o=="string"?o:"",s),[dt.run]:()=>e.kick(),[dt.pause]:o=>e.pause(o===!0),[dt.retry]:()=>e.kick(),[dt.rename]:o=>e.rename(o),[dt.setup]:o=>e.setup(o),[dt.archiveSeen]:()=>e.archiveSeen()}))t.handle(n,async(o,...s)=>{if(!t.isTrustedSender(o))return{ok:!1,error:"untrusted"};try{return{ok:!0,value:await r(...s)}}catch(i){return{ok:!1,error:Me(i)}}});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)),ul(()=>e.stats()),e.start()}var Si=class{session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;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 Qn;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=qr((e,n,r)=>ot("content",e,n,r));httpStatus=0;closed=!1;runFinished=Promise.resolve();archiving=null;archiveRetry={account:"",at:0};resolving=!1;awaitingBytes=new Map;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=Ga(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{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()+fr}};return this.archiving??=(async()=>{try{let r=this.host.readCreds();if(!r.token)return;let o=await fetch(r.cloudUrl.replace(/\/+$/,"")+"/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()}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(6e4)])});if(this.guard(e),!o.ok){n();return}let s=await o.json();if(this.guard(e),s.state!=="done"&&s.state!=="running"){n();return}let i=e.stored.agentArchive,a=s.archive;i?.rewritten||this.turnAgentsOff(e);let c={rewritten:!0,seen:i?.seen??!1,state:s.state};s.state==="done"&&(a?.folderId?Object.assign(c,{folderId:a.folderId,name:a.name??void 0,shelfId:a.shelfId??void 0,shelfName:a.shelfName??void 0,files:a.files??0,at:a.at??Date.now()}):c.seen=!0),e.stored.agentArchive=c,await this.persist(e)}catch(r){if(Me(r)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${Me(r)}`)}finally{this.archiving=null}})()}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=il(n);if(!r)return;e.stored.config=Pt(r,n.revision+1);let o=s=>s==="agents"||s.startsWith("agents/");for(let[s,i]of Object.entries(e.stored.files))o(i.path)&&(delete e.stored.files[s],delete e.stored.unconfirmed?.[s]);for(let[s,i]of Object.entries(e.stored.folders))o(i.path)&&delete e.stored.folders[s];for(let[s,i]of Object.entries(e.stored.pendingUploads??{}))o(i.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=jn(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(ls(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 pi(Yt(e.file),{recursive:!0,mode:448});let o=e.file+".tmp-"+tt();try{await ar(o,r,{mode:384,flag:"wx"}),this.guard(e,!1),await ko(o,e.file),e.persisted=r}finally{await lr(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 ls(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=Ie(this.host.homeDir(),"content-sync"),o=Ie(r,ke(e)+".json"),s=um();try{let d=JSON.parse(await ir(o,"utf8"));gu(d),s={...s,...d,config:Pt(d.config,d.config.revision)},s.jobs=Array.isArray(d.jobs)?d.jobs.slice(-200):[]}catch(d){if(d.code!=="ENOENT")throw Error("Invalid content sync state; original data was retained")}let i,a=Ie(this.host.homeDir(),"content-sync-device.json"),c=async()=>{let d=JSON.parse(await ir(a,"utf8"));if(typeof d?.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(d.id))throw Error("Invalid device sync ID");return d};try{i=await c()}catch(d){if(d.code!=="ENOENT")throw d;i={id:tt()},await pi(Yt(a),{recursive:!0});try{await ar(a,JSON.stringify(i),{flag:"wx",mode:384})}catch(g){if(g.code!=="EEXIST")throw g;i=await c()}}if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=i.id,this.customName=typeof i.name=="string"?i.name:"";let l=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:l,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map};return this.session=u,await this.bindAccount(u),await this.recoverTrash(u),this.guard(u),s.owned&&await this.accountWrite(u,d=>this.host.contentSync.claim(!0,d)),this.setSources(await this.scan(u,l).catch(d=>(this.error=Me(d),[]))),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=Yt(e.file),r=as(this.host.homeDir()),o=ke(e.account),s=jn(r),i=!s?.account&&(await cr(n).catch(c=>{if(c.code==="ENOENT")return[];throw c})).some(c=>/^[a-f0-9]{64}\.json$/.test(c)&&c!==o+".json"),a=s?.pending&&(e.stored.owned||e.stored.config.revision>0);if((s?.account&&s.account!==o||i||a)&&(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 c=jn(r);if(c?.account!==s?.account||c?.epoch!==s?.epoch||c?.pending!==s?.pending)throw Error("account_changed");cs(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 hi(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!s.isDirectory()||!ct(r,s))throw Error("Sync root changed; preview before rebinding");return r}let o=await Pn(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 o of e.stored.roots??[]){let s=n.find(a=>a.prefix===o.prefix);if(!s||s.root!==o.root)throw Error("content_roots_changed_preview_required");let i=await this.rootIdentity(e,o.root);if(o.dev!==void 0&&!tn(o,i))throw Error("Sync root changed; preview before rebinding");if(o.dev!==void 0&&o.dev!==i.dev){let a=String(o.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(a)&&Le(n,c.path).root===o.root&&(c.inode=String(i.dev)+":"+c.inode.slice(a.length),delete c.stat,delete c.statAt)}JSON.stringify(o)!==JSON.stringify({...o,...i})&&(Object.assign(o,i),r=!0)}return r&&await this.persist(e),vo(n)}async write(e,n,r,o){this.guard(e),await ui(e.roots,n,r,o,(s,i)=>this.lock(e,s,i)),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 hi(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[i,a]of e.rootIdentities){let c;try{c=tm(i)}catch{throw Error("Sync root unavailable: "+i)}if(!c.isDirectory()||!ct(a,c))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 kt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return vo(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Ho(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(o){let i=this.dirty.get(o);i?i.last=s:this.dirty.set(o,{first:s,last:s})}this.schedule(o?void 0:s+Iu)}))}logical(e,n){let r=null;for(let i of e.roots)(n===i.root||n.startsWith(i.root+En))&&(!r||i.root.length>r.root.length)&&(r=i);if(!r)return null;let o=ur(r.root,n).split(En).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+bi(e),n.first+Au)}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()}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()),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,i,a){this.guard(e);let c=this.host.readCreds();if(!c.token)throw Error("not_signed_in");let l=c.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(n)}${r}`,u={Authorization:`Bearer ${c.token}`,"X-Content-Device":this.deviceId,...a},d;if(s instanceof Buffer){u["Content-Type"]="application/octet-stream",u["Content-Length"]=String(s.length);let m=async function*(){for(let y=0;y<s.length;y+=64*1024)e.abort.signal.throwIfAborted(),yield s.subarray(y,y+64*1024),i?.(Math.min(s.length,y+64*1024))};d=_u.from(m())}else s!==void 0&&(u["Content-Type"]="application/json",d=JSON.stringify(s));let g={method:o,headers:u,body:d,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...s instanceof Buffer?{duplex:"half"}:{}},h=await fetch(l,g);if(this.guard(e),!h.ok&&!(h.status===304&&a?.["If-None-Match"])){this.httpStatus=h.status;let m=await h.json().catch(()=>({}));throw Object.assign(new Error(typeof m.detail=="string"?m.detail:`content_http_${h.status}`),{status:h.status})}return o==="DELETE"&&this.tally("deletesSent"),h}async json(e,n,r="",o="GET",s){let i=await(await this.request(e,n,r,o,s)).json();return this.guard(e),i}async manifests(e,n){let r=new Map;for(let s of new Set(n.rules.filter(i=>i.target!=="off").map(i=>i.target))){let i=JSON.parse(await this.manifestText(e,s));go(i,s),r.set(s,i)}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(i=>!i.deleted&&i.kind==="file").map(i=>/^agents\/([^/]+)\/config\.toml$/.exec(i.path)?.[1]).filter(i=>!!i&&Xn.test(i))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),o=r&&Date.now()-r.at<fr?r:void 0,s=await this.request(e,n,"","GET",void 0,void 0,o?{"If-None-Match":o.etag}:void 0);if(s.status===304)return await s.body?.cancel(),o?o.text:(e.manifests.delete(n),this.manifestText(e,n));let i=await s.text();this.guard(e),go(JSON.parse(i),n);let a=s.headers.get("etag");return a?e.manifests.set(n,{etag:a,text:i,at:Date.now()}):e.manifests.delete(n),i}route(e,n,r="file"){if(lo(e)||ni(e,r)===!1)return null;let o=dn(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||oo(gi())}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"){Qc.some(i=>s.path.startsWith(i+"/"))||(r.files++,r.size+=s.size);for(let i=Et(s.path);i;i=Et(i)){let a=n.get(i);a&&(a.size+=s.size,a.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],[i])=>jt(s)-jt(i)||(s<i?-1:1)).slice(0,2e3).map(([s,i])=>({path:s,kind:"folder",size:i.size,files:i.files,...Zn(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,...el((await vn(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||oo(gi()),s=Fs(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=Ie(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+tt();try{await ar(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await ko(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<fr){r-this.devicesAt>=fr&&await this.refreshDevices(e);return}let o=(a,c)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:a,...c?{unique:!0}:{}}),s=async()=>(await this.json(e,"devices")).devices,i=a=>/device_name_(taken|reserved|invalid)/.test(Me(a));try{await o(this.deviceName(),!0)}catch(a){if(!i(a))throw a;let c=!1;if(!this.customName){let l=oo(gi());for(let u=0;u<5&&!c;u++){let d=await s(),g=null;for(let h=2;h<100&&!g;h++){let m=`${l} ${h}`;Fs(m,d,this.deviceId)||(g=m)}if(!g)break;try{await o(g,!0),await this.saveName(g),c=!0}catch(h){if(!i(h))throw h}}}c||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=Ie(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let a=JSON.parse(await ir(e,"utf8"));Array.isArray(a?.devices)&&(n=a.devices)}catch{}let r=new Map(n.filter(a=>a&&typeof a.id=="string").map(a=>[a.id,a])),o=this.devices.map(a=>{let c=r.get(a.id),l=[...Array.isArray(c?.aliases)?c.aliases:[],...c&&typeof c.name=="string"&&c.name!==a.name?[c.name]:[]],u=l.filter((d,g)=>typeof d=="string"&&d!==a.name&&l.lastIndexOf(d)===g).slice(-5);return{id:a.id,name:a.name,...u.length?{aliases:u}:{}}}),s=JSON.stringify({devices:o});if(s===this.cachedDevices)return;let i=e+".tmp-"+tt();try{await ar(i,s,{mode:384,flag:"wx"}),await ko(i,e),this.cachedDevices=s}catch(a){this.error=Me(a)}finally{await lr(i).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=pn(ol(n.stored.config),"","off");for(let a of St)a.id!=="agents"&&r[a.id]===!1&&(o=pn(o,a.path,"off"));let s=new Set(this.sources.filter(a=>a.agent).map(a=>a.path.slice(7))),i=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(a=>typeof a=="string"&&s.has(a)):[];return this.preview(sl(o,i))}async snapshot(e){(e==="zh"||e==="en")&&(this.uiLocale=e);let n=await this.getSession();return!n.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(n).then(r=>{this.session===n&&this.setSources(r)},()=>{})),Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(n).catch(()=>{})),{available:!0,account:ke(n.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(n.stored.config),running:this.running,paused:n.stored.paused,phase:this.phase,jobs:structuredClone(n.stored.jobs),devices:this.devices,sources:this.sources.map(r=>{let o=r.agent&&this.agentNames.get(r.path);return o?{...r,...o.name?{name:o.name}:{},...o.nameEn?{nameEn:o.nameEn}:{}}:r}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...n.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...n.stored.agentArchive?{agentArchive:(({rewritten:r,...o})=>o)(n.stored.agentArchive)}:{}}}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 Qn().snapshot();for(let i of r?.jobs??[])o[i.state]=(o[i.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(i=>({source:i.source,target:i.target})),backlog:r?{jobs:o,blocked:[...this.blocked.values()].reduce((i,a)=>i+a.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=Pt(e,n.stored.config.revision+1),s=await this.host.contentSync.roots();this.guard(n);let i=await this.previewScan(n,s),a=this.effective(o,i);if(n.stored.agentArchive?.state==="running"&&i.some(b=>b.kind==="file"&&b.path.startsWith("agents/")&&this.route(b.path,a)))throw Error("agent_archive_running");let c=await this.manifests(n,a);this.guard(n),this.setSources(i);let l=0,u=0,d=0,g=0,h=new Map;for(let b of i.filter(v=>v.kind==="file")){let v=this.route(b.path,a);if(!v)continue;let $=c.get(v)?.nodes.find(O=>!O.deleted&&O.kind==="file"&&O.path===b.path);if(b.size>_n){l++,g+=b.size;continue}let R=ke(await vn(b));this.guard(n),h.set(b.path,R),R!==$?.hash&&(l++,g+=b.size,$?.version&&d++)}let m=o.enabled?this.agentAsks(n,i,a,c,h):[];for(let[b,v]of c)for(let $ of v.nodes)!$.deleted&&$.kind==="file"&&$.version&&this.route($.path,a)===b&&!i.some(R=>R.path===$.path)&&u++;let y=this.signature(i,c,s),p={token:tt(),config:a,upload:o.enabled?l:0,download:o.enabled?u:0,conflicts:o.enabled?d:0,bytes:o.enabled?g:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,...m.length?{agentAsks:m}:{}};return this.previewValue={value:p,account:n.account,signature:y},p}signature(e,n,r){return ke(JSON.stringify([r,e.map(o=>[o.path,o.size,o.mtime,o.inode]),[...n].map(([o,s])=>[o,s.nodes.map(i=>[i.id,i.revision,i.version,i.deleted])])]))}async apply(e,n){let r=this.serial,o;this.serial=new Promise(s=>{o=s}),await r;try{let s=await this.getSession(),i=this.previewValue;if(!i||i.value.token!==e||i.account!==s.account||i.value.expiresAt<Date.now()||i.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let a=i.value.agentAsks??[],c=mm(n);this.resolving=!0;try{let l=await this.host.contentSync.roots(),u=await this.previewScan(s,l),d=await this.manifests(s,i.value.config);if(this.signature(u,d,l)!==i.signature)throw Error("preview_changed");let g=[];for(let p of l)await hi(p.root).catch(v=>{if(v.code==="ENOENT")return null;throw v})&&g.push({...p,...await Pn(p.root)});let h=structuredClone(i.value.config);for(let p of h.rules){let b=u.find(v=>v.kind==="folder"&&v.path===p.source);b&&(p.sourceId=await li(b))}let m=a.length?Pt(a.reduce((p,b)=>pn(p,`agents/${b.slug}`,"off"),h),h.revision):h;if(this.guard(s),this.previewValue!==i||i.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[p,b]of Object.entries(s.stored.files))(y.config.enabled!==s.stored.config.enabled||!Cu(y.roots??g,g)||this.route(b.path,y.config)!==this.route(b.path,s.stored.config))&&delete s.stored.files[p];for(let[p,b]of Object.entries(s.stored.folders))(y.config.enabled!==s.stored.config.enabled||!Cu(y.roots??g,g)||this.route(b.path,y.config,"folder")!==this.route(b.path,s.stored.config,"folder"))&&delete s.stored.folders[p];s.stored.roots=g,s.rootIdentities=new Map(g.map(p=>[p.root,p])),await this.persist(s);try{await this.accountWrite(s,p=>this.host.contentSync.claim(!0,p))}catch(p){throw s.stored=y,await this.persist(s),await this.accountWrite(s,b=>this.host.contentSync.claim(y.owned,b)).catch(()=>{}),p}if(this.previewValue=null,s.roots=l,await this.watchRoots(s),a.length)try{await this.resolveAsks(s,a,c,h)}catch(p){throw this.fault(Me(p)),p}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 i=e.stored.jobs.findLast(c=>c.path===n&&c.target===r&&c.direction===o&&["failed","paused","queued"].includes(c.state));if(i)return Object.assign(i,{state:"active",done:0,size:s,at:Date.now(),error:void 0,finishedAt:void 0}),i;let a={id:tt(),path:n,target:r,direction:o,state:"active",done:0,size:s,at:Date.now()};return e.stored.jobs.push(a),e.stored.jobs=e.stored.jobs.slice(-200),a}done(e){e.state="done",e.done=e.size??e.done,e.finishedAt=Date.now()}async operation(e,n,r,o,s,i){if(this.guard(e),e.stored.paused)throw Error("paused");let a=this.job(e,n,r,o,s);try{let c=await i(a);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(a),o==="upload"?ot("content","uploads"):o==="download"&&ot("content","downloads");let l=fm[o];return l&&this.tally(l),c}catch(c){throw a.state=e.stored.paused?"paused":"failed",a.error=Me(c),a.finishedAt=Date.now(),c}}async run(){if(this.running||this.closed||this.resolving)return;this.running=!0;let e;this.runFinished=new Promise(a=>{e=a});let n=Date.now();this.wroteLocal=!1;let r=new Set,o,s=!1,i=!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 a=await this.host.contentSync.roots();this.guard(o),o.roots=a,await this.host.contentSync.agentFiles?.prepare().catch(p=>{this.error=Me(p)}),this.guard(o);let c=await this.scan(o,a);await this.recordRoots(o);let l=this.effective(o.stored.config,c),u=await this.manifests(o,l);this.guard(o),await this.register(o),this.openJobs=new Set(o.stored.jobs.filter(p=>["failed","paused","active"].includes(p.state)&&["upload","download","merge"].includes(p.direction)).map(p=>p.target+"\0"+p.path)),await this.folders(o,l,c,u),await this.recordRoots(o),await this.fileRenames(o,l,c,u),c=await this.scan(o,a),l=this.effective(l,c),o.stored.config=l,this.setSources(c),this.phase="syncing";let d=p=>p.endsWith("/"+or),g=new Set,h=new Set,m=p=>p.startsWith("agents/")?p.slice(0,p.lastIndexOf("/")+1):null,y=p=>p.endsWith("/MEMORY.md")&&h.has(m(p)??"");for(let[p,b]of u)for(let v of b.nodes.filter($=>$.kind==="file"&&!$.busy&&d($.path))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.route(v.path,l)!==p||c.some($=>$.path===v.path))){if(this.isBlocked(p,v.path)){h.add(m(v.path)??"");continue}g.add(v.id);try{await this.missing(o,v,p,c,l)}catch($){this.error=Me($),h.add(m(v.path)??"")}}}for(let p of c.filter(b=>b.kind==="file").sort((b,v)=>+!d(b.path)-+!d(v.path))){if(this.guard(o),o.stored.paused)throw Error("paused");let b=this.route(p.path,l);if(!(!b||y(p.path))){if(this.isBlocked(b,p.path)){d(p.path)&&h.add(m(p.path)??"");continue}try{await this.file(o,l,p,b,u.get(b))==="held"&&r.add(p.path)}catch(v){this.error=Me(v),d(p.path)&&h.add(m(p.path)??"")}}}for(let[p,b]of u)for(let v of b.nodes.filter($=>$.kind==="file"&&!$.busy&&!g.has($.id))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.isBlocked(p,v.path)||this.route(v.path,l)!==p||c.some($=>$.path===v.path)||y(v.path))){if(this.holdGone(v.path)){r.add(v.path);continue}try{await this.missing(o,v,p,c,l)}catch($){this.error=Me($)}}}await this.cleanupFolders(o,l,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(o).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=fr)&&(await this.accountWrite(o,p=>this.host.contentSync.changed(p)),this.changedAt=Date.now()),this.guard(o),await this.persist(o),await this.pruneBases(o),i=!0}catch(a){this.error=Me(a)}finally{this.phase=o?.stored.paused?"paused":"idle",s&&(this.noteHealth(n,i),this.live()&&this.runLog.end(i));for(let[a,c]of this.dirty)!r.has(a)&&c.last<n&&this.dirty.delete(a);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&&(ot("content","cycles"),ot("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?Br(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<bi(e)&&r-n.first<Au}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=Me(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(Me(r),[n])}async folders(e,n,r,o){let s=r.filter(a=>a.kind==="folder"),i=new Map;for(let a of s)if(a.localId){if(i.has(a.localId))throw Error(`Duplicate folder sync identity: ${a.path}`);i.set(a.localId,a.path)}for(let[a,c]of o){for(let l of c.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,d)=>jt(u.path)-jt(d.path)))if(!this.isBlocked(a,l.path))try{let u=Object.entries(e.stored.folders).find(([g,h])=>g.startsWith(a+":")&&h.id===l.id)?.[1],d=(u?s.find(g=>g.localId===u.localId):null)??s.find(g=>g.path===l.path);if(u&&d&&l.path!==u.path&&d.path!==u.path&&l.path!==d.path)throw Error(`Concurrent folder rename: ${d.path}`);if(u&&d&&l.path!==u.path&&d.path===u.path){if(this.route(d.path,n,"folder")!==a)continue;if(this.route(l.path,n,"folder")!==a)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,d.path,a,"rename",null,()=>di(e.roots,d.path,l.path,(h,m)=>this.lock(e,h,m)));let g=d.path;for(let h of r)if(h.path===g||h.path.startsWith(g+"/")){let m=h.path;h.path=l.path+m.slice(g.length);let y=Le(e.roots,h.path);h.physical=Ie(y.root,y.relative)}for(let[h,m]of Object.entries(e.stored.files))h.startsWith(a+":")&&m.path.startsWith(u.path+"/")&&(m.path=l.path+m.path.slice(u.path.length));for(let h of n.rules)(h.source===u.path||h.source.startsWith(u.path+"/"))&&(h.source=l.path+h.source.slice(u.path.length))}if(!d&&this.route(l.path,n,"folder")===a&&!u){await Eu(e.roots,l.path,(h,m)=>this.lock(e,h,m));let g=(await this.scan(e)).find(h=>h.path===l.path);g&&(r.push(g),s.push(g))}}catch(u){this.block(a,l.path,u),this.tally("folderConflicts");let d=Object.entries(e.stored.folders).find(([g,h])=>g.startsWith(a+":")&&h.id===l.id)?.[1];d&&this.block(a,d.path,u)}for(let l of s.sort((u,d)=>jt(u.path)-jt(d.path)))if(!this.isBlocked(a,l.path))try{let u=this.route(l.path,n,"folder"),d=n.rules.some(b=>b.target===a&&b.source.startsWith(l.path+"/"));if(u!==a&&!d||ni(l.path,"folder")===!1)continue;let g=await li(l),h=e.stored.folders[Pe(a,g)],m=h?c.nodes.find(b=>b.id===h.id):c.nodes.find(b=>b.path===l.path&&!b.deleted);if(m?.deleted){if(h){let b=!1;for(let v of r.filter($=>$.kind==="file"&&$.path.startsWith(l.path+"/")&&this.route($.path,n)===a)){let $=Object.entries(e.stored.files).find(([R,O])=>R.startsWith(a+":")&&O.path===v.path)?.[1];if(!$){b=!0;break}if(!this.sameAsShadow($,v)){let R=ke(await vn(v));if(R!==$.hash&&!($.memoryDeleted&&yi(v.path)&&R===dr)){b=!0;break}}}if(!b)continue}m=void 0}let y=Et(l.path),p=y?c.nodes.find(b=>b.path===y&&b.kind==="folder"&&!b.deleted)?.id:"";if(y&&!p)throw Error("Cloud parent is unavailable");if(!m)m=await this.json(e,a,"/nodes","POST",{id:h?tt():g,parentId:p,name:Gt(l.path),kind:"folder"}),c.nodes.push(m);else if(h&&m.path!==l.path){if(m.revision!==h.revision)throw Error(`Concurrent folder rename: ${l.path}`);let b=m.path,v=await this.operation(e,l.path,a,"rename",null,()=>this.json(e,a,`/nodes/${m.id}`,"PATCH",{parentId:p,name:Gt(l.path),revision:m.revision}));for(let $ of c.nodes)$.path.startsWith(b+"/")&&($.path=l.path+$.path.slice(b.length));Object.assign(m,v);for(let[$,R]of Object.entries(e.stored.files))$.startsWith(a+":")&&R.path.startsWith(b+"/")&&(R.path=l.path+R.path.slice(b.length))}e.stored.folders[Pe(a,g)]={id:m.id,localId:g,path:l.path,revision:m.revision,parentId:m.parentId,name:m.name}}catch(u){this.block(a,l.path,u);let d=l.localId?e.stored.folders[Pe(a,l.localId)]:void 0;d&&this.block(a,d.path,u),ot("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,l.path,a,"rename",null);g.state="conflict",g.error=Me(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let o=await this.scan(e);for(let[s,i]of r)for(let a of i.nodes.filter(c=>c.kind==="folder"&&!c.busy).sort((c,l)=>jt(l.path)-jt(c.path))){if(this.isBlocked(s,a.path)||this.route(a.path,n,"folder")!==s)continue;let c=Object.entries(e.stored.folders).find(([u,d])=>u.startsWith(s+":")&&d.id===a.id);if(!c)continue;let l=o.find(u=>u.path===a.path&&u.kind==="folder");if(a.deleted&&l){if(o.some(d=>d.path.startsWith(a.path+"/"))||(await cr(l.physical)).some(d=>d!==".forsion-sync-id.json"))continue;await this.operation(e,a.path,s,"delete",null,()=>this.lock(e,l.physical,()=>{st(l.root,ur(l.root,l.physical).split(En).join("/"));let d=om(l.physical);if(d.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let g=Ie(l.physical,".forsion-sync-id.json"),h=d.length?kn(g):null;h&&fi(g);try{sm(l.physical)}catch(m){if(h)try{im(g,h,{flag:"wx",mode:384})}catch{}throw m}})),this.tally("deletesLocal"),delete e.stored.folders[c[0]]}else if(!a.deleted&&!l){if(!await this.absent(e,a.path)||i.nodes.some(u=>u.parentId===a.id&&!u.deleted))continue;await this.operation(e,a.path,s,"delete",null,()=>this.json(e,s,`/nodes/${a.id}`,"DELETE",{revision:a.revision,version:null})),a.deleted=!0,delete e.stored.folders[c[0]]}}}async download(e,n,r,o){if(n.size!==void 0&&n.size>_n)throw Error("File exceeds 50 MB content limit");let s=await this.request(e,r,`/nodes/${n.id}/content`),i=[],a=0;if(s.body){let l=s.body.getReader();for(;;){let u=await l.read();if(u.done)break;if(this.guard(e),a+=u.value.length,a>_n)throw await l.cancel(),Error("Content too large");i.push(u.value),o.done=a}}let c=Buffer.concat(i);if(n.hash&&ke(c)!==n.hash)throw Error("Cloud file changed during download");return c}async fileRenames(e,n,r,o){for(let[s,i]of o)for(let a of i.nodes.filter(c=>c.kind==="file"&&!c.deleted&&!c.busy)){let c=e.stored.files[Pe(s,a.id)];if(!c||c.path===a.path)continue;let l=r.find(u=>u.kind==="file"&&u.path===c.path);if(!(!l||this.route(l.path,n)!==s))try{if(this.route(a.path,n)!==s)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,l.path,s,"rename",null,()=>di(e.roots,l.path,a.path,(u,d)=>this.lock(e,u,d))),c.path=a.path}catch(u){this.block(s,l.path,u),this.block(s,a.path,u)}}}async upload(e,n,r,o,s){if(o.length>_n)throw Error("File exceeds 50 MB content limit");this.guard(e);let i=this.host.readCreds(),a=_u.from((async function*(){for(let l=0;l<o.length;l+=64*1024)e.abort.signal.throwIfAborted(),yield o.subarray(l,l+64*1024),s.done=Math.min(o.length,l+64*1024)})()),c=await fetch(i.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(r)}/nodes/${n.id}/content`,{method:"PUT",headers:{Authorization:`Bearer ${i.token}`,"X-Content-Device":this.deviceId,"Content-Type":"application/octet-stream","Content-Length":String(o.length),"X-Content-Version":n.version??"create"},body:a,duplex:"half",signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)])});if(this.guard(e),!c.ok){let l=await c.json().catch(()=>({}));throw Error(l.detail??`content_http_${c.status}`)}return await c.json()}async shadow(e,n,r,o,s,i){let a=Pe(n,r.id),c=ke(o),l=mi(o);l&&o.length>=xu&&await this.keepBase(e,c,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[a],delete e.stored.unconfirmed?.[a],e.stored.files[a]={id:r.id,path:r.path,version:r.version,hash:c,...l&&o.length<xu?{base:o.toString("utf8")}:{},...i?{inode:i.inode,stat:i.key,statAt:i.at}:s?{inode:s.inode}:{}}}async seen(e,n,r){let o=Le(e.roots,n),s=await kt(Ie(o.root,...o.relative.split("/"))).catch(()=>null);if(!s?.isFile())return;let i=So(s);return{key:sr(i),at:r,inode:i.inode}}sameAsShadow(e,n){return!this.dirty.has(n.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===sr(n)&&gm(n)<=e.statAt-hm}unchanged(e,n,r,o,s){let i=Pe(n,r.id);return this.sameAsShadow(o,s)&&o.id===r.id&&o.path===s.path&&!r.busy&&!r.deleted&&r.version===o.version&&r.hash===o.hash&&!e.stored.unconfirmed?.[i]&&!e.stored.pendingUploads?.[i]&&!this.openJobs.has(n+"\0"+s.path)}hold(e,n){if(e.path.endsWith("/"+or)||n?.stat===sr(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>=bi(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=wi(e),s=Ie(o,n);if(await kt(s).then(()=>!0,()=>!1))return;await pi(o,{recursive:!0,mode:448});let i=s+".tmp-"+tt();try{await ar(i,r,{mode:384,flag:"wx"}),await ko(i,s)}finally{await lr(i).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await ir(Ie(wi(e),n.hash)).catch(o=>{if(o.code==="ENOENT")return null;throw o});return r&&ke(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(o=>o.hash)),r=wi(e);for(let o of await cr(r).catch(()=>[]))n.has(o)||await lr(Ie(r,o)).catch(()=>{})}async file(e,n,r,o,s){if(r.size>_n){ot("content","skippedTooLarge",1,r.path),await this.operation(e,r.path,o,"upload",r.size,async()=>{throw Error("File exceeds 50 MB content limit")});return}let i=s.nodes.find(b=>b.kind==="file"&&!b.deleted&&b.path===r.path);if(!i){let b=Object.entries(e.stored.files).find(([v,$])=>v.startsWith(o+":")&&$.inode===r.inode&&$.path!==r.path)?.[1];if(b){let v=Le(e.roots,b.path),$=await kt(Ie(v.root,v.relative)).then(async O=>So(O).inode!==r.inode||Et(b.path)!==Et(r.path)?!0:(await cr(Yt(r.physical))).includes(Gt(b.path)),O=>O.code==="ENOENT"?!1:Promise.reject(O)),R=s.nodes.find(O=>O.id===b.id&&!O.deleted);if(!$&&R)try{if(R.path!==b.path)throw Error(`Concurrent file rename: ${r.path}`);let O=Et(r.path),w=O?s.nodes.find(C=>C.path===O&&C.kind==="folder"&&!C.deleted)?.id:"";if(O&&!w)throw Error("Rename parent unavailable");let x=await this.operation(e,r.path,o,"rename",null,()=>this.json(e,o,`/nodes/${R.id}`,"PATCH",{name:Gt(r.path),parentId:w,revision:R.revision}));Object.assign(R,x),b.path=r.path,i=R}catch(O){for(let w of new Set([b.path,R.path,r.path]))this.block(o,w,O);throw O}}}let a=i?e.stored.files[Pe(o,i.id)]:Object.entries(e.stored.files).find(([b,v])=>b.startsWith(o+":")&&v.path===r.path)?.[1];if(!a&&i?.version&&o==="default"&&(a=await this.legacyBaseline(r.path,i)),i&&a&&this.unchanged(e,o,i,a,r))return;if(this.hold(r,a))return"held";let c=Date.now(),l=await vn(r),u=ke(l),d={key:sr(r),at:c,inode:r.inode};if(this.guard(e),this.settled(r.path,c),!i){if((a?s.nodes.find(x=>x.id===a.id&&x.deleted):null)&&a&&(a.hash===u||a.memoryDeleted&&yi(r.path)&&u===dr)){yi(r.path)?await this.clearDeletedMemory(e,o,r,a,l,u):(await this.operation(e,r.path,o,"delete",r.size,()=>this.trashFile(e,r,u)),this.tally("deletesLocal"),delete e.stored.files[Pe(o,a.id)]);return}let v=Et(r.path),$=v?s.nodes.find(x=>x.path===v&&!x.deleted&&x.kind==="folder")?.id:"";if(v&&!$)throw Error("Parent folder is unavailable");let R=Object.entries(e.stored.pendingUploads??{}).find(([x,C])=>x.startsWith(o+":")&&C.path===r.path&&!s.nodes.some(D=>D.id===C.id))?.[1];for(let[x,C]of Object.entries(e.stored.pendingUploads??{}))x.startsWith(o+":")&&C.path===r.path&&s.nodes.some(D=>D.id===C.id&&D.deleted)&&delete e.stored.pendingUploads[x];let O=R?.id??tt(),w=Pe(o,O);(e.stored.pendingUploads??={})[w]={id:O,path:r.path},await this.persist(e),i=await this.json(e,o,"/nodes","POST",{id:O,parentId:$,name:Gt(r.path),kind:"file"}),i.id!==O&&delete e.stored.pendingUploads[w],s.nodes.push(i),a=void 0}if(i.busy)return;let g=Pe(o,i.id);if(i.version&&this.awaitingBytes.delete(g),i.hash===u){await this.shadow(e,o,i,l,r,d);return}if(i.hash&&e.stored.unconfirmed?.[g]===i.hash&&(await this.shadow(e,o,i,await this.operation(e,r.path,o,"download",i.size??null,b=>this.download(e,i,o,b)),r),a=e.stored.files[g]),!i.version&&a&&a.hash===u&&!e.stored.pendingUploads?.[g]){let b=this.awaitingBytes.get(g)??Date.now();if(this.awaitingBytes.set(g,b),Date.now()-b<dm)return}if(this.awaitingBytes.delete(g),!i.version||a&&i.version===a.version){(e.stored.unconfirmed??={})[g]=u,await this.persist(e);let b=await this.operation(e,r.path,o,"upload",l.length,v=>this.upload(e,i,o,l,v));Object.assign(i,b),await this.shadow(e,o,i,l,r,d);return}let h=await this.operation(e,r.path,o,"download",i.size??null,b=>this.download(e,i,o,b)),m=h,y=!1;if(!a||a.hash!==u){let b=l.toString("utf8"),v=h.toString("utf8"),$=a?await this.readBase(e,a):null,R=Buffer.from(b).equals(l)&&Buffer.from(v).equals(h)?this.host.contentSync.merge(r.path,b,$,v):null;if(R?(m=Buffer.from(R.content),y=R.conflict):y=!0,y){await this.preserveConflict(e,r.path,l)&&(ot("content","conflicts"),this.tally("conflictCopies"));let O=this.job(e,r.path,o,"merge",l.length);O.state="conflict",O.error="Both versions preserved",O.finishedAt=Date.now()}if(!m.equals(h)){let O=await this.operation(e,r.path,o,"merge",m.length,w=>this.upload(e,i,o,m,w));Object.assign(i,O)}}let p=Date.now();await this.write(e,r.path,m,u),await this.shadow(e,o,i,m,r,await this.seen(e,r.path,p))}async preserveConflict(e,n,r){let o=Le(e.roots,n),s=await Je(o.root,o.relative),i=Gt(n),a=ke(r);for(let c of await cr(Yt(s))){if(c.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==i||!lo(c))continue;let l=Et(n)?Et(n)+"/"+c:c,u=Le(e.roots,l),d=await Je(u.root,u.relative),g=await kt(d);if(g.isFile()&&g.size===r.length&&ke(await ir(d))===a)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=au(n,r,o),i=Le(e.roots,s);if(!await kt(Ie(i.root,...i.relative.split("/"))).then(()=>!0,a=>a.code==="ENOENT"?!1:Promise.reject(a)))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 i=[],a=c=>c.length?Math.max(...c):null;for(let c of n){let l=c.kind==="folder"?Zn(c.path):null;if(!l||so.has(l))continue;let u=`agents/${l}/`,d=this.route(u+"config.toml",r);if(!d||Object.entries(e.stored.files).some(([p,b])=>p.startsWith(d+":")&&b.path.startsWith(u)))continue;let g=(o.get(d)?.nodes??[]).filter(p=>!p.deleted&&p.kind==="file"&&p.version&&p.path.startsWith(u)&&this.route(p.path,r)===d),h=n.filter(p=>p.kind==="file"&&p.path.startsWith(u)&&this.route(p.path,r)===d);if(!g.length||!h.length)continue;let m=new Map(g.map(p=>[p.path,p])),y=h.filter(p=>{let b=m.get(p.path);return!!b&&s.get(p.path)!==b.hash}).length;!y&&h.length===g.length&&h.every(p=>m.has(p.path))||i.push({slug:l,namespace:d,cloudFiles:g.length,localFiles:h.length,differ:y,cloudMtime:a(g.map(p=>p.mtime??0)),localMtime:a(h.map(p=>p.mtime))})}return i}async resolveAsks(e,n,r,o){for(let s of n){try{await this.resolveAsk(e,s,r[s.slug]??"merge",o)}catch(l){throw this.dropShadows(e,s.namespace,`agents/${s.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Me(l)}`)}let i=`agents/${s.slug}`,a=o.rules.find(l=>l.source===i),c=pn(e.stored.config,i,tl(o,i));a&&(c={...c,rules:c.rules.map(l=>l.source===i?{...a,target:l.target}:l)}),e.stored.config=Pt(c,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,o){let s=n.namespace,i=`agents/${n.slug}/`;if(this.dropShadows(e,s,i),r==="local"){await this.archiveAgent(e,s,n.slug),await this.persist(e);return}let a=await this.json(e,s);this.guard(e),go(a,s);let c=new Map(a.nodes.filter(h=>!h.deleted&&!h.busy&&h.kind==="file"&&h.version&&h.path.startsWith(i)&&this.route(h.path,o)===s).map(h=>[h.path,h])),l=h=>h.endsWith("/"+or),u=async(h,m,y)=>{let p=Date.now();return await this.write(e,h,m,y),this.seen(e,h,p)};for(let[h,m]of c){if(!l(h))continue;let y=Le(e.roots,h);if(Tu(Ie(y.root,y.relative)))continue;let p=await this.operation(e,h,s,"download",m.size??null,b=>this.download(e,m,s,b));await this.shadow(e,s,m,p,void 0,await u(h,p,null))}let d=(await this.scan(e)).filter(h=>h.kind==="file"&&h.path.startsWith(i)&&this.route(h.path,o)===s&&h.size<=_n).sort((h,m)=>+!l(h.path)-+!l(m.path)),g=await this.removedDir(e,n.slug);for(let h of d){this.guard(e);let m=await vn(h),y=ke(m),p=c.get(h.path),b=h.path.slice(i.length);if(p&&p.hash===y){await this.shadow(e,s,p,m,h);continue}if(r==="cloud"){if(await this.keep(e,`${g}/${b}`,m),p){let w=await this.operation(e,h.path,s,"download",p.size??null,x=>this.download(e,p,s,x));await this.shadow(e,s,p,w,h,await u(h.path,w,y))}else b==="MEMORY.md"?await this.write(e,h.path,Buffer.alloc(0),y):await this.removeLocal(e,h,y);continue}if(!p)continue;let v=await this.operation(e,h.path,s,"download",p.size??null,w=>this.download(e,p,s,w)),$=s==="default"?await this.legacyBaseline(h.path,p):void 0;if($?.hash===y){await this.shadow(e,s,p,v,h,await u(h.path,v,y));continue}let R=$?await this.readBase(e,$):null,O=mi(m)&&mi(v)?this.host.contentSync.merge(h.path,m.toString("utf8"),R,v.toString("utf8")):null;if(O&&!O.conflict){let w=Buffer.from(O.content);w.equals(m)||await this.write(e,h.path,w,y),await this.shadow(e,s,p,v)}else(p.mtime??0)>h.mtime?(await this.keep(e,`${g}/${b}`,m),await this.shadow(e,s,p,v,h,await u(h.path,v,y))):(await this.keep(e,`${g}/${b}`,v),await this.shadow(e,s,p,v))}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=a=>String(a).padStart(2,"0"),i=`${o.getFullYear()}-${s(o.getMonth()+1)}-${s(o.getDate())} ${s(o.getHours())}${s(o.getMinutes())}`;for(let a=1;;a++){let c=`${r}/.removed/${n} ${i}${a>1?` ${a}`:""}`,l=Le(e.roots,c);if(!await kt(Ie(l.root,...l.relative.split("/"))).then(()=>!0,u=>u.code==="ENOENT"?!1:Promise.reject(u)))return c}}async keep(e,n,r){this.guard(e),await ui(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(st(n.root,ur(n.root,n.physical).split(En).join("/")),ke(kn(n.physical))!==r)throw Error("Local file changed before replacing");fi(n.physical)})}async archiveAgent(e,n,r){let o=this.host.readCreds();if(!o.token)throw Error("not_signed_in");let s=await fetch(o.cloudUrl.replace(/\/+$/,"")+"/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:tt(),locale:this.locale()}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)])});this.guard(e);let i=await s.json().catch(()=>({}));if(this.guard(e),!s.ok||i?.state!=="done")throw Error(typeof i?.detail=="string"?i.detail:`agent_archive_http_${s.status}`)}async absent(e,n){this.guard(e);let r=Le(e.roots,n),o=await Je(r.root,r.relative);try{return await kt(o),!1}catch(s){if(s.code==="ENOENT")return!0;throw s}}async missing(e,n,r,o,s){let i=e.stored.files[Pe(r,n.id)],a=e.stored.pendingUploads?.[Pe(r,n.id)];if(n.deleted){i&&delete e.stored.files[Pe(r,n.id)],a&&delete e.stored.pendingUploads[Pe(r,n.id)];return}if(n.busy||i?.inode&&this.blocked.has(r)&&o.some(u=>u.kind==="file"&&u.inode===i.inode&&this.isBlocked(r,u.path)&&this.route(u.path,s)===r))return;if(!n.version){a&&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[Pe(r,n.id)],n.deleted=!0);return}if(i&&i.version===n.version){if(!await this.absent(e,n.path))return;await this.operation(e,n.path,r,"delete",n.size??null,()=>this.json(e,r,`/nodes/${n.id}`,"DELETE",{revision:n.revision,version:n.version})),delete e.stored.files[Pe(r,n.id)],n.deleted=!0;return}let c=await this.operation(e,n.path,r,"download",n.size??null,u=>this.download(e,n,r,u)),l=Date.now();await this.write(e,n.path,c,null),await this.shadow(e,r,n,c,void 0,await this.seen(e,n.path,l))}async recoverTrash(e){for(let n of[...e.stored.trash??[]]){if(n.parentId){let l=(await vo(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);l&&(n.path=l.path+"/"+Gt(n.path))}let r=Le(e.roots,n.path),o=await Je(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,i=await this.rootIdentity(e,s),a=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(a&&!tn(a,i))throw Error("Sync recovery root changed; journal retained");let c=Ie(s,n.stage);await kt(c).then(()=>!0,l=>l.code==="ENOENT"?!1:Promise.reject(l))&&await this.lock(e,o,()=>{if(st(s,n.stage,!0),ke(kn(c))!==n.hash)throw Error("Sync recovery content changed");st(r.root,r.relative),am(Yt(o),{recursive:!0});let l=Tu(o)?o+` (sync recovery ${tt().slice(0,8)})`:o;try{rm(c,l)}catch(u){if(u.code!=="EXDEV")throw u;if(cm(c,l,lm.COPYFILE_EXCL),ke(kn(l))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}fi(c)},!0),e.stored.trash=e.stored.trash.filter(l=>l!==n)}}async clearDeletedMemory(e,n,r,o,s,i){o.memoryDeleted&&o.hash===dr&&i===dr||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!o.memoryDeleted&&s.length){let l=r.path==="human/MEMORY.md",u=await this.removedDir(e,l?"memory":r.path.split("/")[1],l?"human":"agents");await this.keep(e,`${u}/MEMORY.md`,s)}o.memoryDeleted=!0,await this.persist(e);let a=Date.now();s.length&&await this.write(e,r.path,Buffer.alloc(0),i);let c=await this.seen(e,r.path,a);e.stored.files[Pe(n,o.id)]={...o,hash:dr,base:"",stat:void 0,statAt:void 0,...c?{inode:c.inode,stat:c.key,statAt:c.at}:{}}}),this.tally("deletesLocal"))}async trashFile(e,n,r){this.guard(e);let o=await Je(n.root,ur(n.root,n.physical).split(En).join("/")),s={path:n.path,stage:".forsion-sync-trash-"+tt(),hash:r},i=Ie(n.root,s.stage),a=await this.rootIdentity(e,n.root);s.stageRoot=n.root,s.stageDev=a.dev,s.stageIno=a.ino,s.stageIdentity=a;try{let c=JSON.parse(kn(Ie(Yt(o),".forsion-sync-id.json"),"utf8")).id;/^[a-f0-9-]{36}$/i.test(c)&&(s.parentId=c)}catch{}(e.stored.trash??=[]).push(s),await this.persist(e);try{await this.lock(e,o,()=>{if(st(n.root,ur(n.root,o).split(En).join("/")),ke(kn(o))!==r)throw Error("Local file changed before deletion");nm(o,i)}),await this.host.contentSync.trash(i),e.stored.trash=e.stored.trash.filter(c=>c!==s)}catch(c){throw this.host.accountId()===e.account&&!e.abort.signal.aborted&&await this.recoverTrash(e),c}}};function mm(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))Xn.test(n)&&Xc.includes(r)&&(e[n]=r);return e}function Tu(t){try{return em(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}Li(va);function nv(t){Sa(t.contentSync?.withWriteLock?.bind(t.contentSync)),Ji(t),rs(t),Ru(t),t.log("[forsion-extend] cloud account handlers registered"),Go(t)?Jo(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Xo(t)?Zo(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),us(t)?ds(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),As(t)?Ts(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),Rs(t)?Ds(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),qs(t)?Fl(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),qs(t)&&ou(t)}export{Xa as ACCOUNT_SEAM,Fc as AMADEUS_SEAM,Yo as CONNECT_MAX_FILES,_a as CONNECT_MAX_FILE_BYTES,Ca as CONNECT_MAX_TOTAL_BYTES,jr as DIAGNOSTICS_VAULT,Ma as FORSION_CONNECT_LOCAL_SDK,Gi as PAY_PERIODS,Yi as PAY_TABS,ja as PENZOR_MAX_FILE,Te as SYNC_IPC,Hc as UNIT_SEAM,$n as UPLOAD_MAX_FILE,Yn as UnitCapsReporter,Vn as UnitHost,ze as cloudJson,Aa as collectProjectFiles,Hr as conflictCopyPath,Qf as conflictCopyVariant,Oa as connectMetaOf,Ka as createAccountCloud,Lc as createAmadeusCloud,Nr as createPenzorRemote,zc as createUnitHub,$r as deviceHeader,Ko as expectedPartsOf,Ne as forsionAccountId,Cr as forsionRefreshToken,Mn as forsionWhoami,us as hasAccountHost,As as hasAmadeusHost,Go as hasConnectHost,Xo as hasRemoteSyncHost,Rs as hasUnitHost,Pa as makePreviewProxy,Va as multipartFrame,Ia as readConnectMeta,ds as registerAccount,Ts as registerAmadeus,nv as registerCloud,Jo as registerConnect,Zo as registerPenzor,rs as registerPenzorTransfers,Ds as registerUnit,Fr as safeDownloadName,Da as scanSdkUsage,_r as shouldRefreshToken,Qo as speedOf,Uc as streamWorthy,Ec as stripConflictSuffix,ep as textFingerprint,Ro as tokenAgeMs,Bi as tokenRemainingMs,es as uploadError,Ra as writeConnectMeta};
|
|
286
286
|
/*! Bundled license information:
|
|
287
287
|
|
|
288
288
|
chokidar/index.js:
|