@forsion/extend 0.10.8 → 0.10.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/desktop.mjs CHANGED
@@ -1,8 +1,8 @@
1
- var Oo=null;function Yi(t){Oo=t}function ve(){if(!Oo)throw new Error("core host not set (call setCoreHost first)");return Oo}var Gi=new TextEncoder,rd=new TextDecoder("utf-8",{ignoreBOM:!0}),Rn=t=>Gi.encode(t),vt=t=>rd.decode(t),_r=t=>typeof t=="string"?Gi.encode(t).length:t.length;function Ji(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Cr(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 Ki(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 Mo(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(vt(Cr(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Po(t,e=Date.now()){let n=Mo(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Xi(t,e=Date.now()){let n=Mo(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var od=36e5;function Ar(t,e=Date.now()){return!!t&&Po(t,e)>=od}async function xr(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 Dn=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,sd=(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 Zi(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(k=>k.id===h),p=Mo(d.token),S={...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(S)&&n({version:1,accounts:[...m.filter(k=>k.id!==h),S]})},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(/\/+$/,""),S;try{S=await fetch(`${p}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(A=>A.json())}catch(A){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${p}:${A?.message||A}`)}if(y(),!S?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let k=S.verification_uri_complete||`${S.verification_uri}?code=${S.user_code}`,P=new URL(`${p}/auth`);P.searchParams.set("logout","1"),P.searchParams.set("app","forsion-desktop"),P.searchParams.set("redirect",k);let R=P.toString();g?.({url:R,userCode:String(S.user_code||"")}),t.openExternal(R);let O=Date.now()+(S.expires_in||600)*1e3,w=(S.interval||2)*1e3;for(;Date.now()<O;){await sd(w,m.signal),y();let A=null;try{A=await fetch(`${p}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:S.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),A.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let C=await A.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 kt(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 On(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function He(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 id=50*1024*1024,ad=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function cd(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(!ad.has(o)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(o))return null;n.append(o,s)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>id)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 Qi(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=cd(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=kt(o.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let i=await On(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 ea(t){if(!t.token)return"";try{let e=await He(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 ta=["membership","credits","storefront"],na=["monthly","quarterly","yearly"],ld=/^[A-Za-z0-9_-]{1,64}$/;function ra(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 ea(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&&!ta.includes(s))return{ok:!1,error:"invalid_tab"};if(i!==void 0&&(typeof i!="string"||!ld.test(i)))return{ok:!1,error:"invalid_plan"};if(a!==void 0&&!na.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 ea(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 He(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 He(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 He(i,"POST","/api/token-quota/background/convert",{percent:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:pointsAutoDeduct",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 He(i,"POST","/api/token-quota/auto-deduct",{enabled: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 He(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=Rn(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:Ji(u)})}try{let u=await On(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=kt(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 On(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)}}),Qi(t)}import{createHash as xa}from"node:crypto";import{existsSync as af,promises as cf,readFileSync as lf,renameSync as uf,statSync as df}from"node:fs";import ff from"node:path";import{EventEmitter as Fd}from"node:events";import{stat as Ld}from"node:fs";import{readdir as Ud,stat as Hd}from"node:fs/promises";import*as le from"node:path";import{lstat as oa,readdir as ud,realpath as dd,stat as fd}from"node:fs/promises";import{join as pd,resolve as hd,sep as sa}from"node:path";import{Readable as gd}from"node:stream";var Ve={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},tn={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Ve.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(tn);var la="READDIRP_RECURSIVE_ERROR",md=new Set(["ENOENT","EPERM","EACCES","ELOOP",la]),ia=[Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE],yd=new Set([Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE]),wd=new Set([Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE]),bd=t=>md.has(t.code),Sd=process.platform==="win32",aa=t=>!0,ca=t=>{if(t===void 0)return aa;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 aa},$o=class extends gd{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??tn.highWaterMark});let n={...tn,...e},r=n.root??tn.root,o=n.type??tn.type;this._fileFilter=ca(n.fileFilter),this._directoryFilter=ca(n.directoryFilter);let s=n.lstat?oa:fd;Sd?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:tn.depth,this._wantsDir=yd.has(o),this._wantsFile=wd.has(o),this._wantsEverything=o===Ve.EVERYTHING_TYPE,this._root=hd(r),this._relStart=this._root.endsWith(sa)?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 ud(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=pd(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){bd(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 dd(n),o=await oa(r);if(o.isFile())return"file";if(o.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===sa){let i=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return i.code=la,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 ua(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&&!ia.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${ia.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 $o(r)}import{watch as vd,unwatchFile as da,watchFile as kd}from"node:fs";import{realpath as No,lstat as Ed,open as _d,stat as pa}from"node:fs/promises";import{type as Cd}from"node:os";import*as me from"node:path";var Ad="data",Lo="end",ha="close",Or=()=>{};var Mr=process.platform,Uo=Mr==="win32",xd=Mr==="darwin",Td=Mr==="linux",Id=Mr==="freebsd",ga=Cd()==="OS400",Se={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},it=Se,Rd="watch",Dd={lstat:Ed,stat:pa},zt="listeners",Tr="errHandlers",nn="rawEmitters",Od=[zt,Tr,nn],Md=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"]),Pd=t=>Md.has(me.extname(t).slice(1).toLowerCase()),Fo=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Mn=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},$d=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Pn=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ma=t=>t instanceof Set?t.size===0:!t,Ir=new Map;function fa(t,e,n,r,o){let s=(i,a)=>{n(t),o(i,a,{watchedPath:t}),a&&t!==a&&Rr(me.resolve(t,a),zt,me.join(t,a))};try{return vd(t,{persistent:e.persistent},s)}catch(i){r(i);return}}var Rr=(t,e,n,r,o)=>{let s=Ir.get(t);s&&Fo(s[e],i=>{i(n,r,o)})},Nd=(t,e,n,r)=>{let{listener:o,errHandler:s,rawEmitter:i}=r,a=Ir.get(e),c;if(!n.persistent)return c=fa(t,n,o,s,i),c?c.close.bind(c):void 0;if(a)Mn(a,zt,o),Mn(a,Tr,s),Mn(a,nn,i);else{if(c=fa(t,n,Rr.bind(null,e,zt),s,Rr.bind(null,e,nn)),!c)return;c.on(it.ERROR,async l=>{let u=Rr.bind(null,e,Tr);if(a&&(a.watcherUnusable=!0),Uo&&l.code==="EPERM")try{await(await _d(t,"r")).close(),u(l)}catch{}else u(l)}),a={listeners:o,errHandlers:s,rawEmitters:i,watcher:c},Ir.set(e,a)}return()=>{Pn(a,zt,o),Pn(a,Tr,s),Pn(a,nn,i),ma(a.listeners)&&(a.watcher.close(),Ir.delete(e),Od.forEach($d(a)),a.watcher=void 0,Object.freeze(a))}},jo=new Map,jd=(t,e,n,r)=>{let{listener:o,rawEmitter:s}=r,i=jo.get(e),a=i&&i.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(da(e),i=void 0),i?(Mn(i,zt,o),Mn(i,nn,s)):(i={listeners:o,rawEmitters:s,options:n,watcher:kd(e,n,(c,l)=>{Fo(i.rawEmitters,d=>{d(it.CHANGE,e,{curr:c,prev:l})});let u=c.mtimeMs;(c.size!==l.size||u>l.mtimeMs||u===0)&&Fo(i.listeners,d=>d(t,c))})},jo.set(e,i)),()=>{Pn(i,zt,o),Pn(i,nn,s),ma(i.listeners)&&(jo.delete(e),da(e),i.options=i.watcher=void 0,Object.freeze(i))}},Dr=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=Or);let l;if(r.usePolling){let u=r.interval!==r.binaryInterval;c.interval=u&&Pd(s)?r.binaryInterval:r.interval,l=jd(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})}else l=Nd(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(Rd,e,5)){if(!d||d.mtimeMs===0)try{let g=await pa(e);if(this.fsw.closed)return;let h=g.atimeMs,m=g.mtimeMs;if((!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(it.CHANGE,e,g),(xd||Td||Id)&&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(it.CHANGE,e,d),a=d}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(it.ADD,e,0))return;this.fsw._emit(it.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 No(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(it.CHANGE,r,e.stats)):(i.add(o),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(it.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(Ad,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(it.ERROR,this._boundHandleError),new Promise((g,h)=>{if(!d)return h();d.once(Lo,()=>{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(it.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 Dd[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 No(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 No(e):e;if(this.fsw.closed)return;let g=me.dirname(a.watchPath);if(this.fsw._getWatchedDir(g).add(a.watchPath),this.fsw._emit(it.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 Ho="/",zd="//",va=".",Bd="..",qd="string",Wd=/\\/g,ka=/\/\//g,Vd=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Yd=/^\.[/\\]/;function Pr(t){return Array.isArray(t)?t:[t]}var zo=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Gd(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=le.relative(t.path,e);return n?!n.startsWith("..")&&!le.isAbsolute(n):!1}return!1}:()=>!1}function Jd(t){if(typeof t!="string")throw new Error("string expected");t=le.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ka,"/"),e&&(t="/"+t),t}function ya(t,e,n){let r=Jd(e);for(let o=0;o<t.length;o++){let s=t[o];if(s(r,n))return!0}return!1}function Kd(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Pr(t).map(o=>Gd(o));return e==null?(o,s)=>ya(r,o,s):ya(r,e)}var wa=t=>{let e=Pr(t).flat();if(!e.every(n=>typeof n===qd))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ea)},ba=t=>{let e=t.replace(Wd,Ho),n=!1;return e.startsWith(zd)&&(n=!0),e=e.replace(ka,Ho),n&&(e=Ho+e),e},Ea=t=>ba(le.normalize(ba(t))),Sa=(t="")=>e=>typeof e=="string"?Ea(le.isAbsolute(e)?e:le.join(t,e)):e,Xd=(t,e)=>le.isAbsolute(t)?t:le.join(e,t),Zd=Object.freeze(new Set),Bo=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!==va&&e!==Bd&&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 Ud(r)}catch{this._removeWatcher&&this._removeWatcher(le.dirname(r),le.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=Or,this.items=Zd,Object.freeze(this)}},Qd="stat",ef="lstat",qo=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let o=e;this.path=e=e.replace(Yd,""),this.watchPath=o,this.fullWatchPath=le.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?Qd:ef}entryPath(e){return le.join(this.watchPath,le.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)}},$r=class extends Fd{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?Pr(e.ignored):Pr([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};ga&&(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=Or,this._readyEmitted=!0,process.nextTick(()=>this.emit(Se.READY)))},this._emitRaw=(...c)=>this.emit(Se.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new Dr(this),Object.freeze(o)}_addIgnoredPath(e){if(zo(e)){for(let n of this._ignoredPaths)if(zo(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)zo(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=wa(e);return o&&(s=s.map(i=>Xd(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(le.dirname(a),le.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=wa(e),{cwd:r}=this.options;return n.forEach(o=>{!le.isAbsolute(o)&&!this._closers.has(o)&&(r&&(o=le.join(r,o)),o=le.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?le.relative(this.options.cwd,r):r)||va;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==Se.ERROR&&this.emit(Se.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let o=this.options;Uo&&(n=le.normalize(n)),o.cwd&&(n=le.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===Se.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(Se.ALL,...c),this._pendingUnlinks.delete(l)})},typeof o.atomic=="number"?o.atomic:100),this;e===Se.ADD&&this._pendingUnlinks.has(n)&&(e=Se.CHANGE,this._pendingUnlinks.delete(n))}if(i&&(e===Se.ADD||e===Se.CHANGE)&&this._readyEmitted){let c=(l,u)=>{l?(e=Se.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===Se.CHANGE&&!this._throttle(Se.CHANGE,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===Se.ADD||e===Se.ADD_DIR||e===Se.CHANGE)){let c=o.cwd?le.join(o.cwd,n):n,l;try{l=await Hd(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(Se.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&&!le.isAbsolute(e)&&(c=le.join(this.options.cwd,e));let l=new Date,u=this._pendingWrites;function d(g){Ld(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&&Vd.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(Sa(r)),a=[...[...this._ignoredPaths].map(Sa(r)),...s];this._userIgnored=Kd(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new qo(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=le.resolve(e);return this._watched.has(n)||this._watched.set(n,new Bo(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let o=le.join(e,n),s=le.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=le.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Se.ADD)return;this._watched.delete(o),this._watched.delete(s);let d=r?Se.UNLINK_DIR:Se.UNLINK;l&&!this._isIgnored(o)&&this._emit(d,o),this._closePath(o)}_closePath(e){this._closeFile(e);let n=le.dirname(e);this._getWatchedDir(n).remove(le.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:Se.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=ua(e,r);return this._streams.add(o),o.once(ha,()=>{o=void 0}),o.once(Lo,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function Wo(t,e={}){let n=new $r(e);return n.add(t),n}var _a={watch:Wo,FSWatcher:$r};import{execFile as tf}from"node:child_process";import{stat as Ca}from"node:fs/promises";import{resolve as nf}from"node:path";import{promisify as rf}from"node:util";function Bt(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 rn(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 ft(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Aa=rf(tf);function of(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 sf(t){if(process.platform!=="darwin")return;let{stdout:e}=await Aa("/bin/df",["-P",nf(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 Aa("/usr/sbin/diskutil",["info","-plist",n],{timeout:5e3,maxBuffer:256*1024});return of(r)}async function $n(t,e=sf,n=process.platform){let r=await Ca(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 Ca(t);if(!i.isDirectory()||!ft(o,i))throw Error("Sync root changed while reading its identity");return{...o,...s?{volumeId:s}:{}}}var Vo;function Ta(t){Vo=t}var Ia={fs:cf,path:ff,directoryIdentity:$n,sha256Hex:t=>xa("sha256").update(t).digest("hex"),tmpTag:()=>process.pid,existsSync:af,async compareAndReplace(t,e,n,r,o){if(!Vo)throw new Error("This host needs the shared content write lock for safe cloud downloads");let s=!1;return await Vo(e,()=>{if(!r())return;if(o){let a;try{a=df(o.path)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||!ft(o.identity,a))return}let i=null;try{i=xa("sha256").update(lf(e)).digest("hex")}catch(a){if(a.code!=="ENOENT")throw a}i===n&&(uf(t,e),s=!0)}),s},watch(t,e,n){let r=_a.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 pf,lstatSync as Jo,readFileSync as Ko,writeFileSync as hf,realpathSync as Ra,opendirSync as gf,openSync as mf,fstatSync as yf,readSync as wf,closeSync as bf,constants as Yo}from"node:fs";import{join as Nr,extname as Da,sep as Sf}from"node:path";var Xo=300,Oa=5*1024*1024,Ma=20*1024*1024,vf=50*1024*1024,Pa=new Set(["node_modules"]),kf=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function $a(t,e){let n=[],r=0,o=(s,i)=>{for(let a of pf(s)){if(a.startsWith("."))continue;let c=Nr(s,a),l;try{l=Jo(c)}catch{continue}if(l.isSymbolicLink())continue;let u=i?`${i}/${a}`:a;if(l.isDirectory()){Pa.has(a)||o(c,u);continue}if(!l.isFile()||a.endsWith(".d.ts"))continue;if(n.length>=Xo)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Xo}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let d=Da(a).toLowerCase(),g,h=e.mimeOf(d)??"application/octet-stream";if(kf.has(d)){let m=e.transpile(Ko(c,"utf8"),d,u);g=Buffer.from(m??"","utf8"),h="text/javascript"}else g=Ko(c);if(g.length>Oa)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${u}`);if(r+=g.length,r>Ma)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 Na=".forsion-connect.json";function ja(t){try{return JSON.parse(Ko(Nr(t,Na),"utf8"))}catch{return{}}}function Fa(t,e){try{hf(Nr(t,Na),JSON.stringify(e,null,2)+`
3
- `,"utf8")}catch{}}var Ef=new Set([".html",".htm",".js",".mjs",".cjs",".ts",".tsx",".jsx",".mts",".cts",".vue",".svelte"]),_f=400,Cf=5e3,Go=2*1024*1024,Af=12,xf=/\bforsion\.ai\.(chat|generateImage|agent|status)\b/g;function La(t){try{if(!Jo(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=mf(c,Yo.O_RDONLY|(Yo.O_NOFOLLOW||0)|(Yo.O_NONBLOCK||0))}catch{return null}try{if(!yf(l).isFile())return null;s??=Buffer.allocUnsafe(Go+1);let u=0;for(;u<s.length;){let d=wf(l,s,u,s.length-u,null);if(d<=0)break;u+=d}return u>Go?null:s.toString("utf8",0,u)}catch{return null}finally{try{bf(l)}catch{}}},a=(c,l)=>{let u;try{u=gf(c)}catch{return}try{for(;;){if(r>=_f||o>=Cf)return;let d;try{d=u.readSync()}catch{return}if(!d)return;o++;let g=d.name;if(g.startsWith(".")||Pa.has(g))continue;let h=Nr(c,g),m;try{m=Jo(h)}catch{continue}if(m.isSymbolicLink())continue;if(m.isDirectory()){l<Af&&a(h,l+1);continue}if(!m.isFile()||m.size>Go||!Ef.has(Da(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(xf))n.add(`forsion.ai.${p[1]}`)}}}finally{try{u.closeSync()}catch{}}};return a(t,0),{usesSdk:e,sdkMethods:[...n].sort()}}function Ua(t){let e=ja(t),n=La(t);return n?{...e,...n}:e}function Ha(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>vf)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})}
1
+ var ji=null;function na(t){ji=t}function ve(){if(!ji)throw new Error("core host not set (call setCoreHost first)");return ji}var ra=new TextEncoder,ud=new TextDecoder("utf-8",{ignoreBOM:!0}),$n=t=>ra.encode(t),Et=t=>ud.decode(t),Dr=t=>typeof t=="string"?ra.encode(t).length:t.length;function ia(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Or(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 sa(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Fe(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let i=r.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(i),c=>c.charCodeAt(0)),o=JSON.parse(new TextDecoder().decode(s)),a=o.userId??o.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function Fi(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Et(Or(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Li(t,e=Date.now()){let n=Fi(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function oa(t,e=Date.now()){let n=Fi(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var dd=36e5;function Mr(t,e=Date.now()){return!!t&&Li(t,e)>=dd}async function Pr(t,e,n=8e3,r){if(!t||!e)return null;let i=t.replace(/\/+$/,"");try{let s=await fetch(`${i}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!s.ok)return null;let o=await s.json().catch(()=>null),a=typeof o?.token=="string"?o.token:"";return a&&a!==e?a:null}catch{return null}}var Nn=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,fd=(t,e)=>new Promise((n,r)=>{let i=()=>{clearTimeout(s),r(new Error("Sign-in cancelled."))},s=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);e.aborted?i():e.addEventListener("abort",i,{once:!0})});function aa(t,e){let n=f=>e.write(JSON.stringify(f,null,2)),r=()=>{let f;try{f=e.read()}catch(h){return h?.code==="ENOENT"?[]:null}if(f===null)return[];try{let h=JSON.parse(f);return Array.isArray(h.accounts)?h.accounts.filter(p=>p&&typeof p.token=="string"&&p.id===Fe(p.cloudUrl,p.token)):null}catch{return null}},i=(f,h)=>{let p=Fe(f.cloudUrl||"",f.token||"");if(!p||!f.token||!f.cloudUrl)return;let m=r();if(!m)return;let w=m.find(g=>g.id===p),y=Fi(f.token),S={...w,id:p,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:h?.username||w?.username||y?.username,nickname:h?.nickname||w?.nickname};JSON.stringify(w)!==JSON.stringify(S)&&n({version:1,accounts:[...m.filter(g=>g.id!==p),S]})},s=()=>{let f=t.readCreds();i(f);let h=Fe(f.cloudUrl,f.token);return(r()??[]).map(({token:p,...m})=>({...m,active:m.id===h}))},o=f=>{let h=r()?.find(p=>p.id===f);if(!h)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:h.cloudUrl,token:h.token}},a=f=>{let h=Fe(f.cloudUrl||"",f.token||""),p=r();h&&p&&n({version:1,accounts:p.filter(m=>m.id!==h)})},c=null;return{rememberForsionAccount:i,forsionAccounts:s,savedForsionAccount:o,forgetForsionAccount:a,cancelForsionLogin:()=>{c?.abort(),c=null},forsionDeviceLogin:async(f,h,p)=>{if(c)throw new Error("A sign-in is already in progress.");if(!f)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;c=m;let w=()=>{if(m.signal.aborted||c!==m)throw new Error("Sign-in cancelled.")};try{let y=f.replace(/\/+$/,""),S;try{S=await fetch(`${y}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(A=>A.json())}catch(A){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${y}:${A?.message||A}`)}if(w(),!S?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let g=S.verification_uri_complete||`${S.verification_uri}?code=${S.user_code}`,P=new URL(`${y}/auth`);P.searchParams.set("logout","1"),P.searchParams.set("app","forsion-desktop"),P.searchParams.set("redirect",g);let x=P.toString();h?.({url:x,userCode:String(S.user_code||"")}),t.openExternal(x);let D=Date.now()+(S.expires_in||600)*1e3,k=(S.interval||2)*1e3;for(;Date.now()<D;){await fd(k,m.signal),w();let A=null;try{A=await fetch(`${y}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:S.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{w();continue}if(w(),A.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let E=await A.json().catch(()=>({status:"pending"}));if(w(),E.status==="approved"&&E.token){let M={cloudUrl:y,token:E.token};return await p(M,w),w(),{token:E.token,cloudUrl:y}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{c===m&&(c=null)}},readAccounts:()=>r()??[]}}function _t(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,i;try{r=new URL(n),i=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||i.origin!==r.origin||!i.pathname.startsWith("/api/")?null:i.toString()}function jn(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function qe(t,e,n,r,i=6e4){let s=await(t.fetch??fetch)(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token&&!t.fetch?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(i)}),o=await s.json().catch(()=>({}));return{status:s.status,json:o}}var pd=50*1024*1024,hd=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function gd(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[i,s]of Object.entries(e.fields)){if(!hd.has(i)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(i))return null;n.append(i,s)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>pd)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 ca(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=gd(n);if(!r)return{status:400,json:{error:"invalid_request"}};let i=await t.getCloud();if(!i.token)return{status:401,error:"not_signed_in"};let s=_t(i.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let o=await jn(i,s,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:o.status,json:await o.json().catch(()=>null)}}catch(o){return{status:0,error:String(o?.message||o)}}})}async function Ui(t){if(!t.token)return"";try{let e=await qe(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 la=["membership","credits","storefront"],ua=["monthly","quarterly","yearly"],md=/^[A-Za-z0-9_-]{1,64}$/;function da(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(i,s)=>{if(!t.isTrustedSender(i))return n;let o=await t.getCloud(),a=o.base;if(!a)return{ok:!1};let c=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",l=await Ui(o),u=`${a}/account${l?`?${l}`:""}${c}`;return o.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(i,s,o,a)=>{if(!t.isTrustedSender(i))return n;if(s!==void 0&&!la.includes(s))return{ok:!1,error:"invalid_tab"};if(o!==void 0&&(typeof o!="string"||!md.test(o)))return{ok:!1,error:"invalid_plan"};if(a!==void 0&&!ua.includes(a))return{ok:!1,error:"invalid_period"};let c=(s??"membership")==="membership"&&o?`&plan=${encodeURIComponent(o)}${a?`&period=${a}`:""}`:"",l=await t.getCloud(),u=l.base;if(!u)return{ok:!1};let f=await Ui(l),h=`${u}/pay?tab=${s??"membership"}${c}${f?`&${f}`:""}&redirect=${encodeURIComponent(`${u}/account`)}`;return l.signal?.throwIfAborted(),await t.openExternal(h),{ok:!0}}),t.handle("auth:resumeAutoRenew",async i=>{if(!t.isTrustedSender(i))return n;let s=await t.getCloud(),o=s.base;if(!o)return{ok:!1};let a=await Ui(s);if(!a.startsWith("code="))return{ok:!1,error:"handoff_unavailable"};let c=`${o}/pay?tab=membership&action=resume_autorenew&${a}&redirect=${encodeURIComponent(`${o}/account`)}`;return s.signal?.throwIfAborted(),await t.openExternal(c),{ok:!0}}),t.handle("profile:publicOrigin",async i=>{if(!t.isTrustedSender(i))return n;let{base:s}=await t.getCloud();if(!s)return{ok:!1};try{let o=await fetch(`${s}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});o.body?.cancel().catch(()=>{});let a=o.status>=300&&o.status<400?o.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 i=>{if(!t.isTrustedSender(i))return e;let s=await r();if(!s.token)return{status:401,json:null};try{return await qe(s,"GET","/api/token-quota/my",void 0,15e3)}catch(o){return{status:0,json:{detail:String(o?.message||o)}}}}),t.handle("account:useResetCard",async(i,s)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.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 qe(o,"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(i,s)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(!Number.isInteger(s)||s<1||s>100)return{status:400,json:{error:"invalid_percent"}};try{return await qe(o,"POST","/api/token-quota/background/convert",{percent:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:pointsAutoDeduct",async(i,s)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await qe(o,"POST","/api/token-quota/auto-deduct",{enabled:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:bgAutoMain",async(i,s)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await qe(o,"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(i,s)=>{if(!t.isTrustedSender(i))return n;let o=await t.getCloud();if(!o.base||!o.token)return{ok:!1,error:"not-logged-in"};if(s?.expectedAccountId!==void 0){let u=s.expectedAccountId;if(typeof u!="string"||!u||Fe(o.base,o.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=$n(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:ia(u)})}try{let u=await jn(o,`${o.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 h=`HTTP ${u.status}`;try{h=(await u.json())?.detail||h}catch{}return{ok:!1,error:h}}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(i,s)=>{if(!t.isTrustedSender(i))return{status:0,error:"untrusted"};let o=s??{},a=typeof o.path=="string"?o.path:"",c=o.projectSource===void 0?null:o.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(o.timeoutMs)||15e3)),u=typeof o.method=="string"?o.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 f=await t.getCloud();if(!String(f.base||""))return{status:0,error:"no_cloud_url"};let h=_t(f.base,a);if(!h)return{status:0,error:"bad_path"};if(!f.token)return{status:401,error:"not_signed_in"};let p=o.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,w=setTimeout(()=>m.abort(),l);try{let y=await jn(f,h,{method:u,headers:{...p?{"Content-Type":"application/json"}:{},...c?{"X-Project-Source":c}:{}},body:p?JSON.stringify(o.body):void 0,signal:m.signal});return{status:y.status,json:await y.json().catch(()=>null)}}catch(y){return{status:0,error:String(y?.message||y)}}finally{clearTimeout(w)}}),ca(t)}import{createHash as $a}from"node:crypto";import{existsSync as hf,promises as gf,readFileSync as mf,renameSync as yf,statSync as wf}from"node:fs";import bf from"node:path";import{setTimeout as Sf}from"node:timers/promises";import{EventEmitter as Wd}from"node:events";import{stat as Vd}from"node:fs";import{readdir as Yd,stat as Gd}from"node:fs/promises";import*as ue from"node:path";import{lstat as fa,readdir as yd,realpath as wd,stat as bd}from"node:fs/promises";import{join as Sd,resolve as vd,sep as pa}from"node:path";import{Readable as kd}from"node:stream";var Xe={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},an={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Xe.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(an);var ya="READDIRP_RECURSIVE_ERROR",Ed=new Set(["ENOENT","EPERM","EACCES","ELOOP",ya]),ha=[Xe.DIR_TYPE,Xe.EVERYTHING_TYPE,Xe.FILE_DIR_TYPE,Xe.FILE_TYPE],_d=new Set([Xe.DIR_TYPE,Xe.EVERYTHING_TYPE,Xe.FILE_DIR_TYPE]),Cd=new Set([Xe.EVERYTHING_TYPE,Xe.FILE_DIR_TYPE,Xe.FILE_TYPE]),Ad=t=>Ed.has(t.code),xd=process.platform==="win32",ga=t=>!0,ma=t=>{if(t===void 0)return ga;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 ga},Hi=class extends kd{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??an.highWaterMark});let n={...an,...e},r=n.root??an.root,i=n.type??an.type;this._fileFilter=ma(n.fileFilter),this._directoryFilter=ma(n.directoryFilter);let s=n.lstat?fa:bd;xd?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:an.depth,this._wantsDir=_d.has(i),this._wantsFile=Cd.has(i),this._wantsEverything=i===Xe.EVERYTHING_TYPE,this._root=vd(r),this._relStart=this._root.endsWith(pa)?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 o={path:this._root,depth:1};o.pending=this._exploreDir(this._root,1),this.parents=[o],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:i,depth:s}=n,o=r.splice(0,e).map(c=>this._formatEntry(c,i)),a=this._isDirent?o:await Promise.all(o);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 i=this.parents.pop();if(!i){this.push(null);break}let s=i.pending??this._exploreDir(i.path,i.depth),o=this.parents[this.parents.length-1];if(o&&!o.pending&&(o.pending=this._exploreDir(o.path,o.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 yd(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,i=Sd(n,r),s={path:i.slice(this._relStart),fullPath:i,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(i).then(o=>(s.stats=o,s),o=>{this._onError(o)})}_onError(e){Ad(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 wd(n),i=await fa(r);if(i.isFile())return"file";if(i.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===pa){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=ya,this._onError(o),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function wa(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Xe.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!ha.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${ha.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 Hi(r)}import{watch as Td,unwatchFile as ba,watchFile as Id}from"node:fs";import{realpath as zi,lstat as Rd,open as Dd,stat as va}from"node:fs/promises";import{type as Od}from"node:os";import*as ye from"node:path";var Md="data",Wi="end",ka="close",Lr=()=>{};var Ur=process.platform,Vi=Ur==="win32",Pd=Ur==="darwin",$d=Ur==="linux",Nd=Ur==="freebsd",Ea=Od()==="OS400",be={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},at=be,jd="watch",Fd={lstat:Rd,stat:va},Yt="listeners",$r="errHandlers",cn="rawEmitters",Ld=[Yt,$r,cn],Ud=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"]),Hd=t=>Ud.has(ye.extname(t).slice(1).toLowerCase()),qi=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Fn=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},zd=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Ln=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},_a=t=>t instanceof Set?t.size===0:!t,Nr=new Map;function Sa(t,e,n,r,i){let s=(o,a)=>{n(t),i(o,a,{watchedPath:t}),a&&t!==a&&jr(ye.resolve(t,a),Yt,ye.join(t,a))};try{return Td(t,{persistent:e.persistent},s)}catch(o){r(o);return}}var jr=(t,e,n,r,i)=>{let s=Nr.get(t);s&&qi(s[e],o=>{o(n,r,i)})},Bd=(t,e,n,r)=>{let{listener:i,errHandler:s,rawEmitter:o}=r,a=Nr.get(e),c;if(!n.persistent)return c=Sa(t,n,i,s,o),c?c.close.bind(c):void 0;if(a)Fn(a,Yt,i),Fn(a,$r,s),Fn(a,cn,o);else{if(c=Sa(t,n,jr.bind(null,e,Yt),s,jr.bind(null,e,cn)),!c)return;c.on(at.ERROR,async l=>{let u=jr.bind(null,e,$r);if(a&&(a.watcherUnusable=!0),Vi&&l.code==="EPERM")try{await(await Dd(t,"r")).close(),u(l)}catch{}else u(l)}),a={listeners:i,errHandlers:s,rawEmitters:o,watcher:c},Nr.set(e,a)}return()=>{Ln(a,Yt,i),Ln(a,$r,s),Ln(a,cn,o),_a(a.listeners)&&(a.watcher.close(),Nr.delete(e),Ld.forEach(zd(a)),a.watcher=void 0,Object.freeze(a))}},Bi=new Map,qd=(t,e,n,r)=>{let{listener:i,rawEmitter:s}=r,o=Bi.get(e),a=o&&o.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(ba(e),o=void 0),o?(Fn(o,Yt,i),Fn(o,cn,s)):(o={listeners:i,rawEmitters:s,options:n,watcher:Id(e,n,(c,l)=>{qi(o.rawEmitters,f=>{f(at.CHANGE,e,{curr:c,prev:l})});let u=c.mtimeMs;(c.size!==l.size||u>l.mtimeMs||u===0)&&qi(o.listeners,f=>f(t,c))})},Bi.set(e,o)),()=>{Ln(o,Yt,i),Ln(o,cn,s),_a(o.listeners)&&(Bi.delete(e),ba(e),o.options=o.watcher=void 0,Object.freeze(o))}},Fr=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,i=ye.dirname(e),s=ye.basename(e);this.fsw._getWatchedDir(i).add(s);let a=ye.resolve(e),c={persistent:r.persistent};n||(n=Lr);let l;if(r.usePolling){let u=r.interval!==r.binaryInterval;c.interval=u&&Hd(s)?r.binaryInterval:r.interval,l=qd(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})}else l=Bd(e,a,c,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,n,r){if(this.fsw.closed)return;let i=ye.dirname(e),s=ye.basename(e),o=this.fsw._getWatchedDir(i),a=n;if(o.has(s))return;let c=async(u,f)=>{if(this.fsw._throttle(jd,e,5)){if(!f||f.mtimeMs===0)try{let h=await va(e);if(this.fsw.closed)return;let p=h.atimeMs,m=h.mtimeMs;if((!p||p<=m||m!==a.mtimeMs)&&this.fsw._emit(at.CHANGE,e,h),(Pd||$d||Nd)&&a.ino!==h.ino){this.fsw._closeFile(u),a=h;let w=this._watchWithNodeFs(e,c);w&&this.fsw._addPathCloser(u,w)}else a=h}catch{this.fsw._remove(i,s)}else if(o.has(s)){let h=f.atimeMs,p=f.mtimeMs;(!h||h<=p||p!==a.mtimeMs)&&this.fsw._emit(at.CHANGE,e,f),a=f}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(at.ADD,e,0))return;this.fsw._emit(at.ADD,e,n)}return l}async _handleSymlink(e,n,r,i){if(this.fsw.closed)return;let s=e.fullPath,o=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await zi(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(i)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(at.CHANGE,r,e.stats)):(o.add(i),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(at.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,i,s,o,a){e=ye.join(e,"");let c=i?`${e}:${i}`:e;if(a=this.fsw._throttle("readdir",c,1e3),!a)return;let l=this.fsw._getWatchedDir(r.path),u=new Set,f=this.fsw._readdirp(e,{fileFilter:h=>r.filterPath(h),directoryFilter:h=>r.filterDir(h)});if(f)return f.on(Md,async h=>{if(this.fsw.closed){f=void 0;return}let p=h.path,m=ye.join(e,p);if(u.add(p),!(h.stats.isSymbolicLink()&&await this._handleSymlink(h,e,m,p))){if(this.fsw.closed){f=void 0;return}(p===i||!i&&!l.has(p))&&(this.fsw._incrReadyCount(),m=ye.join(s,ye.relative(s,m)),this._addToNodeFs(m,n,r,o+1))}}).on(at.ERROR,this._boundHandleError),new Promise((h,p)=>{if(!f)return p();f.once(Wi,()=>{if(this.fsw.closed){f=void 0;return}let m=a?a.clear():!1;h(void 0),l.getChildren().filter(w=>w!==e&&!u.has(w)).forEach(w=>{this.fsw._remove(e,w)}),f=void 0,m&&this._handleRead(e,!1,r,i,s,o,a)})})}async _handleDir(e,n,r,i,s,o,a){let c=this.fsw._getWatchedDir(ye.dirname(e)),l=c.has(ye.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!l&&this.fsw._emit(at.ADD_DIR,e,n),c.add(ye.basename(e)),this.fsw._getWatchedDir(e);let u,f,h=this.fsw.options.depth;if((h==null||i<=h)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,r,o,s,e,i,u),this.fsw.closed))return;f=this._watchWithNodeFs(e,(p,m)=>{m&&m.mtimeMs===0||this._handleRead(p,!1,o,s,e,i,u)})}return f}async _addToNodeFs(e,n,r,i,s){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e);r&&(a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await Fd[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let l=this.fsw.options.followSymlinks,u;if(c.isDirectory()){let f=ye.resolve(e),h=l?await zi(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,i,s,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(c.isSymbolicLink()){let f=l?await zi(e):e;if(this.fsw.closed)return;let h=ye.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(at.ADD,a.watchPath,c),u=await this._handleDir(h,c,n,i,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(ye.resolve(e),f)}else u=this._handleFile(a.watchPath,c,n);return o(),u&&this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};var Yi="/",Jd="//",Ia=".",Kd="..",Xd="string",Zd=/\\/g,Ra=/\/\//g,Qd=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,ef=/^\.[/\\]/;function Hr(t){return Array.isArray(t)?t:[t]}var Gi=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function tf(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 nf(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(Ra,"/"),e&&(t="/"+t),t}function Ca(t,e,n){let r=nf(e);for(let i=0;i<t.length;i++){let s=t[i];if(s(r,n))return!0}return!1}function rf(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Hr(t).map(i=>tf(i));return e==null?(i,s)=>Ca(r,i,s):Ca(r,e)}var Aa=t=>{let e=Hr(t).flat();if(!e.every(n=>typeof n===Xd))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Da)},xa=t=>{let e=t.replace(Zd,Yi),n=!1;return e.startsWith(Jd)&&(n=!0),e=e.replace(Ra,Yi),n&&(e=Yi+e),e},Da=t=>xa(ue.normalize(xa(t))),Ta=(t="")=>e=>typeof e=="string"?Da(ue.isAbsolute(e)?e:ue.join(t,e)):e,sf=(t,e)=>ue.isAbsolute(t)?t:ue.join(e,t),of=Object.freeze(new Set),Ji=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!==Ia&&e!==Kd&&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 Yd(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=Lr,this.items=of,Object.freeze(this)}},af="stat",cf="lstat",Ki=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let i=e;this.path=e=e.replace(ef,""),this.watchPath=i,this.fullWatchPath=ue.resolve(i),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?af:cf}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)}},zr=class extends Wd{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Hr(e.ignored):Hr([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};Ea&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let c=s.toLowerCase();c==="false"||c==="0"?i.usePolling=!1:c==="true"||c==="1"?i.usePolling=!0:i.usePolling=!!c}let o=process.env.CHOKIDAR_INTERVAL;o&&(i.interval=Number.parseInt(o,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Lr,this._readyEmitted=!0,process.nextTick(()=>this.emit(be.READY)))},this._emitRaw=(...c)=>this.emit(be.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new Fr(this),Object.freeze(i)}_addIgnoredPath(e){if(Gi(e)){for(let n of this._ignoredPaths)if(Gi(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)Gi(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let s=Aa(e);return i&&(s=s.map(o=>sf(o,i))),s.forEach(o=>{this._removeIgnoredPath(o)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async o=>{let a=await this._nodeFsHandler._addToNodeFs(o,!r,void 0,0,n);return a&&this._emitReady(),a})).then(o=>{this.closed||o.forEach(a=>{a&&this.add(ue.dirname(a),ue.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=Aa(e),{cwd:r}=this.options;return n.forEach(i=>{!ue.isAbsolute(i)&&!this._closers.has(i)&&(r&&(i=ue.join(r,i)),i=ue.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let i=r();i instanceof Promise&&e.push(i)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let s=(this.options.cwd?ue.relative(this.options.cwd,r):r)||Ia;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==be.ERROR&&this.emit(be.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let i=this.options;Vi&&(n=ue.normalize(n)),i.cwd&&(n=ue.relative(i.cwd,n));let s=[n];r!=null&&s.push(r);let o=i.awaitWriteFinish,a;if(o&&(a=this._pendingWrites.get(n)))return a.lastChange=new Date,this;if(i.atomic){if(e===be.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(be.ALL,...c),this._pendingUnlinks.delete(l)})},typeof i.atomic=="number"?i.atomic:100),this;e===be.ADD&&this._pendingUnlinks.has(n)&&(e=be.CHANGE,this._pendingUnlinks.delete(n))}if(o&&(e===be.ADD||e===be.CHANGE)&&this._readyEmitted){let c=(l,u)=>{l?(e=be.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,o.stabilityThreshold,e,c),this}if(e===be.CHANGE&&!this._throttle(be.CHANGE,n,50))return this;if(i.alwaysStat&&r===void 0&&(e===be.ADD||e===be.ADD_DIR||e===be.CHANGE)){let c=i.cwd?ue.join(i.cwd,n):n,l;try{l=await Gd(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(be.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let s=i.get(n);if(s)return s.count++,!1;let o,a=()=>{let l=i.get(n),u=l?l.count:0;return i.delete(n),clearTimeout(o),l&&clearTimeout(l.timeoutObject),u};o=setTimeout(a,r);let c={timeoutObject:o,clear:a,count:0};return i.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,i){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let o=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 f(h){Vd(c,(p,m)=>{if(p||!u.has(e)){p&&p.code!=="ENOENT"&&i(p);return}let w=Number(new Date);h&&m.size!==h.size&&(u.get(e).lastChange=w);let y=u.get(e);w-y.lastChange>=n?(u.delete(e),i(void 0,m)):a=setTimeout(f,o,m)})}u.has(e)||(u.set(e,{lastChange:l,cancelWait:()=>(u.delete(e),clearTimeout(a),r)}),a=setTimeout(f,o))}_isIgnored(e,n){if(this.options.atomic&&Qd.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(Ta(r)),a=[...[...this._ignoredPaths].map(Ta(r)),...s];this._userIgnored=rf(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Ki(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=ue.resolve(e);return this._watched.has(n)||this._watched.set(n,new Ji(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let i=ue.join(e,n),s=ue.resolve(i);if(r=r??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(i).getChildren().forEach(h=>this._remove(i,h));let c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=i;if(this.options.cwd&&(u=ue.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===be.ADD)return;this._watched.delete(i),this._watched.delete(s);let f=r?be.UNLINK_DIR:be.UNLINK;l&&!this._isIgnored(i)&&this._emit(f,i),this._closePath(i)}_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:be.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},i=wa(e,r);return this._streams.add(i),i.once(ka,()=>{i=void 0}),i.once(Wi,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function Xi(t,e={}){let n=new zr(e);return n.add(t),n}var Oa={watch:Xi,FSWatcher:zr};import{execFile as lf}from"node:child_process";import{stat as Ma}from"node:fs/promises";import{resolve as uf}from"node:path";import{promisify as df}from"node:util";function Gt(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 ln(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 Pa=df(lf);function ff(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 pf(t){if(process.platform!=="darwin")return;let{stdout:e}=await Pa("/bin/df",["-P",uf(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
2
+ `).slice(1).map(i=>i.trim().split(/\s+/)[0]).find(i=>/^\/dev\/disk\d+(?:s\d+)*$/.test(i));if(!n)return;let{stdout:r}=await Pa("/usr/sbin/diskutil",["info","-plist",n],{timeout:5e3,maxBuffer:256*1024});return ff(r)}async function Un(t,e=pf,n=process.platform){let r=await Ma(t);if(!r.isDirectory())throw Error("Sync root is not a directory");let i={dev:r.dev,ino:r.ino,...(n==="darwin"||n==="win32")&&r.birthtimeMs>0?{birthtimeMs:r.birthtimeMs}:{}},s=await e(t),o=await Ma(t);if(!o.isDirectory()||!ct(i,o))throw Error("Sync root changed while reading its identity");return{...i,...s?{volumeId:s}:{}}}var Zi;function Na(t){Zi=t}var ja={fs:gf,path:bf,directoryIdentity:Un,sha256Hex:t=>$a("sha256").update(t).digest("hex"),tmpTag:()=>process.pid,existsSync:hf,async compareAndReplace(t,e,n,r,i){if(!Zi)throw new Error("This host needs the shared content write lock for safe cloud downloads");let s=!1,o=Zi,a=()=>{if(!r())return;if(i){let l;try{l=wf(i.path)}catch(u){if(u.code==="ENOENT")return;throw u}if(!l.isDirectory()||!ct(i.identity,l))return}let c=null;try{c=$a("sha256").update(mf(e)).digest("hex")}catch(l){if(l.code!=="ENOENT")throw l}c===n&&(yf(t,e),s=!0)};for(let c=0;;c++)try{return await o(e,a),s}catch(l){let u=l.code;if(s||process.platform!=="win32"||c>=4||u!=="EPERM"&&u!=="EBUSY")throw l;await Sf(20*2**c)}},watch(t,e,n){let r=Oa.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 vf,lstatSync as ts,readFileSync as ns,writeFileSync as kf,realpathSync as Fa,opendirSync as Ef,openSync as _f,fstatSync as Cf,readSync as Af,closeSync as xf,constants as Qi}from"node:fs";import{join as Br,extname as La,sep as Tf}from"node:path";var rs=300,Ua=5*1024*1024,Ha=20*1024*1024,If=50*1024*1024,za=new Set(["node_modules"]),Rf=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Ba(t,e){let n=[],r=0,i=(s,o)=>{for(let a of vf(s)){if(a.startsWith("."))continue;let c=Br(s,a),l;try{l=ts(c)}catch{continue}if(l.isSymbolicLink())continue;let u=o?`${o}/${a}`:a;if(l.isDirectory()){za.has(a)||i(c,u);continue}if(!l.isFile()||a.endsWith(".d.ts"))continue;if(n.length>=rs)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${rs}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let f=La(a).toLowerCase(),h,p=e.mimeOf(f)??"application/octet-stream";if(Rf.has(f)){let m=e.transpile(ns(c,"utf8"),f,u);h=Buffer.from(m??"","utf8"),p="text/javascript"}else h=ns(c);if(h.length>Ua)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${u}`);if(r+=h.length,r>Ha)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:u,content_b64:h.toString("base64"),content_type:p,size:h.length})}};if(i(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 qa=".forsion-connect.json";function Wa(t){try{return JSON.parse(ns(Br(t,qa),"utf8"))}catch{return{}}}function Va(t,e){try{kf(Br(t,qa),JSON.stringify(e,null,2)+`
3
+ `,"utf8")}catch{}}var Df=new Set([".html",".htm",".js",".mjs",".cjs",".ts",".tsx",".jsx",".mts",".cts",".vue",".svelte"]),Of=400,Mf=5e3,es=2*1024*1024,Pf=12,$f=/\bforsion\.ai\.(chat|generateImage|agent|status)\b/g;function Ya(t){try{if(!ts(t).isDirectory())return null}catch{return null}let e=!1,n=new Set,r=0,i=0,s=null,o=c=>{let l;try{l=_f(c,Qi.O_RDONLY|(Qi.O_NOFOLLOW||0)|(Qi.O_NONBLOCK||0))}catch{return null}try{if(!Cf(l).isFile())return null;s??=Buffer.allocUnsafe(es+1);let u=0;for(;u<s.length;){let f=Af(l,s,u,s.length-u,null);if(f<=0)break;u+=f}return u>es?null:s.toString("utf8",0,u)}catch{return null}finally{try{xf(l)}catch{}}},a=(c,l)=>{let u;try{u=Ef(c)}catch{return}try{for(;;){if(r>=Of||i>=Mf)return;let f;try{f=u.readSync()}catch{return}if(!f)return;i++;let h=f.name;if(h.startsWith(".")||za.has(h))continue;let p=Br(c,h),m;try{m=ts(p)}catch{continue}if(m.isSymbolicLink())continue;if(m.isDirectory()){l<Pf&&a(p,l+1);continue}if(!m.isFile()||m.size>es||!Df.has(La(h).toLowerCase()))continue;r++;let w=o(p);if(w!==null){!e&&w.includes("forsion-connect.js")&&(e=!0);for(let y of w.matchAll($f))n.add(`forsion.ai.${y[1]}`)}}}finally{try{u.closeSync()}catch{}}};return a(t,0),{usesSdk:e,sdkMethods:[...n].sort()}}function Ga(t){let e=Wa(t),n=Ya(t);return n?{...e,...n}:e}function Ja(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 i="/__forsion/agent-events/";if(r.startsWith(i)){let s=r.slice(i.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,i)=>{let[s,o]=(r.url||"").split("?"),a=(m,w)=>{i.headersSent||(i.statusCode=m,i.setHeader("Content-Type","application/json")),i.end(JSON.stringify({detail:w}))},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 f;if(c.method==="POST"){let m=[],w=0;try{for await(let y of r){if(w+=y.length,w>If)return r.destroy(),a(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");m.push(y)}}catch(y){return a(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${y?.message||String(y)}`)}f=Buffer.concat(m)}if(c.agentRun){let m;try{m=JSON.parse((f||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return a(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}f=Buffer.from(JSON.stringify({session_id:typeof m.session_id=="string"?m.session_id:"",message:typeof m.message=="string"?m.message:"",app_id:"connect",agent_config:{}}))}let h=new AbortController,p=setTimeout(()=>h.abort(new Error("proxy timeout")),c.timeoutMs??3e5);r.on("close",()=>h.abort());try{let m=await fetch(l+c.path+(o?`?${o}`:""),{method:c.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...u?{Authorization:`Bearer ${u}`}:{}},body:f&&f.length?new Uint8Array(f):void 0,signal:h.signal});if(i.statusCode=m.status,i.setHeader("Content-Type",m.headers.get("content-type")||"application/json"),i.setHeader("Cache-Control","no-store"),m.body)for await(let w of m.body)i.write(w);i.end()}catch(m){let w=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${m?.message||String(m)}`;if(i.headersSent){try{i.write(`data: ${JSON.stringify({error:w})}
4
4
 
5
- `)}catch{}o.end()}else a(502,y)}finally{clearTimeout(h)}}}var za=`
5
+ `)}catch{}i.end()}else a(502,w)}finally{clearTimeout(p)}}}var Ka=`
6
6
  (function () {
7
7
  'use strict';
8
8
  if (window.forsion) return;
@@ -196,69 +196,69 @@ var Oo=null;function Yi(t){Oo=t}function ve(){if(!Oo)throw new Error("core host
196
196
  ai: { chat: chat, agent: agentRun, generateImage: generateImage, status: aiStatus }
197
197
  };
198
198
  })();
199
- `,Tf=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function If(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function Zo(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Qo(t){t.setPreviewHooks({sdkJs:za,proxy:Ha(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Ua(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 He(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=Ra(n.dir);let s=null;try{s=Ra(t.projectsRoot())}catch{}if(!(!!s&&(r===s||r.startsWith(s+Sf)))&&!If(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}=$a(r,Tf(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 He(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};Fa(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 He(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 He(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 He(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 He(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 Rf}from"node:crypto";import{hostname as Df}from"node:os";async function Nn(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 Ba=t=>`${t.seq}:${t.hash}`,jr=(t=Df())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},Of=t=>Rf("sha256").update(t).digest("hex");function es(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 Fr(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=jr(),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:Ba(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(Of(u)!==c.hash)throw new Error(`penzor hash mismatch: ${s}`);return u},async writeFile(s,i,a,c,l){let u=es(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:Ba(h)}},async rm(s,i,a){let c=es(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 Lr="forsion-diagnostics",Wa=50*1024*1024,qa=new Map;async function Mf(t,e){let n=qa.get(e);if(n)return{id:n};let r=await Nn(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?(qa.set(e,o),{id:o}):{error:"penzor-auth-unverified"}}var ts=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function ns(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===Lr)return{error:"penzor-bad-vault"};let s=await Mf(n.cloudUrl,n.token);if("error"in s)return s;let i=n.token;return{remote:Fr({baseUrl:n.cloudUrl,vault:o,getToken:()=>i}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${s.id}|${o}`,maxFileBytes:Wa}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as $f}from"node:fs";import{access as Nf,link as jf,lstat as Ff,mkdir as Lf,open as Uf,readdir as Hf,rename as zf,stat as Za,unlink as ss}from"node:fs/promises";import{request as Bf}from"node:http";import{request as qf}from"node:https";import{homedir as Wf}from"node:os";import{basename as Qa,extname as Vf,isAbsolute as Yf,join as Fn}from"node:path";import{randomUUID as Hr}from"node:crypto";var jn=52428800;var Va=["bytes","signed","text"],Ya=/^[A-Za-z0-9_-]{1,64}$/,Ga=/^[a-z0-9][a-z0-9-]{0,63}$/;function Ur(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 Pf={".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 Ja(t){let e=t.lastIndexOf(".");return Pf[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function Ka(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
199
+ `,Nf=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function jf(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function is(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function ss(t){t.setPreviewHooks({sdkJs:Ka,proxy:Ja(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Ga(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 qe(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=Fa(n.dir);let s=null;try{s=Fa(t.projectsRoot())}catch{}if(!(!!s&&(r===s||r.startsWith(s+Tf)))&&!jf(t,r))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let i=await t.getCloud();if(!i.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:s,totalBytes:o}=Ba(r,Nf(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 qe(i,"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};Va(r,{slug:String(c.slug)});let l=typeof c.publicUrl=="string"&&/^https?:\/\//i.test(c.publicUrl)?c.publicUrl:`${i.base}${c.url}`;return{ok:!0,slug:c.slug,handle:c.handle,url:l,totalBytes:o}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:unpublish",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await qe(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return i===401||i===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingApply",async(e,n)=>{if(!n||typeof n.slug!="string"||!n.slug||typeof n.summary!="string"||!n.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await qe(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200?{ok:!1,code:s?.code||"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0,status:s.status}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await qe(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await qe(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 Ff}from"node:crypto";import{hostname as Lf}from"node:os";async function Hn(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let r=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let i=await r.json();if(!i)return{status:"offline"};let s=i.avatar||i.avatarUrl||i.avatar_url||void 0;return s&&/^\/(?!\/)/.test(s)&&(s=n+s),{status:"ok",user:{username:i.username||i.nickname||void 0,nickname:i.nickname||void 0,avatar:s,membershipTier:i.membershipTier||i.membership_tier||void 0}}}catch{return{status:"offline"}}}var Xa=t=>`${t.seq}:${t.hash}`,qr=(t=Lf())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},Uf=t=>Ff("sha256").update(t).digest("hex");function os(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 Wr(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=qr(),i=async(s,o)=>{let a=t.getToken();if(!a)throw new Error("penzor-not-logged-in");let c=await fetch(s,{...o,headers:{...o.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 ${o.method??"GET"} ${c.status}: ${l.slice(0,200)}`)}return c};return{kind:"penzor",async walk(s){let o=await i(n("/manifest"),{method:"GET",signal:s}),{files:a}=await o.json();return a.map(c=>({key:c.path,size:c.size,mtimeMs:c.mtimeMs,id:Xa(c),hash:c.hash}))},async readFile(s,o){let c=await(await i(n(`/file?path=${encodeURIComponent(s)}`),{method:"GET",signal:o})).json(),l=await fetch(c.url,{signal:o});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${s}`);let u=Buffer.from(await l.arrayBuffer());if(Uf(u)!==c.hash)throw new Error(`penzor hash mismatch: ${s}`);return u},async writeFile(s,o,a,c,l){let u=os(l),f=new URLSearchParams({path:s,mtimeMs:String(Math.floor(a)||0)});u&&(f.set("baseSeq",String(u.baseSeq)),u.baseHash&&f.set("baseHash",u.baseHash));let p=await(await i(n(`/file?${f.toString()}`),{method:"PUT",body:new Uint8Array(o),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:c})).json();return{key:s,size:p.size,mtimeMs:p.mtimeMs,id:Xa(p)}},async rm(s,o,a){let c=os(a),l=new URLSearchParams({path:s});c&&c.baseSeq>0&&(l.set("baseSeq",String(c.baseSeq)),c.baseHash&&l.set("baseHash",c.baseHash)),await i(n(`/file?${l.toString()}`),{method:"DELETE",signal:o})},async check(){try{return await i(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var Vr="forsion-diagnostics",Qa=50*1024*1024,Za=new Map;async function Hf(t,e){let n=Za.get(e);if(n)return{id:n};let r=await Hn(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let i=r.user?.username?.trim();return i?(Za.set(e,i),{id:i}):{error:"penzor-auth-unverified"}}var as=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function cs(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,i=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(i)||i===Vr)return{error:"penzor-bad-vault"};let s=await Hf(n.cloudUrl,n.token);if("error"in s)return s;let o=n.token;return{remote:Wr({baseUrl:n.cloudUrl,vault:i,getToken:()=>o}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${s.id}|${i}`,maxFileBytes:Qa}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as Bf}from"node:fs";import{access as qf,link as Wf,lstat as Vf,mkdir as Yf,open as Gf,readdir as Jf,rename as Kf,stat as oc,unlink as ds}from"node:fs/promises";import{request as Xf}from"node:http";import{request as Zf}from"node:https";import{homedir as Qf}from"node:os";import{basename as ac,extname as ep,isAbsolute as tp,join as Bn}from"node:path";import{randomUUID as Gr}from"node:crypto";var zn=52428800;var ec=["bytes","signed","text"],tc=/^[A-Za-z0-9_-]{1,64}$/,nc=/^[a-z0-9][a-z0-9-]{0,63}$/;function Yr(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 zf={".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 rc(t){let e=t.lastIndexOf(".");return zf[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function ic(t,e,n,r){let i=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",s=encodeURIComponent(n).replace(/['()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),o="";for(let[a,c]of Object.entries(e))o+=`--${t}\r
200
200
  Content-Disposition: form-data; name="${a}"\r
201
201
  \r
202
202
  ${c}\r
203
- `;return i+=`--${t}\r
204
- Content-Disposition: form-data; name="file"; filename="${o}"; filename*=UTF-8''${s}\r
203
+ `;return o+=`--${t}\r
204
+ Content-Disposition: form-data; name="file"; filename="${i}"; filename*=UTF-8''${s}\r
205
205
  Content-Type: ${r}\r
206
206
  \r
207
- `,{head:i,tail:`\r
207
+ `,{head:o,tail:`\r
208
208
  --${t}--\r
209
- `}}function rs(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 os(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 Gf=3,is=6e4,Jf=200,Kf=Va;function ec(t,e,n,r){let{head:o,tail:s}=Ka(t,e,n,r);return{head:Buffer.from(o,"utf8"),tail:Buffer.from(s,"utf8")}}function Xf(t,e,n,r,o,s,i,a){return new Promise((c,l)=>{let u=new URL(t),d=(u.protocol==="https:"?qf:Bf)(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(is,()=>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 $f(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 as(t,e={}){let n=e.downloadsDir??(()=>Fn(Wf(),"Downloads")),r=e.post??Xf,o=e.now??Date.now,s=[],i=new Map,a=Promise.resolve(),c=async()=>{let w=await t.getCloud(),A=typeof t.accountId=="function"?t.accountId():null;return{...w,account:A||`${w.base}|${w.token}`}},l=w=>{let{account:A,attempt:C,relDir:D,abort:L,samples:j,dl:X,...K}=w;return{...K,speed:w.state==="active"?rs(j,o()):0}},u=(w,A,C=null)=>{w.state=A,w.error=C,w.abort=null,w.finishedAt=o(),w.samples=[];let D=s.filter(L=>L.state==="done"||L.state==="canceled");for(let L of D.slice(0,Math.max(0,D.length-Jf)))s.splice(s.indexOf(L),1);d()};function d(){for(let w of["up","down"]){let A=s.filter(C=>C.kind===w&&C.state==="active").length;for(let C of s){if(A>=Gf)break;if(C.kind!==w||C.state!=="queued")continue;A++,C.state="active",C.startedAt=o(),C.done=0,C.samples=[[o(),0]],C.abort=new AbortController;let D=++C.attempt,L=()=>C.attempt===D&&C.state==="active";(w==="up"?S(C,L):P(C,L)).catch(j=>{L()&&u(C,"failed",g(j))})}}}let g=w=>{let A=String(w?.message||w);return A==="changed"||A==="too_large"||A==="quota"||A==="account_changed"||A==="not_signed_in"||A.startsWith("http_")||A==="bad_response"||A==="gone"?A:"network"},h=(w,A)=>{w.done=A;let C=o(),D=w.samples[w.samples.length-1];for((!D||C-D[0]>=200)&&w.samples.push([C,A]);w.samples.length>2&&C-w.samples[0][0]>3500;)w.samples.shift()};async function m(w){let A=await c();if(A.account!==w.account)throw new Error("account_changed");if(!A.token)throw new Error("not_signed_in");return A}async function y(w,A,C,D){let L=kt(w,C);if(!L)throw new Error("bad_path");let j=await fetch(L,{method:D.method??"GET",headers:{Authorization:`Bearer ${A}`,...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:j.status,json:await j.json().catch(()=>null)}}function p(w,A,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 L=D,j=X=>{if(X===0)return Promise.resolve(w.targetId);let K=w.relDir.slice(0,X).join("/"),te=L.get(K);return te||(te=j(X-1).then(async ne=>{let Q=w.relDir[X-1],ee=await y(A,C,"/files",{method:"POST",body:{type:"directory",parentId:ne,name:Q},projectSource:w.projectSource});if(ee.status===201&&typeof ee.json?.id=="string")return ee.json.id;if(ee.status===409){let ge=await y(A,C,`/files${ne==="ROOT"?"":`?parentId=${encodeURIComponent(ne)}`}`,{projectSource:w.projectSource}),ue=Array.isArray(ge.json)?ge.json.find(Ee=>Ee?.fileType==="directory"&&Ee?.name===Q):null;if(ue?.id)return String(ue.id)}throw new Error(ee.status===401?"not_signed_in":`http_${ee.status}`)}),te.catch(()=>L.delete(K)),L.set(K,te)),te};return j(w.relDir.length)}async function S(w,A){let{base:C,token:D}=await m(w),L=await Za(w.localPath).catch(()=>null);if(!L?.isFile())throw new Error("gone");if(L.size>52428800)throw new Error("too_large");w.size=L.size;let j=await p(w,C,D);if(!A())return;w.parentId=j;let X=kt(C,"/files/upload");if(!X)throw new Error("bad_path");let K=`----penzor${Hr().replace(/-/g,"")}`,{head:te,tail:ne}=ec(K,{parentId:j,autoRename:"true"},w.name,Ja(w.name)),Q=await r(X,{Authorization:`Bearer ${D}`,"Content-Type":`multipart/form-data; boundary=${K}`,...w.projectSource?{"X-Project-Source":w.projectSource}:{}},te,w.localPath,L.size,ne,ee=>{A()&&h(w,ee)},w.abort.signal);A()&&(Q.status===201||Q.status===200?(w.fileId=typeof Q.body?.id=="string"?Q.body.id:null,h(w,w.size),u(w,"done")):u(w,"failed",os(Q.status,Q.body)))}function k(w,A,C,D){let L=async()=>{let X=Vf(C),K=X?C.slice(0,-X.length):C;for(let te=0;te<1e3;te++){if(!D())throw new Error("aborted");let ne=Fn(A,te===0?C:`${K} (${te})${X}`);try{await jf(w,ne)}catch(Q){let ee=Q.code;if(ee==="EEXIST")continue;if(ee!=="EPERM"&&ee!=="ENOTSUP"&&ee!=="EOPNOTSUPP"&&ee!=="ENOSYS"&&ee!=="EXDEV")throw Q;if(await Nf(ne).then(()=>!0,()=>!1))continue;await zf(w,ne)}if(!D())throw await ss(ne).catch(()=>{}),new Error("aborted");return await ss(w).catch(()=>{}),ne}throw new Error("too many duplicates")},j=a.then(L,L);return a=j.catch(()=>{}),j}async function P(w,A){let C=w.dl,{base:D,token:L}=await m(w);if(!A())return;let j=kt(D,C.path);if(!j)throw new Error("bad_path");let X=w.abort.signal,K=C.subdir?Fn(n(),C.subdir):n();await Lf(K,{recursive:!0});let te=Fn(K,`.${w.id}-${w.attempt}.penzor-part`),ne=await Uf(te,"wx"),Q=!1;try{let ee=new AbortController,ge=setTimeout(()=>ee.abort(),is),ue=()=>{clearTimeout(ge),ge=setTimeout(()=>ee.abort(),is)},Ee=AbortSignal.any([X,ee.signal]);try{let he=await fetch(j,{headers:{Authorization:`Bearer ${L}`},signal:Ee});if(!he.ok)throw new Error(he.status===401?"not_signed_in":`http_${he.status}`);let nt=he.body,rt=Number(he.headers.get("content-length"))||w.size;if(C.mode!=="bytes"){let ye=await he.json().catch(()=>null);if(C.mode==="text"){if(typeof ye?.content!="string")throw new Error("bad_response");let z=Buffer.from(ye.content,"utf8");await ne.writeFile(z),w.size=z.length,h(w,z.length),nt=null}else{if(typeof ye?.url!="string"||!/^https?:\/\//i.test(ye.url))throw new Error("bad_response");let z=await fetch(ye.url,{signal:Ee});if(!z.ok)throw new Error(`http_${z.status}`);nt=z.body,rt=Number(z.headers.get("content-length"))||w.size}}if(nt){w.size=rt;let ye=0;for await(let z of nt){ue();for(let G=0;G<z.length;){let{bytesWritten:_}=await ne.write(z,G,z.length-G);if(_<=0)throw new Error("short_write");G+=_}if(ye+=z.length,!A())throw new Error("aborted");h(w,ye)}ye>w.size&&(w.size=ye)}}finally{clearTimeout(ge)}if(await ne.close(),!A()||(w.localPath=await k(te,K,C.name,A),Q=!0,!A()))return;u(w,"done")}finally{Q||(await ne.close().catch(()=>{}),await ss(te).catch(()=>{}))}}let R=(w,A)=>{let C={...w,id:Hr(),attempt:0,done:0,state:A?"failed":"queued",error:A??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:A?o():null};return s.push(C),C};async function O(w){let A=[],C=async(D,L)=>{if(L.length>32)return!0;let j=await(L.length?Ff(D):Za(D)).catch(()=>null);if(!j)return!0;if(j.isFile())return A.push({path:D,size:j.size,relDir:L}),A.length<=2e3;if(!j.isDirectory())return!0;let X=(await Hf(D).catch(()=>[])).filter(K=>!K.startsWith(".")).sort();for(let K of X)if(!await C(Fn(D,K),[...L,Qa(D)]))return!1;return!0};for(let D of w)if(!await C(D,[]))return"too_many";return A}return t.handle("penzor:device",w=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let A=jr();return{ok:!0,name:A?decodeURIComponent(A):null}}),t.handle("penzor:upload",async(w,A)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=A??{},D=Array.isArray(C.paths)?C.paths.filter(ue=>typeof ue=="string"&&Yf(ue)):[],L=typeof C.parentId=="string"&&Ya.test(C.parentId)?C.parentId:null,j=typeof C.projectSource=="string"&&Ga.test(C.projectSource)?C.projectSource:null;if(!D.length)return{ok:!1,error:"no_files"};if(!L||!j)return{ok:!1,error:"bad_target"};let{base:X,token:K,account:te}=await c();if(!K)return{ok:!1,error:"not_signed_in"};let ne=await O(D);if(ne==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!ne.length)return{ok:!1,error:"no_files"};let Q=ne.filter(ue=>ue.size<=52428800).reduce((ue,Ee)=>ue+Ee.size,0);try{let ue=await y(X,K,"/storage/quota",{}),Ee=Number(ue.json?.used),he=Number(ue.json?.quota);if(ue.status===200&&he>0&&Ee+Q>he)return{ok:!1,error:"quota",short:Ee+Q-he}}catch{}if((await c()).account!==te)return{ok:!1,error:"account_changed"};let ee=Hr(),ge=ne.map(ue=>R({kind:"up",name:Qa(ue.path),size:ue.size,projectSource:j,parentId:ue.relDir.length?null:L,targetId:L,fileId:null,localPath:ue.path,batch:ee,account:te,relDir:ue.relDir},ue.size>52428800?"too_large":void 0).id);return d(),{ok:!0,ids:ge,batch:ee}}),t.handle("penzor:download",async(w,A)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=A??{},D=Kf.includes(C.mode)?C.mode:null,L=Ur(C.name);if(!D)return{ok:!1,error:"bad_mode"};if(!L)return{ok:!1,error:"bad_name"};let{base:j,token:X,account:K}=await c();if(typeof C.path!="string"||!kt(j,C.path))return{ok:!1,error:"bad_path"};if(!X)return{ok:!1,error:"not_signed_in"};let te=C.subdir==null?null:Ur(C.subdir),ne=R({kind:"down",name:L,size:Math.max(0,Number(C.size)||0),localPath:null,batch:typeof C.batch=="string"&&C.batch.length<=64?C.batch:Hr(),account:K,relDir:[],dl:{path:C.path,mode:D,name:L,subdir:te}});return d(),{ok:!0,id:ne.id}}),t.handle("penzor:transfers",w=>t.isTrustedSender(w)?{ok:!0,items:s.map(l)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(w,A)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=A??{},D=s.find(j=>j.id===C.id);if(!D)return{ok:!1,error:"not_found"};let L=()=>{D.abort?.abort(),D.abort=null,D.done=0,D.samples=[]};switch(C.op){case"pause":(D.state==="active"||D.state==="queued")&&(L(),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")&&(L(),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,A)=>{if(!t.isTrustedSender(w))return{ok:!1,error:"untrusted"};let C=A?.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 A=s.filter(C=>C.state==="active"||C.state==="queued"||C.state==="paused").length;return A?w==="zh"?{message:`\u8FD8\u6709 ${A} \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:A===1?"1 file hasn't finished transferring":`${A} 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 sp,writeFileSync as ip,mkdirSync as ap,chmodSync as cp,renameSync as lp}from"node:fs";import{join as up}from"node:path";import{mkdirSync as Zf,readFileSync as Qf,renameSync as ep,unlinkSync as tp,writeFileSync as np}from"node:fs";import{dirname as rp,join as op}from"node:path";import{randomUUID as tc}from"node:crypto";var ds=t=>op(t,"content-sync","active-account.json"),cs=()=>Error("Invalid content sync account binding; original data was retained");function Ln(t){try{let e=JSON.parse(Qf(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 cs();return e}catch(e){if(e?.code==="ENOENT")return null;throw cs()}}function fs(t,e){Zf(rp(t),{recursive:!0,mode:448});let n=t+".tmp-"+tc();try{np(n,JSON.stringify(e),{flag:"wx",mode:384}),ep(n,t)}finally{try{tp(n)}catch{}}}var ls=new WeakMap,us=new WeakSet;function nc(t,e){let n=ls.get(t);return n||ls.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function ps(t){if(us.has(t))throw cs()}function on(t,e,n){if(!t.contentSync||e===n)return;let r=ds(t.homeDir());try{let o=Ln(r);fs(r,{version:1,account:o?.account??null,epoch:tc(),pending:!0}),us.delete(t)}catch(o){throw us.add(t),o}finally{for(let o of ls.get(t)??[])o()}}function dp(t){let e=()=>up(t(),"auth-accounts.json");return{read:()=>sp(e(),"utf8"),write:n=>{ap(t(),{recursive:!0});let r=`${e()}.tmp`;ip(r,n,{encoding:"utf8",mode:384}),cp(r,384),lp(r,e())}}}var oc=t=>Zi(t,dp(()=>t.homeDir())),sc=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],hs=t=>sc.every(e=>typeof t[e]=="function");function gs(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=oc(t),o=0,s=()=>{let c=t.readCreds();return Dn(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 Nn(d,g):null,m=await t.accountBackendState(),{base:y}=await t.getCloud(),p=t.readCreds(),S=Dn(y,p.token)!==Dn(d,g),k=Dn(d,g);!S&&h?.status==="ok"&&h.user&&(a={key:k,user:h.user},r.rememberForsionAccount({...p,cloudUrl:d},h.user));let P=S?void 0:h?.status==="ok"?h.user:h?.status==="offline"&&a?.key===k?a.user:void 0;if(S)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 rc};try{await t.accountClear(O,()=>{on(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!==rc)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:P?.username||null,nickname:P?.nickname||null,avatar:P?.avatar||null,membershipTier:P?.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.")},()=>{on(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.")},()=>{on(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,()=>{on(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{on(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(!Ar(d))return;let{base:g}=await t.getCloud(),h=await xr(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 rc=Symbol("stale-auth-intent");import{promises as dn}from"node:fs";import Wt from"node:path";import{execFile as Hp}from"node:child_process";import zp from"node:os";var ms=null;function ic(t){ms=t}var ac=null;function cc(t){ac=t}var lc=()=>ac;function Be(){if(!ms)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return ms}var je=()=>Be().accountId();function Un(t=je()){return t?ve().sha256Hex(t):"signed-out"}var Ye=(t=je())=>Be().readConfig(t),Et=(t,e=je())=>Be().writeConfig(t,e),sn=(t,e=je())=>Be().updateConfig(t,e),Dt=(t=je())=>Be().cloudVaultDir(t),zr=t=>Be().isManagedCloudVault(t);function fp(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 uc(t,e){let n=fp(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 pp(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]})}uc(e,t).forEach(c=>o(c,"a")),uc(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 k=c.oStart,P=k+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(k,w[2]),w[3]=Math.max(P,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]),S={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(S)}i=u}return a(e.length),s}function dc(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=pp(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 Br(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 hp(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 gp(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 qr(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 fc(t,e,n){let r=dc(t.split(`
209
+ `}}function ls(t,e){let n=t.filter(([a])=>e-a<=3e3);if(n.length<2)return 0;let[r,i]=n[0],[s,o]=n[n.length-1];return s>r?Math.max(0,(o-i)/(s-r)*1e3):0}function us(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 np=3,fs=6e4,rp=200,ip=ec;function cc(t,e,n,r){let{head:i,tail:s}=ic(t,e,n,r);return{head:Buffer.from(i,"utf8"),tail:Buffer.from(s,"utf8")}}function sp(t,e,n,r,i,s,o,a){return new Promise((c,l)=>{let u=new URL(t),f=(u.protocol==="https:"?Zf:Xf)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+i+s.length)}},p=>{let m=[];p.on("data",w=>m.push(w)),p.on("end",()=>{let w=null;try{w=JSON.parse(Buffer.concat(m).toString("utf8"))}catch{}c({status:p.statusCode??0,body:w})}),p.on("error",l)}),h=()=>{f.destroy(new Error("aborted"))};if(a.aborted)return h();a.addEventListener("abort",h,{once:!0}),f.setTimeout(fs,()=>f.destroy(new Error("timeout"))),f.on("error",p=>{a.removeEventListener("abort",h),l(p)}),(async()=>{try{f.write(n);let p=0;for await(let m of Bf(r)){let w=m;if(p+=w.length,p>i)throw new Error("changed");f.write(w)||await new Promise(y=>f.once("drain",y)),o(p)}if(p!==i)throw new Error("changed");f.end(s)}catch(p){f.destroy(p)}})()})}function ps(t,e={}){let n=e.downloadsDir??(()=>Bn(Qf(),"Downloads")),r=e.post??sp,i=e.now??Date.now,s=[],o=new Map,a=Promise.resolve(),c=async()=>{let k=await t.getCloud(),A=typeof t.accountId=="function"?t.accountId():null;return{...k,account:A||`${k.base}|${k.token}`}},l=k=>{let{account:A,attempt:E,relDir:M,abort:W,samples:j,dl:B,...ie}=k;return{...ie,speed:k.state==="active"?ls(j,i()):0}},u=(k,A,E=null)=>{k.state=A,k.error=E,k.abort=null,k.finishedAt=i(),k.samples=[];let M=s.filter(W=>W.state==="done"||W.state==="canceled");for(let W of M.slice(0,Math.max(0,M.length-rp)))s.splice(s.indexOf(W),1);f()};function f(){for(let k of["up","down"]){let A=s.filter(E=>E.kind===k&&E.state==="active").length;for(let E of s){if(A>=np)break;if(E.kind!==k||E.state!=="queued")continue;A++,E.state="active",E.startedAt=i(),E.done=0,E.samples=[[i(),0]],E.abort=new AbortController;let M=++E.attempt,W=()=>E.attempt===M&&E.state==="active";(k==="up"?S(E,W):P(E,W)).catch(j=>{W()&&u(E,"failed",h(j))})}}}let h=k=>{let A=String(k?.message||k);return A==="changed"||A==="too_large"||A==="quota"||A==="account_changed"||A==="not_signed_in"||A.startsWith("http_")||A==="bad_response"||A==="gone"?A:"network"},p=(k,A)=>{k.done=A;let E=i(),M=k.samples[k.samples.length-1];for((!M||E-M[0]>=200)&&k.samples.push([E,A]);k.samples.length>2&&E-k.samples[0][0]>3500;)k.samples.shift()};async function m(k){let A=await c();if(A.account!==k.account)throw new Error("account_changed");if(!A.token)throw new Error("not_signed_in");return A}async function w(k,A,E,M){let W=_t(k,E);if(!W)throw new Error("bad_path");let j=await fetch(W,{method:M.method??"GET",headers:{Authorization:`Bearer ${A}`,...M.body!==void 0?{"Content-Type":"application/json"}:{},...M.projectSource?{"X-Project-Source":M.projectSource}:{}},body:M.body!==void 0?JSON.stringify(M.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:j.status,json:await j.json().catch(()=>null)}}function y(k,A,E){if(!k.relDir.length)return Promise.resolve(k.targetId);let M=o.get(k.batch);M||o.set(k.batch,M=new Map);let W=M,j=B=>{if(B===0)return Promise.resolve(k.targetId);let ie=k.relDir.slice(0,B).join("/"),se=W.get(ie);return se||(se=j(B-1).then(async X=>{let ee=k.relDir[B-1],ne=await w(A,E,"/files",{method:"POST",body:{type:"directory",parentId:X,name:ee},projectSource:k.projectSource});if(ne.status===201&&typeof ne.json?.id=="string")return ne.json.id;if(ne.status===409){let fe=await w(A,E,`/files${X==="ROOT"?"":`?parentId=${encodeURIComponent(X)}`}`,{projectSource:k.projectSource}),oe=Array.isArray(fe.json)?fe.json.find(Te=>Te?.fileType==="directory"&&Te?.name===ee):null;if(oe?.id)return String(oe.id)}throw new Error(ne.status===401?"not_signed_in":`http_${ne.status}`)}),se.catch(()=>W.delete(ie)),W.set(ie,se)),se};return j(k.relDir.length)}async function S(k,A){let{base:E,token:M}=await m(k),W=await oc(k.localPath).catch(()=>null);if(!W?.isFile())throw new Error("gone");if(W.size>52428800)throw new Error("too_large");k.size=W.size;let j=await y(k,E,M);if(!A())return;k.parentId=j;let B=_t(E,"/files/upload");if(!B)throw new Error("bad_path");let ie=`----penzor${Gr().replace(/-/g,"")}`,{head:se,tail:X}=cc(ie,{parentId:j,autoRename:"true"},k.name,rc(k.name)),ee=await r(B,{Authorization:`Bearer ${M}`,"Content-Type":`multipart/form-data; boundary=${ie}`,...k.projectSource?{"X-Project-Source":k.projectSource}:{}},se,k.localPath,W.size,X,ne=>{A()&&p(k,ne)},k.abort.signal);A()&&(ee.status===201||ee.status===200?(k.fileId=typeof ee.body?.id=="string"?ee.body.id:null,p(k,k.size),u(k,"done")):u(k,"failed",us(ee.status,ee.body)))}function g(k,A,E,M){let W=async()=>{let B=ep(E),ie=B?E.slice(0,-B.length):E;for(let se=0;se<1e3;se++){if(!M())throw new Error("aborted");let X=Bn(A,se===0?E:`${ie} (${se})${B}`);try{await Wf(k,X)}catch(ee){let ne=ee.code;if(ne==="EEXIST")continue;if(ne!=="EPERM"&&ne!=="ENOTSUP"&&ne!=="EOPNOTSUPP"&&ne!=="ENOSYS"&&ne!=="EXDEV")throw ee;if(await qf(X).then(()=>!0,()=>!1))continue;await Kf(k,X)}if(!M())throw await ds(X).catch(()=>{}),new Error("aborted");return await ds(k).catch(()=>{}),X}throw new Error("too many duplicates")},j=a.then(W,W);return a=j.catch(()=>{}),j}async function P(k,A){let E=k.dl,{base:M,token:W}=await m(k);if(!A())return;let j=_t(M,E.path);if(!j)throw new Error("bad_path");let B=k.abort.signal,ie=E.subdir?Bn(n(),E.subdir):n();await Yf(ie,{recursive:!0});let se=Bn(ie,`.${k.id}-${k.attempt}.penzor-part`),X=await Gf(se,"wx"),ee=!1;try{let ne=new AbortController,fe=setTimeout(()=>ne.abort(),fs),oe=()=>{clearTimeout(fe),fe=setTimeout(()=>ne.abort(),fs)},Te=AbortSignal.any([B,ne.signal]);try{let we=await fetch(j,{headers:{Authorization:`Bearer ${W}`},signal:Te});if(!we.ok)throw new Error(we.status===401?"not_signed_in":`http_${we.status}`);let Je=we.body,Be=Number(we.headers.get("content-length"))||k.size;if(E.mode!=="bytes"){let Oe=await we.json().catch(()=>null);if(E.mode==="text"){if(typeof Oe?.content!="string")throw new Error("bad_response");let q=Buffer.from(Oe.content,"utf8");await X.writeFile(q),k.size=q.length,p(k,q.length),Je=null}else{if(typeof Oe?.url!="string"||!/^https?:\/\//i.test(Oe.url))throw new Error("bad_response");let q=await fetch(Oe.url,{signal:Te});if(!q.ok)throw new Error(`http_${q.status}`);Je=q.body,Be=Number(q.headers.get("content-length"))||k.size}}if(Je){k.size=Be;let Oe=0;for await(let q of Je){oe();for(let J=0;J<q.length;){let{bytesWritten:C}=await X.write(q,J,q.length-J);if(C<=0)throw new Error("short_write");J+=C}if(Oe+=q.length,!A())throw new Error("aborted");p(k,Oe)}Oe>k.size&&(k.size=Oe)}}finally{clearTimeout(fe)}if(await X.close(),!A()||(k.localPath=await g(se,ie,E.name,A),ee=!0,!A()))return;u(k,"done")}finally{ee||(await X.close().catch(()=>{}),await ds(se).catch(()=>{}))}}let x=(k,A)=>{let E={...k,id:Gr(),attempt:0,done:0,state:A?"failed":"queued",error:A??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:A?i():null};return s.push(E),E};async function D(k){let A=[],E=async(M,W)=>{if(W.length>32)return!0;let j=await(W.length?Vf(M):oc(M)).catch(()=>null);if(!j)return!0;if(j.isFile())return A.push({path:M,size:j.size,relDir:W}),A.length<=2e3;if(!j.isDirectory())return!0;let B=(await Jf(M).catch(()=>[])).filter(ie=>!ie.startsWith(".")).sort();for(let ie of B)if(!await E(Bn(M,ie),[...W,ac(M)]))return!1;return!0};for(let M of k)if(!await E(M,[]))return"too_many";return A}return t.handle("penzor:device",k=>{if(!t.isTrustedSender(k))return{ok:!1,error:"untrusted"};let A=qr();return{ok:!0,name:A?decodeURIComponent(A):null}}),t.handle("penzor:upload",async(k,A)=>{if(!t.isTrustedSender(k))return{ok:!1,error:"untrusted"};let E=A??{},M=Array.isArray(E.paths)?E.paths.filter(oe=>typeof oe=="string"&&tp(oe)):[],W=typeof E.parentId=="string"&&tc.test(E.parentId)?E.parentId:null,j=typeof E.projectSource=="string"&&nc.test(E.projectSource)?E.projectSource:null;if(!M.length)return{ok:!1,error:"no_files"};if(!W||!j)return{ok:!1,error:"bad_target"};let{base:B,token:ie,account:se}=await c();if(!ie)return{ok:!1,error:"not_signed_in"};let X=await D(M);if(X==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!X.length)return{ok:!1,error:"no_files"};let ee=X.filter(oe=>oe.size<=52428800).reduce((oe,Te)=>oe+Te.size,0);try{let oe=await w(B,ie,"/storage/quota",{}),Te=Number(oe.json?.used),we=Number(oe.json?.quota);if(oe.status===200&&we>0&&Te+ee>we)return{ok:!1,error:"quota",short:Te+ee-we}}catch{}if((await c()).account!==se)return{ok:!1,error:"account_changed"};let ne=Gr(),fe=X.map(oe=>x({kind:"up",name:ac(oe.path),size:oe.size,projectSource:j,parentId:oe.relDir.length?null:W,targetId:W,fileId:null,localPath:oe.path,batch:ne,account:se,relDir:oe.relDir},oe.size>52428800?"too_large":void 0).id);return f(),{ok:!0,ids:fe,batch:ne}}),t.handle("penzor:download",async(k,A)=>{if(!t.isTrustedSender(k))return{ok:!1,error:"untrusted"};let E=A??{},M=ip.includes(E.mode)?E.mode:null,W=Yr(E.name);if(!M)return{ok:!1,error:"bad_mode"};if(!W)return{ok:!1,error:"bad_name"};let{base:j,token:B,account:ie}=await c();if(typeof E.path!="string"||!_t(j,E.path))return{ok:!1,error:"bad_path"};if(!B)return{ok:!1,error:"not_signed_in"};let se=E.subdir==null?null:Yr(E.subdir),X=x({kind:"down",name:W,size:Math.max(0,Number(E.size)||0),localPath:null,batch:typeof E.batch=="string"&&E.batch.length<=64?E.batch:Gr(),account:ie,relDir:[],dl:{path:E.path,mode:M,name:W,subdir:se}});return f(),{ok:!0,id:X.id}}),t.handle("penzor:transfers",k=>t.isTrustedSender(k)?{ok:!0,items:s.map(l)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(k,A)=>{if(!t.isTrustedSender(k))return{ok:!1,error:"untrusted"};let E=A??{},M=s.find(j=>j.id===E.id);if(!M)return{ok:!1,error:"not_found"};let W=()=>{M.abort?.abort(),M.abort=null,M.done=0,M.samples=[]};switch(E.op){case"pause":(M.state==="active"||M.state==="queued")&&(W(),M.state="paused",f());break;case"resume":M.state==="paused"&&(M.state="queued",f());break;case"cancel":(M.state==="active"||M.state==="queued"||M.state==="paused")&&(W(),u(M,"canceled"));break;case"retry":(M.state==="failed"||M.state==="canceled")&&(M.state="queued",M.error=null,M.finishedAt=null,M.done=0,f());break;case"dismiss":M.state!=="active"&&M.state!=="queued"&&s.splice(s.indexOf(M),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(k,A)=>{if(!t.isTrustedSender(k))return{ok:!1,error:"untrusted"};let E=A?.which==="all";for(let M of[...s])(M.state==="done"||M.state==="canceled"||E&&M.state==="failed")&&s.splice(s.indexOf(M),1);return{ok:!0}}),t.addQuitGuard?.(k=>{let A=s.filter(E=>E.state==="active"||E.state==="queued"||E.state==="paused").length;return A?k==="zh"?{message:`\u8FD8\u6709 ${A} \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:A===1?"1 file hasn't finished transferring":`${A} 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 pp,writeFileSync as hp,mkdirSync as gp,chmodSync as mp,renameSync as yp}from"node:fs";import{join as wp}from"node:path";import{mkdirSync as op,readFileSync as ap,renameSync as cp,unlinkSync as lp,writeFileSync as up}from"node:fs";import{dirname as dp,join as fp}from"node:path";import{randomUUID as lc}from"node:crypto";var ys=t=>fp(t,"content-sync","active-account.json"),hs=()=>Error("Invalid content sync account binding; original data was retained");function qn(t){try{let e=JSON.parse(ap(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 hs();return e}catch(e){if(e?.code==="ENOENT")return null;throw hs()}}function ws(t,e){op(dp(t),{recursive:!0,mode:448});let n=t+".tmp-"+lc();try{up(n,JSON.stringify(e),{flag:"wx",mode:384}),cp(n,t)}finally{try{lp(n)}catch{}}}var gs=new WeakMap,ms=new WeakSet;function uc(t,e){let n=gs.get(t);return n||gs.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function bs(t){if(ms.has(t))throw hs()}function un(t,e,n){if(!t.contentSync||e===n)return;let r=ys(t.homeDir());try{let i=qn(r);ws(r,{version:1,account:i?.account??null,epoch:lc(),pending:!0}),ms.delete(t)}catch(i){throw ms.add(t),i}finally{for(let i of gs.get(t)??[])i()}}function bp(t){let e=()=>wp(t(),"auth-accounts.json");return{read:()=>pp(e(),"utf8"),write:n=>{gp(t(),{recursive:!0});let r=`${e()}.tmp`;hp(r,n,{encoding:"utf8",mode:384}),mp(r,384),yp(r,e())}}}var fc=t=>aa(t,bp(()=>t.homeDir())),pc=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],Ss=t=>pc.every(e=>typeof t[e]=="function");function vs(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=fc(t),i=0,s=()=>{let c=t.readCreds();return Nn(c.cloudUrl,c.token)},o=c=>Fe(c.cloudUrl??"",c.token??""),a=null;t.handle("auth:status",async c=>{if(!t.isTrustedSender(c))return n;let l=i,u=s(),{base:f}=await t.getCloud(),h=t.readCreds().token,p=h?await Hn(f,h):null,m=await t.accountBackendState(),{base:w}=await t.getCloud(),y=t.readCreds(),S=Nn(w,y.token)!==Nn(f,h),g=Nn(f,h);!S&&p?.status==="ok"&&p.user&&(a={key:g,user:p.user},r.rememberForsionAccount({...y,cloudUrl:f},p.user));let P=S?void 0:p?.status==="ok"?p.user:p?.status==="offline"&&a?.key===g?a.user:void 0;if(S)return{loggedIn:!!y.token,tokenValid:null,cloudUrl:w,accountId:Fe(w,y.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:y.token?"tangu-login":null,backendState:m};if(p?.status==="expired"){await t.accountTransition(async()=>{if(l!==i||s()!==u)return;let D=()=>{if(l!==i||s()!==u)throw dc};try{await t.accountClear(D,()=>{un(t,t.accountId?.()??null,null),t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++i,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),a=null})}catch(k){if(k!==dc)throw k}});let x=t.readCreds();return{loggedIn:!!x.token,tokenValid:null,cloudUrl:x.cloudUrl||f,accountId:Fe(x.cloudUrl||f,x.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:x.token?"tangu-login":null,backendState:m}}return{loggedIn:!!h,tokenValid:p&&p.status==="ok"?!0:null,cloudUrl:f,accountId:Fe(f,h),username:P?.username||null,nickname:P?.nickname||null,avatar:P?.avatar||null,membershipTier:P?.membershipTier||null,tokenSource:h?"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=++i;return r.cancelForsionLogin(),t.accountTransition(async()=>{let f=r.savedForsionAccount(l);return await t.accountCommit(f,()=>{if(u!==i)throw new Error("Account switch cancelled.")},()=>{un(t,t.accountId?.()??null,o(f)),r.rememberForsionAccount(f),a=null}),{ok:!0,cloudUrl:f.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(c,l)=>{if(!t.isTrustedSender(c))return e;let u=++i;r.cancelForsionLogin();let{base:f}=await t.getCloud();if(u!==i)throw new Error("Sign-in cancelled.");let h=(l||f||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(h,m=>t.broadcast("auth:device",m),(m,w)=>t.accountTransition(()=>t.accountCommit(m,()=>{if(w(),u!==i)throw new Error("Sign-in cancelled.")},()=>{un(t,t.accountId?.()??null,o(m)),r.rememberForsionAccount(m),a=null})))).cloudUrl}}),t.handle("auth:logout",async c=>t.isTrustedSender(c)?(++i,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:l}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{un(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{un(t,o(c),o(l))}catch{t.log("[content-sync] account transition could not be recorded; sync is stopped")}++i,r.cancelForsionLogin(),c.token&&!l.token&&r.forgetForsionAccount(c),a=null,r.rememberForsionAccount(l)}),t.setTokenRefresher(async c=>{let l=i,u=s(),f=t.readCreds().token;if(!Mr(f))return;let{base:h}=await t.getCloud(),p=await Pr(h,f,c,`desktop/${t.appVersion()}`);if(!p){t.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}l!==i||s()!==u||(r.rememberForsionAccount({cloudUrl:h,token:p}),t.writeCreds({cloudUrl:h,token:p}),t.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),t.log("[forsion-extend] account core registered")}var dc=Symbol("stale-auth-intent");import{promises as gn}from"node:fs";import Kt from"node:path";import{execFile as Jp}from"node:child_process";import Kp from"node:os";var ks=null;function hc(t){ks=t}var gc=null;function mc(t){gc=t}var yc=()=>gc;function Le(){if(!ks)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return ks}var Pe=()=>Le().accountId();function Wn(t=Pe()){return t?ve().sha256Hex(t):"signed-out"}var Ze=(t=Pe())=>Le().readConfig(t),Ct=(t,e=Pe())=>Le().writeConfig(t,e),dn=(t,e=Pe())=>Le().updateConfig(t,e),At=(t=Pe())=>Le().cloudVaultDir(t),Jr=t=>Le().isManagedCloudVault(t);function Sp(t,e){let n=Object.create(null);for(let s=0;s<e.length;s++){let o=e[s];n[o]?n[o].push(s):n[o]=[s]}let i=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let s=0;s<t.length;s++){let o=t[s],a=n[o]||[],c=0,l=i[0];for(let u of a){let f;for(f=c;f<i.length&&!(i[f].buffer2index<u&&(f===i.length-1||i[f+1].buffer2index>u));f++);if(f<i.length){let h={buffer1index:s,buffer2index:u,chain:i[f]};if(c===i.length?i.push(l):i[c]=l,c=f+1,l=h,c===i.length)break}}i[c]=l}return i[i.length-1]}function wc(t,e){let n=Sp(t,e),r=[],i=t.length,s=e.length;for(let o=n;o!==null;o=o.chain){let a=i-o.buffer1index-1,c=s-o.buffer2index-1;i=o.buffer1index,s=o.buffer2index,(a||c)&&r.push({buffer1:[i+1,a],buffer1Content:t.slice(i+1,i+1+a),buffer2:[s+1,c],buffer2Content:e.slice(s+1,s+1+c)})}return r.reverse(),r}function vp(t,e,n){let r=[];function i(c,l){r.push({ab:l,oStart:c.buffer1[0],oLength:c.buffer1[1],abStart:c.buffer2[0],abLength:c.buffer2[1]})}wc(e,t).forEach(c=>i(c,"a")),wc(e,n).forEach(c=>i(c,"b")),r.sort((c,l)=>c.oStart-l.oStart);let s=[],o=0;function a(c){c>o&&(s.push({stable:!0,buffer:"o",bufferStart:o,bufferLength:c-o,bufferContent:e.slice(o,c)}),o=c)}for(;r.length;){let c=r.shift(),l=c.oStart,u=c.oStart+c.oLength,f=[c];for(a(l);r.length;){let h=r[0],p=h.oStart;if(p>u)break;u=Math.max(u,p+h.oLength),f.push(r.shift())}if(f.length===1){if(c.abLength>0){let h=c.ab==="a"?t:n;s.push({stable:!0,buffer:c.ab,bufferStart:c.abStart,bufferLength:c.abLength,bufferContent:h.slice(c.abStart,c.abStart+c.abLength)})}}else{let h={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;f.length;){c=f.shift();let g=c.oStart,P=g+c.oLength,x=c.abStart,D=x+c.abLength,k=h[c.ab];k[0]=Math.min(x,k[0]),k[1]=Math.max(D,k[1]),k[2]=Math.min(g,k[2]),k[3]=Math.max(P,k[3])}let p=h.a[0]+(l-h.a[2]),m=h.a[1]+(u-h.a[3]),w=h.b[0]+(l-h.b[2]),y=h.b[1]+(u-h.b[3]),S={stable:!1,aStart:p,aLength:m-p,aContent:t.slice(p,m),oStart:l,oLength:u-l,oContent:e.slice(l,u),bStart:w,bLength:y-w,bContent:n.slice(w,y)};s.push(S)}o=u}return a(e.length),s}function bc(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=[],o=vp(t,e,n),a=[];function c(){a.length&&s.push({ok:a}),a=[]}function l(u,f){if(u.length!==f.length)return!1;for(let h=0;h<u.length;h++)if(u[h]!==f[h])return!1;return!0}return o.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 Kr(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),i=n<0?t:t.slice(n+1),s=i.lastIndexOf("."),o=s>0?i.slice(0,s):i,a=s>0?i.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}${o} (conflict ${l})${a}`}function kp(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),i=r?t.slice(0,n):t,s=r?t.slice(n):"";return`${i}-${e}${s}`}function Ep(t){let e=3735928559,n=1103547991;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=Math.imul(e^s,2654435761),n=Math.imul(n^s,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let r=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${r.toString(36)}`}function Xr(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,i=n.seq!==e.seq;return!r&&!i?{kind:"none"}:r?i?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function Sc(t,e,n){let r=bc(t.split(`
210
210
  `),e.split(`
211
211
  `),n.split(`
212
- `),{excludeFalseConflicts:!0}),o=[];for(let s of r){if(s.conflict)return null;s.ok&&o.push(...s.ok)}return o.join(`
213
- `)}function ys(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var pc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function hc(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function gc(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 Wr(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 Vr(t){let e=null;return{error(n){n!==e&&(e=n,t?.(n))},ok(){e=null}}}var mp=/[\u0000-\u001f\u007f]/;function Ot(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||mp.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function ws(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Ot(n):n.startsWith(`${e}/`)?Ot(n.slice(e.length+1)):null}function mc(t,e){return e===""?t:`${e}/${t}`}function Hn(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Fe(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var Ze=t=>t==="page"||t==="db";var yp=1024,Te=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},yc=t=>12e4+Math.ceil(t/256);function wp(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 wc(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>=yp&&(l["Content-Encoding"]="gzip",u=await Ki(u))):c?.form&&(u=c.form);let d=await r(a,{method:i,headers:l,body:u,signal:wp(c?.timeoutMs??3e4,c?.signal)});if(!d.ok){let h=null;try{h=await d.json()}catch{}throw n(),new Te(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:yc(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 Te(g.redirected&&(g.status===401||g.status===403)?502:g.status,null,"asset:"+a);clearTimeout(d),d=setTimeout(u,yc(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 bc(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
- `),S=h||"message";h="",m=[];let k=null;try{k=p?JSON.parse(p):null}catch{return}S==="hello"?e.onHello(Number(k?.seq??0)):S==="change"?e.onChange(k):S==="reset"?e.onReset():S==="presence"?e.onPresence?.(k):S==="presence-roster"&&e.onPresenceRoster?.(k)};try{for(;;){let{done:p,value:S}=await u.read();if(p)break;for(g+=d.decode(S,{stream:!0});;){let k=g.indexOf(`
215
- `);if(k<0)break;let P=g.slice(0,k).replace(/\r$/,"");if(g=g.slice(k+1),P==="")y();else{if(P.startsWith(":"))continue;P.startsWith("event:")?h=P.slice(6).trim():P.startsWith("data:")&&m.push(P.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 qt=t=>ve().path.join(Be().userDataDir(),Be().isDevMode()?`${t}.dev.json`:`${t}.json`),bs=qt,an=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Yr=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Gr=t=>typeof t=="string"&&Ot(t)===t,Sc=t=>typeof t=="string"&&t.length>0,bp=t=>an(t)&&Yr(t.seq)&&Sc(t.hash)&&Yr(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),Sp=t=>an(t)&&Gr(t.from)&&Gr(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||an(t.hashes)&&Object.values(t.hashes).every(Sc));async function Ss(t){let e;try{e=await ve().fs.readFile(bs(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(!an(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Bt(n.rootIdentity)||!an(n.files)||!Object.entries(n.files).every(([r,o])=>Gr(r)&&bp(o))||n.cursor!==void 0&&!Yr(n.cursor)||n.lastSyncAt!=null&&!Yr(n.lastSyncAt)||n.pending!==void 0&&(!an(n.pending)||!Object.entries(n.pending).every(([r,o])=>Gr(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 vc(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=bs(t),l=`${c}.tmp-${ve().tmpTag()}-${Date.now()}-0`;await ve().fs.writeFile(l,a,"utf8"),await ve().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 kc(t){try{await ve().fs.unlink(bs(t))}catch{}}var zn=/^[0-9a-f]{64}$/;function Ec(t){let e=ve(),n=()=>qt(t).replace(/\.json$/,".bases"),r=a=>e.path.join(n(),a),o=a=>e.fs.access(r(a)).then(()=>!0,()=>!1),s=new Map,i=(a,c)=>{let l=(s.get(a)??Promise.resolve()).then(c,c);return s.set(a,l),l.finally(()=>{s.get(a)===l&&s.delete(a)}),l};return{put(a,c){return zn.test(a)?i(a,async()=>{try{if(await o(a))return;await e.fs.mkdir(n(),{recursive:!0});let l=`${r(a)}.tmp-${e.tmpTag()}-${Date.now()}`;await e.fs.writeFile(l,c,"utf8"),await e.fs.rename(l,r(a))}catch{}}):Promise.resolve()},async get(a){if(!zn.test(a))return null;try{let c=await e.fs.readFile(r(a),"utf8");return e.sha256Hex(c)===a?c:null}catch{return null}},drop(a,c){return zn.test(a)?i(a,async()=>{if(!(c&&!c()))try{await e.fs.rm(r(a),{force:!0})}catch{}}):Promise.resolve()},async has(a){return zn.test(a)&&o(a)},async prune(a){let c;try{c=(await e.fs.readdir(n(),{withFileTypes:!0})).filter(l=>l.isFile()).map(l=>l.name)}catch{return}for(let l of c)if(!a.has(l)&&!(!zn.test(l)&&!/^[0-9a-f]{64}\.tmp-/.test(l)))try{await e.fs.rm(e.path.join(n(),l),{force:!0})}catch{}}}}var vp=5*1024*1024,kp=5*1024*1024,Ep=3e4,_p=5e3,Cp=5*6e4,Ap=2500,xp=3e3,Tp=5,Ip=256*1024,Rp=5,Jr=1024*1024,_c=200,Dp=6e4,Op=50,Mp=".sync-trash",_t=t=>ve().sha256Hex(t);function Bn(t,e={localRoot:Dt(),shadowName:`amadeus-sync-${Un()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=f=>{let b=ws(f,"");if(!b)return null;for(let E of e.excludePrefixes??[])if(b===E.replace(/\/$/,"")||b.startsWith(E))return null;if(e.ignoreNames?.length&&b.split("/").some(E=>e.ignoreNames.includes(E)))return null;let v=e.serverDir?`${e.serverDir}/${b}`:b;return e.inScope&&!e.inScope(v,Fe(v))?null:v},r=f=>{let b;if(e.serverDir){if(!f.startsWith(`${e.serverDir}/`))return null;b=f.slice(e.serverDir.length+1)}else{for(let v of e.excludePrefixes??[])if(f.startsWith(v))return null;b=f}return b.split("/").some(v=>Hn(v)||!!e.ignoreNames?.includes(v))?null:b},o=(f,b)=>!e.inScope||e.inScope(f,b),s=e.accountId??je(),{fs:i,path:a,directoryIdentity:c}=ve(),l=f=>i.access(f).then(()=>!0,()=>!1),u=!1,d=0,g=Promise.resolve(),h=new Set,m="disabled",y=null,p=null,S=null,k=null,P=null,R=null,O=()=>{let f=t.loadCreds();if(!R||s!==je()||!f.token||f.cloudUrl?.replace(/\/+$/,"")!==R.cloudUrl.replace(/\/+$/,""))throw new Te(401,{code:"ACCOUNT_CHANGED"},"sync-session");return f.token},w=null,A=0,C=new Map,D=null,L=vc(e.shadowName),j=Ec(e.shadowName),X=!1,K=new Map,te=!1,ne=!1,Q=[],ee=(f,b,v)=>{try{t.onHealth?.(f,b,v)}catch{}},ge=Vr(ee),ue=0,Ee=()=>{ne||ee("massDeleteGuard"),ne=!0},he=()=>{p&&(p.pending=K.size?Object.fromEntries(K):void 0,L.save(p))},nt=()=>{ne=!1,Q.length=0},rt=()=>{if(ne)return!0;let f=Date.now();for(;Q.length&&f-Q[0]>Dp;)Q.shift();return Q.length>=Op?(Ee(),!0):!1},ye=[],z=new Set,G=!1,_=null,x=null,T=null,I=null,M=()=>{!u||I||(I=setTimeout(()=>{I=null,t.onStatus(Ht())},200))},H=(f,b)=>{let v=m;m=f,b!==void 0&&(y=b),W(v,f),M()},W=(f,b)=>{if(b==="syncing"&&f!=="syncing"&&(ue=Date.now()),b==="idle"&&f==="syncing"&&(ee("cycles"),ee("cycleMsTotal",Math.max(0,Date.now()-ue))),b==="idle"||b==="disabled"){ge.ok();return}let v=gc(b,y);v&&ge.error(v)},B=(f,b)=>{C.set(f,b),ee(hc(b),1,f)},q=(f,b=!1)=>{if(u){if(f.key){if(z.has(f.key))return;z.add(f.key)}b?ye.unshift(f):ye.push(f),be()}},J=new Map,Z=f=>{if(!u)return;let b=(p?.files[f]?.size??0)>Ip,v=(e.pushQuietMs??xp)*(b?Rp:1),E=Date.now(),$=J.get(f);$&&clearTimeout($.timer);let F=$?.since??E,V=Math.max(0,Math.min(v,F+v*Tp-E)),N=setTimeout(()=>{J.delete(f),q({key:f,run:()=>xe(f,!0)})},V);J.set(f,{timer:N,since:F}),M()},re=()=>{for(let{timer:f}of J.values())clearTimeout(f);J.clear()},de=f=>!(f instanceof Te)||f.status>=500||f.status===0,we=f=>f instanceof Te&&(f.status===401||f.status===403),_e=(f,b)=>{B(f,b?.body?.code||`http ${b?.status}`),M()},be=async()=>{if(!G){G=!0;try{for(;ye.length;){(m==="idle"||m==="starting")&&H("syncing");let f=ye.shift();f.key&&z.delete(f.key);try{await f.run()}catch(b){if(!u)return;if(we(b)){ye.length=0,z.clear(),vr(),H("auth-required","login-expired");return}if(de(b)){q(f,!0),vr(),H("offline",b?.message||"network error"),$e();return}_e(f.key??"(op)",b)}}u&&m==="syncing"&&(p&&(p.lastSyncAt=Date.now(),L.save(p)),H("idle",null))}finally{G=!1;for(let f of h)f();h.clear()}}},$e=()=>{!u||_||(_=setTimeout(()=>{_=null,In()},Ep))},fe=new Map,ot=0,pe=null,xo=()=>!!x||!!pe||!u,Ai=f=>f instanceof Te&&f.status>=500||f?.name==="TimeoutError",xi=e.pushRetryMs??_p,xn=(f,b)=>{(b||!fe.has(f))&&fe.set(f,b)},Ti=(f,b,v)=>{B(f,b instanceof Te?`http ${b.status}`:"timeout"),xn(f,v),ot=Math.min(ot*2||xi,Cp),x=setTimeout(hr,ot),M()},Ii=(f,b,v)=>{let E=new AbortController,$=b(E.signal).then(V=>()=>V,V=>()=>{throw V}),F={path:f,abort:E,after:[],settle:async()=>{let V=await $;if(pe===F){pe=null;try{await v(V)}catch(N){if(we(N)||de(N))throw N;_e(f,N)}finally{for(let N of F.after)q(N);Ri(f)}}}};pe=F,$.then(()=>q({run:F.settle}))},Zt=(f,b)=>{for(let[v,E]of[...fe])!E||!qe(v,f)||(fe.delete(v),C.delete(v),b!==null&&fe.set(b+v.slice(f.length),E));M()},hr=()=>{x=null;let[f]=fe;if(f===void 0)return;let[b]=f;z.delete(b),q({key:b,run:async()=>{if(pe?.path===b)return;let v=fe.get(b),E=!v&&fe.delete(b);(v||E)&&C.delete(b);try{v?await ut(b,v.seq):E&&await xe(b,!0)}finally{E&&We(b)&&xn(b),Ri(b)}}})},Ri=f=>{if(!xo())if(fe.has(f)){let b=fe.get(f);fe.delete(f),fe.set(f,b),x=setTimeout(hr,ot||xi)}else hr()},Oe=f=>{if(!w||!p)throw new Error("engine not bound");let b=r(f);if(b===null)throw new Error("path outside binding: "+f);let v=a.resolve(w,mc(b,p.folder)),E=a.relative(w,v);if(E.startsWith("..")||a.isAbsolute(E))throw new Error("path escapes vault: "+f);return v},gr=f=>({size:f,mtimeMs:-1}),Di=async f=>{try{let b=await i.stat(f);return b.isFile()?{size:b.size,mtimeMs:Math.floor(b.mtimeMs)}:null}catch{return null}},Wu=async f=>{if(!i.lstat||!w)return Di(f);let b=a.relative(w,f).split(a.sep),v=w;for(let[E,$]of b.entries()){v=a.join(v,$);let F=await i.lstat(v).catch(V=>{if(V?.code==="ENOENT")return null;throw V});if(!F)return null;if(F.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(E===b.length-1&&F.isFile())return{size:F.size,mtimeMs:Math.floor(F.mtimeMs)};if(E===b.length-1||!F.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},Vu=0,Oi=async(f,b,v,E)=>{if(!await st())throw Error("Cloud vault sync root is unavailable or changed");let $=w&&S?{path:w,identity:S}:void 0;await i.mkdir(a.dirname(f),{recursive:!0});let F=`${f}.tmp-${ve().tmpTag()}-${Date.now()}-${Vu++}`;await i.writeFile(F,b);let V=await Di(F)??gr(_r(b));try{if(!E())return null;let N=ve().compareAndReplace;if(!N)throw new Error("Host does not support safe cloud download commits");let Y=await N(F,f,v,E,$);if(!Y&&!await st())throw Error("Cloud vault sync root is unavailable or changed");return Y?V:null}finally{await st()&&await i.rm(F,{force:!0})}},Mi=async f=>{let b;try{b=await i.readdir(f,{withFileTypes:!0})}catch{return}for(let v of b)v.isDirectory()&&await Mi(a.join(f,v.name));try{await i.rmdir(f)}catch{}},lt=async f=>{let b=Oe(f),v=await Wu(b);if(!await st())throw Error("Cloud vault sync root is unavailable or changed");if(i.lstat&&!v)return null;let E;try{E=await i.readFile(b)}catch(F){if(F?.code!=="ENOENT")throw F;if(!await st())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:Ze(Fe(f))?_t(vt(E)):_t(E),size:v?.size??E.length,mtimeMs:v?.mtimeMs??-1,buf:E}},Rt=async(f,b,v,E,$)=>{if(!p)return;let F=p.files[f]?.hash;p.files[f]={seq:b,hash:v,size:E.size,mtimeMs:E.mtimeMs},L.save(p),$!==void 0&&await Pi(f,v,$),F&&F!==v&&await $i(F)},Pi=async(f,b,v)=>{if(!Ze(Fe(f))||_r(v)>Jr)return;let E=typeof v=="string"?v:vt(v);_t(E)===b&&await j.put(b,E)},$i=async f=>{let b=()=>!!p&&!Object.values(p.files).some(v=>v.hash===f);b()&&await j.drop(f,b)},Ke=f=>{if(p&&f in p.files){let b=p.files[f].hash;delete p.files[f],L.save(p),$i(b)}},ut=async(f,b)=>{if(!k||!p||We(f))return;let v=Ce,E=Fe(f);if(Ze(E)){let N;try{N=await k.getFile(p.vaultId,f),ee("downloads")}catch(Y){if(Y instanceof Te&&Y.status===404){await To(f);return}throw Y}await Ni(f,E,N.content,N.seq,N.hash??_t(N.content),v);return}if(xo()){xn(f,{seq:b}),M();return}let{vaultId:$}=p,F=k,V={seq:b};fe.set(f,V),Ii(f,N=>F.getAsset($,f,N),async N=>{let Y=fe.get(f)===V,U;try{U=N(),ot=0,ee("downloads")}catch(oe){if(!Y)return;if(fe.delete(f),oe instanceof Te&&oe.status===404){B(f,"ASSET_404"),M();return}if(Ai(oe)){Ti(f,oe,{seq:b});return}throw oe}Y&&await Ni(f,E,U,b??0,_t(U),v)}),M()},Ni=async(f,b,v,E,$,F)=>{if(!p)return;let V=async ce=>{await Rt(f,E,$,ce,v),fe.get(f)&&(fe.delete(f),C.delete(f))},N=await lt(f);if(F!==Ce||We(f))return;if(N&&N.hash===$){await V(N);return}let Y=p.files[f];if(N&&Y&&$===Y.hash&&N.hash!==Y.hash){await V(gr(Y.size)),q({key:f,run:()=>xe(f)});return}let U=N?_t(N.buf):null;if(N&&(!Y||N.hash!==Y.hash)){if(Y&&Ze(b)&&typeof v=="string"&&await Yu(f,Y,N,v,E,$,()=>F===Ce&&!We(f))||F!==Ce||We(f)||!await Gu(f,()=>F===Ce&&!We(f)))return;U=null}let oe=await Oi(Oe(f),v,U,()=>u&&F===Ce&&!We(f));if(!oe){q({key:f,run:()=>xe(f)});return}await V(oe)},Yu=async(f,b,v,E,$,F,V)=>{try{if(!k||!p||v.buf.length>Jr||E.length>Jr)return!1;let N=await j.get(b.hash);if(N===null){let ce=(await k.listVersions(p.vaultId,f)).find(Xe=>Xe.seq===b.seq);if(!ce)return!1;let Ie=await k.getVersion(p.vaultId,ce.id);if(_t(Ie)!==b.hash)return!1;N=Ie}let Y=vt(v.buf),U;if(Fe(f)==="db"){let oe=lc(),ce=oe?oe(f,Y,N,E):null;U=ce&&!ce.conflict?ce.content:null}else U=fc(Y,N,E);return U===null?!1:await Oi(Oe(f),U,_t(v.buf),()=>u&&V())?(await Rt(f,$,F,gr(_r(U)),E),q({key:f,run:()=>xe(f)}),!0):(q({key:f,run:()=>xe(f)}),!0)}catch{return!1}},Gu=async(f,b)=>{let v=Ot(Br(f,new Date));if(!v)return!0;let E=v.lastIndexOf("."),$=E>v.lastIndexOf("/"),F=$?v.slice(0,E):v,V=$?v.slice(E):"",N=v,Y=ve().existsSync;if(Y)for(let U=2;Y(Oe(N));U++)N=`${F}-${U}${V}`;else for(let U=2;await l(Oe(N));U++)N=`${F}-${U}${V}`;if(!b())return!1;try{await i.rename(Oe(f),Oe(N))}catch(U){if(U?.code==="ENOENT")return!0;throw U}return A++,ee("conflicts"),q({key:N,run:()=>xe(N)}),M(),!0},ji=async f=>{if(!w)return;let b=Oe(f),v=r(f)??f,E=a.join(w,Mp,new Date().toISOString().slice(0,10),...v.split("/")),$=await l(E)?`${E}.${Date.now()}`:E;try{await i.mkdir(a.dirname($),{recursive:!0}),await i.rename(b,$)}catch(F){if(F?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${b}: ${F?.message??String(F)}`)}},To=async f=>{if(!p)return;Zt(f,null);let b=await lt(f);if(We(f))return;let v=p.files[f]??null,E=qr(b?.hash??null,v,null);if(E.kind==="deleteLocal"){if(!te&&rt()){K.set(f,"local"),he(),M();return}Q.push(Date.now()),await ji(f),Ke(f)}else E.kind==="pushCreate"?(Ke(f),q({key:f,run:()=>xe(f)})):Ke(f)},Fi=(f,b)=>{if(p){Zt(f,b);for(let v of Object.keys(p.files))if(v===f||v.startsWith(`${f}/`)){let E=b+v.slice(f.length);p.files[E]=p.files[v],delete p.files[v]}L.save(p)}},Li=async f=>{if(!k||!p||f.seq<=p.cursor||!await st())return;if(f.origin.client&&k.clientId===f.origin.client){p.cursor=f.seq,L.save(p);return}let b=f.type==="structure"?"folder":f.type,v=$=>r($)!==null&&o($,b);if(!v(f.path)&&!(f.newPath&&v(f.newPath))){p.cursor=f.seq,L.save(p);return}let E=f.path;if(f.op!=="write"&&f.op!=="mkdir"){for(;pe&&(qe(pe.path,E)||f.newPath&&qe(pe.path,f.newPath));)await pe.settle();if(!u)return}switch(f.op){case"write":await ut(E,f.fileSeq);break;case"delete":await To(E);break;case"move":{let $=f.newPath;if(!$)break;let F=p.files[E],V=await lt(E),N=!!fe.get(E);if(Zt(E,$),N&&xn($,{seq:f.fileSeq}),V&&F)try{await i.mkdir(a.dirname(Oe($)),{recursive:!0}),await i.rename(Oe(E),Oe($)),p.files[$]={...F,seq:N?F.seq:f.fileSeq??F.seq},delete p.files[E],L.save(p)}catch{await ut($,f.fileSeq)}else Ke(E),await ut($,f.fileSeq);break}case"mkdir":await i.mkdir(Oe(E),{recursive:!0});break;case"rename-folder":case"move-folder":{let $=f.newPath;if(!$)break;try{await i.mkdir(a.dirname(Oe($)),{recursive:!0}),await i.rename(Oe(E),Oe($))}catch{}Fi(E,$);break}case"delete-folder":{let $=`${E}/`;for(let F of Object.keys(p.files))(F===E||F.startsWith($))&&await To(F);Zt(E,null),await Mi(Oe(E));break}}if(p.cursor=f.seq,L.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{}},Ju=async(f,b,v)=>{let E=Number(b?.seq??0),$=b?.content??null;if($!==null&&_t($)===v.hash){await Rt(f,E,v.hash,v,$);return}if($===null&&E===0){if(!p?.files[f]){B(f,b?.code||"EXISTS"),M();return}Ke(f),q({key:f,run:()=>xe(f)});return}await ut(f,E)},mr=async(f,b)=>{if(!k||!p)return;let v=await lt(f);if(!v){q({key:f,run:()=>xe(f)});return}if(v.size>vp){B(f,"TOO_LARGE"),M();return}let E=vt(v.buf);try{let $=await k.putFile(p.vaultId,f,E,b);ee("uploads"),C.delete(f),await Rt(f,$.seq,$.hash??v.hash,v,v.buf)}catch($){if($ instanceof Te&&$.status===409){await Ju(f,$.body,v);return}throw $}},yr=async(f,b)=>{if(!k||!p)return;let v=await lt(f);if(!v){q({key:f,run:()=>xe(f)});return}if(v.size>(D??kp)){B(f,"TOO_LARGE"),M();return}if(xn(f),M(),xo())return;let{vaultId:E}=p,$=k;Ii(f,F=>$.putBinary(E,f,v.buf,{baseSeq:b,signal:F}),async F=>{if(p){fe.get(f)||fe.delete(f);try{let V=F();ot=0,ee("uploads"),C.delete(f),await Rt(f,V.seq,v.hash,v)}catch(V){if(Ai(V)){Ti(f,V);return}if(!(V instanceof Te)||V.status!==409)throw V;let N=Number(V.body?.seq??0),Y=V.body?.hash??null;if(Y!==null&&Y===v.hash){await Rt(f,N,v.hash,v);return}if(N===0){if(!p.files[f]){B(f,V.body?.code||"EXISTS"),M();return}Ke(f),q({key:f,run:()=>xe(f)});return}await ut(f,N)}}})},Ui=async f=>{if(!k||!p||We(f))return;let b=Ce,v=p.files[f];if(v){if(Ze(Fe(f)))try{let E=await k.getFile(p.vaultId,f);if(E.seq!==v.seq){await ut(f,E.seq);return}}catch(E){if(E instanceof Te&&E.status===404){Ke(f);return}throw E}if(!(!await st()||b!==Ce||We(f))){try{await k.deleteFile(p.vaultId,f,v.seq,{confirmed:te})}catch(E){if(E instanceof Te&&E.status===409){await ut(f,Number(E.body?.seq??0)||null);return}if(E instanceof Te&&E.status===429&&E.body?.code==="MASS_DELETE_BLOCKED"){K.set(f,"remote"),Ee(),he(),M();return}throw E}Ke(f)}}},Io=f=>i.stat(f).catch(b=>{if(b?.code==="ENOENT")return null;throw b}),Ro=f=>{let b=S??p?.rootIdentity,v=f!==null&&f.isDirectory();return v&&(!b||ft(b,f))?!0:(H("error",`${v?"vault-changed":"vault-missing"}: ${w}`),$e(),!1)},st=async()=>!!w&&Ro(await Io(w)),Ce=0,wr=new Set,br=new Map,ze=f=>JSON.stringify([f.from,f.to]),qe=(f,b)=>f===b||f.startsWith(`${b}/`),We=f=>[...p?.moves??[],...wr].some(b=>qe(f,b.from)||qe(f,b.to)),St=()=>!!(p?.moves?.length||wr.size),Sr=async f=>{if(!k||!p)return;let{from:b,to:v,kind:E}=f;if(r(b)===null||r(v)===null)throw new Error("Invalid queued cloud move");if(pe&&(qe(pe.path,b)||qe(pe.path,v))){pe.after.push({key:`move:${ze(f)}`,run:()=>Sr(f)});return}f.hashes??=Object.fromEntries(Object.entries(p.files).filter(([N])=>qe(N,b)).map(([N,Y])=>[N.slice(b.length),Y.hash])),L.save(p),await L.flush(!0);let $,F=!1;try{if(E==="folder"){let N=a.posix.dirname(b)==="."?"":a.posix.dirname(b),Y=a.posix.dirname(v)==="."?"":a.posix.dirname(v);N===Y?await k.renameFolder(p.vaultId,b,a.posix.basename(v)):await k.moveFolder(p.vaultId,b,Y)}else{let N=await k.move(p.vaultId,b,v);$=Number(N.seq)}}catch(N){if(!(N instanceof Te)||N.status!==404)throw N;let Y=await k.tree(p.vaultId);if(Y.entries.some(ce=>qe(ce.path,b))||Y.folders.some(ce=>qe(ce,b)))throw N;let oe=Y.entries.find(ce=>ce.path===v);if($=oe?.seq,F=!oe&&!Y.entries.some(ce=>qe(ce.path,v))&&!Y.folders.some(ce=>qe(ce,v)),!F){let ce=Object.entries(f.hashes);if(!(ce.length>0&&ce.every(([Xe,dt])=>Y.entries.some(en=>en.path===v+Xe&&en.hash===dt))))throw new Te(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(F){for(let N of Object.keys(p.files))qe(N,b)&&delete p.files[N];Zt(b,null)}else Fi(b,v),$!==void 0&&p.files[v]&&!fe.get(v)&&(p.files[v].seq=$);p.moves=(p.moves??[]).filter(N=>ze(N)!==ze(f)),L.save(p);try{await L.flush(!0)}catch(N){throw p.moves.unshift(f),L.save(p),N}let V=br.get(ze(f));br.delete(ze(f)),V?.(),We(v)||(E==="folder"?await Do():await xe(v))},xe=async(f,b=!1)=>{if(!p||We(f))return;if(pe?.path===f){pe.after.push({key:f,run:()=>xe(f,b)});return}if(!o(f,Fe(f))){Ke(f);return}if(!await st())return;let v=await lt(f);if(We(f))return;let E=p.files[f]??null,$=qr(v?.hash??null,E,E?{seq:E.seq,hash:E.hash}:null);switch($.kind){case"push":Ze(Fe(f))?await mr(f,$.baseSeq):await yr(f,$.baseSeq);break;case"pushCreate":Ze(Fe(f))?await mr(f,0):await yr(f,0);break;case"pushDelete":if(b){Er();break}if(!te&&(K.has(f)||rt())){K.set(f,"remote"),he(),M();break}Q.push(Date.now()),await Ui(f);break;case"dropShadow":Ke(f);break;default:v&&E&&v.hash===E.hash&&v.mtimeMs>=0&&(E.size!==v.size||E.mtimeMs!==v.mtimeMs)&&await Rt(f,E.seq,E.hash,v,v.buf);break}},Hi=async()=>{let f=new Map;if(!w||!p)return f;let b=w,v=null,E=async $=>{if(v)return;let F;try{F=await i.readdir($,{withFileTypes:!0})}catch(V){v=`${$}: ${V?.message??String(V)}`;return}for(let V of F){if(Hn(V.name)||V.isDirectory()&&e.ignoreNames?.includes(V.name))continue;let N=a.join($,V.name);if(V.isDirectory())await E(N);else if(V.isFile()){let Y=a.relative(b,N).split(a.sep).join("/"),U=n(Y);if(!U)continue;try{let oe=await i.stat(N);if(!oe.isFile())continue;f.set(U,{size:oe.size,mtimeMs:Math.floor(oe.mtimeMs)})}catch(oe){if(oe?.code==="ENOENT")continue;v=`${N}: ${oe?.message??String(oe)}`;return}}}};return await E(b),v?(H("error",`scan-failed: ${v}`),$e(),null):f},Do=async()=>{let f=Ce;if(St()||f!==Ce||!p||!await st())return;let b=await Hi();if(!b||St()||f!==Ce)return;let v=!1;for(let[F,V]of[...K])(V==="remote"&&b.has(F)||V==="local"&&!b.has(F))&&(K.delete(F),v=!0);K.size||nt();for(let[F,V]of b){let N=p.files[F];N&&N.size===V.size&&N.mtimeMs===V.mtimeMs||q({key:F,run:()=>xe(F)})}let E=Object.keys(p.files),$=E.filter(F=>!b.has(F));if($.length&&!te&&(ne||ys($.length,E.length,_c))){Ee();for(let F of $)K.set(F,"remote");he(),M();return}v&&(he(),M());for(let F of $)K.has(F)||q({key:F,run:()=>xe(F)})},Ku=async f=>{if(!p)return;let b=new Set;for(let[v,E]of Object.entries(p.files)){if(!Ze(Fe(v))||E.size>Jr)continue;b.add(E.hash);let $=f.get(v);if(!(!$||$.size!==E.size||$.mtimeMs!==E.mtimeMs||await j.has(E.hash)))try{let F=await lt(v);F&&F.hash===E.hash&&await Pi(v,E.hash,F.buf)}catch{}}await j.prune(b)},Qt=async()=>{if(pe){pe.after.push({run:Qt});return}let f=Ce;if(St()||f!==Ce||!k||!p||!w||!await st())return;let b=await k.tree(p.vaultId);if(b.maxFileBytes!==void 0&&b.maxFileBytes!==D&&(D=b.maxFileBytes,M()),St()||f!==Ce)return;let v=new Map;for(let U of b.entries)r(U.path)===null||!o(U.path,U.kind)||v.set(U.path,U);for(let[U,oe]of[...fe])oe&&!v.has(U)&&Zt(U,null);let E=await Hi();if(!E||St()||f!==Ce)return;X||(X=!0,await Ku(E));let $=new Set([...v.keys(),...E.keys(),...Object.keys(p.files)]),F=Object.keys(p.files).length,V=[];for(let U of $){if(St()||f!==Ce)return;let oe=p.files[U]??null,ce=v.get(U)??null,Ie=E.get(U)??null,Xe=null,dt=gr(Ie?.size??0);if(Ie)if(oe&&oe.size===Ie.size&&oe.mtimeMs===Ie.mtimeMs)Xe=oe.hash,dt=Ie;else{let en=await lt(U);en&&(Xe=en.hash,dt=en)}V.push({sp:U,d:qr(Xe,oe,ce?{seq:ce.seq,hash:ce.hash}:null),rSeq:ce?.seq??null,localHash:Xe,localStat:dt})}if(St()||f!==Ce)return;let N=V.filter(U=>U.d.kind==="deleteLocal"||U.d.kind==="pushDelete").length,Y=!te&&(ne||ys(N,F,_c));Y&&N&&Ee(),K.clear();for(let{sp:U,d:oe,rSeq:ce,localHash:Ie,localStat:Xe}of V){if(St()||f!==Ce)return;if(Y&&(oe.kind==="deleteLocal"||oe.kind==="pushDelete")){K.set(U,oe.kind==="deleteLocal"?"local":"remote");continue}if((oe.kind==="deleteLocal"||oe.kind==="pushDelete")&&((await lt(U))?.hash??null)!==Ie){q({key:U,run:()=>xe(U)});continue}if(St()||f!==Ce)return;switch(oe.kind){case"adopt":{let dt=Ze(Fe(U))?await lt(U):null;await Rt(U,ce,Ie,Xe,dt&&dt.hash===Ie?dt.buf:void 0);break}case"pull":await ut(U,ce);break;case"push":Ze(Fe(U))?await mr(U,oe.baseSeq):await yr(U,oe.baseSeq);break;case"pushCreate":Ze(Fe(U))?await mr(U,0):await yr(U,0);break;case"pushDelete":await Ui(U);break;case"deleteLocal":await ji(U),Ke(U);break;case"conflict":await ut(U,ce);break;case"dropShadow":Ke(U);break;case"none":break}}te&&(te=!1,Q.length=0),K.size||nt(),he(),Y&&M();for(let U of b.folders)if(!(r(U)===null||!o(U,"folder")))try{await i.mkdir(Oe(U),{recursive:!0})}catch{}p.cursor=b.seq,p.lastSyncAt=Date.now(),L.save(p)},Xu=async()=>{if(!k||!p)return;let f=p.cursor,b=await k.changes(p.vaultId,f);if(b.changes.length===0&&b.seq>f||b.changes.length>0&&b.changes[0].seq!==f+1){await Qt();return}for(let E of b.changes)await Li(E)},Tn=null,zi=[],Bi=()=>{Tn&&zi.push(Tn.close()),Tn=null},Zu=()=>{if(!u||Tn||!w)return;let f=ve();if(!f.watch)return;let b=v=>{if(!w)return;let E=a.relative(w,v);if(!E||E.startsWith(".."))return;let $=n(E);$&&Z($)};Tn=f.watch(w,{depth:12,ignored:v=>{let E=a.basename(v);return Hn(E)||!!e.ignoreNames?.includes(E)}},{change:b,add:b,unlink:()=>Er(),unlinkDir:()=>Er()})},vr=()=>{P?.stop(),P=null},Qu=()=>{if(!u||!k||!p||P)return;let f=R;f&&(P=bc({baseUrl:f.cloudUrl,vaultId:p.vaultId,token:f.token,getToken:O},{getSince:()=>p?.cursor??0,onHello:b=>{p&&b>p.cursor&&q({run:Xu})},onChange:b=>{q({run:()=>Li(b)})},onReset:()=>{q({run:Qt})},onOpen:()=>{(m==="offline"||m==="starting")&&H("idle",null),q({run:Do})},onDown:()=>{(m==="idle"||m==="syncing")&&H("offline")},onPresence:b=>t.onPresence?.(p?.vaultId??"",b),onPresenceRoster:b=>t.onPresenceRoster?.(p?.vaultId??"",b)}))},ed=async()=>{let f=await Ye(s);if(f.cloudSync?.deviceId)return f.cloudSync.deviceId;let b=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Et({cloudSync:{...f.cloudSync??{},deviceId:b}},s),b},td=async f=>{vr(),Bi(),S=null,ye.length=0,z.clear(),K.clear(),te=!1,ne=!1,Q.length=0;let b=await Ye(s);if(f!==d)return;let v=b.cloudSync;if(v?.enabled===!1){w=null,k=null,H("disabled",null);return}if(!s||s!==je()){H("auth-required","not-logged-in");return}if(w=e.localRoot,e.requireRootExists){let V=await i.stat(w).then(N=>N.isDirectory()).catch(()=>!1);if(f!==d)return;if(!V){H("error",`vault-missing: ${w}`),$e();return}}if(f!==d)return;let E=t.loadCreds();if(!E.cloudUrl||!E.token){k=null,H("auth-required","not-logged-in");return}H("starting",null);let $=v?.deviceId??await ed();if(f!==d)return;let F=e.clientIdSuffix?`${$}#${e.clientIdSuffix}`:$;R={cloudUrl:E.cloudUrl,token:E.token},k=wc({baseUrl:E.cloudUrl,token:E.token,clientId:F,getToken:()=>{if(f!==d)throw new Te(401,{code:"ACCOUNT_CHANGED"},"sync-session");return O()}});try{let V=e.vaultId==="first"?v?.vaultId:e.vaultId;if(!V){let U=await k.listVaults();if(f!==d)return;if(!U.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");V=U[0].id,await Et({cloudSync:{...v??{},vaultId:V}},s)}if(f!==d)return;let N=await Ss(e.shadowName);if(f!==d||(p=N&&N.vaultRoot===w&&N.vaultId===V&&N.folder===""?N:{vaultRoot:w,folder:"",vaultId:V,cursor:0,lastSyncAt:null,files:{}},f!==d))return;for(let[U,oe]of Object.entries(p.pending??{}))K.set(U,oe);K.size&&(ne=!0);let Y=await Io(w);if(f!==d||!Y&&!e.requireRootExists&&!p.rootIdentity&&!Object.keys(p.files).length&&(await i.mkdir(w,{recursive:!0}),Y=await Io(w),f!==d))return;if(!Y?.isDirectory()){Ro(Y);return}if(typeof Y.dev=="number"&&Number.isInteger(Y.dev)&&Y.dev>=0&&typeof Y.ino=="number"&&Number.isInteger(Y.ino)&&Y.ino>0){let U=c?await c(w):{dev:Y.dev,ino:Y.ino,...Y.birthtimeMs&&Y.birthtimeMs>0?{birthtimeMs:Y.birthtimeMs}:{}};if(f!==d)return;if(!Bt(U))throw Error("Invalid sync root identity; original state retained");if(!ft(U,Y)||p.rootIdentity&&!rn(p.rootIdentity,U)){H("error",`vault-changed: ${w}`),$e();return}if(S=U,JSON.stringify(p.rootIdentity)!==JSON.stringify(U)&&(p.rootIdentity=U,L.save(p),await L.flush(!0)),f!==d||!await st())return}else if(!Ro(Y))return;Zu();for(let U of p.moves??[])q({key:`move:${ze(U)}`,run:()=>Sr(U)});q({run:Qt}),q({run:async()=>{Qu()}})}catch(V){if(f!==d)return;we(V)?H("auth-required","login-expired"):(H("offline",V?.message||String(V)),$e())}},qi=()=>{u=!1,vr(),Bi(),ye.length=0,z.clear(),re();for(let f of[_,x,T,I])f&&clearTimeout(f);_=x=T=I=null,pe?.abort.abort(),pe=null},Wi=async()=>{G&&await new Promise(f=>h.add(f)),await Promise.all(zi.splice(0)),await L.flush(),p=null,S=null,k=null,R=null,w=null,A=0,C.clear(),fe.clear(),ot=0,D=null,K.clear(),te=!1,ne=!1,Q.length=0,m="disabled",y=null},nd=()=>{Vi()},kr=null,In=()=>{X=!1,kr?.(),kr=Be().onBeforeQuit(nd);let f=++d;qi();let b=g.catch(()=>{}).then(async()=>{await Wi(),f===d&&(u=!0,await td(f))});return g=b,b},Vi=()=>{kr?.(),kr=null,++d,qi();let f=g.catch(()=>{}).then(Wi);return g=f,f},Ht=()=>({enabled:m!=="disabled",state:m==="idle"&&(J.size||fe.size)?"syncing":m,lastSyncAt:p?.lastSyncAt??null,pending:ye.length+J.size+fe.size,conflicts:A,skipped:[...C].map(([f,b])=>({path:f,reason:b})),error:y,pendingDeletions:K.size,maxFileBytes:D});return{getStatus:Ht,start(){In()},notifyLocal(f,b,v){if(!p||m==="disabled"||m==="auth-required")return;let E=n(f),$=v?n(v):null;if(b==="write"&&E){Hn(E.split("/").pop()||"")||Z(E);return}if(b==="remove"){if(!E)return;let F=`${E}/`,V=!1;for(let N of Object.keys(p.files))(N===E||N.startsWith(F))&&(V=!0,q({key:N,run:()=>xe(N)}));!V&&E&&q({key:E,run:()=>xe(E)})}},holdLocalMove(f,b){let v=$=>e.serverDir?`${e.serverDir}/${$.replace(/\\/g,"/").normalize("NFC")}`:$.replace(/\\/g,"/").normalize("NFC"),E={from:v(f),to:v(b)};return++Ce,wr.add(E),()=>{wr.delete(E)}},async notifyLocalMove(f,b,v,E){let $=n(f),F=n(b),V=p??await Ss(e.shadowName),N=ws(f,""),Y=N&&(e.serverDir?`${e.serverDir}/${N}`:N);if(!$&&F&&Y&&V&&Object.keys(V.files).some(U=>U===Y||U.startsWith(`${Y}/`))&&($=Y),!$&&!F){v?.();return}if($&&F){let U=p??V;if(!U){v?.();return}let oe=E??(Object.keys(U.files).some(Ie=>Ie.startsWith(`${$}/`))?"folder":"file"),ce={from:$,to:F,kind:oe};U.moves??=[],U.moves.some(Ie=>ze(Ie)===ze(ce))||(U.moves.push(ce),++Ce),v&&br.set(ze(ce),v),L.save(U);try{await L.flush(!0)}catch(Ie){throw U.moves=U.moves.filter(Xe=>ze(Xe)!==ze(ce)),br.delete(ze(ce)),L.save(U),Ie}p===U&&u&&m!=="disabled"&&m!=="auth-required"&&q({key:`move:${ze(ce)}`,run:()=>Sr(ce)});return}$&&this.notifyLocal(f,"remove"),F&&(q({key:F,run:()=>xe(F)}),Er()),v?.()},async setEnabled(f){let b=await Ye(s);return await Et({cloudSync:{...b.cloudSync??{},enabled:f}},s),await In(),Ht()},async restart(){return await In(),Ht()},async syncNow(){if(C.clear(),m==="disabled"||m==="auth-required"||!k)await In();else{x&&(clearTimeout(x),hr());for(let f of p?.moves??[])q({key:`move:${ze(f)}`,run:()=>Sr(f)});q({run:Qt})}return Ht()},confirmMassDeletions(){return K.size&&(te=!0,ne=!1,K.clear(),Q.length=0,he(),q({run:Qt})),Ht()},stop:Vi};function Er(){u&&(T&&clearTimeout(T),T=setTimeout(()=>{T=null,q({run:Do})},Ap))}}function vs(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 ks(t){return/\.md$/i.test(t)?vs(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function Cc(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 Pp=t=>ve().sha256Hex(t).slice(0,8),$p=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Kr="\u4E0E\u6211\u5171\u4EAB";function Ac(t,e){let n=Pp(`${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:`${Kr}/${$p(t.title)}-${n}`,serverDir:r,inScope:(o,s)=>e.some(i=>Cc(i,o,s)),scopeKey:e.map(o=>o.root).join("\0")}}function xc(t){return Ac(t,[vs(t.path),...(t.items??[]).map(ks)])}function Tc(t){let e=t.map(xc),n=t.flatMap((o,s)=>{let i=e[s].serverDir?`${e[s].serverDir}/`:"";return(o.items??[]).filter(a=>!a.startsWith(i)).map(a=>Ac({vaultId:o.vaultId,path:a,title:(a.split("/").pop()??a).replace(/\.md$/i,"")},[ks(a)]))}),r=new Map;for(let o of[...e,...n])r.has(o.key)||r.set(o.key,o);return[...r.values()]}var Np=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 Ic(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=Np(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,Fe(i)));return a?`${a.localRelDir}/${a.serverDir?i.slice(a.serverDir.length+1):i}`:null}function Es(){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 S=null;try{S=await y.json()}catch{}throw Object.assign(new Error(S?.detail||`http ${y.status}`),{status:y.status,code:S?.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(vt(Cr(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=xc(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(S=>h.startsWith(`${S.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 Oc}from"node:fs";import jp from"node:path";var _s=".forsion-vault.md",Rc=t=>`${t}/${_s}`;function Xr(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 Dc=t=>`---
212
+ `),{excludeFalseConflicts:!0}),i=[];for(let s of r){if(s.conflict)return null;s.ok&&i.push(...s.ok)}return i.join(`
213
+ `)}function Es(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var vc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function kc(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function Ec(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 Zr(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 _p=/[\u0000-\u001f\u007f]/;function Nt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||_p.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function _s(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Nt(n):n.startsWith(`${e}/`)?Nt(n.slice(e.length+1)):null}function _c(t,e){return e===""?t:`${e}/${t}`}function Vn(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Ue(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var rt=t=>t==="page"||t==="db";var Cp=1024,xe=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},Cc=t=>12e4+Math.ceil(t/256);function Ap(t,e){let n=AbortSignal.timeout(t);if(!e)return n;let r=new AbortController;for(let i of[n,e])i.addEventListener("abort",()=>r.abort(i.reason),{once:!0});return r.signal}function Ac(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=()=>t.getToken?.()??t.token,r=async(o,a)=>{let c=n();for(let l=0;;l++){let u={...a.headers,Authorization:`Bearer ${c}`},f=await fetch(o,{...a,headers:u});if(n(),f.status!==401||f.redirected)return f;let h=await f.text(),p=n();if(p===c||l>0)return new Response(h,{status:f.status,statusText:f.statusText,headers:f.headers});c=p}},i=async(o,a,c)=>{let l={Authorization:`Bearer ${t.token}`,...c?.headers};o!=="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>=Cp&&(l["Content-Encoding"]="gzip",u=await sa(u))):c?.form&&(u=c.form);let f=await r(a,{method:o,headers:l,body:u,signal:Ap(c?.timeoutMs??3e4,c?.signal)});if(!f.ok){let p=null;try{p=await f.json()}catch{}throw n(),new xe(f.status,p,a)}let h=await f.json();return n(),h},s=o=>new URLSearchParams(o).toString();return{clientId:t.clientId,async listVaults(){return((await i("GET",`${e}/vaults`)).vaults??[]).map(a=>({id:String(a.id),name:String(a.name),lastChangeSeq:Number(a.lastChangeSeq??0)}))},async tree(o){let a=await i("GET",`${e}/vaults/${o}/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(o,a){let c=await i("GET",`${e}/vaults/${o}/file?${s({path:a})}`);return{content:String(c.content??""),seq:Number(c.seq??0),hash:c.hash??null}},putFile(o,a,c,l,u=!1){return i("PUT",`${e}/vaults/${o}/file`,{json:{path:a,content:c,baseSeq:l,...u?{force:!0}:{}}})},async deleteFile(o,a,c,l){let u={path:a};c!==void 0&&(u.baseSeq=String(c)),await i("DELETE",`${e}/vaults/${o}/file?${s(u)}`,l?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(o,a,c){return i("POST",`${e}/vaults/${o}/move`,{json:{from:a,to:c}})},renameFolder(o,a,c){return i("POST",`${e}/vaults/${o}/folders/rename`,{json:{path:a,newName:c}})},moveFolder(o,a,c){return i("POST",`${e}/vaults/${o}/folders/move`,{json:{path:a,dest:c}})},async deleteFolder(o,a){await i("DELETE",`${e}/vaults/${o}/folders?${s({path:a})}`)},putBinary(o,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"),i("POST",`${e}/vaults/${o}/binary`,{form:u,timeoutMs:Cc(c.length),signal:l?.signal})},async listVersions(o,a){return((await i("GET",`${e}/vaults/${o}/file/versions?${s({path:a})}`)).versions??[]).map(l=>({id:String(l.id),seq:Number(l.seq??0)}))},async getVersion(o,a){let c=await i("GET",`${e}/vaults/${o}/file/versions/${a}`);return String(c.content??"")},async getAsset(o,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")),f=setTimeout(u,12e4);try{let h=await r(`${e}/vaults/${o}/asset?${s({ref:a})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:l.signal});if(!h.ok)throw new xe(h.redirected&&(h.status===401||h.status===403)?502:h.status,null,"asset:"+a);clearTimeout(f),f=setTimeout(u,Cc(Number(h.headers.get("content-length"))||0));let p=new Uint8Array(await h.arrayBuffer());return n(),p}finally{clearTimeout(f)}},async changes(o,a){let c=await i("GET",`${e}/vaults/${o}/changes?${s({since:String(a)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function xc(t,e){let n=!1,r=0,i=null,s=null,o=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,a=l=>{if(n)return;i?.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;i=new AbortController;let l;try{if(l=await fetch(o(),{headers:{Authorization:`Bearer ${t.getToken?.()??t.token}`,Accept:"text/event-stream"},signal:i.signal}),n){await l.body?.cancel();return}t.getToken?.()}catch(y){a(y);return}if(!l.ok||!l.body){a(new Error(`sse http ${l.status}`));return}r=0,e.onOpen();let u=l.body.getReader(),f=new TextDecoder,h="",p="",m=[],w=()=>{if(t.getToken?.(),!m.length&&!p)return;let y=m.join(`
214
+ `),S=p||"message";p="",m=[];let g=null;try{g=y?JSON.parse(y):null}catch{return}S==="hello"?e.onHello(Number(g?.seq??0)):S==="change"?e.onChange(g):S==="reset"?e.onReset():S==="presence"?e.onPresence?.(g):S==="presence-roster"&&e.onPresenceRoster?.(g)};try{for(;;){let{done:y,value:S}=await u.read();if(y)break;for(h+=f.decode(S,{stream:!0});;){let g=h.indexOf(`
215
+ `);if(g<0)break;let P=h.slice(0,g).replace(/\r$/,"");if(h=h.slice(g+1),P==="")w();else{if(P.startsWith(":"))continue;P.startsWith("event:")?p=P.slice(6).trim():P.startsWith("data:")&&m.push(P.slice(5).replace(/^ /,""))}}}}catch(y){n||a(y);return}a(new Error("sse stream ended"))};return c(),{stop:()=>{n=!0,s&&clearTimeout(s),i?.abort()}}}var Jt=t=>ve().path.join(Le().userDataDir(),Le().isDevMode()?`${t}.dev.json`:`${t}.json`),Cs=Jt,jt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Yn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Gn=t=>typeof t=="string"&&Nt(t)===t,As=t=>typeof t=="string"&&t.length>0,xp=t=>jt(t)&&Yn(t.seq)&&As(t.hash)&&Yn(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),Tp=t=>jt(t)&&Gn(t.from)&&Gn(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||jt(t.hashes)&&Object.values(t.hashes).every(As));async function xs(t){let e;try{e=await ve().fs.readFile(Cs(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(!jt(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Gt(n.rootIdentity)||n.mirrorMissing!==void 0&&n.mirrorMissing!==!0||n.mirrorRestore!==void 0&&n.mirrorRestore!=="list"&&(!jt(n.mirrorRestore)||!Object.entries(n.mirrorRestore).every(([r,i])=>Gn(r)&&jt(i)&&Yn(i.seq)&&(i.hash===null||As(i.hash))))||!jt(n.files)||!Object.entries(n.files).every(([r,i])=>Gn(r)&&xp(i))||n.cursor!==void 0&&!Yn(n.cursor)||n.lastSyncAt!=null&&!Yn(n.lastSyncAt)||n.pending!==void 0&&(!jt(n.pending)||!Object.entries(n.pending).every(([r,i])=>Gn(r)&&(i==="local"||i==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(Tp)))throw Error("Invalid cloud vault sync state; original data was retained");return{...n,cursor:n.cursor??0,lastSyncAt:n.lastSyncAt??null}}function Tc(t){let e=null,n=null,r=Promise.resolve(),i=null,s=()=>{if(!e)return r;let o=e,a=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let c=Cs(t),l=`${c}.tmp-${ve().tmpTag()}-${Date.now()}-0`;await ve().fs.writeFile(l,a,"utf8"),await ve().fs.rename(l,c),i=null}catch(c){e??=o,i=c}}),r};return{save(o){e=o,!n&&(n=setTimeout(()=>{n=null,s()},500))},async flush(o=!1){if(n&&(clearTimeout(n),n=null),await s(),o&&i)throw i}}}async function Ic(t){try{await ve().fs.unlink(Cs(t))}catch{}}var Jn=/^[0-9a-f]{64}$/;function Rc(t){let e=ve(),n=()=>Jt(t).replace(/\.json$/,".bases"),r=a=>e.path.join(n(),a),i=a=>e.fs.access(r(a)).then(()=>!0,()=>!1),s=new Map,o=(a,c)=>{let l=(s.get(a)??Promise.resolve()).then(c,c);return s.set(a,l),l.finally(()=>{s.get(a)===l&&s.delete(a)}),l};return{put(a,c){return Jn.test(a)?o(a,async()=>{try{if(await i(a))return;await e.fs.mkdir(n(),{recursive:!0});let l=`${r(a)}.tmp-${e.tmpTag()}-${Date.now()}`;await e.fs.writeFile(l,c,"utf8"),await e.fs.rename(l,r(a))}catch{}}):Promise.resolve()},async get(a){if(!Jn.test(a))return null;try{let c=await e.fs.readFile(r(a),"utf8");return e.sha256Hex(c)===a?c:null}catch{return null}},drop(a,c){return Jn.test(a)?o(a,async()=>{if(!(c&&!c()))try{await e.fs.rm(r(a),{force:!0})}catch{}}):Promise.resolve()},async has(a){return Jn.test(a)&&i(a)},async prune(a){let c;try{c=(await e.fs.readdir(n(),{withFileTypes:!0})).filter(l=>l.isFile()).map(l=>l.name)}catch{return}for(let l of c)if(!a.has(l)&&!(!Jn.test(l)&&!/^[0-9a-f]{64}\.tmp-/.test(l)))try{await e.fs.rm(e.path.join(n(),l),{force:!0})}catch{}}}}var Ip=5*1024*1024,Rp=5*1024*1024,Dp=3e4,Op=5e3,Mp=5*6e4,Pp=2500,$p=3e3,Np=5,jp=256*1024,Fp=5,ei=1024*1024,Dc=200,Lp=6e4,Up=50,Hp=".sync-trash",xt=t=>ve().sha256Hex(t);function Kn(t,e){let n=e??{localRoot:At(),shadowName:`amadeus-sync-${Wn()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]},r=d=>{let b=_s(d,"");if(!b)return null;for(let _ of n.excludePrefixes??[])if(b===_.replace(/\/$/,"")||b.startsWith(_))return null;if(n.ignoreNames?.length&&b.split("/").some(_=>n.ignoreNames.includes(_)))return null;let v=n.serverDir?`${n.serverDir}/${b}`:b;return n.inScope&&!n.inScope(v,Ue(v))?null:v},i=d=>{let b;if(n.serverDir){if(!d.startsWith(`${n.serverDir}/`))return null;b=d.slice(n.serverDir.length+1)}else{for(let v of n.excludePrefixes??[])if(d.startsWith(v))return null;b=d}return b.split("/").some(v=>Vn(v)||!!n.ignoreNames?.includes(v))?null:b},s=(d,b)=>!n.inScope||n.inScope(d,b),o=n.accountId??Pe(),{fs:a,path:c,directoryIdentity:l}=ve(),u=d=>a.access(d).then(()=>!0,()=>!1),f=!1,h=!1,p=0,m=Promise.resolve(),w=new Set,y="disabled",S=null,g=null,P=null,x=null,D=null,k=null,A=()=>{let d=t.loadCreds();if(!k||o!==Pe()||!d.token||d.cloudUrl?.replace(/\/+$/,"")!==k.cloudUrl.replace(/\/+$/,""))throw new xe(401,{code:"ACCOUNT_CHANGED"},"sync-session");return d.token},E=null,M=0,W=new Map,j=null,B=Tc(n.shadowName),ie=Rc(n.shadowName),se=!1,X=new Map,ee=!1,ne=!1,fe=[],oe=(d,b,v)=>{try{t.onHealth?.(d,b,v)}catch{}},Te=Qr(oe),we=0,Je=()=>{ne||oe("massDeleteGuard"),ne=!0},Be=()=>{g&&(g.pending=X.size?Object.fromEntries(X):void 0,B.save(g))},Oe=()=>{ne=!1,fe.length=0},q=()=>{if(ne)return!0;let d=Date.now();for(;fe.length&&d-fe[0]>Lp;)fe.shift();return fe.length>=Up?(Je(),!0):!1},J=[],C=new Set,I=!1,T=null,R=null,H=null,V=null,N=()=>{!f||V||(V=setTimeout(()=>{V=null,t.onStatus($t())},200))},U=(d,b)=>{let v=y;y=d,b!==void 0&&(S=b),Q(v,d),N()},Q=(d,b)=>{if(b==="syncing"&&d!=="syncing"&&(we=Date.now()),b==="idle"&&d==="syncing"&&(oe("cycles"),oe("cycleMsTotal",Math.max(0,Date.now()-we))),b==="idle"||b==="disabled"){Te.ok();return}let v=Ec(b,S);v&&Te.error(v)},K=(d,b)=>{W.set(d,b),oe(kc(b),1,d)},z=(d,b=!1)=>{if(!(!f||!h)){if(d.key){if(C.has(d.key))return;C.add(d.key)}b?J.unshift(d):J.push(d),rn()}},re=new Map,pe=d=>{if(!f)return;let b=(g?.files[d]?.size??0)>jp,v=(n.pushQuietMs??$p)*(b?Fp:1),_=Date.now(),O=re.get(d);O&&clearTimeout(O.timer);let F=O?.since??_,Y=Math.max(0,Math.min(v,F+v*Np-_)),$=setTimeout(()=>{re.delete(d),z({key:d,run:()=>Ae(d,!0)})},Y);re.set(d,{timer:$,since:F}),N()},Ee=()=>{for(let{timer:d}of re.values())clearTimeout(d);re.clear()},_e=d=>!(d instanceof xe)||d.status>=500||d.status===0,ge=d=>d instanceof xe&&(d.status===401||d.status===403),tt=(d,b)=>{K(d,b?.body?.code||`http ${b?.status}`),N()},rn=async()=>{if(!I){I=!0;try{for(;J.length;){(y==="idle"||y==="starting")&&U("syncing");let d=J.shift();d.key&&C.delete(d.key);try{await d.run()}catch(b){if(!f)return;if(ge(b)){J.length=0,C.clear(),Mn(),U("auth-required","login-expired");return}if(_e(b)){z(d,!0),Mn(),U("offline",b?.message||"network error"),vt();return}tt(d.key??"(op)",b)}}f&&y==="syncing"&&(g&&(g.lastSyncAt=Date.now(),B.save(g)),U("idle",null))}finally{I=!1;for(let d of w)d();w.clear()}}},vt=()=>{!f||T||(T=setTimeout(()=>{T=null,Pn()},Dp))},de=new Map,Vt=0,Ie=null,Di=()=>!!R||!!Ie||!f,Po=d=>d instanceof xe&&d.status>=500||d?.name==="TimeoutError",$o=n.pushRetryMs??Op,Dn=(d,b)=>{(b||!de.has(d))&&de.set(d,b)},No=(d,b,v)=>{K(d,b instanceof xe?`http ${b.status}`:"timeout"),Dn(d,v),Vt=Math.min(Vt*2||$o,Mp),R=setTimeout(vr,Vt),N()},jo=(d,b,v)=>{let _=new AbortController,O=b(_.signal).then(Y=>()=>Y,Y=>()=>{throw Y}),F={path:d,abort:_,after:[],settle:async()=>{let Y=await O;if(Ie===F){Ie=null;try{await v(Y)}catch($){if(ge($)||_e($))throw $;tt(d,$)}finally{for(let $ of F.after)z($);Fo(d)}}}};Ie=F,O.then(()=>z({run:F.settle}))},sn=(d,b)=>{for(let[v,_]of[...de])!_||!Ke(v,d)||(de.delete(v),W.delete(v),b!==null&&de.set(b+v.slice(d.length),_));N()},vr=()=>{R=null;let[d]=de;if(d===void 0)return;let[b]=d;C.delete(b),z({key:b,run:async()=>{if(Ie?.path===b)return;let v=de.get(b),_=!v&&de.delete(b);(v||_)&&W.delete(b);try{v?await ft(b,v.seq):_&&await Ae(b,!0)}finally{_&&Ye(b)&&Dn(b),Fo(b)}}})},Fo=d=>{if(!Di())if(de.has(d)){let b=de.get(d);de.delete(d),de.set(d,b),R=setTimeout(vr,Vt||$o)}else vr()},Me=d=>{if(!E||!g)throw new Error("engine not bound");let b=i(d);if(b===null)throw new Error("path outside binding: "+d);let v=c.resolve(E,_c(b,g.folder)),_=c.relative(E,v);if(_.startsWith("..")||c.isAbsolute(_))throw new Error("path escapes vault: "+d);return v},kr=d=>({size:d,mtimeMs:-1}),Lo=async d=>{try{let b=await a.stat(d);return b.isFile()?{size:b.size,mtimeMs:Math.floor(b.mtimeMs)}:null}catch{return null}},Zu=async d=>{if(!a.lstat||!E)return Lo(d);let b=c.relative(E,d).split(c.sep),v=E;for(let[_,O]of b.entries()){v=c.join(v,O);let F=await a.lstat(v).catch(Y=>{if(Y?.code==="ENOENT")return null;throw Y});if(!F)return null;if(F.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(_===b.length-1&&F.isFile())return{size:F.size,mtimeMs:Math.floor(F.mtimeMs)};if(_===b.length-1||!F.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},Qu=0,Uo=async(d,b,v,_)=>{if(!await We())throw Error("Cloud vault sync root is unavailable or changed");let O=E&&P?{path:E,identity:P}:void 0;await a.mkdir(c.dirname(d),{recursive:!0});let F=`${d}.tmp-${ve().tmpTag()}-${Date.now()}-${Qu++}`;await a.writeFile(F,b);let Y=await Lo(F)??kr(Dr(b));try{if(!_())return null;let $=ve().compareAndReplace;if(!$)throw new Error("Host does not support safe cloud download commits");let Z=await $(F,d,v,_,O);if(!Z&&!await We())throw Error("Cloud vault sync root is unavailable or changed");return Z?Y:null}finally{await We()&&await a.rm(F,{force:!0})}},Ho=async d=>{let b;try{b=await a.readdir(d,{withFileTypes:!0})}catch{return}for(let v of b)v.isDirectory()&&await Ho(c.join(d,v.name));try{await a.rmdir(d)}catch{}},dt=async d=>{let b=Me(d),v=await Zu(b);if(!await We())throw Error("Cloud vault sync root is unavailable or changed");if(a.lstat&&!v)return null;let _;try{_=await a.readFile(b)}catch(F){if(F?.code!=="ENOENT")throw F;if(!await We())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:rt(Ue(d))?xt(Et(_)):xt(_),size:v?.size??_.length,mtimeMs:v?.mtimeMs??-1,buf:_}},Mt=async(d,b,v,_,O)=>{if(!g)return;let F=g.files[d]?.hash;g.files[d]={seq:b,hash:v,size:_.size,mtimeMs:_.mtimeMs},g.mirrorRestore&&g.mirrorRestore!=="list"&&delete g.mirrorRestore[d],B.save(g),O!==void 0&&await zo(d,v,O),F&&F!==v&&await Bo(F)},zo=async(d,b,v)=>{if(!rt(Ue(d))||Dr(v)>ei)return;let _=typeof v=="string"?v:Et(v);xt(_)===b&&await ie.put(b,_)},Bo=async d=>{let b=()=>!!g&&!Object.values(g.files).some(v=>v.hash===d);b()&&await ie.drop(d,b)},nt=d=>{if(g&&d in g.files){let b=g.files[d].hash;delete g.files[d],B.save(g),Bo(b)}},ft=async(d,b)=>{if(!x||!g||Ye(d))return;let v=Se,_=Ue(d);if(rt(_)){let $;try{$=await x.getFile(g.vaultId,d),oe("downloads")}catch(Z){if(Z instanceof xe&&Z.status===404){await Oi(d);return}throw Z}await qo(d,_,$.content,$.seq,$.hash??xt($.content),v);return}if(Di()){Dn(d,{seq:b}),N();return}let{vaultId:O}=g,F=x,Y={seq:b};de.set(d,Y),jo(d,$=>F.getAsset(O,d,$),async $=>{let Z=de.get(d)===Y,te;try{te=$(),Vt=0,oe("downloads")}catch(L){if(!Z)return;if(de.delete(d),L instanceof xe&&L.status===404){K(d,"ASSET_404"),N();return}if(Po(L)){No(d,L,{seq:b});return}throw L}Z&&await qo(d,_,te,b??0,xt(te),v)}),N()},qo=async(d,b,v,_,O,F)=>{if(!g)return;let Y=async me=>{await Mt(d,_,O,me,v),de.get(d)&&(de.delete(d),W.delete(d))},$=await dt(d);if(F!==Se||Ye(d))return;let Z=g.mirrorRestore,te=Z&&Z!=="list"&&Object.hasOwn(Z,d)?Z[d]:void 0;if(te&&(te.hash!==O||te.seq!==_)){let me={...te};Object.assign(te,{hash:O,seq:_}),B.save(g);try{await B.flush(!0)}catch(Ge){throw Object.assign(te,me),B.save(g),Ge}if(!f||F!==Se||Ye(d))return}if($&&$.hash===O){await Y($);return}let L=g.files[d];if($&&L&&O===L.hash&&$.hash!==L.hash){await Y(kr(L.size)),z({key:d,run:()=>Ae(d)});return}let G=$?xt($.buf):null;if($&&(!L||$.hash!==L.hash)){if(L&&rt(b)&&typeof v=="string"&&await ed(d,L,$,v,_,O,()=>F===Se&&!Ye(d))||F!==Se||Ye(d)||!await td(d,()=>F===Se&&!Ye(d)))return;G=null}let he=await Uo(Me(d),v,G,()=>f&&F===Se&&!Ye(d));if(!he){z({key:d,run:()=>Ae(d)});return}await Y(he)},ed=async(d,b,v,_,O,F,Y)=>{try{if(!x||!g||v.buf.length>ei||_.length>ei)return!1;let $=await ie.get(b.hash);if($===null){let G=(await x.listVersions(g.vaultId,d)).find(me=>me.seq===b.seq);if(!G)return!1;let he=await x.getVersion(g.vaultId,G.id);if(xt(he)!==b.hash)return!1;$=he}let Z=Et(v.buf),te;if(Ue(d)==="db"){let L=yc(),G=L?L(d,Z,$,_):null;te=G&&!G.conflict?G.content:null}else te=Sc(Z,$,_);return te===null?!1:await Uo(Me(d),te,xt(v.buf),()=>f&&Y())?(await Mt(d,O,F,kr(Dr(te)),_),z({key:d,run:()=>Ae(d)}),!0):(z({key:d,run:()=>Ae(d)}),!0)}catch{return!1}},td=async(d,b)=>{let v=Nt(Kr(d,new Date));if(!v)return!0;let _=v.lastIndexOf("."),O=_>v.lastIndexOf("/"),F=O?v.slice(0,_):v,Y=O?v.slice(_):"",$=v,Z=ve().existsSync;if(Z)for(let te=2;Z(Me($));te++)$=`${F}-${te}${Y}`;else for(let te=2;await u(Me($));te++)$=`${F}-${te}${Y}`;if(!b())return!1;try{await a.rename(Me(d),Me($))}catch(te){if(te?.code==="ENOENT")return!0;throw te}return M++,oe("conflicts"),z({key:$,run:()=>Ae($)}),N(),!0},Wo=async d=>{if(!E)return;let b=Me(d),v=i(d)??d,_=c.join(E,Hp,new Date().toISOString().slice(0,10),...v.split("/")),O=await u(_)?`${_}.${Date.now()}`:_;try{await a.mkdir(c.dirname(O),{recursive:!0}),await a.rename(b,O)}catch(F){if(F?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${b}: ${F?.message??String(F)}`)}},Oi=async d=>{if(!g)return;sn(d,null);let b=await dt(d);if(Ye(d))return;let v=g.files[d]??null,_=Xr(b?.hash??null,v,null);if(_.kind==="deleteLocal"){if(!ee&&q()){X.set(d,"local"),Be(),N();return}fe.push(Date.now()),await Wo(d),nt(d)}else _.kind==="pushCreate"?(nt(d),z({key:d,run:()=>Ae(d)})):nt(d)},Vo=(d,b)=>{if(g){sn(d,b);for(let v of Object.keys(g.files))if(v===d||v.startsWith(`${d}/`)){let _=b+v.slice(d.length);g.files[_]=g.files[v],delete g.files[v]}B.save(g)}},Yo=async d=>{if(!x||!g||d.seq<=g.cursor||!await We())return;if(d.origin.client&&x.clientId===d.origin.client){g.cursor=d.seq,B.save(g);return}let b=d.type==="structure"?"folder":d.type,v=O=>i(O)!==null&&s(O,b);if(!v(d.path)&&!(d.newPath&&v(d.newPath))){g.cursor=d.seq,B.save(g);return}let _=d.path;if(d.op!=="write"&&d.op!=="mkdir"){for(;Ie&&(Ke(Ie.path,_)||d.newPath&&Ke(Ie.path,d.newPath));)await Ie.settle();if(!f)return}switch(d.op){case"write":await ft(_,d.fileSeq);break;case"delete":await Oi(_);break;case"move":{let O=d.newPath;if(!O)break;let F=g.files[_],Y=await dt(_),$=!!de.get(_);if(sn(_,O),$&&Dn(O,{seq:d.fileSeq}),Y&&F)try{await a.mkdir(c.dirname(Me(O)),{recursive:!0}),await a.rename(Me(_),Me(O)),g.files[O]={...F,seq:$?F.seq:d.fileSeq??F.seq},delete g.files[_],B.save(g)}catch{await ft(O,d.fileSeq)}else nt(_),await ft(O,d.fileSeq);break}case"mkdir":await a.mkdir(Me(_),{recursive:!0});break;case"rename-folder":case"move-folder":{let O=d.newPath;if(!O)break;try{await a.mkdir(c.dirname(Me(O)),{recursive:!0}),await a.rename(Me(_),Me(O))}catch{}Vo(_,O);break}case"delete-folder":{let O=`${_}/`;for(let F of Object.keys(g.files))(F===_||F.startsWith(O))&&await Oi(F);sn(_,null),await Ho(Me(_));break}}if(g.cursor=d.seq,B.save(g),d.op==="move"||d.op==="rename-folder"||d.op==="move-folder"||d.op==="delete"||d.op==="delete-folder")try{await t.onRemoteApplied?.(d)}catch{}},nd=async(d,b,v)=>{let _=Number(b?.seq??0),O=b?.content??null;if(O!==null&&xt(O)===v.hash){await Mt(d,_,v.hash,v,O);return}if(O===null&&_===0){if(!g?.files[d]){K(d,b?.code||"EXISTS"),N();return}nt(d),z({key:d,run:()=>Ae(d)});return}await ft(d,_)},Er=async(d,b)=>{if(!x||!g)return;let v=await dt(d);if(!v){z({key:d,run:()=>Ae(d)});return}if(v.size>Ip){K(d,"TOO_LARGE"),N();return}let _=Et(v.buf);try{let O=await x.putFile(g.vaultId,d,_,b);oe("uploads"),W.delete(d),await Mt(d,O.seq,O.hash??v.hash,v,v.buf)}catch(O){if(O instanceof xe&&O.status===409){await nd(d,O.body,v);return}throw O}},_r=async(d,b)=>{if(!x||!g)return;let v=await dt(d);if(!v){z({key:d,run:()=>Ae(d)});return}if(v.size>(j??Rp)){K(d,"TOO_LARGE"),N();return}if(Dn(d),N(),Di())return;let{vaultId:_}=g,O=x;jo(d,F=>O.putBinary(_,d,v.buf,{baseSeq:b,signal:F}),async F=>{if(g){de.get(d)||de.delete(d);try{let Y=F();Vt=0,oe("uploads"),W.delete(d),await Mt(d,Y.seq,v.hash,v)}catch(Y){if(Po(Y)){No(d,Y);return}if(!(Y instanceof xe)||Y.status!==409)throw Y;let $=Number(Y.body?.seq??0),Z=Y.body?.hash??null;if(Z!==null&&Z===v.hash){await Mt(d,$,v.hash,v);return}if($===0){if(!g.files[d]){K(d,Y.body?.code||"EXISTS"),N();return}nt(d),z({key:d,run:()=>Ae(d)});return}await ft(d,$)}}})},Go=async d=>{if(!x||!g||Ye(d))return;let b=Se,v=g.files[d];if(v){if(rt(Ue(d)))try{let _=await x.getFile(g.vaultId,d);if(_.seq!==v.seq){await ft(d,_.seq);return}}catch(_){if(_ instanceof xe&&_.status===404){nt(d);return}throw _}if(!(!await We()||b!==Se||Ye(d))){try{await x.deleteFile(g.vaultId,d,v.seq,{confirmed:ee})}catch(_){if(_ instanceof xe&&_.status===409){await ft(d,Number(_.body?.seq??0)||null);return}if(_ instanceof xe&&_.status===429&&_.body?.code==="MASS_DELETE_BLOCKED"){X.set(d,"remote"),Je(),Be(),N();return}throw _}nt(d)}}},Cr=d=>a.stat(d).catch(b=>{if(b?.code==="ENOENT")return null;throw b}),Mi=async d=>{let b=Le();if(e||!o||o!==Pe()||d!==At(o)||!b.isManagedCloudVault(d)||!a.lstat)return!1;let v=b.homeDir(),_=c.relative(v,d);if(!_||_.startsWith("..")||c.isAbsolute(_))return!1;let O=v;for(let F of _.split(c.sep)){O=c.join(O,F);let Y=await a.lstat(O).catch($=>{if($.code==="ENOENT")return null;throw $});if(Y&&(!Y.isDirectory()||Y.isSymbolicLink()))return!1}return!0},Pt=d=>(h=!1,ee=!1,J.length=0,C.clear(),Ni(),Mn(),U("error",`${d}: ${E}`),vt(),!1),Pi=d=>{let b=P??g?.rootIdentity,v=d!==null&&d.isDirectory();return v&&(!b||ct(b,d))?!0:Pt(v?"vault-changed":"vault-missing")},We=async()=>!!E&&Pi(await Cr(E)),Se=0,Ar=new Set,xr=new Map,Ve=d=>JSON.stringify([d.from,d.to]),Ke=(d,b)=>d===b||d.startsWith(`${b}/`),Ye=d=>[...g?.moves??[],...Ar].some(b=>Ke(d,b.from)||Ke(d,b.to)),pt=()=>!!(g?.moves?.length||Ar.size),Tr=async d=>{if(!x||!g)return;let{from:b,to:v,kind:_}=d;if(i(b)===null||i(v)===null)throw new Error("Invalid queued cloud move");if(Ie&&(Ke(Ie.path,b)||Ke(Ie.path,v))){Ie.after.push({key:`move:${Ve(d)}`,run:()=>Tr(d)});return}if(d.hashes??=Object.fromEntries(Object.entries(g.files).filter(([$])=>Ke($,b)).map(([$,Z])=>[$.slice(b.length),Z.hash])),B.save(g),await B.flush(!0),!await We())return;let O,F=!1;try{if(_==="folder"){let $=c.posix.dirname(b)==="."?"":c.posix.dirname(b),Z=c.posix.dirname(v)==="."?"":c.posix.dirname(v);$===Z?await x.renameFolder(g.vaultId,b,c.posix.basename(v)):await x.moveFolder(g.vaultId,b,Z)}else{let $=await x.move(g.vaultId,b,v);O=Number($.seq)}}catch($){if(!($ instanceof xe)||$.status!==404)throw $;let Z=await x.tree(g.vaultId);if(Z.entries.some(G=>Ke(G.path,b))||Z.folders.some(G=>Ke(G,b)))throw $;let L=Z.entries.find(G=>G.path===v);if(O=L?.seq,F=!L&&!Z.entries.some(G=>Ke(G.path,v))&&!Z.folders.some(G=>Ke(G,v)),!F){let G=Object.entries(d.hashes);if(!(G.length>0&&G.every(([me,Ge])=>Z.entries.some(je=>je.path===v+me&&je.hash===Ge))))throw new xe(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(F){for(let $ of Object.keys(g.files))Ke($,b)&&delete g.files[$];sn(b,null)}else Vo(b,v),O!==void 0&&g.files[v]&&!de.get(v)&&(g.files[v].seq=O);g.moves=(g.moves??[]).filter($=>Ve($)!==Ve(d)),B.save(g);try{await B.flush(!0)}catch($){throw g.moves.unshift(d),B.save(g),$}let Y=xr.get(Ve(d));xr.delete(Ve(d)),Y?.(),Ye(v)||(_==="folder"?await $i():await Ae(v))},Ae=async(d,b=!1)=>{if(!g||Ye(d))return;if(Ie?.path===d){Ie.after.push({key:d,run:()=>Ae(d,b)});return}if(!s(d,Ue(d))){nt(d);return}if(!await We())return;let v=await dt(d);if(Ye(d))return;let _=g.files[d]??null,O=Xr(v?.hash??null,_,_?{seq:_.seq,hash:_.hash}:null);switch(O.kind){case"push":rt(Ue(d))?await Er(d,O.baseSeq):await _r(d,O.baseSeq);break;case"pushCreate":rt(Ue(d))?await Er(d,0):await _r(d,0);break;case"pushDelete":if(b){Rr();break}if(!ee&&(X.has(d)||q())){X.set(d,"remote"),Be(),N();break}fe.push(Date.now()),await Go(d);break;case"dropShadow":nt(d);break;default:v&&_&&v.hash===_.hash&&v.mtimeMs>=0&&(_.size!==v.size||_.mtimeMs!==v.mtimeMs)&&await Mt(d,_.seq,_.hash,v,v.buf);break}},Jo=async()=>{let d=new Map;if(!E||!g)return d;let b=E,v=null,_=async O=>{if(v)return;let F;try{F=await a.readdir(O,{withFileTypes:!0})}catch(Y){v=`${O}: ${Y?.message??String(Y)}`;return}for(let Y of F){if(Vn(Y.name)||Y.isDirectory()&&n.ignoreNames?.includes(Y.name))continue;let $=c.join(O,Y.name);if(Y.isDirectory())await _($);else if(Y.isFile()){let Z=c.relative(b,$).split(c.sep).join("/"),te=r(Z);if(!te)continue;try{let L=await a.stat($);if(!L.isFile())continue;d.set(te,{size:L.size,mtimeMs:Math.floor(L.mtimeMs)})}catch(L){if(L?.code==="ENOENT")continue;v=`${$}: ${L?.message??String(L)}`;return}}}};return await _(b),v?(U("error",`scan-failed: ${v}`),vt(),null):d},$i=async()=>{let d=Se;if(pt()||d!==Se||!g||!await We())return;let b=await Jo();if(!b||pt()||d!==Se||!await We())return;let v=!1;for(let[F,Y]of[...X])(Y==="remote"&&b.has(F)||Y==="local"&&!b.has(F))&&(X.delete(F),v=!0);X.size||Oe();for(let[F,Y]of b){let $=g.files[F];$&&$.size===Y.size&&$.mtimeMs===Y.mtimeMs||z({key:F,run:()=>Ae(F)})}let _=Object.keys(g.files),O=_.filter(F=>!b.has(F));if(O.length&&!ee&&(ne||Es(O.length,_.length,Dc))){Je();for(let F of O)X.set(F,"remote");Be(),N();return}v&&(Be(),N());for(let F of O)X.has(F)||z({key:F,run:()=>Ae(F)})},rd=async d=>{if(!g)return;let b=new Set;for(let[v,_]of Object.entries(g.files)){if(!rt(Ue(v))||_.size>ei)continue;b.add(_.hash);let O=d.get(v);if(!(!O||O.size!==_.size||O.mtimeMs!==_.mtimeMs||await ie.has(_.hash)))try{let F=await dt(v);F&&F.hash===_.hash&&await zo(v,_.hash,F.buf)}catch{}}await ie.prune(b)},on=async()=>{if(Ie){Ie.after.push({run:on});return}let d=Se;if(pt()||d!==Se||!x||!g||!E||!await We())return;let b=await x.tree(g.vaultId);if(b.maxFileBytes!==void 0&&b.maxFileBytes!==j&&(j=b.maxFileBytes,N()),pt()||d!==Se)return;let v=new Map;for(let L of b.entries)i(L.path)===null||!s(L.path,L.kind)||v.set(L.path,L);for(let[L,G]of[...de])G&&!v.has(L)&&sn(L,null);let _=await Jo();if(!_||pt()||d!==Se||!await We())return;if(g.mirrorRestore==="list"){for(let G of Object.keys(g.files))!_.has(G)&&!X.has(G)&&delete g.files[G];let L=Object.create(null);for(let[G,{seq:he,hash:me}]of v)Object.hasOwn(g.files,G)||(L[G]={seq:he,hash:me});g.mirrorRestore=L,B.save(g);try{await B.flush(!0)}catch(G){throw g.mirrorRestore="list",B.save(g),G}}let O=g.mirrorRestore;se||(se=!0,await rd(_));let F=new Set([...v.keys(),..._.keys(),...Object.keys(g.files),...Object.keys(O??{})]),Y=Object.keys(g.files).length,$=[];for(let L of F){if(pt()||d!==Se)return;let G=g.files[L]??null,he=v.get(L)??null,me=_.get(L)??null,Ge=null,je=kr(me?.size??0);if(me)if(G&&G.size===me.size&&G.mtimeMs===me.mtimeMs)Ge=G.hash,je=me;else{let kt=await dt(L);kt&&(Ge=kt.hash,je=kt)}if(O&&Object.hasOwn(O,L)){let kt=O[L];!G&&Ge!==null&&kt.hash===Ge&&(G=g.files[L]={seq:kt.seq,hash:Ge,size:je.size,mtimeMs:je.mtimeMs}),(G||!he)&&delete O[L]}$.push({sp:L,d:Xr(Ge,G,he?{seq:he.seq,hash:he.hash}:null),rSeq:he?.seq??null,localHash:Ge,localStat:je})}if(pt()||d!==Se)return;let Z=$.filter(L=>L.d.kind==="deleteLocal"||L.d.kind==="pushDelete").length,te=!ee&&(ne||Es(Z,Y,Dc));te&&Z&&Je(),X.clear();for(let{sp:L,d:G,rSeq:he,localHash:me,localStat:Ge}of $){if(pt()||d!==Se)return;if(te&&(G.kind==="deleteLocal"||G.kind==="pushDelete")){X.set(L,G.kind==="deleteLocal"?"local":"remote");continue}if((G.kind==="deleteLocal"||G.kind==="pushDelete")&&((await dt(L))?.hash??null)!==me){z({key:L,run:()=>Ae(L)});continue}if(pt()||d!==Se)return;switch(G.kind){case"adopt":{let je=rt(Ue(L))?await dt(L):null;await Mt(L,he,me,Ge,je&&je.hash===me?je.buf:void 0);break}case"pull":await ft(L,he);break;case"push":rt(Ue(L))?await Er(L,G.baseSeq):await _r(L,G.baseSeq);break;case"pushCreate":rt(Ue(L))?await Er(L,0):await _r(L,0);break;case"pushDelete":await Go(L);break;case"deleteLocal":await Wo(L),nt(L);break;case"conflict":await ft(L,he);break;case"dropShadow":nt(L);break;case"none":break}}ee&&(ee=!1,fe.length=0),X.size||Oe(),Be(),te&&N();for(let L of b.folders)if(!(i(L)===null||!s(L,"folder")))try{await a.mkdir(Me(L),{recursive:!0})}catch{}g.cursor=b.seq,g.lastSyncAt=Date.now(),O&&!Object.keys(O).length&&delete g.mirrorRestore,B.save(g)},id=async()=>{if(!x||!g)return;let d=g.cursor,b=await x.changes(g.vaultId,d);if(b.changes.length===0&&b.seq>d||b.changes.length>0&&b.changes[0].seq!==d+1){await on();return}for(let _ of b.changes)await Yo(_)},On=null,Ko=[],Ni=()=>{On&&Ko.push(On.close()),On=null},sd=()=>{if(!f||On||!E)return;let d=ve();if(!d.watch)return;let b=v=>{if(!E)return;let _=c.relative(E,v);if(!_||_.startsWith(".."))return;let O=r(_);O&&pe(O)};On=d.watch(E,{depth:12,ignored:v=>{let _=c.basename(v);return Vn(_)||!!n.ignoreNames?.includes(_)}},{change:b,add:b,unlink:()=>Rr(),unlinkDir:()=>Rr()})},Mn=()=>{D?.stop(),D=null},od=()=>{if(!f||!x||!g||D)return;let d=k;d&&(D=xc({baseUrl:d.cloudUrl,vaultId:g.vaultId,token:d.token,getToken:A},{getSince:()=>g?.cursor??0,onHello:b=>{g&&b>g.cursor&&z({run:id})},onChange:b=>{z({run:()=>Yo(b)})},onReset:()=>{z({run:on})},onOpen:()=>{(y==="offline"||y==="starting")&&U("idle",null),z({run:$i})},onDown:()=>{(y==="idle"||y==="syncing")&&U("offline")},onPresence:b=>t.onPresence?.(g?.vaultId??"",b),onPresenceRoster:b=>t.onPresenceRoster?.(g?.vaultId??"",b)}))},ad=async()=>{let d=await Ze(o);if(d.cloudSync?.deviceId)return d.cloudSync.deviceId;let b=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Ct({cloudSync:{...d.cloudSync??{},deviceId:b}},o),b},cd=async d=>{Mn(),Ni(),P=null,J.length=0,C.clear(),X.clear(),ee=!1,ne=!1,fe.length=0;let b=await Ze(o);if(d!==p)return;let v=b.cloudSync;if(v?.enabled===!1){E=null,x=null,U("disabled",null);return}if(!o||o!==Pe()){U("auth-required","not-logged-in");return}if(E=n.localRoot,n.requireRootExists){let Y=await a.stat(E).then($=>$.isDirectory()).catch(()=>!1);if(d!==p)return;if(!Y){U("error",`vault-missing: ${E}`),vt();return}}if(d!==p)return;let _=t.loadCreds();if(!_.cloudUrl||!_.token){x=null,U("auth-required","not-logged-in");return}U("starting",null);let O=v?.deviceId??await ad();if(d!==p)return;let F=n.clientIdSuffix?`${O}#${n.clientIdSuffix}`:O;k={cloudUrl:_.cloudUrl,token:_.token},x=Ac({baseUrl:_.cloudUrl,token:_.token,clientId:F,getToken:()=>{if(d!==p)throw new xe(401,{code:"ACCOUNT_CHANGED"},"sync-session");return A()}});try{let Y=n.vaultId==="first"?v?.vaultId:n.vaultId;if(!Y){let L=await x.listVaults();if(d!==p)return;if(!L.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");Y=L[0].id,await Ct({cloudSync:{...v??{},vaultId:Y}},o)}if(d!==p)return;let $=await xs(n.shadowName);if(d!==p||(g=$&&$.vaultRoot===E&&$.vaultId===Y&&$.folder===""?$:{vaultRoot:E,folder:"",vaultId:Y,cursor:0,lastSyncAt:null,files:{}},d!==p))return;for(let[L,G]of Object.entries(g.pending??{}))X.set(L,G);X.size&&(ne=!0);let Z=await Cr(E);if(d!==p)return;let te=()=>pt()||!!Object.keys(g?.pending??{}).length;if(!Z&&!n.requireRootExists){if(g.rootIdentity||Object.keys(g.files).length||g.mirrorMissing||te()){let L=await Mi(E);if(d!==p)return;if(!L||te()){Pt("vault-missing");return}if(g.mirrorMissing=!0,B.save(g),await B.flush(!0),d!==p)return;let G=await Mi(E);if(d!==p)return;if(!G||te()){Pt("vault-missing");return}}if(await a.mkdir(E,{recursive:!0}),Z=await Cr(E),d!==p)return}if(!Z?.isDirectory()){Pi(Z);return}if(typeof Z.dev=="number"&&Number.isInteger(Z.dev)&&Z.dev>=0&&typeof Z.ino=="number"&&Number.isInteger(Z.ino)&&Z.ino>0){let L=l?await l(E):{dev:Z.dev,ino:Z.ino,...Z.birthtimeMs&&Z.birthtimeMs>0?{birthtimeMs:Z.birthtimeMs}:{}};if(d!==p)return;if(!Gt(L))throw Error("Invalid sync root identity; original state retained");let G=g.rootIdentity,he=G&&!ln(G,L);if(!ct(L,Z)){Pt("vault-changed");return}let me=!G&&!e&&Le().isManagedCloudVault(E)&&(Object.keys(g.files).length>0||te());if(he||g.mirrorMissing||me){let je=(!G||(G.volumeId?G.volumeId===L.volumeId:G.dev===L.dev))&&await Mi(E),kt=je&&(await a.readdir(E,{withFileTypes:!0})).every(ta=>ta.isDirectory()&&n.excludePrefixes?.includes(ta.name+"/")),ea=kt&&await Cr(E);if(d!==p)return;if(kt){if(!ea||!ct(L,ea)||te()){Pt("vault-changed");return}g.files={},g.cursor=0,g.lastSyncAt=null,g.mirrorRestore="list"}else if(he||g.mirrorMissing&&!G){Pt("vault-changed");return}else if(me){if(!je||te()){Pt("vault-changed");return}g.mirrorRestore="list"}}if(P=L,(g.mirrorMissing||JSON.stringify(G)!==JSON.stringify(L))&&(delete g.mirrorMissing,g.rootIdentity=L,B.save(g),await B.flush(!0)),d!==p||!await We())return}else{if(g.mirrorMissing){Pt("vault-changed");return}if(!Pi(Z))return}if(d!==p)return;h=!0,sd();for(let L of g.moves??[])z({key:`move:${Ve(L)}`,run:()=>Tr(L)});z({run:on}),z({run:async()=>{od()}})}catch(Y){if(d!==p)return;ge(Y)?U("auth-required","login-expired"):(U("offline",Y?.message||String(Y)),vt())}},Xo=()=>{f=!1,h=!1,Mn(),Ni(),J.length=0,C.clear(),Ee();for(let d of[T,R,H,V])d&&clearTimeout(d);T=R=H=V=null,Ie?.abort.abort(),Ie=null},Zo=async()=>{I&&await new Promise(d=>w.add(d)),await Promise.all(Ko.splice(0)),await B.flush(),g=null,P=null,x=null,k=null,E=null,M=0,W.clear(),de.clear(),Vt=0,j=null,X.clear(),ee=!1,ne=!1,fe.length=0,y="disabled",S=null},ld=()=>{Qo()},Ir=null,Pn=()=>{se=!1,Ir?.(),Ir=Le().onBeforeQuit(ld);let d=++p;Xo();let b=m.catch(()=>{}).then(async()=>{await Zo(),d===p&&(f=!0,await cd(d))});return m=b,b},Qo=()=>{Ir?.(),Ir=null,++p,Xo();let d=m.catch(()=>{}).then(Zo);return m=d,d},$t=()=>({enabled:y!=="disabled",state:y==="idle"&&(re.size||de.size)?"syncing":y,lastSyncAt:g?.lastSyncAt??null,pending:J.length+re.size+de.size,conflicts:M,skipped:[...W].map(([d,b])=>({path:d,reason:b})),error:S,pendingDeletions:X.size,maxFileBytes:j});return{getStatus:$t,start(){Pn()},notifyLocal(d,b,v){if(!g||y==="disabled"||y==="auth-required")return;let _=r(d),O=v?r(v):null;if(b==="write"&&_){Vn(_.split("/").pop()||"")||pe(_);return}if(b==="remove"){if(!_)return;let F=`${_}/`,Y=!1;for(let $ of Object.keys(g.files))($===_||$.startsWith(F))&&(Y=!0,z({key:$,run:()=>Ae($)}));!Y&&_&&z({key:_,run:()=>Ae(_)})}},holdLocalMove(d,b){let v=O=>n.serverDir?`${n.serverDir}/${O.replace(/\\/g,"/").normalize("NFC")}`:O.replace(/\\/g,"/").normalize("NFC"),_={from:v(d),to:v(b)};return++Se,Ar.add(_),()=>{Ar.delete(_)}},async notifyLocalMove(d,b,v,_){let O=r(d),F=r(b),Y=g??await xs(n.shadowName),$=_s(d,""),Z=$&&(n.serverDir?`${n.serverDir}/${$}`:$);if(!O&&F&&Z&&Y&&Object.keys(Y.files).some(te=>te===Z||te.startsWith(`${Z}/`))&&(O=Z),!O&&!F){v?.();return}if(O&&F){let te=g??Y;if(!te){v?.();return}let L=_??(Object.keys(te.files).some(he=>he.startsWith(`${O}/`))?"folder":"file"),G={from:O,to:F,kind:L};te.moves??=[],te.moves.some(he=>Ve(he)===Ve(G))||(te.moves.push(G),++Se),v&&xr.set(Ve(G),v),B.save(te);try{await B.flush(!0)}catch(he){throw te.moves=te.moves.filter(me=>Ve(me)!==Ve(G)),xr.delete(Ve(G)),B.save(te),he}g===te&&f&&y!=="disabled"&&y!=="auth-required"&&z({key:`move:${Ve(G)}`,run:()=>Tr(G)});return}O&&this.notifyLocal(d,"remove"),F&&(z({key:F,run:()=>Ae(F)}),Rr()),v?.()},async setEnabled(d){let b=await Ze(o);return await Ct({cloudSync:{...b.cloudSync??{},enabled:d}},o),await Pn(),$t()},async restart(){return await Pn(),$t()},async syncNow(){if(W.clear(),!h){let d=p;if(await m,d!==p)return $t()}if(y==="disabled"||y==="auth-required"||y==="error"||y==="offline"||!h||!x)await Pn();else{R&&(clearTimeout(R),vr());for(let d of g?.moves??[])z({key:`move:${Ve(d)}`,run:()=>Tr(d)});z({run:on})}return $t()},confirmMassDeletions(){return!h||!X.size||(ee=!0,z({run:on})),$t()},stop:Qo};function Rr(){f&&(H&&clearTimeout(H),H=setTimeout(()=>{H=null,z({run:$i})},Pp))}}function Ts(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 Is(t){return/\.md$/i.test(t)?Ts(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function Oc(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 zp=t=>ve().sha256Hex(t).slice(0,8),Bp=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",ti="\u4E0E\u6211\u5171\u4EAB";function Mc(t,e){let n=zp(`${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:`${ti}/${Bp(t.title)}-${n}`,serverDir:r,inScope:(i,s)=>e.some(o=>Oc(o,i,s)),scopeKey:e.map(i=>i.root).join("\0")}}function Pc(t){return Mc(t,[Ts(t.path),...(t.items??[]).map(Is)])}function $c(t){let e=t.map(Pc),n=t.flatMap((i,s)=>{let o=e[s].serverDir?`${e[s].serverDir}/`:"";return(i.items??[]).filter(a=>!a.startsWith(o)).map(a=>Mc({vaultId:i.vaultId,path:a,title:(a.split("/").pop()??a).replace(/\.md$/i,"")},[Is(a)]))}),r=new Map;for(let i of[...e,...n])r.has(i.key)||r.set(i.key,i);return[...r.values()]}var qp=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 Nc(t,e){let n=c=>c.normalize("NFC"),r=n(e.replace(/\\/g,"/")),i=t.find(c=>r.startsWith(`${n(c.localRelDir)}/`));if(!i)return null;let s=r.slice(n(i.localRelDir).length+1),o=qp(i.serverDir?`${i.serverDir}/${s}`:s);if(!o||o===".."||o.startsWith("../"))return null;let a=[i,...t].find(c=>c.vaultId===i.vaultId&&(!c.serverDir||o.startsWith(`${c.serverDir}/`))&&c.inScope(o,Ue(o)));return a?`${a.localRelDir}/${a.serverDir?o.slice(a.serverDir.length+1):o}`:null}function Rs(){let t=Le().readCreds(),e=Fe(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let f=Le().readCreds();if(n.signal.aborted||!e||Fe(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},i=()=>{let f=r();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},s=async(f,h,p)=>{let m=r();if(!m.cloudUrl||!m.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let w=await fetch(`${m.cloudUrl.replace(/\/+$/,"")}/api/amadeus${h}`,{method:f,headers:{Authorization:`Bearer ${m.token}`,...p!==void 0?{"Content-Type":"application/json"}:{}},body:p!==void 0?JSON.stringify(p):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!w.ok){let S=null;try{S=await w.json()}catch{}throw Object.assign(new Error(S?.detail||`http ${w.status}`),{status:w.status,code:S?.code})}let y=await w.json();return r(),y},o=null,a=async()=>(r(),o||(o=(await s("GET","/vaults")).vaults[0]?.id??"default",o)),c=()=>{try{let f=(r().token??"").split(".")[1],h=JSON.parse(Et(Or(f)));return typeof h.userId=="string"?h.userId:null}catch{return null}},l=async()=>(await s("GET","/shared-with-me")).items.map(h=>{let p=Pc(h),m=h.path.split("/").pop()??h.path;return{...h,localPath:`${p.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(/\/+$/,"")||i()}catch{u=i()}return u},async heartbeat(f,h){let p=(f??"").replace(/\\/g,"/"),m,w=null,y=h.find(S=>p.startsWith(`${S.localRelDir}/`));y?(m=y.vaultId,w=y.serverDir?`${y.serverDir}/${p.slice(y.localRelDir.length+1)}`:p.slice(y.localRelDir.length+1)):(m=await a(),w=p||null),await s("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:w})}}}import{promises as Lc}from"node:fs";import Wp from"node:path";var Ds=".forsion-vault.md",jc=t=>`${t}/${Ds}`;function ni(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 Fc=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 Cs(t){let e=Ge(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function cn(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=Cs(o);return!!s&&r.startsWith(s)})}function As(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 qn(t,e,n){let r=!1,o=t.map(s=>{let i=As(s,e,n);return i===null?s:(r=!0,i)});return{changed:r,next:o}}async function Mc(t){let e=await Oc.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 Oc.readFile(jp.join(t,o.name,_s),"utf8").catch(()=>null);if(s===null)continue;n.push(o.name);let i=Xr(s);i?.length&&(r[o.name]=i)}return{names:n.sort(),devices:r}}var Re={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 Zr=t=>ve().sha256Hex(t).slice(0,8);function Pc(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Mt(t,e=[]){let n=[],r=[];for(let o of t){let s=Ge(o.path);if(!s)continue;r.push(s);let i=Cs(o);i&&n.push(i)}return{entries:t,exclude:e,prefixes:n,paths:r}}function $c(t,e){let n=Pc(Ge(e));if(!n)return!1;if(cn(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 Wn(t,e,n){let r=!1,o=t.map(s=>{let i=As(s.path,e,n);return i===null?s:(r=!0,{...s,path:i})});return{changed:r,next:o}}function Nc(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?Wn(t,n,r):{changed:!1,next:t}}function xs(t,e){let n=Ot(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Kr?`\u300C${Kr}\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 Fp,promises as jc}from"node:fs";async function Fc(t,e){try{await jc.copyFile(qt(t),qt(e),Fp.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await jc.unlink(qt(t)).catch(()=>{}),!0}var Lp=/^\d{4}-\d{2}-\d{2}$/,Lc=["vault","content"],Uc=new Set(pc),Up=40,ln=t=>new Date(t).toISOString().slice(0,10),Yn=t=>typeof t=="string"&&Lp.test(t),Hc=!1,Qe=Object.create(null),un=!1,Ts=()=>Date.now(),Vn=new Set,Qr="";function at(t,e,n=1,r){try{if(!Hc||!Uc.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let o=ln(Ts());if(r!==void 0){o!==Qr&&(Vn.clear(),Qr=o);let a=`${t}\0${e}\0${r}`;if(Vn.has(a))return;Vn.add(a)}let s=Qe[o]??={},i=s[t]??={};i[e]=(i[e]??0)+Math.round(n),un=!0}catch{}}function Is(t){Hc=t}function zc(t){if(Qe=Object.create(null),Vn.clear(),Qr="",un=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!Yn(e)||!n||typeof n!="object"))for(let r of Lc){let o=n[r];if(!o||typeof o!="object")continue;let s={};for(let[i,a]of Object.entries(o))Uc.has(i)&&typeof a=="number"&&Number.isFinite(a)&&a>0&&(s[i]=Math.round(a));Object.keys(s).length&&((Qe[e]??={})[r]=s)}}}function Bc(){let t=ln(Ts()-Up*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 qc=()=>un,Wc=()=>{un=!1};function Vc(t,e){let n=[];for(let r of Object.keys(Qe).sort())if(!(r<=t||r>e))for(let o of Lc){let s=Qe[r][o];s&&Object.keys(s).length&&n.push({day:r,system:o,counts:{...s}})}return n}function Rs(t){for(let e of Object.keys(Qe))e<=t&&(delete Qe[e],un=!0)}function Yc(){Object.keys(Qe).length&&(un=!0),Qe=Object.create(null),Vn.clear(),Qr=""}function Gc(t){Ts=t}var Jc=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],Ds=t=>Jc.every(e=>typeof t[e]=="function"),Bp=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function Os(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Re.get,()=>e?e.get():Bp()),t.handle(Re.setEnabled,(r,o)=>n().setEnabled(o)),t.handle(Re.syncNow,()=>n().syncNow()),t.handle(Re.confirmDeletions,()=>n().confirmDeletions()),t.handle(Re.entryGet,()=>n().entryGet()),t.handle(Re.otherSideDbs,()=>n().otherSideDbs()),t.handle(Re.entryEnable,(r,o)=>n().entryEnable(o)),t.handle(Re.entryDisable,(r,o)=>n().entryDisable(o)),t.handle(Re.entryMark,(r,o,s)=>n().entryMark(o,s)),t.handle(Re.entryClosure,(r,o,s)=>n().entryClosure(o,s)),t.handle(Re.collabCall,(r,o,s)=>n().collabCall(o,s)),t.handle(Re.switchSide,(r,o)=>n().switchSide(r.sender.id,o)),t.setAmadeusSyncFactory(r=>{ic(r),cc(qp(t));let o=Kc(r);return e=o.handlers,o.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function qp(t){let e=t.contentSync?.merge;return e?(n,r,o,s)=>{if(!/\.db$/i.test(n)||/^(agents|human)(\/|$)/.test(n))return null;let i;try{i=e(n,r,o,s)}catch{return null}return i&&!i.conflict&&!Wp(o,r,i.content)?null:i}:null}function Wp(t,e,n){let r,o,s;try{[r,o,s]=[JSON.parse(t),JSON.parse(e),JSON.parse(n)]}catch{return!1}let i=l=>Array.isArray(l)&&l.every(u=>u&&typeof u=="object"&&typeof u.id=="string")?l.map(u=>u.id):null,a=(l,u)=>l.filter(d=>u.includes(d)),c=(l,u)=>l.length===u.length&&l.every((d,g)=>d===u[g]);for(let l of Object.keys(o)){let u=i(o[l]),d=i(r?.[l]);if(!u||!d||c(a(d,u),a(u,d)))continue;let g=i(s?.[l]);if(!g||!c(a(u,g),a(g,u)))return!1}return!0}function Kc(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,o=!1,s=Es(),i=new Map,a=()=>{let _=Date.now();for(let[x,T]of i)_-T.at>7e4&&i.delete(x);e(Re.presence,[...i.values()])},l={loadCreds:()=>t.readCreds(),onHealth:(_,x,T)=>at("vault",_,x,T),onStatus:_=>e(Re.status,{..._,pendingDeletions:Ee(),side:p()?"cloud":"local"}),onPresence:(_,x)=>{let T=x;T?.userId&&(i.set(T.userId,{userId:T.userId,username:String(T.username??"user"),page:T.page??null,at:Number(T.at)||Date.now()}),a())},onPresenceRoster:(_,x)=>{if(Array.isArray(x)){for(let T of x){let I=T;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:x=>{_===r&&l.onStatus(x)},onPresence:(x,T)=>{_===r&&l.onPresence(x,T)},onPresenceRoster:(x,T)=>{_===r&&l.onPresenceRoster(x,T)}}},d=Bn(u()),g=new Map,h=[],m=0,y=async()=>{if(!o||!je())return;let _=r,x=++m,T=s,I;try{I=await T.sharedWithMe()}catch{return}if(_!==r||!o||x!==m)return;let M=Tc(I);h=M;let H=new Map(M.map(W=>[W.key,W.scopeKey]));for(let[W,B]of g)if(H.get(W)!==B.plan.scopeKey){if(await B.engine.stop(),_!==r)return;g.delete(W)}for(let W of M){if(g.has(W.key))continue;let B=Bn(u(),{localRoot:Wt.join(Dt(),...W.localRelDir.split("/")),shadowName:`amadeus-sync-${Un()}-share-${W.key}`,vaultId:W.vaultId,serverDir:W.serverDir,inScope:W.inScope});g.set(W.key,{engine:B,plan:W}),B.start()}},p=()=>n()===Dt(),S=(_,x=_.base)=>{_.base=x;let T=[x,..._.pendingMoves];_.scope.current=Mt(T.flatMap(I=>I.entries),T.flatMap(I=>I.exclude))},k=new Map,P=new Set,R=new Set,O=null,w=()=>O??=new Promise(_=>{let x=()=>zp.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return _(x());Hp("scutil",["--get","ComputerName"],{timeout:1500},(T,I)=>_(!T&&String(I).trim()||x()))}),A=async()=>{let _=(await Ye()).cloudSync?.deviceId;return _?{id:_,name:await w()}:null},C=new Map,D=(_,x,T)=>{let I=r,M=(C.get(_)??Promise.resolve()).catch(()=>{}).then(async()=>{I!==r||T&&!await T()||I!==r||await L(_,x,I)});return C.set(_,M),M.finally(()=>{C.get(_)===M&&C.delete(_)}).catch(()=>{}),M},L=async(_,x,T)=>{let I=s,M=encodeURIComponent(await I.ensureOwnVault()),H=Rc(_);for(let W=0;W<3;W++){let B=null;try{B=await I.call("GET",`/vaults/${M}/file?path=${encodeURIComponent(H)}`)}catch(J){if(J?.status!==404)throw J}let q=x(!!B,B?Xr(B.content):null);if(q===void 0||T!==r)return;try{if(q===null){B&&await I.call("DELETE",`/vaults/${M}/file?path=${encodeURIComponent(H)}&baseSeq=${B.seq}`);return}await I.call("PUT",`/vaults/${M}/file`,{path:H,content:Dc(q),baseSeq:B?.seq??0});return}catch(J){if(J?.status!==409)throw J}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},j=async _=>!!(await Ye()).entrySync?.some(x=>x.cloudName===_&&x.entries.length>0),X=(_,x)=>D(_,(T,I)=>{let M=I?.find(W=>W.id===x.id);if(M&&M.name===x.name)return;let H=M?.since??new Date().toISOString().slice(0,10);return[...(I??[]).filter(W=>W.id!==x.id),{...x,since:H}]},()=>j(_)),K=(_,x)=>D(_,(T,I)=>{if(!T||!I?.some(H=>H.id===x))return;let M=I.filter(H=>H.id!==x);return M.length?M:null},async()=>!await j(_)),te=()=>{e(Re.entryChange)},ne=async(_,x)=>{let T=k.get(_);if(!T)return;let I=W=>W&&W.startsWith(`${T.cloudName}/`)?W.slice(T.cloudName.length+1):null,M=I(x.path);if(!M)return;let H=!1;await sn(W=>{if(k.get(_)!==T)return!1;let B=(W.entrySync??[]).find(de=>de.vaultRoot===_);if(!B)return!1;let q=x.op,J=I(x.newPath),Z=Nc(B.entries,q,M,J),re=J?qn(B.exclude??[],M,J):{changed:!1,next:B.exclude??[]};if(!Z.changed&&!re.changed)return!1;H=!0,B.entries=Z.next,re.changed&&(B.exclude=re.next),S(T,Mt(B.entries,B.exclude??[]))}),H&&k.get(_)===T&&te()},Q=_=>{let x=r;return{...u(),onStatus:T=>{x===r&&e(Re.status,{...T,pendingDeletions:Ee(),side:"local",binding:_})},onRemoteApplied:async T=>{x===r&&await ne(_,T)}}},ee=async()=>{let _=je();if(!o||!_)return;let x=r,T=s,I=Un(_);await t.adoptLegacyCloudState(_,Fc);let M=await Ye(_),H=M.entrySync??[];if(x!==r||!o||_!==je())return;let W=new Map(H.map(B=>[B.vaultRoot,B]));for(let[B,q]of k){let J=W.get(B);if(!(J&&J.cloudName===q.cloudName)&&(await q.engine.stop(),x!==r||(k.delete(B),J&&await kc(`amadeus-sync-${I}-entry-${Zr(B)}`),x!==r)))return}for(let B of H){let q=k.get(B.vaultRoot);if(q){S(q,Mt(B.entries,B.exclude??[]));continue}let J={current:Mt(B.entries,B.exclude??[])},Z=B.cloudName,re=Bn(Q(B.vaultRoot),{accountId:_,localRoot:B.vaultRoot,shadowName:`amadeus-sync-${I}-entry-${Zr(B.vaultRoot)}`,vaultId:"first",serverDir:Z,clientIdSuffix:`entry-${Zr(B.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:de=>de===Z?!0:de.startsWith(`${Z}/`)?$c(J.current,de.slice(Z.length+1)):!1});k.set(B.vaultRoot,{engine:re,scope:J,cloudName:Z,base:J.current,pendingMoves:new Set}),re.start()}if(M.cloudSync?.enabled!==!1)for(let B of H){let q=B.entries.length>0,J=q?P:R;J.has(B.cloudName)||((q?R:P).delete(B.cloudName),(async()=>{try{let Z=await A();if(!Z||x!==r||(await(q?X(B.cloudName,Z):K(B.cloudName,Z.id)),x!==r))return;J.add(B.cloudName),(q?R:P).delete(B.cloudName)}catch{}})())}},ge=async(_,x,T,I,M)=>{let H=x.replace(/\\/g,"/").normalize("NFC"),W=T.replace(/\\/g,"/").normalize("NFC"),B=!1,q,J,Z,re=M??"file";try{await sn(async de=>{if(k.get(_)!==I)return!1;let we=(de.entrySync??[]).find(pe=>pe.vaultRoot===_);if(!we)return!1;let _e=Wn(we.entries,H,W),be=qn(we.exclude??[],H,W),$e=cn(we.entries,we.exclude,H);!M&&await dn.stat(Wt.join(_,...W.split("/"))).then(pe=>pe.isDirectory(),()=>!1)&&(re="folder");let fe=re==="folder"?"folder":/\.md$/i.test(W)?"page":"asset";$e&&!cn(_e.next,be.next,W)&&(_e.next.push({path:W,kind:fe}),_e.changed=!0),B=_e.changed||be.changed;let ot=we.entries.filter(pe=>Wn([pe],H,W).changed);return $e&&!ot.some(pe=>pe.path===H)&&ot.push({path:H,kind:fe}),q=Mt(ot,(we.exclude??[]).filter(pe=>qn([pe],H,W).changed)),J=I.base,I.pendingMoves.add(q),we.entries=_e.next,we.exclude=be.next,Z=Mt(we.entries,we.exclude),S(I,Z),B})}catch(de){throw q&&I.pendingMoves.delete(q),S(I,I.base===Z&&J?J:I.base),de}try{q&&await I.engine.notifyLocalMove(H,W,()=>{I.pendingMoves.delete(q),S(I)},re)}catch(de){throw q&&I.pendingMoves.delete(q),await sn(we=>{let _e=we.entrySync?.find(be=>be.vaultRoot===_);if(!_e)return!1;_e.entries=Wn(_e.entries,W,H).next,_e.exclude=qn(_e.exclude??[],W,H).next,S(I,Mt(_e.entries,_e.exclude))}),de}B&&k.get(_)===I&&te()},ue=_=>{let x=_.replace(/\\/g,"/");for(let{engine:T,plan:I}of g.values())if(x.startsWith(`${I.localRelDir}/`))return{engine:T,rel:x.slice(I.localRelDir.length+1)};return{engine:d,rel:x}};t.setMutationHooks((_,x)=>{if(p()){let T=ue(_);T.engine.notifyLocal(T.rel,x);return}k.get(n()??"")?.engine.notifyLocal(_,x)},(_,x,T)=>{if(p()){let H=ue(_),W=ue(x);if(H.engine===W.engine)return H.engine.notifyLocalMove(H.rel,W.rel,void 0,T);H.engine.notifyLocal(H.rel,"remove"),W.engine.notifyLocal(W.rel,"write");return}let I=n()??"",M=k.get(I);if(M)return ge(I,_,x,M,T)},(_,x)=>{if(p()){let T=ue(_),I=ue(x),M=[T.engine.holdLocalMove(T.rel,I.rel)];return T.engine!==I.engine&&M.push(I.engine.holdLocalMove(T.rel,I.rel)),()=>{for(let H of M)H()}}return k.get(n()??"")?.engine.holdLocalMove(_,x)});let Ee=()=>{let _=d.getStatus().pendingDeletions;for(let{engine:x}of g.values())_+=x.getStatus().pendingDeletions;for(let{engine:x}of k.values())_+=x.getStatus().pendingDeletions;return _},he=_=>({..._,pendingDeletions:Ee(),side:p()?"cloud":"local"}),nt=()=>{if(!o)return Promise.resolve(d.getStatus());y();for(let{engine:_}of g.values())_.syncNow();for(let{engine:_}of k.values())_.syncNow();return d.syncNow()},rt=async()=>{let _=++r;o=!1,s.stop();let x=[d.stop(),...[...g.values()].map(({engine:I})=>I.stop()),...[...k.values()].map(({engine:I})=>I.stop())];if(g.clear(),k.clear(),h=[],P.clear(),R.clear(),i.clear(),a(),await Promise.all(x),await t.awaitPendingVaultWrites(),_!==r)return;let T=n();if(T&&zr(T)){let I=await Ye();if(_!==r)return;let M=I.localVault&&!zr(I.localVault)?I.localVault:Wt.join(t.workspaceDir(),"Amadeus");if(await dn.mkdir(M,{recursive:!0}),_!==r||(await Et({lastVault:M,localVault:M,lastPage:void 0}),_!==r))return;await t.activateRoot(M,!1)}_===r&&te()};return{handlers:{get:()=>he(d.getStatus()),setEnabled:async _=>{if(!o)throw new Error("Cloud account is changing");let x=r;return await d.setEnabled(_),x!==r?d.getStatus():(await Promise.all([...g.values(),...k.values()].map(({engine:T})=>T.restart())),he(d.getStatus()))},syncNow:()=>nt(),confirmDeletions:()=>{for(let{engine:_}of g.values())_.confirmMassDeletions();for(let{engine:_}of k.values())_.confirmMassDeletions();return he(d.confirmMassDeletions())},entryGet:async()=>{let _=await Ye(),x=Dt(),T=await Mc(x);return{vaults:_.entrySync??[],activeRoot:n(),cloudRoot:x,mirrorVaults:T.names,mirrorVaultDevices:T.devices,deviceId:_.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let _=n();if(!_)return null;let x=Dt(),T=await Ye(),I=_===x?T.localVault&&T.localVault!==x?T.localVault:null:x;if(!I)return null;let M=[],H=500,W=async(B,q)=>{if(M.length>=H)return;let J;try{J=await dn.readdir(B,{withFileTypes:!0})}catch{return}for(let Z of J){if(M.length>=H)break;if(Z.name.startsWith(".")||Z.isSymbolicLink())continue;let re=q?`${q}/${Z.name}`:Z.name;if(Z.isDirectory())await W(Wt.join(B,Z.name),re);else if(Z.isFile()&&/\.db$/i.test(Z.name))try{M.push({rel:re,source:await dn.readFile(Wt.join(B,Z.name),"utf8")})}catch{}}};return await W(I,""),{root:I,vaultName:I===x?"\u4E91\u7AEF":Wt.basename(I),dbs:M}},entryEnable:async _=>{let x=r,T=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 M=await Ye(),H=M.entrySync??[],W=H.find(B=>B.vaultRoot===I);if(!W){let B=(_.cloudName??Wt.basename(I)).normalize("NFC").trim(),q=xs(B,H.map(J=>J.cloudName));if(q)return{error:q};if(!_.merge)try{let J=await T.ensureOwnVault(),Z=await T.call("GET",`/vaults/${encodeURIComponent(J)}/tree`);if((Z.folders??[]).some(de=>de===B||de.startsWith(`${B}/`))||(Z.entries??[]).some(de=>de.path===B||de.path.startsWith(`${B}/`)))return{conflict:B}}catch(J){return{error:J?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}W={vaultRoot:I,cloudName:B,entries:[]},H.push(W)}return x!==r||!o?{error:"Cloud account changed; retry from the current account"}:(await sn(B=>{if(x!==r||!o)return!1;let q=B.entrySync??[],J=q.find(be=>be.vaultRoot===I);if(!J){let be=xs(W.cloudName,q.map($e=>$e.cloudName));if(be)throw new Error(be);J={vaultRoot:I,cloudName:W.cloudName,entries:[]},q.push(J)}let Z=be=>String(be??"").replace(/\\/g,"/").normalize("NFC"),re=new Set;for(let be of _.entries??[]){let $e=Z(be.path);$e&&(re.add($e),!J.entries.some(fe=>fe.path===$e)&&J.entries.push({path:$e,kind:be.kind==="folder"||be.kind==="asset"?be.kind:"page"}))}let de=(_.exclude??[]).map(Z).filter(Boolean),we=new Set([...re,...(_.include??[]).map(Z).filter(Boolean)]);J.exclude=[...new Set([...(J.exclude??[]).filter(be=>!we.has(be)),...de])];let _e=new Set(de);J.entries=J.entries.filter(be=>!_e.has(be.path)),B.entrySync=q,W=J},M.cloudAccountId),x!==r?{error:"Cloud account changed; retry from the current account"}:(await ee(),k.get(I)?.engine.syncNow(),te(),{ok:!0,cloudName:W.cloudName}))},entryDisable:async _=>{let x=n(),T=!1,I=r;return await sn(M=>{if(I!==r||!o)return!1;let H=(M.entrySync??[]).find(q=>q.vaultRoot===x);if(!x||!H)return!1;let W=String(_??"").replace(/\\/g,"/").normalize("NFC"),B=H.entries.length;if(H.entries=H.entries.filter(q=>q.path!==W),cn(H.entries,H.exclude,W))H.exclude=[...new Set([...H.exclude??[],W])];else if(H.entries.length===B)return!1;T=!0}),!T||I!==r?{ok:!1}:(await ee(),te(),{ok:!0})},entryMark:async(_,x)=>{let T=String(_??"").normalize("NFC");if(!T||T.includes("/")||T.startsWith("."))return{error:"invalid name"};if(!o||!je())return{error:"Sign in first"};try{await D(T,I=>x?I?void 0:[]:I?null:void 0)}catch(I){return{error:I?.message||String(I)}}return d.syncNow(),{ok:!0}},entryClosure:(_,x)=>t.relatedClosure(String(_??""),x==="folder"?"folder":"page"),collabCall:async(_,x)=>{let T=s,I=async()=>T.ensureOwnVault(),M=W=>String((x??[])[W]??""),H=W=>(x??[])[W]??{};switch(_){case"listVaults":return(await T.call("GET","/vaults")).vaults;case"activeVaultId":return I();case"pageShare":return T.call("GET",`/vaults/${encodeURIComponent(await I())}/page-shares?path=${encodeURIComponent(M(0))}`);case"relatedItems":return T.call("GET",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(M(0))}/related`);case"setShareItem":return T.call("POST",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(M(0))}/items`,{path:M(1),included:(x??[])[2]===!0});case"createPageShare":return T.call("POST",`/vaults/${encodeURIComponent(await I())}/page-shares`,{path:M(0),...H(1)});case"updatePageShare":return T.call("PATCH",`/vaults/${encodeURIComponent(M(2)||await I())}/page-shares/${encodeURIComponent(M(0))}`,H(1));case"revokePageShare":return T.call("DELETE",`/vaults/${encodeURIComponent(await I())}/page-shares/${encodeURIComponent(M(0))}`);case"setParticipantRole":return T.call("PATCH",`/vaults/${encodeURIComponent(M(3)||await I())}/page-shares/${encodeURIComponent(M(0))}/members/${encodeURIComponent(M(1))}`,{role:M(2)});case"removeParticipant":return T.call("DELETE",`/vaults/${encodeURIComponent(M(2)||await I())}/page-shares/${encodeURIComponent(M(0))}/members/${encodeURIComponent(M(1))}`);case"sharedWithMe":{let W=await T.sharedWithMe();return y(),W}case"leaveShare":{let W=T.myUserId();if(!W)throw new Error("\u672A\u767B\u5F55");let B=await T.call("DELETE",`/vaults/${encodeURIComponent(M(1)||await I())}/page-shares/${encodeURIComponent(M(0))}/members/${encodeURIComponent(W)}`);return y(),B}case"publishes":return T.call("GET",`/vaults/${encodeURIComponent(await I())}/shares`);case"listAllShares":{let W=(await T.call("GET","/vaults")).vaults||[],B=T.myUserId(),q=[],J=[];for(let Z of W){try{let re=await T.call("GET",`/vaults/${encodeURIComponent(Z.id)}/shares`);for(let de of re.shares||[])q.push({...de,vaultId:Z.id,vaultName:Z.name||""})}catch(re){t.log(`[connect] listAllShares publishes vault ${Z.id} failed: ${re?.message}`)}try{let re=await T.call("GET",`/vaults/${encodeURIComponent(Z.id)}/page-shares?expired=1`),de=re?.shares||re?.pageShares||(Array.isArray(re)?re:[]);for(let we of de){let _e=we.created_by??we.createdBy;(!B||!_e||_e===B)&&J.push({...we,vaultId:Z.id,vaultName:Z.name||""})}}catch(re){t.log(`[connect] listAllShares pageShares vault ${Z.id} failed: ${re?.message}`)}}return{publishes:q,pageShares:J,linkBase:await T.linkBase()}}case"createPublish":{let W=await T.call("POST",`/vaults/${encodeURIComponent(await I())}/shares`,{mode:M(0),path:M(1)});return{...W,url:`${await T.linkBase()}/share/${W.token}`}}case"revokePublish":return T.call("DELETE",`/vaults/${encodeURIComponent(await I())}/shares/${encodeURIComponent(M(0))}`);case"revokePublishIn":return T.call("DELETE",`/vaults/${encodeURIComponent(M(0))}/shares/${encodeURIComponent(M(1))}`);case"revokePageShareIn":return T.call("DELETE",`/vaults/${encodeURIComponent(M(0))}/page-shares/${encodeURIComponent(M(1))}`);case"myUserId":return T.myUserId();case"linkBase":return T.linkBase();case"heartbeat":return T.heartbeat((x??[])[0]??null,h);default:throw new Error(`unknown collab fn: ${_}`)}},switchSide:async(_,x)=>{let T=await Ye();if(x==="cloud"){if(!o||!je())throw new Error("Sign in to open cloud notes");let H=Dt();await dn.mkdir(H,{recursive:!0}),T.lastVault&&!zr(T.lastVault)&&await Et({localVault:T.lastVault}),await Et({lastVault:H});let W=await t.activateRoot(H,!1);return t.bindRenderer(_,H),{...W,side:"cloud"}}let I=T.localVault&&await dn.stat(T.localVault).then(H=>H.isDirectory()).catch(()=>!1)?T.localVault:null;if(!I){let H=await t.ensureDefaultVault();return t.bindRenderer(_,H.root),{...H,side:"local"}}await Et({lastVault:I});let M=await t.activateRoot(I,!1);return t.bindRenderer(_,I),{...M,side:"local"}}},instance:{start:()=>{o=!0,d.start(),y(),ee()},stopAllSync:rt,restartAllSync:async()=>{let _=rt(),x=r;await _,x===r&&(s=Es(),d=Bn(u()),o=!0,await Promise.all([d.restart(),y(),ee()]),x===r&&(te(),e(Re.status,he(d.getStatus()))))},resolveSharedAsset:_=>Ic(h,_)}}}import{hostname as Vp}from"node:os";var Yp=256*1024;function Xc(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>Yp}var Ms=45e3,Gp=3e3,Jp=16*1024,Kp=6e4,eo=t=>`${t.replace(/\/+$/,"")}/api`,Gn=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??Kp}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??Ms,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(`${eo(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"))>Jp,h=setTimeout(()=>r.abort(),g?0:Gp),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??Ms,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(`${eo(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Vp(),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??Ms,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(`
218
+ `;var Qe=t=>t.replace(/\\/g,"/").normalize("NFC");function Os(t){let e=Qe(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function fn(t,e,n){let r=Qe(n);if(!r)return!1;if(t.some(i=>Qe(i.path)===r))return!0;for(let i of e??[]){let s=Qe(i);if(!s)continue;let o=`${s.replace(/\.md$/i,"")}.fd`;if(r===s||r.startsWith(`${s}/`)||r===o||r.startsWith(`${o}/`))return!1}return t.some(i=>{let s=Os(i);return!!s&&r.startsWith(s)})}function Ms(t,e,n){let r=Qe(t),i=Qe(e);return r===i?Qe(n):r.startsWith(`${i}/`)?Qe(n)+r.slice(i.length):null}function Xn(t,e,n){let r=!1,i=t.map(s=>{let o=Ms(s,e,n);return o===null?s:(r=!0,o)});return{changed:r,next:i}}async function Uc(t){let e=await Lc.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let i of e){if(!i.isDirectory()||i.name.startsWith("."))continue;let s=await Lc.readFile(Wp.join(t,i.name,Ds),"utf8").catch(()=>null);if(s===null)continue;n.push(i.name);let o=ni(s);o?.length&&(r[i.name]=o)}return{names:n.sort(),devices:r}}var Re={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 ri=t=>ve().sha256Hex(t).slice(0,8);function Hc(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Ft(t,e=[]){let n=[],r=[];for(let i of t){let s=Qe(i.path);if(!s)continue;r.push(s);let o=Os(i);o&&n.push(o)}return{entries:t,exclude:e,prefixes:n,paths:r}}function zc(t,e){let n=Hc(Qe(e));if(!n)return!1;if(fn(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let i of t.paths)if(i.startsWith(r))return!0;for(let i of t.prefixes)if(i.startsWith(r))return!0;return!1}function Zn(t,e,n){let r=!1,i=t.map(s=>{let o=Ms(s.path,e,n);return o===null?s:(r=!0,{...s,path:o})});return{changed:r,next:i}}function Bc(t,e,n,r){if(e==="delete"||e==="delete-folder"){let i=Qe(n),s=t.filter(o=>{let a=Qe(o.path);return!(a===i||e==="delete-folder"&&a.startsWith(`${i}/`))});return{changed:s.length!==t.length,next:s}}return r?Zn(t,n,r):{changed:!1,next:t}}function Ps(t,e){let n=Nt(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===ti?`\u300C${ti}\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 Vp,promises as qc}from"node:fs";async function Wc(t,e){try{await qc.copyFile(Jt(t),Jt(e),Vp.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await qc.unlink(Jt(t)).catch(()=>{}),!0}var Yp=/^\d{4}-\d{2}-\d{2}$/,Vc=["vault","content"],Yc=new Set(vc),Gp=40,pn=t=>new Date(t).toISOString().slice(0,10),er=t=>typeof t=="string"&&Yp.test(t),Gc=!1,it=Object.create(null),hn=!1,$s=()=>Date.now(),Qn=new Set,ii="";function lt(t,e,n=1,r){try{if(!Gc||!Yc.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let i=pn($s());if(r!==void 0){i!==ii&&(Qn.clear(),ii=i);let a=`${t}\0${e}\0${r}`;if(Qn.has(a))return;Qn.add(a)}let s=it[i]??={},o=s[t]??={};o[e]=(o[e]??0)+Math.round(n),hn=!0}catch{}}function Ns(t){Gc=t}function Jc(t){if(it=Object.create(null),Qn.clear(),ii="",hn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!er(e)||!n||typeof n!="object"))for(let r of Vc){let i=n[r];if(!i||typeof i!="object")continue;let s={};for(let[o,a]of Object.entries(i))Yc.has(o)&&typeof a=="number"&&Number.isFinite(a)&&a>0&&(s[o]=Math.round(a));Object.keys(s).length&&((it[e]??={})[r]=s)}}}function Kc(){let t=pn($s()-Gp*864e5),e={};for(let n of Object.keys(it).sort()){if(n<t){delete it[n];continue}e[n]=JSON.parse(JSON.stringify(it[n]))}return e}var Xc=()=>hn,Zc=()=>{hn=!1};function Qc(t,e){let n=[];for(let r of Object.keys(it).sort())if(!(r<=t||r>e))for(let i of Vc){let s=it[r][i];s&&Object.keys(s).length&&n.push({day:r,system:i,counts:{...s}})}return n}function js(t){for(let e of Object.keys(it))e<=t&&(delete it[e],hn=!0)}function el(){Object.keys(it).length&&(hn=!0),it=Object.create(null),Qn.clear(),ii=""}function tl(t){$s=t}var nl=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],Fs=t=>nl.every(e=>typeof t[e]=="function"),Xp=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function Ls(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Re.get,()=>e?e.get():Xp()),t.handle(Re.setEnabled,(r,i)=>n().setEnabled(i)),t.handle(Re.syncNow,()=>n().syncNow()),t.handle(Re.confirmDeletions,()=>n().confirmDeletions()),t.handle(Re.entryGet,()=>n().entryGet()),t.handle(Re.otherSideDbs,()=>n().otherSideDbs()),t.handle(Re.entryEnable,(r,i)=>n().entryEnable(i)),t.handle(Re.entryDisable,(r,i)=>n().entryDisable(i)),t.handle(Re.entryMark,(r,i,s)=>n().entryMark(i,s)),t.handle(Re.entryClosure,(r,i,s)=>n().entryClosure(i,s)),t.handle(Re.collabCall,(r,i,s)=>n().collabCall(i,s)),t.handle(Re.switchSide,(r,i)=>n().switchSide(r.sender.id,i)),t.setAmadeusSyncFactory(r=>{hc(r),mc(Zp(t));let i=rl(r);return e=i.handlers,i.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function Zp(t){let e=t.contentSync?.merge;return e?(n,r,i,s)=>{if(!/\.db$/i.test(n)||/^(agents|human)(\/|$)/.test(n))return null;let o;try{o=e(n,r,i,s)}catch{return null}return o&&!o.conflict&&!Qp(i,r,o.content)?null:o}:null}function Qp(t,e,n){let r,i,s;try{[r,i,s]=[JSON.parse(t),JSON.parse(e),JSON.parse(n)]}catch{return!1}let o=l=>Array.isArray(l)&&l.every(u=>u&&typeof u=="object"&&typeof u.id=="string")?l.map(u=>u.id):null,a=(l,u)=>l.filter(f=>u.includes(f)),c=(l,u)=>l.length===u.length&&l.every((f,h)=>f===u[h]);for(let l of Object.keys(i)){let u=o(i[l]),f=o(r?.[l]);if(!u||!f||c(a(f,u),a(u,f)))continue;let h=o(s?.[l]);if(!h||!c(a(u,h),a(h,u)))return!1}return!0}function rl(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,i=!1,s=Rs(),o=new Map,a=()=>{let C=Date.now();for(let[I,T]of o)C-T.at>7e4&&o.delete(I);e(Re.presence,[...o.values()])},l={loadCreds:()=>t.readCreds(),onHealth:(C,I,T)=>lt("vault",C,I,T),onStatus:C=>e(Re.status,{...C,pendingDeletions:Te(),side:y()?"cloud":"local"}),onPresence:(C,I)=>{let T=I;T?.userId&&(o.set(T.userId,{userId:T.userId,username:String(T.username??"user"),page:T.page??null,at:Number(T.at)||Date.now()}),a())},onPresenceRoster:(C,I)=>{if(Array.isArray(I)){for(let T of I){let R=T;R?.userId&&o.set(R.userId,{userId:R.userId,username:String(R.username??"user"),page:R.page??null,at:Number(R.at)||Date.now()})}a()}}},u=()=>{let C=r;return{...l,onStatus:I=>{C===r&&l.onStatus(I)},onPresence:(I,T)=>{C===r&&l.onPresence(I,T)},onPresenceRoster:(I,T)=>{C===r&&l.onPresenceRoster(I,T)}}},f=Kn(u()),h=new Map,p=[],m=0,w=async()=>{if(!i||!Pe())return;let C=r,I=++m,T=s,R;try{R=await T.sharedWithMe()}catch{return}if(C!==r||!i||I!==m)return;let H=$c(R);p=H;let V=new Map(H.map(N=>[N.key,N.scopeKey]));for(let[N,U]of h)if(V.get(N)!==U.plan.scopeKey){if(await U.engine.stop(),C!==r)return;h.delete(N)}for(let N of H){if(h.has(N.key))continue;let U=Kn(u(),{localRoot:Kt.join(At(),...N.localRelDir.split("/")),shadowName:`amadeus-sync-${Wn()}-share-${N.key}`,vaultId:N.vaultId,serverDir:N.serverDir,inScope:N.inScope});h.set(N.key,{engine:U,plan:N}),U.start()}},y=()=>n()===At(),S=(C,I=C.base)=>{C.base=I;let T=[I,...C.pendingMoves];C.scope.current=Ft(T.flatMap(R=>R.entries),T.flatMap(R=>R.exclude))},g=new Map,P=new Set,x=new Set,D=null,k=()=>D??=new Promise(C=>{let I=()=>Kp.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return C(I());Jp("scutil",["--get","ComputerName"],{timeout:1500},(T,R)=>C(!T&&String(R).trim()||I()))}),A=async()=>{let C=(await Ze()).cloudSync?.deviceId;return C?{id:C,name:await k()}:null},E=new Map,M=(C,I,T)=>{let R=r,H=(E.get(C)??Promise.resolve()).catch(()=>{}).then(async()=>{R!==r||T&&!await T()||R!==r||await W(C,I,R)});return E.set(C,H),H.finally(()=>{E.get(C)===H&&E.delete(C)}).catch(()=>{}),H},W=async(C,I,T)=>{let R=s,H=encodeURIComponent(await R.ensureOwnVault()),V=jc(C);for(let N=0;N<3;N++){let U=null;try{U=await R.call("GET",`/vaults/${H}/file?path=${encodeURIComponent(V)}`)}catch(K){if(K?.status!==404)throw K}let Q=I(!!U,U?ni(U.content):null);if(Q===void 0||T!==r)return;try{if(Q===null){U&&await R.call("DELETE",`/vaults/${H}/file?path=${encodeURIComponent(V)}&baseSeq=${U.seq}`);return}await R.call("PUT",`/vaults/${H}/file`,{path:V,content:Fc(Q),baseSeq:U?.seq??0});return}catch(K){if(K?.status!==409)throw K}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},j=async C=>!!(await Ze()).entrySync?.some(I=>I.cloudName===C&&I.entries.length>0),B=(C,I)=>M(C,(T,R)=>{let H=R?.find(N=>N.id===I.id);if(H&&H.name===I.name)return;let V=H?.since??new Date().toISOString().slice(0,10);return[...(R??[]).filter(N=>N.id!==I.id),{...I,since:V}]},()=>j(C)),ie=(C,I)=>M(C,(T,R)=>{if(!T||!R?.some(V=>V.id===I))return;let H=R.filter(V=>V.id!==I);return H.length?H:null},async()=>!await j(C)),se=()=>{e(Re.entryChange)},X=async(C,I)=>{let T=g.get(C);if(!T)return;let R=N=>N&&N.startsWith(`${T.cloudName}/`)?N.slice(T.cloudName.length+1):null,H=R(I.path);if(!H)return;let V=!1;await dn(N=>{if(g.get(C)!==T)return!1;let U=(N.entrySync??[]).find(pe=>pe.vaultRoot===C);if(!U)return!1;let Q=I.op,K=R(I.newPath),z=Bc(U.entries,Q,H,K),re=K?Xn(U.exclude??[],H,K):{changed:!1,next:U.exclude??[]};if(!z.changed&&!re.changed)return!1;V=!0,U.entries=z.next,re.changed&&(U.exclude=re.next),S(T,Ft(U.entries,U.exclude??[]))}),V&&g.get(C)===T&&se()},ee=C=>{let I=r;return{...u(),onStatus:T=>{I===r&&e(Re.status,{...T,pendingDeletions:Te(),side:"local",binding:C})},onRemoteApplied:async T=>{I===r&&await X(C,T)}}},ne=async()=>{let C=Pe();if(!i||!C)return;let I=r,T=s,R=Wn(C);await t.adoptLegacyCloudState(C,Wc);let H=await Ze(C),V=H.entrySync??[];if(I!==r||!i||C!==Pe())return;let N=new Map(V.map(U=>[U.vaultRoot,U]));for(let[U,Q]of g){let K=N.get(U);if(!(K&&K.cloudName===Q.cloudName)&&(await Q.engine.stop(),I!==r||(g.delete(U),K&&await Ic(`amadeus-sync-${R}-entry-${ri(U)}`),I!==r)))return}for(let U of V){let Q=g.get(U.vaultRoot);if(Q){S(Q,Ft(U.entries,U.exclude??[]));continue}let K={current:Ft(U.entries,U.exclude??[])},z=U.cloudName,re=Kn(ee(U.vaultRoot),{accountId:C,localRoot:U.vaultRoot,shadowName:`amadeus-sync-${R}-entry-${ri(U.vaultRoot)}`,vaultId:"first",serverDir:z,clientIdSuffix:`entry-${ri(U.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:pe=>pe===z?!0:pe.startsWith(`${z}/`)?zc(K.current,pe.slice(z.length+1)):!1});g.set(U.vaultRoot,{engine:re,scope:K,cloudName:z,base:K.current,pendingMoves:new Set}),re.start()}if(H.cloudSync?.enabled!==!1)for(let U of V){let Q=U.entries.length>0,K=Q?P:x;K.has(U.cloudName)||((Q?x:P).delete(U.cloudName),(async()=>{try{let z=await A();if(!z||I!==r||(await(Q?B(U.cloudName,z):ie(U.cloudName,z.id)),I!==r))return;K.add(U.cloudName),(Q?x:P).delete(U.cloudName)}catch{}})())}},fe=async(C,I,T,R,H)=>{let V=I.replace(/\\/g,"/").normalize("NFC"),N=T.replace(/\\/g,"/").normalize("NFC"),U=!1,Q,K,z,re=H??"file";try{await dn(async pe=>{if(g.get(C)!==R)return!1;let Ee=(pe.entrySync??[]).find(de=>de.vaultRoot===C);if(!Ee)return!1;let _e=Zn(Ee.entries,V,N),ge=Xn(Ee.exclude??[],V,N),tt=fn(Ee.entries,Ee.exclude,V);!H&&await gn.stat(Kt.join(C,...N.split("/"))).then(de=>de.isDirectory(),()=>!1)&&(re="folder");let rn=re==="folder"?"folder":/\.md$/i.test(N)?"page":"asset";tt&&!fn(_e.next,ge.next,N)&&(_e.next.push({path:N,kind:rn}),_e.changed=!0),U=_e.changed||ge.changed;let vt=Ee.entries.filter(de=>Zn([de],V,N).changed);return tt&&!vt.some(de=>de.path===V)&&vt.push({path:V,kind:rn}),Q=Ft(vt,(Ee.exclude??[]).filter(de=>Xn([de],V,N).changed)),K=R.base,R.pendingMoves.add(Q),Ee.entries=_e.next,Ee.exclude=ge.next,z=Ft(Ee.entries,Ee.exclude),S(R,z),U})}catch(pe){throw Q&&R.pendingMoves.delete(Q),S(R,R.base===z&&K?K:R.base),pe}try{Q&&await R.engine.notifyLocalMove(V,N,()=>{R.pendingMoves.delete(Q),S(R)},re)}catch(pe){throw Q&&R.pendingMoves.delete(Q),await dn(Ee=>{let _e=Ee.entrySync?.find(ge=>ge.vaultRoot===C);if(!_e)return!1;_e.entries=Zn(_e.entries,N,V).next,_e.exclude=Xn(_e.exclude??[],N,V).next,S(R,Ft(_e.entries,_e.exclude))}),pe}U&&g.get(C)===R&&se()},oe=C=>{let I=C.replace(/\\/g,"/");for(let{engine:T,plan:R}of h.values())if(I.startsWith(`${R.localRelDir}/`))return{engine:T,rel:I.slice(R.localRelDir.length+1)};return{engine:f,rel:I}};t.setMutationHooks((C,I)=>{if(y()){let T=oe(C);T.engine.notifyLocal(T.rel,I);return}g.get(n()??"")?.engine.notifyLocal(C,I)},(C,I,T)=>{if(y()){let V=oe(C),N=oe(I);if(V.engine===N.engine)return V.engine.notifyLocalMove(V.rel,N.rel,void 0,T);V.engine.notifyLocal(V.rel,"remove"),N.engine.notifyLocal(N.rel,"write");return}let R=n()??"",H=g.get(R);if(H)return fe(R,C,I,H,T)},(C,I)=>{if(y()){let T=oe(C),R=oe(I),H=[T.engine.holdLocalMove(T.rel,R.rel)];return T.engine!==R.engine&&H.push(R.engine.holdLocalMove(T.rel,R.rel)),()=>{for(let V of H)V()}}return g.get(n()??"")?.engine.holdLocalMove(C,I)});let Te=()=>{let C=f.getStatus().pendingDeletions;for(let{engine:I}of h.values())C+=I.getStatus().pendingDeletions;for(let{engine:I}of g.values())C+=I.getStatus().pendingDeletions;return C},we=C=>({...C,pendingDeletions:Te(),side:y()?"cloud":"local"}),Je=()=>{if(!i)return Promise.resolve(f.getStatus());w();for(let{engine:C}of h.values())C.syncNow();for(let{engine:C}of g.values())C.syncNow();return f.syncNow()},Be=async()=>{let C=++r;i=!1,s.stop();let I=[f.stop(),...[...h.values()].map(({engine:R})=>R.stop()),...[...g.values()].map(({engine:R})=>R.stop())];if(h.clear(),g.clear(),p=[],P.clear(),x.clear(),o.clear(),a(),await Promise.all(I),await t.awaitPendingVaultWrites(),C!==r)return;let T=n();if(T&&Jr(T)){let R=await Ze();if(C!==r)return;let H=R.localVault&&!Jr(R.localVault)?R.localVault:Kt.join(t.workspaceDir(),"Amadeus");if(await gn.mkdir(H,{recursive:!0}),C!==r||(await Ct({lastVault:H,localVault:H,lastPage:void 0}),C!==r))return;await t.activateRoot(H,!1)}C===r&&se()};return{handlers:{get:()=>we(f.getStatus()),setEnabled:async C=>{if(!i)throw new Error("Cloud account is changing");let I=r;return await f.setEnabled(C),I!==r?f.getStatus():(await Promise.all([...h.values(),...g.values()].map(({engine:T})=>T.restart())),we(f.getStatus()))},syncNow:()=>Je(),confirmDeletions:()=>{for(let{engine:C}of h.values())C.confirmMassDeletions();for(let{engine:C}of g.values())C.confirmMassDeletions();return we(f.confirmMassDeletions())},entryGet:async()=>{let C=await Ze(),I=At(),T=await Uc(I);return{vaults:C.entrySync??[],activeRoot:n(),cloudRoot:I,mirrorVaults:T.names,mirrorVaultDevices:T.devices,deviceId:C.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let C=n();if(!C)return null;let I=At(),T=await Ze(),R=C===I?T.localVault&&T.localVault!==I?T.localVault:null:I;if(!R)return null;let H=[],V=500,N=async(U,Q)=>{if(H.length>=V)return;let K;try{K=await gn.readdir(U,{withFileTypes:!0})}catch{return}for(let z of K){if(H.length>=V)break;if(z.name.startsWith(".")||z.isSymbolicLink())continue;let re=Q?`${Q}/${z.name}`:z.name;if(z.isDirectory())await N(Kt.join(U,z.name),re);else if(z.isFile()&&/\.db$/i.test(z.name))try{H.push({rel:re,source:await gn.readFile(Kt.join(U,z.name),"utf8")})}catch{}}};return await N(R,""),{root:R,vaultName:R===I?"\u4E91\u7AEF":Kt.basename(R),dbs:H}},entryEnable:async C=>{let I=r,T=s;if(!i||!Pe())return{error:"Sign in to enable cloud sync"};let R=n();if(!R||y())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let H=await Ze(),V=H.entrySync??[],N=V.find(U=>U.vaultRoot===R);if(!N){let U=(C.cloudName??Kt.basename(R)).normalize("NFC").trim(),Q=Ps(U,V.map(K=>K.cloudName));if(Q)return{error:Q};if(!C.merge)try{let K=await T.ensureOwnVault(),z=await T.call("GET",`/vaults/${encodeURIComponent(K)}/tree`);if((z.folders??[]).some(pe=>pe===U||pe.startsWith(`${U}/`))||(z.entries??[]).some(pe=>pe.path===U||pe.path.startsWith(`${U}/`)))return{conflict:U}}catch(K){return{error:K?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}N={vaultRoot:R,cloudName:U,entries:[]},V.push(N)}return I!==r||!i?{error:"Cloud account changed; retry from the current account"}:(await dn(U=>{if(I!==r||!i)return!1;let Q=U.entrySync??[],K=Q.find(ge=>ge.vaultRoot===R);if(!K){let ge=Ps(N.cloudName,Q.map(tt=>tt.cloudName));if(ge)throw new Error(ge);K={vaultRoot:R,cloudName:N.cloudName,entries:[]},Q.push(K)}let z=ge=>String(ge??"").replace(/\\/g,"/").normalize("NFC"),re=new Set;for(let ge of C.entries??[]){let tt=z(ge.path);tt&&(re.add(tt),!K.entries.some(rn=>rn.path===tt)&&K.entries.push({path:tt,kind:ge.kind==="folder"||ge.kind==="asset"?ge.kind:"page"}))}let pe=(C.exclude??[]).map(z).filter(Boolean),Ee=new Set([...re,...(C.include??[]).map(z).filter(Boolean)]);K.exclude=[...new Set([...(K.exclude??[]).filter(ge=>!Ee.has(ge)),...pe])];let _e=new Set(pe);K.entries=K.entries.filter(ge=>!_e.has(ge.path)),U.entrySync=Q,N=K},H.cloudAccountId),I!==r?{error:"Cloud account changed; retry from the current account"}:(await ne(),g.get(R)?.engine.syncNow(),se(),{ok:!0,cloudName:N.cloudName}))},entryDisable:async C=>{let I=n(),T=!1,R=r;return await dn(H=>{if(R!==r||!i)return!1;let V=(H.entrySync??[]).find(Q=>Q.vaultRoot===I);if(!I||!V)return!1;let N=String(C??"").replace(/\\/g,"/").normalize("NFC"),U=V.entries.length;if(V.entries=V.entries.filter(Q=>Q.path!==N),fn(V.entries,V.exclude,N))V.exclude=[...new Set([...V.exclude??[],N])];else if(V.entries.length===U)return!1;T=!0}),!T||R!==r?{ok:!1}:(await ne(),se(),{ok:!0})},entryMark:async(C,I)=>{let T=String(C??"").normalize("NFC");if(!T||T.includes("/")||T.startsWith("."))return{error:"invalid name"};if(!i||!Pe())return{error:"Sign in first"};try{await M(T,R=>I?R?void 0:[]:R?null:void 0)}catch(R){return{error:R?.message||String(R)}}return f.syncNow(),{ok:!0}},entryClosure:(C,I)=>t.relatedClosure(String(C??""),I==="folder"?"folder":"page"),collabCall:async(C,I)=>{let T=s,R=async()=>T.ensureOwnVault(),H=N=>String((I??[])[N]??""),V=N=>(I??[])[N]??{};switch(C){case"listVaults":return(await T.call("GET","/vaults")).vaults;case"activeVaultId":return R();case"pageShare":return T.call("GET",`/vaults/${encodeURIComponent(await R())}/page-shares?path=${encodeURIComponent(H(0))}`);case"relatedItems":return T.call("GET",`/vaults/${encodeURIComponent(await R())}/page-shares/${encodeURIComponent(H(0))}/related`);case"setShareItem":return T.call("POST",`/vaults/${encodeURIComponent(await R())}/page-shares/${encodeURIComponent(H(0))}/items`,{path:H(1),included:(I??[])[2]===!0});case"createPageShare":return T.call("POST",`/vaults/${encodeURIComponent(await R())}/page-shares`,{path:H(0),...V(1)});case"updatePageShare":return T.call("PATCH",`/vaults/${encodeURIComponent(H(2)||await R())}/page-shares/${encodeURIComponent(H(0))}`,V(1));case"revokePageShare":return T.call("DELETE",`/vaults/${encodeURIComponent(await R())}/page-shares/${encodeURIComponent(H(0))}`);case"setParticipantRole":return T.call("PATCH",`/vaults/${encodeURIComponent(H(3)||await R())}/page-shares/${encodeURIComponent(H(0))}/members/${encodeURIComponent(H(1))}`,{role:H(2)});case"removeParticipant":return T.call("DELETE",`/vaults/${encodeURIComponent(H(2)||await R())}/page-shares/${encodeURIComponent(H(0))}/members/${encodeURIComponent(H(1))}`);case"sharedWithMe":{let N=await T.sharedWithMe();return w(),N}case"leaveShare":{let N=T.myUserId();if(!N)throw new Error("\u672A\u767B\u5F55");let U=await T.call("DELETE",`/vaults/${encodeURIComponent(H(1)||await R())}/page-shares/${encodeURIComponent(H(0))}/members/${encodeURIComponent(N)}`);return w(),U}case"publishes":return T.call("GET",`/vaults/${encodeURIComponent(await R())}/shares`);case"listAllShares":{let N=(await T.call("GET","/vaults")).vaults||[],U=T.myUserId(),Q=[],K=[];for(let z of N){try{let re=await T.call("GET",`/vaults/${encodeURIComponent(z.id)}/shares`);for(let pe of re.shares||[])Q.push({...pe,vaultId:z.id,vaultName:z.name||""})}catch(re){t.log(`[connect] listAllShares publishes vault ${z.id} failed: ${re?.message}`)}try{let re=await T.call("GET",`/vaults/${encodeURIComponent(z.id)}/page-shares?expired=1`),pe=re?.shares||re?.pageShares||(Array.isArray(re)?re:[]);for(let Ee of pe){let _e=Ee.created_by??Ee.createdBy;(!U||!_e||_e===U)&&K.push({...Ee,vaultId:z.id,vaultName:z.name||""})}}catch(re){t.log(`[connect] listAllShares pageShares vault ${z.id} failed: ${re?.message}`)}}return{publishes:Q,pageShares:K,linkBase:await T.linkBase()}}case"createPublish":{let N=await T.call("POST",`/vaults/${encodeURIComponent(await R())}/shares`,{mode:H(0),path:H(1)});return{...N,url:`${await T.linkBase()}/share/${N.token}`}}case"revokePublish":return T.call("DELETE",`/vaults/${encodeURIComponent(await R())}/shares/${encodeURIComponent(H(0))}`);case"revokePublishIn":return T.call("DELETE",`/vaults/${encodeURIComponent(H(0))}/shares/${encodeURIComponent(H(1))}`);case"revokePageShareIn":return T.call("DELETE",`/vaults/${encodeURIComponent(H(0))}/page-shares/${encodeURIComponent(H(1))}`);case"myUserId":return T.myUserId();case"linkBase":return T.linkBase();case"heartbeat":return T.heartbeat((I??[])[0]??null,p);default:throw new Error(`unknown collab fn: ${C}`)}},switchSide:async(C,I)=>{let T=await Ze();if(I==="cloud"){if(!i||!Pe())throw new Error("Sign in to open cloud notes");let V=At();await gn.mkdir(V,{recursive:!0}),T.lastVault&&!Jr(T.lastVault)&&await Ct({localVault:T.lastVault}),await Ct({lastVault:V});let N=await t.activateRoot(V,!1);return t.bindRenderer(C,V),{...N,side:"cloud"}}let R=T.localVault&&await gn.stat(T.localVault).then(V=>V.isDirectory()).catch(()=>!1)?T.localVault:null;if(!R){let V=await t.ensureDefaultVault();return t.bindRenderer(C,V.root),{...V,side:"local"}}await Ct({lastVault:R});let H=await t.activateRoot(R,!1);return t.bindRenderer(C,R),{...H,side:"local"}}},instance:{start:()=>{i=!0,f.start(),w(),ne()},stopAllSync:Be,restartAllSync:async()=>{let C=Be(),I=r;await C,I===r&&(s=Rs(),f=Kn(u()),i=!0,await Promise.all([f.restart(),w(),ne()]),I===r&&(se(),e(Re.status,we(f.getStatus()))))},resolveSharedAsset:C=>Nc(p,C)}}}import{hostname as eh}from"node:os";var th=256*1024;function il(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>th}var Us=45e3,nh=3e3,rh=16*1024,ih=6e4,si=t=>`${t.replace(/\/+$/,"")}/api`,tr=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??ih}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(n),r.ctrl.abort())}sleep(e){return new Promise(n=>{let r=setTimeout(i,e);function i(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,i()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,i=()=>r.abort();e.signal.addEventListener("abort",i,{once:!0}),this.conn=r;try{let{cloudUrl:s,token:o}=this.deps.getCreds();if(!o)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let a=this.deps.getPairing();if(!a){if(a=await this.register(s,o,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??Us,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,f;try{f=await this.hubFetch(`${si(s)}/units/${a.unitId}/channel`,{headers:{Authorization:`Bearer ${o}`,"X-Unit-Secret":a.secret,...c?{"X-Unit-Lan-Url":c}:{}},signal:r.signal})}finally{u&&clearTimeout(u)}if(f.status===403||f.status===404){let h=Number(f.headers.get("content-length"))>rh,p=setTimeout(()=>r.abort(),h?0:nh),m=await f.json().then(w=>w?.code,()=>null);throw clearTimeout(p),m==="UNIT_NOT_FOUND"||m==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${f.status} ${m}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${f.status} (not a hub verdict; keeping pairing and retrying)`)}if(!f.ok||!f.body)throw new Error(`channel HTTP ${f.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(f.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(s){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(s?.message||s),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",i),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,r){let i=this.deps.readIdleMs??Us,s=i?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(i/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},i):null;try{let o=await this.hubFetch(`${si(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:eh(),platform:process.platform}),signal:r.signal});if(!o.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${o.status}`);let a=await o.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(),i=new TextDecoder,s="",o=this.deps.readIdleMs??Us,a=null,c=()=>{o&&(a&&clearTimeout(a),a=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(o/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(()=>{})},o))};c();try{for(;;){let{done:l,value:u}=await r.read();if(l||n.signal.aborted)return;c(),s=this.parseFrames(s+i.decode(u,{stream:!0}),n)}}finally{a&&clearTimeout(a)}}parseFrames(e,n){let r=e,i;for(;(i=r.indexOf(`
219
219
 
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,proxyOperator:e.proxyOperator})),s=await fetch(u,{method:e.method,headers:o,body:e.body??void 0,signal:n.signal})}catch(u){if(n.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${u?.message||u}`})),void 0,n.signal);return}let 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&&Xc(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(`${eo(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=`${eo(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,S=new ReadableStream({async pull(k){++m===2&&p&&clearTimeout(p);let{done:P,value:R}=await h.read();P?k.close():k.enqueue(R)},cancel(k){return h.cancel(k)}},{highWaterMark:0});try{await this.hubFetch(d,{method:"POST",headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":c.secret,"Content-Type":"application/octet-stream"},body:S,signal:r.signal,duplex:"half"})}catch(k){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${k?.message||k}`);try{await h.cancel()}catch{}}finally{p&&clearTimeout(p)}}};function Xp(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(typeof n!="string"||n.length===0||n.length>64)&&!e.includes(n)&&(e.push(n),e.length>=16))break;return e}var Jn=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}capsChanged(){this.engineChanged()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(l){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${l?.message||l}`);return}let n={engine:e,tools:[]};if(typeof this.d.features=="function"){let l=[];try{l=this.d.features()}catch(u){this.d.log(`[unit-caps] \u8BFB\u80FD\u529B\u58F0\u660E\u5931\u8D25:${u?.message||u}`)}n.features=Xp(l)}let r=JSON.stringify(n);if(r===this.lastSent)return;let o=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!o||!s.token||!s.cloudUrl)return;let i=this.gen;this.inflight=!0;let a=new AbortController,c=setTimeout(()=>a.abort(),this.d.timeoutMs??1e4);try{let l=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(o.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(l,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":o.secret,"Content-Type":"application/json"},body:r,signal:a.signal});try{await u.text()}catch{}if(i!==this.gen)return;u.ok?(this.lastSent=r,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}${n.features?`(\u80FD\u529B\u58F0\u660E ${n.features.length} \u9879)`:""}`)):u.status===404||u.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${u.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):u.status===400||u.status===401||u.status===403?this.warned.has(u.status)||(this.warned.add(u.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${u.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${u.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(l){i===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${a.signal.aborted?"\u8D85\u65F6":l?.message||l}`)}finally{clearTimeout(c),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var Zc=["setUnitHubFactory"],Ps=t=>Zc.every(e=>typeof t[e]=="function");function Qc(t){let e=new Jn({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),...typeof t.capsFeatures=="function"?{features:()=>t.capsFeatures()}:{},log:r=>t.log(r)}),n=new Gn({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged(),capsChanged:()=>e.capsChanged()}}function $s(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",(n,r)=>e("GET",r!=null&&typeof r=="object"&&r.shared===!0?"/units?shared=1":"/units")),t.handle("units:update",(n,r,o)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:o?.name,icon:o?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:o,token:s}=await t.getCloud();await t.openExternal(`${o}/api/units/${r}/open${s?`#token=${encodeURIComponent(s)}`:""}`)}),t.setUnitHubFactory(Qc),t.log("[forsion-extend] unit hub registered")}import{createHash as yh}from"node:crypto";import{constants as El,mkdirSync as wh,readFileSync as bh,renameSync as Sh,writeFileSync as vh}from"node:fs";import{lstat as xt,open as jl,readFile as kh,readdir as Fl,statfs as Eh}from"node:fs/promises";import{cpus as _h,freemem as Ch,homedir as _l,hostname as Ll,release as Ah,totalmem as xh}from"node:os";import{basename as Ul,join as ae}from"node:path";var Zp=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Kn=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(Zp);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 Qp(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function eh(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 se=class extends Error{line;column;codeblock;constructor(e,n){let[r,o]=Qp(n.toml,n.ptr),s=eh(n.toml,r,o);super(`Invalid TOML document: ${e}
220
+ `))>=0;){let s=r.slice(0,i);if(r=r.slice(i+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 o=s.split(`
222
+ `).find(a=>a.startsWith("data: "))?.slice(6);if(o)try{let a=JSON.parse(o);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 i={ctrl:r,conn:n};this.inflight.set(e.id,i);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===i&&this.inflight.delete(e.id)}}async handle(e,n){let r=this.deps.getUnitWeb();if(!r.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,n.signal);return}let i={"x-unit-internal":r.internalSecret};e.ct&&(i["Content-Type"]=e.ct),e.accept&&(i.Accept=e.accept);let s;try{let u=new URL(`${r.url}${e.path}`);Object.assign(i,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:u,proxyCaller:e.proxyCaller,proxyOperator:e.proxyOperator})),s=await fetch(u,{method:e.method,headers:i,body:e.body??void 0,signal:n.signal})}catch(u){if(n.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${u?.message||u}`})),void 0,n.signal);return}let o=s.headers.get("content-type")||"",a={};for(let u of["content-security-policy","x-content-type-options"]){let f=s.headers.get(u);f&&(a[u]=f)}let c=o||"application/octet-stream";s.body&&il(o,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,i,s,o){if(o?.aborted)return;let{cloudUrl:a,token:c}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let u=this.requestTimeoutMs*2,f=[...u?[AbortSignal.timeout(u)]:[],...o?[o]:[]],h=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${si(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:i.toString("base64")}),...h?{signal:h}:{}}).then(p=>{p.body?.cancel().catch(()=>{})}).catch(p=>{o?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${p?.name==="TimeoutError"?`${Math.round(u/1e3)}s \u672A\u5B8C\u6210`:p?.message||p}`)})}async streamBack(e,n,r,i,s){let{cloudUrl:o,token:a}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let l=s?.["content-security-policy"],u=s?.["x-content-type-options"],f=`${si(o)}/units/${c.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(i)}`+(l?`&csp=${encodeURIComponent(l)}`:"")+(u?`&xcto=${encodeURIComponent(u)}`:""),h=n.body;if(!h)return;let p=h.getReader(),m=0,w=this.requestTimeoutMs,y=w?setTimeout(()=>{m>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(w/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},w):null,S=new ReadableStream({async pull(g){++m===2&&y&&clearTimeout(y);let{done:P,value:x}=await p.read();P?g.close():g.enqueue(x)},cancel(g){return p.cancel(g)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":c.secret,"Content-Type":"application/octet-stream"},body:S,signal:r.signal,duplex:"half"})}catch(g){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${g?.message||g}`);try{await p.cancel()}catch{}}finally{y&&clearTimeout(y)}}};function sh(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(typeof n!="string"||n.length===0||n.length>64)&&!e.includes(n)&&(e.push(n),e.length>=16))break;return e}var nr=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}capsChanged(){this.engineChanged()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(l){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${l?.message||l}`);return}let n={engine:e,tools:[]};if(typeof this.d.features=="function"){let l=[];try{l=this.d.features()}catch(u){this.d.log(`[unit-caps] \u8BFB\u80FD\u529B\u58F0\u660E\u5931\u8D25:${u?.message||u}`)}n.features=sh(l)}let r=JSON.stringify(n);if(r===this.lastSent)return;let i=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!i||!s.token||!s.cloudUrl)return;let o=this.gen;this.inflight=!0;let a=new AbortController,c=setTimeout(()=>a.abort(),this.d.timeoutMs??1e4);try{let l=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(i.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(l,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":i.secret,"Content-Type":"application/json"},body:r,signal:a.signal});try{await u.text()}catch{}if(o!==this.gen)return;u.ok?(this.lastSent=r,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}${n.features?`(\u80FD\u529B\u58F0\u660E ${n.features.length} \u9879)`:""}`)):u.status===404||u.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${u.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):u.status===400||u.status===401||u.status===403?this.warned.has(u.status)||(this.warned.add(u.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${u.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${u.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(l){o===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${a.signal.aborted?"\u8D85\u65F6":l?.message||l}`)}finally{clearTimeout(c),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var sl=["setUnitHubFactory"],Hs=t=>sl.every(e=>typeof t[e]=="function");function ol(t){let e=new nr({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),...typeof t.capsFeatures=="function"?{features:()=>t.capsFeatures()}:{},log:r=>t.log(r)}),n=new tr({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged(),capsChanged:()=>e.capsChanged()}}function zs(t){let e=async(n,r,i)=>{let{base:s,token:o}=await t.getCloud();if(!o)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let a=await fetch(`${s}/api${r}`,{method:n,headers:{Authorization:`Bearer ${o}`,...i!==void 0?{"Content-Type":"application/json"}:{}},body:i!==void 0?JSON.stringify(i):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",(n,r)=>e("GET",r!=null&&typeof r=="object"&&r.shared===!0?"/units?shared=1":"/units")),t.handle("units:update",(n,r,i)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:i?.name,icon:i?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:i,token:s}=await t.getCloud();await t.openExternal(`${i}/api/units/${r}/open${s?`#token=${encodeURIComponent(s)}`:""}`)}),t.setUnitHubFactory(ol),t.log("[forsion-extend] unit hub registered")}import{createHash as Ch}from"node:crypto";import{constants as Rl,mkdirSync as Ah,readFileSync as xh,renameSync as Th,writeFileSync as Ih}from"node:fs";import{lstat as Rt,open as ql,readFile as Rh,readdir as Wl,statfs as Dh}from"node:fs/promises";import{cpus as Oh,freemem as Mh,homedir as Dl,hostname as Vl,release as Ph,totalmem as $h}from"node:os";import{basename as Yl,join as le}from"node:path";var oh=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,rr=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,i="Z";if(typeof e=="string"){let s=e.match(oh);s?(s[1]||(n=!1,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=!1,n.#e=null,n}};function ah(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function ch(t,e,n){let r=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
223
+ `,o===e&&(i+=" ".repeat(s+n+2),i+=`^
224
+ `))}return i}var ae=class extends Error{line;column;codeblock;constructor(e,n){let[r,i]=ah(n.toml,n.ptr),s=ch(n.toml,r,i);super(`Invalid TOML document: ${e}
225
225
 
226
- ${s}`,n),this.line=r,this.column=o,this.codeblock=s}};var th=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,nh=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,rh=/^[+-]?0[0-9_]/;function to(t,e){let n=t[e++],r=n,o=n==="'",s=n===t[e]&&n===t[e+1];s&&(t[e+=2]===`
226
+ ${s}`,n),this.line=r,this.column=i,this.codeblock=s}};var lh=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,uh=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,dh=/^[+-]?0[0-9_]/;function oi(t,e){let n=t[e++],r=n,i=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],s&&(n===`
228
+ `&&(e+=2));let o="",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 se("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 se("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 se("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 se("unrecognized escape sequence",{toml:t,ptr:l});a=l+1,c=0}else if(n!==" "&&n!==" "){if(c===2)throw new se("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:a});c=!o&&n==="\\"?1:0,a=l}}throw new se("unfinished string",{toml:t,ptr:e})}function el(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=th.test(t);if(o||nh.test(t)){if(rh.test(t))throw new se("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let i=+t;if(isNaN(i))throw new se("invalid number",{toml:e,ptr:n});if(o){if((o=!Number.isSafeInteger(i))&&!r)throw new se("integer value cannot be represented losslessly",{toml:e,ptr:n});(o||r===!0)&&(i=BigInt(t))}return i}let s=new Kn(t);if(!s.isValid())throw new se("invalid value",{toml:e,ptr:n});return s}function no(t,e=0,n=t.length){let r=t.indexOf(`
232
- `,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function fn(t,e){for(let n=e;n<t.length;n++){let r=t[n];if(r===`
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?o:o+t.slice(a,l),l+(s?3:1)];if(!c)!i&&n==="\\"&&(o+=t.slice(a,a=l),c=1);else if(c===1)if(n==="x"||n==="u"||n==="U"){let u=0,f=n==="x"?2:n==="u"?4:8;for(let h=0;h<f;h++,l++){let p=t.charCodeAt(l+1),m=p>=48&&p<=57?p-48:p>=65&&p<=70?p-65+10:p>=97&&p<=102?p-97+10:-1;if(m<0)throw new 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});o+=String.fromCodePoint(u),a=l+1,c=0}else if(n===" "||n===" ")c=2;else{if(n==="b")o+="\b";else if(n==="t")o+=" ";else if(n==="n")o+=`
231
+ `;else if(n==="f")o+="\f";else if(n==="r")o+="\r";else if(n==="e")o+="\x1B";else if(n==='"')o+='"';else if(n==="\\")o+="\\";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=!i&&n==="\\"?1:0,a=l}}throw new ae("unfinished string",{toml:t,ptr:e})}function al(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 i=lh.test(t);if(i||uh.test(t)){if(dh.test(t))throw new ae("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let o=+t;if(isNaN(o))throw new ae("invalid number",{toml:e,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new ae("integer value cannot be represented losslessly",{toml:e,ptr:n});(i||r===!0)&&(o=BigInt(t))}return o}let s=new rr(t);if(!s.isValid())throw new ae("invalid value",{toml:e,ptr:n});return s}function ai(t,e=0,n=t.length){let r=t.indexOf(`
232
+ `,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function mn(t,e){for(let n=e;n<t.length;n++){let r=t[n];if(r===`
233
233
  `)return n;if(r==="\r"&&t[n+1]===`
234
- `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new se("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function pt(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=fn(t,e)}return e}function tl(t,e,n,r,o=!1){if(!r)return e=no(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let i=t[s];if(i==="#")s=no(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 se("cannot find end of structure",{toml:t,ptr:e})}function oh(t,e,n){let r=t.slice(e,n),o=r.indexOf("#");return o>-1&&(fn(t,o),r=r.slice(0,o)),[r.trimEnd(),o]}function Xn(t,e,n,r,o){if(r===0)throw new se("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let s=t[e];if(s==="["||s==="{"){let[c,l]=s==="["?rl(t,e,r,o):nl(t,e,r,o);if(n){if(l=pt(t,l),t[l]===",")l++;else if(t[l]!==n)throw new se("expected comma or end of structure",{toml:t,ptr:l})}return[c,l]}if(s==='"'||s==="'"){let[c,l]=to(t,e);if(n){if(l=pt(t,l),t[l]&&t[l]!==","&&t[l]!==n&&t[l]!==`
239
- `&&t[l]!=="\r")throw new se("unexpected character encountered",{toml:t,ptr:l});t[l]===","&&l++}return[c,l]}let i=tl(t,e,",",n),a=oh(t,e,i-(t[i-1]===","?1:0));if(!a[0])throw new se("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&a[1]>-1&&(i=pt(t,e+a[1]),t[i]===","&&i++),[el(a[0],t,e,o),i]}var sh=/^[a-zA-Z0-9-_]+[ \t]*$/;function ro(t,e,n="="){let r=e-1,o=[],s=t.indexOf(n,e);if(s<0)throw new se("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 se("multiline strings are not allowed in keys",{toml:t,ptr:e});let[a,c]=to(t,e);r=t.indexOf(".",c);let l=t.slice(c,r<0||r>s?s:r),u=no(l);if(u>-1)throw new se("newlines are not allowed in keys",{toml:t,ptr:e+r+u});if(l.trimStart())throw new se("found extra tokens after the string part",{toml:t,ptr:c});if(s<c&&(s=t.indexOf(n,c),s<0))throw new se("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(!sh.test(a))throw new se("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,pt(t,s+1,!0,!0)]}function nl(t,e,n,r){let o={},s=new Set,i;for(e++;(i=t[e++])!=="}"&&i;){if(i===",")throw new se("expected value, found comma",{toml:t,ptr:e-1});if(i==="#")e=fn(t,e);else if(i!==" "&&i!==" "&&i!==`
240
- `&&i!=="\r"){let a,c=o,l=!1,[u,d]=ro(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 se("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 se("trying to redefine an already defined value",{toml:t,ptr:e});let[g,h]=Xn(t,d,"}",n-1,r);s.add(g),c[a]=g,e=h}}if(!i)throw new se("unfinished table encountered",{toml:t,ptr:e});return[o,e]}function rl(t,e,n,r){let o=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new se("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=fn(t,e);else if(s!==" "&&s!==" "&&s!==`
241
- `&&s!=="\r"){let i=Xn(t,e-1,"]",n-1,r);o.push(i[0]),e=i[1]}}if(!s)throw new se("unfinished array encountered",{toml:t,ptr:e});return[o,e]}function ol(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 oo(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},o={},s=r,i=o;for(let a=pt(t,0);a<t.length;){if(t[a]==="["){let c=t[++a]==="[",l=ro(t,a+=+c,"]");if(c){if(t[l[1]-1]!=="]")throw new se("expected end of table declaration",{toml:t,ptr:l[1]-1});l[1]++}let u=ol(l[0],r,o,c?2:1);if(!u)throw new se("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=ro(t,a),l=ol(c[0],s,i,0);if(!l)throw new se("trying to redefine an already defined table or value",{toml:t,ptr:a});let u=Xn(t,c[1],void 0,e,n);l[1][l[0]]=u[0],a=u[1]}if(a=pt(t,a,!0),t[a]&&t[a]!==`
242
- `&&t[a]!=="\r")throw new se("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=pt(t,a)}return r}var io=14,ih=1440*6e4,ah=12e4,ch=15e3,Ns=1792*1024,lh=7,Ct=t=>t.toISOString().slice(0,10),ht=t=>Date.parse(Ct(t))-(lh-1)*ih,sl=["sessions","activity"],so=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function js(t,e,n){let r=t?.day===Ct(n)?t:void 0;return Object.fromEntries(sl.map(o=>[o,so(r?.[o])??Math.min(Math.max(so(e[o])??0,ht(n)),n.getTime())]))}function Fs(t,e,n,r,o,s){let i=e?.day===Ct(r)?e:void 0,a={sent:{...t},file:{day:Ct(r)}};for(let c of sl){let l=c in o&&!s.includes(c)&&!(`${c}Error`in o),u=so(i?.[c]);l?(a.file[c]=n[c],a.sent[c]=r.getTime()):u!==void 0&&(a.sent[c]=Math.min(so(t[c])??u,u))}return a}function il(t,e=[]){let n={...t},r=Rn(JSON.stringify(n));for(let o of["activity","sessions","memory","runs","engine"]){if(r.length<=Ns)break;o in n&&(delete n[o],e.push(o),r=Rn(JSON.stringify({...n,truncated:e})))}return r.length>Ns?null:r}async function Ls(t,e,n,r=new Date){let o=AbortSignal.timeout(ah);await t.writeFile(`${e}/${Ct(r)}.json`,n,r.getTime(),o);try{let s=Ct(new Date(r.getTime()-io*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 Us={mode:"scheduled",intervalHours:24,requestedAt:0};function Zn(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:Us.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Hs(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(ch)});return e.status===404?{...Us}:e.ok?Zn(await e.json()):null}catch{return null}}var cl=["merge","cloud","local"],ll={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Pt(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 uh(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 $t(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=Pt(i.source,!0),c=uh(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 pn(t,e){let n=null;for(let r of e)(!r.source||t===r.source||t.startsWith(r.source+"/"))&&(!n||r.source.length>n.source.length)&&(n=r);return n}var gt={get:"penzor:sync:get",preview:"penzor:sync:preview",apply:"penzor:sync:apply",run:"penzor:sync:run",pause:"penzor:sync:pause",retry:"penzor:sync:retry",rename:"penzor:sync:rename",setup:"penzor:sync:setup",archiveSeen:"penzor:sync:archiveSeen"},ao=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,al=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),zs=(t,e,n)=>{let r=al(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(o=>o.id!==n&&al(o.name)===r)?"taken":null:null},ul=["Amadeus","agents","human","Plugins"];var At=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var Qn=/^[a-z0-9][a-z0-9-]{0,63}$/,co=new Set(["muse"]),er=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&Qn.test(e[1])?e[1]:null},dh=t=>[...co].some(e=>Bs(t,`agents/${e}`));function dl(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 hn=(t,e)=>pn(e,t)?.target??"off",Bs=(t,e)=>t===e||t.startsWith(e+"/"),fh=t=>At.some(e=>Bs(t,e.path)),qs=t=>t.some(e=>e.id==="default")?lo():"default",fl=(t,e)=>t.enabled?hn(t.rules,e):"off";function pl(t,e,n){n==="off"&&(t=t.filter(s=>e?!s.source.startsWith(e+"/"):!s.source||fh(s.source)));let r=t.find(s=>s.source===e),o=t.filter(s=>s!==r);return e&&hn(o,e)===n?o:r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:e?lo():qs(t),source:e,target:n}]}function gn(t,e,n,r=!1){if(dh(e))return t;let o=t.rules;if(!t.enabled){let s=o.find(a=>!a.source),i=e?o.filter(a=>a.source&&Bs(a.source,e)):[];o=[{id:s?.id??qs(i),source:"",target:"off"},...i],e!=="agents"&&(o=Ws(o,"agents","off"))}if(!e)for(let s of At)o.some(i=>i.source===s.path)||(o=[...o,{id:lo(),source:s.path,target:hn(o,s.path)}]);return hl({...t,rules:pl(o,e,n)},r)}function hl(t,e=!1){let n=r=>hn(t.rules,r)!=="off";return{...t,enabled:At.some(r=>n(r.path))||t.rules.some(r=>r.source&&r.target!=="off")||e&&n("")}}function gl(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:qs(t.rules),source:"",target:"default"},...t.rules];for(let n of At)n.id!=="agents"&&hn(e,n.path)==="off"&&(e=pl(e,n.path,"default"));return e=Ws(e,"agents","off"),{...t,enabled:!0,rules:e}}function Ws(t,e,n){let r=t.find(o=>o.source===e);return r?t.map(o=>o===r?{...o,target:n}:o):[...t,{id:lo(),source:e,target:n}]}function ml(t,e){let n=t;for(let r of new Set(e))Qn.test(r)&&!co.has(r)&&(n=gn(n,`agents/${r}`,"default"));return n}function yl(t){let e=hn(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=Ws(t.rules.filter(o=>!o.source.startsWith("agents/")),"agents","off");return t.enabled?hl({...t,rules:r},!0):{...t,rules:r}}var ph=0,lo=()=>`rule-${Date.now().toString(36)}-${(ph++).toString(36)}`;var wl=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var hh=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function bl(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 tr=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||hh.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]}:{}}))}}},Sl=null;function vl(t){Sl=t}function kl(){try{return Sl?.()??null}catch{return null}}var Th=(t,e=[])=>{let n=il(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},Hl=60*6e4,Ih=2*6e4,Rh=10*6e4,Cl=Hl,Dh=4*1024*1024,Oh=256*1024,Al=["user","teamwork","discussion","delegate"],Mh=/^(?:New remarks in the team chat:|You are activated now \()/,zl={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Ys=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,Bl=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,o)=>Ys.test(o)||e&&!/\s/.test(o)?n:`${r}[path]${r}`),ql=t=>Bl(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>Ys.test(e)?e:"[path]"),or=4e3,fo=(t,e)=>typeof t=="string"&&t?yt(ql(wt(t.slice(0,or))),e):void 0,Ph={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},$h=64*1024,Vs=500,Nh={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},jh=256*1024,xl=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],Fh=["description","developer_instructions"],Lh=["memory","harness","project_memory","human","dream","log_appended"],Uh=["homeDir","readCreds","accountId","appVersion"],Gs=t=>Uh.every(e=>typeof t[e]=="function"),Tl=_l().length>3?_l():null;function wt(t){return typeof t=="string"?(Tl?t.split(Tl).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(wt):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]":wt(n)])):t}var Hh=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ie=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,zh=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function mn(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[zh(o,r)]=Hh.test(o)&&ie(s,80)!==void 0?s:mn(s,e+1);return n}var Bh={"":/^(?: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)$/},Il={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},qh=/^(?:apps|enabled_skill_ids)$/,Rl=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Wh(t){try{let e=oo(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=Bh[c].test(l)?l:`[key:${l.length}]`,g=Il[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===""&&qh.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(Il,c);if(u&&Rl(l))a(c,`[${c}]`,l);else if(u&&Array.isArray(l)&&l.length>0&&l.every(Rl))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 Wl=async t=>{try{return(await xt(t)).isFile()?await kh(t,"utf8"):null}catch{return null}},rr=t=>xt(t).then(e=>e.isDirectory(),()=>!1),yn=async t=>{try{return JSON.parse(await Wl(t)??"null")}catch{return null}},mt=async(t,e=200)=>{try{return(await Fl(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function Vh(t,e){if(!(await xt(t)).isFile())return"";let n=await jl(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 Yh(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:ie(t.cloud?.defaultModel)??null,models:mn(t.models),tts:mn(t.tts),asr:mn(t.asr),specialAgents:mn(t.specialAgents),pluginSettings:mn(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:ie(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(r=>ie(r)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,r])=>({name:ie(n,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(t.channels).map(([n,r])=>({name:ie(n,64)??"[name]",enabled:r?.enabled===!0}))}}var Gh=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function Dl(t){let e=[];for(let n of await mt(t,100)){let r=ae(t,n);if(!await rr(r))continue;let o=await Wl(ae(r,"config.toml"));e.push({id:n,config:o===null?null:Wh(o).slice(0,4096),files:(await mt(r,400)).filter(s=>Gh.has(s))})}return e}async function Ol(t){let e=[];for(let n of await mt(t,300)){let r=await yn(ae(t,n,"manifest.json"));r&&e.push({id:ie(r.id)??n,version:ie(r.version,40)??null,name:ie(r.nameEn)??ie(r.name)??null})}return e}var Vt=t=>String(t?.code||t?.message||t).slice(0,120);async function Jh(t,e,n,r=Oh){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 Fl(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 Vh(ae(t,h),Dh).catch(S=>{if(S?.code==="ENOENT")return"";throw S})).split(`
245
- `).filter(S=>/^\d{12} /.test(S)&&S.slice(0,12)>=a&&S.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:Vt(g)}}return{activity:l.reverse(),...d?{activityTruncated:!0}:{}}}var yt=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},Ml=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},wn=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function Kh(t,e,n=zl,r=ht(e)){let o=ae(t,"tangu","state.db"),s=await xt(o).then(a=>a.isFile(),a=>a?.code==="ENOENT"?!1:Vt(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=[wn(r),wn(e.getTime()),ht(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
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 ht(t,e,n,r){let i;for(;;){for(;(i=t[e])===" "||i===" "||!n&&(i===`
235
+ `||i==="\r"&&t[e+1]===`
236
+ `);)e++;if(r||i!=="#")break;e=mn(t,e)}return e}function cl(t,e,n,r,i=!1){if(!r)return e=ai(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let o=t[s];if(o==="#")s=ai(t,s);else{if(o===n)return s+1;if(o===r||i&&(o===`
237
+ `||o==="\r"&&t[s+1]===`
238
+ `))return s}}throw new ae("cannot find end of structure",{toml:t,ptr:e})}function fh(t,e,n){let r=t.slice(e,n),i=r.indexOf("#");return i>-1&&(mn(t,i),r=r.slice(0,i)),[r.trimEnd(),i]}function ir(t,e,n,r,i){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==="["?ul(t,e,r,i):ll(t,e,r,i);if(n){if(l=ht(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]=oi(t,e);if(n){if(l=ht(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 o=cl(t,e,",",n),a=fh(t,e,o-(t[o-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&&(o=ht(t,e+a[1]),t[o]===","&&o++),[al(a[0],t,e,i),o]}var ph=/^[a-zA-Z0-9-_]+[ \t]*$/;function ci(t,e,n="="){let r=e-1,i=[],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 o=t[e=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===t[e+1]&&o===t[e+2])throw new ae("multiline strings are not allowed in keys",{toml:t,ptr:e});let[a,c]=oi(t,e);r=t.indexOf(".",c);let l=t.slice(c,r<0||r>s?s:r),u=ai(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});i.push(a)}else{r=t.indexOf(".",e);let a=t.slice(e,r<0||r>s?s:r);if(!ph.test(a))throw new ae("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});i.push(a.trimEnd())}}while(r+1&&r<s);return[i,ht(t,s+1,!0,!0)]}function ll(t,e,n,r){let i={},s=new Set,o;for(e++;(o=t[e++])!=="}"&&o;){if(o===",")throw new ae("expected value, found comma",{toml:t,ptr:e-1});if(o==="#")e=mn(t,e);else if(o!==" "&&o!==" "&&o!==`
240
+ `&&o!=="\r"){let a,c=i,l=!1,[u,f]=ci(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[h,p]=ir(t,f,"}",n-1,r);s.add(h),c[a]=h,e=p}}if(!o)throw new ae("unfinished table encountered",{toml:t,ptr:e});return[i,e]}function ul(t,e,n,r){let i=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new ae("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=mn(t,e);else if(s!==" "&&s!==" "&&s!==`
241
+ `&&s!=="\r"){let o=ir(t,e-1,"]",n-1,r);i.push(o[0]),e=o[1]}}if(!s)throw new ae("unfinished array encountered",{toml:t,ptr:e});return[i,e]}function dl(t,e,n,r){let i=e,s=n,o,a=!1,c;for(let l=0;l<t.length;l++){if(l){if(i=a?i[o]:i[o]={},s=(c=s[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let u=i.length-1;i=i[u],s=s[u].c}}if(o=t[l],(a=Object.hasOwn(i,o))&&s[o]?.t===0&&s[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})),s[o]={t:l<t.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=s[o],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=a?i[o]:i[o]={};else if(r===0&&a)return null;return[o,i,c.c]}function li(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let a=ht(t,0);a<t.length;){if(t[a]==="["){let c=t[++a]==="[",l=ci(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=dl(l[0],r,i,c?2:1);if(!u)throw new ae("trying to redefine an already defined table or value",{toml:t,ptr:a});o=u[2],s=u[1],a=l[1]}else{let c=ci(t,a),l=dl(c[0],s,o,0);if(!l)throw new ae("trying to redefine an already defined table or value",{toml:t,ptr:a});let u=ir(t,c[1],void 0,e,n);l[1][l[0]]=u[0],a=u[1]}if(a=ht(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=ht(t,a)}return r}var di=14,hh=1440*6e4,gh=12e4,mh=15e3,Bs=1792*1024,yh=7,Tt=t=>t.toISOString().slice(0,10),gt=t=>Date.parse(Tt(t))-(yh-1)*hh,fl=["sessions","activity"],ui=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function qs(t,e,n){let r=t?.day===Tt(n)?t:void 0;return Object.fromEntries(fl.map(i=>[i,ui(r?.[i])??Math.min(Math.max(ui(e[i])??0,gt(n)),n.getTime())]))}function Ws(t,e,n,r,i,s){let o=e?.day===Tt(r)?e:void 0,a={sent:{...t},file:{day:Tt(r)}};for(let c of fl){let l=c in i&&!s.includes(c)&&!(`${c}Error`in i),u=ui(o?.[c]);l?(a.file[c]=n[c],a.sent[c]=r.getTime()):u!==void 0&&(a.sent[c]=Math.min(ui(t[c])??u,u))}return a}function pl(t,e=[]){let n={...t},r=$n(JSON.stringify(n));for(let i of["activity","sessions","memory","runs","engine"]){if(r.length<=Bs)break;i in n&&(delete n[i],e.push(i),r=$n(JSON.stringify({...n,truncated:e})))}return r.length>Bs?null:r}async function Vs(t,e,n,r=new Date){let i=AbortSignal.timeout(gh);await t.writeFile(`${e}/${Tt(r)}.json`,n,r.getTime(),i);try{let s=Tt(new Date(r.getTime()-di*24*60*6e4));for(let o of await t.walk(i)){let a=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(o.key);a&&a[1]===e&&a[2]<s&&await t.rm(o.key,i)}}catch{}}var Ys={mode:"scheduled",intervalHours:24,requestedAt:0};function sr(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:Ys.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Gs(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(mh)});return e.status===404?{...Ys}:e.ok?sr(await e.json()):null}catch{return null}}var gl=["merge","cloud","local"],ml={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Lt(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 wh(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 Ut(t,e){let n=t;if(!n||n.version!==1||typeof n.enabled!="boolean"||!Array.isArray(n.rules)||n.rules.length>512)throw Error("Invalid content sync configuration");let r=new Set,i=new Set,s=n.rules.map(o=>{let a=Lt(o.source,!0),c=wh(o.target);if(typeof o.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(o.id)||i.has(o.id)||r.has(a))throw Error("Duplicate or invalid sync rule");return i.add(o.id),r.add(a),{id:o.id,source:a,target:c,...o.sourceId&&/^[a-f0-9-]{36}$/i.test(o.sourceId)?{sourceId:o.sourceId}:{}}});return{version:1,revision:e,enabled:n.enabled,rules:s}}function yn(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 mt={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"},fi=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,hl=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Js=(t,e,n)=>{let r=hl(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(i=>i.id!==n&&hl(i.name)===r)?"taken":null:null},yl=["Amadeus","agents","human","Plugins"];var It=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var or=/^[a-z0-9][a-z0-9-]{0,63}$/,pi=new Set(["muse"]),ar=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&or.test(e[1])?e[1]:null},bh=t=>[...pi].some(e=>Ks(t,`agents/${e}`));function wl(t){let e=t.split(/^\s*\[/m)[0]??"",n=s=>{let o=new RegExp(`^[ \\t]*${s}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(o?.[1]!=null?o[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):o?.[2])?.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,80)||void 0},r=n("name"),i=n("name_en");return{...r?{name:r}:{},...i?{nameEn:i}:{}}}var wn=(t,e)=>yn(e,t)?.target??"off",Ks=(t,e)=>t===e||t.startsWith(e+"/"),Sh=t=>It.some(e=>Ks(t,e.path)),Xs=t=>t.some(e=>e.id==="default")?hi():"default",bl=(t,e)=>t.enabled?wn(t.rules,e):"off";function Sl(t,e,n){n==="off"&&(t=t.filter(s=>e?!s.source.startsWith(e+"/"):!s.source||Sh(s.source)));let r=t.find(s=>s.source===e),i=t.filter(s=>s!==r);return e&&wn(i,e)===n?i:r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:e?hi():Xs(t),source:e,target:n}]}function bn(t,e,n,r=!1){if(bh(e))return t;let i=t.rules;if(!t.enabled){let s=i.find(a=>!a.source),o=e?i.filter(a=>a.source&&Ks(a.source,e)):[];i=[{id:s?.id??Xs(o),source:"",target:"off"},...o],e!=="agents"&&(i=Zs(i,"agents","off"))}if(!e)for(let s of It)i.some(o=>o.source===s.path)||(i=[...i,{id:hi(),source:s.path,target:wn(i,s.path)}]);return vl({...t,rules:Sl(i,e,n)},r)}function vl(t,e=!1){let n=r=>wn(t.rules,r)!=="off";return{...t,enabled:It.some(r=>n(r.path))||t.rules.some(r=>r.source&&r.target!=="off")||e&&n("")}}function kl(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:Xs(t.rules),source:"",target:"default"},...t.rules];for(let n of It)n.id!=="agents"&&wn(e,n.path)==="off"&&(e=Sl(e,n.path,"default"));return e=Zs(e,"agents","off"),{...t,enabled:!0,rules:e}}function Zs(t,e,n){let r=t.find(i=>i.source===e);return r?t.map(i=>i===r?{...i,target:n}:i):[...t,{id:hi(),source:e,target:n}]}function El(t,e){let n=t;for(let r of new Set(e))or.test(r)&&!pi.has(r)&&(n=bn(n,`agents/${r}`,"default"));return n}function _l(t){let e=wn(t.rules,"agents")!=="off"||t.rules.some(i=>i.source.startsWith("agents/")&&i.target!=="off"),n=t.rules.some(i=>i.source.startsWith("agents/"));if(!e&&!n)return null;let r=Zs(t.rules.filter(i=>!i.source.startsWith("agents/")),"agents","off");return t.enabled?vl({...t,rules:r},!0):{...t,rules:r}}var vh=0,hi=()=>`rule-${Date.now().toString(36)}-${(vh++).toString(36)}`;var Cl=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var kh=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function Al(t,e=[]){let n=t;for(let r of[...e].filter(i=>i&&i.length>=2).sort((i,s)=>s.length-i.length))n=n.split(r).join("[path]");return n.replace(/^(Duplicate folder sync identity|Concurrent (?:folder|file) rename): [\s\S]*$/,"$1: [path]")}var cr=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||kh.test(e))return;this.count("errors"),/^File exceeds \d+ MB/.test(e)&&this.count("tooLarge");let i=this.errors[this.errors.length-1];if(i&&i.text===e){i.n++,i.at=r,this.addPaths(n);return}this.errors.push({first:r,at:r,n:1,text:e}),this.addPaths(n),this.errors.length>20&&this.errors.shift()}addPaths(e){let n=this.errors[this.errors.length-1],r=e.filter(i=>typeof i=="string"&&i);!n||!r.length||(n.paths=[...new Set([...n.paths??[],...r])].slice(0,8))}end(e,n=this.clock()){let r=this.cur;if(!r)return;this.cur=null;let i={at:r.at,ms:Math.max(0,n-r.at),completed:e,counts:r.counts};this.last=i,this.totals.runs++,e&&this.totals.completedRuns++,!e||Object.keys(r.counts).length?(this.runs.push(i),this.runs.length>20&&this.runs.shift()):this.totals.idleRuns++}snapshot(){let e=n=>({...n,counts:{...n.counts}});return{since:this.since,lastRun:this.last&&e(this.last),runs:this.runs.map(e),totals:{...this.totals},errors:this.errors.map(n=>({...n,...n.paths?{paths:[...n.paths]}:{}}))}}},xl=null;function Tl(t){xl=t}function Il(){try{return xl?.()??null}catch{return null}}var Nh=(t,e=[])=>{let n=pl(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},Gl=60*6e4,jh=2*6e4,Fh=10*6e4,Ol=Gl,Lh=4*1024*1024,Uh=256*1024,Ml=["user","teamwork","discussion","delegate"],Hh=/^(?:New remarks in the team chat:|You are activated now \()/,Jl={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},eo=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,Kl=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,i)=>eo.test(i)||e&&!/\s/.test(i)?n:`${r}[path]${r}`),Xl=t=>Kl(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>eo.test(e)?e:"[path]"),dr=4e3,mi=(t,e)=>typeof t=="string"&&t?wt(Xl(bt(t.slice(0,dr))),e):void 0,zh={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},Bh=64*1024,Qs=500,qh={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},Wh=256*1024,Pl=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],Vh=["description","developer_instructions"],Yh=["memory","harness","project_memory","human","dream","log_appended"],Gh=["homeDir","readCreds","accountId","appVersion"],to=t=>Gh.every(e=>typeof t[e]=="function"),$l=Dl().length>3?Dl():null;function bt(t){return typeof t=="string"?($l?t.split($l).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(bt):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]":bt(n)])):t}var Jh=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ce=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,Kh=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function Sn(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[r,[i,s]]of Object.entries(t).slice(0,100).entries())n[Kh(i,r)]=Jh.test(i)&&ce(s,80)!==void 0?s:Sn(s,e+1);return n}var Xh={"":/^(?: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)$/},Nl={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},Zh=/^(?:apps|enabled_skill_ids)$/,jl=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Qh(t){try{let e=li(t),n=[],r=[],i=8192,s=(c,l)=>i<=0?!1:(i-=l.length+1,c.push(l),!0),o=(c,l,u)=>{let f=Xh[c].test(l)?l:`[key:${l.length}]`,h=Nl[c].test(l),p;return typeof u=="boolean"||typeof u=="number"?p=String(u):h&&typeof u=="string"&&!/[\r\n]/.test(u)&&JSON.stringify(u).length<=120?p=JSON.stringify(u):h&&u instanceof Date?p=u.toISOString():c===""&&Zh.test(l)&&Array.isArray(u)&&u.every(m=>typeof m=="string"&&!/[\r\n]/.test(m))&&JSON.stringify(u).length<=2e3&&(p=`[${u.map(m=>JSON.stringify(m)).join(", ")}]`),`${f} = ${p??`"[text:${typeof u=="string"?u.length:JSON.stringify(u).length}]"`}`},a=(c,l,u)=>{if(s(r,l)){for(let[f,h]of Object.entries(u))if(!s(r,o(c,f,h)))return}};for(let[c,l]of Object.entries(e)){let u=c!==""&&Object.hasOwn(Nl,c);if(u&&jl(l))a(c,`[${c}]`,l);else if(u&&Array.isArray(l)&&l.length>0&&l.every(jl))for(let f of l)a(c,`[[${c}]]`,f);else s(n,o("",c,l));if(i<=0)break}return[...n,...r].join(`
243
+ `)}catch{return`[unparsed:${t.length}]`}}var Zl=async t=>{try{return(await Rt(t)).isFile()?await Rh(t,"utf8"):null}catch{return null}},ur=t=>Rt(t).then(e=>e.isDirectory(),()=>!1),vn=async t=>{try{return JSON.parse(await Zl(t)??"null")}catch{return null}},yt=async(t,e=200)=>{try{return(await Wl(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function eg(t,e){if(!(await Rt(t)).isFile())return"";let n=await ql(t,"r");try{let{size:r}=await n.stat(),i=Math.max(0,r-e),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let o=s.toString("utf8");return i>0?o.slice(o.indexOf(`
244
+ `)+1):o}finally{await n.close()}}function tg(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:Sn(t.models),tts:Sn(t.tts),asr:Sn(t.asr),specialAgents:Sn(t.specialAgents),pluginSettings:Sn(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 ng=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function Fl(t){let e=[];for(let n of await yt(t,100)){let r=le(t,n);if(!await ur(r))continue;let i=await Zl(le(r,"config.toml"));e.push({id:n,config:i===null?null:Qh(i).slice(0,4096),files:(await yt(r,400)).filter(s=>ng.has(s))})}return e}async function Ll(t){let e=[];for(let n of await yt(t,300)){let r=await vn(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 Xt=t=>String(t?.code||t?.message||t).slice(0,120);async function rg(t,e,n,r=Uh){let i=h=>String(h).padStart(2,"0"),s=h=>{let p=new Date(h);return`${p.getFullYear()}${i(p.getMonth()+1)}${i(p.getDate())}${i(p.getHours())}${i(p.getMinutes())}`},o=h=>`${h.slice(0,4)}-${h.slice(4,6)}-${h.slice(6,8)}.log`,a=s(n),c=s(e.getTime()),l=[],u=r,f=!1;try{let h=(await Wl(t)).filter(p=>/^\d{4}-\d{2}-\d{2}\.log$/.test(p)&&p>=o(a)&&p<=o(c)).sort().reverse();for(let p of h){if(f)break;let w=(await eg(le(t,p),Lh).catch(S=>{if(S?.code==="ENOENT")return"";throw S})).split(`
245
+ `).filter(S=>/^\d{12} /.test(S)&&S.slice(0,12)>=a&&S.slice(0,12)<c),y=w.length;for(;y>0&&Buffer.byteLength(w[y-1])+1<=u;)u-=Buffer.byteLength(w[--y])+1;y>0&&(f=!0),y<w.length&&l.push({date:p.slice(0,10),log:w.slice(y).join(`
246
+ `)})}}catch(h){return h?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:Xt(h)}}return{activity:l.reverse(),...f?{activityTruncated:!0}:{}}}var wt=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},Ul=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},kn=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function ig(t,e,n=Jl,r=gt(e)){let i=le(t,"tangu","state.db"),s=await Rt(i).then(a=>a.isFile(),a=>a?.code==="ENOENT"?!1:Xt(a));if(s!==!0)return s===!1?{sessions:[]}:{sessions:[],sessionsError:s};let o;try{let{DatabaseSync:a}=await import("node:sqlite");o=new a(i,{readOnly:!0}),o.exec("PRAGMA busy_timeout = 1500");let l="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",u=[kn(r),kn(e.getTime()),gt(e)],f=o.prepare(`SELECT s.id, s.kind, s.parent_session_id, s.app_id, s.title, s.model_id, s.project_name, s.archived, s.created_at, s.updated_at, MAX(m.updated_at) AS changed_at
247
247
  FROM chat_messages m JOIN chat_sessions s ON s.id = m.session_id
248
- WHERE s.kind IN (${Al.map(()=>"?").join(", ")}) AND ${l} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...Al,...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 S=g.all(p.id,...u,n.messages+1),k=S.length>n.messages,P=[],R=0;for(let A of S.slice(0,n.messages)){let C=Ml(A.tool_calls),D=p.kind==="teamwork"&&A.role==="user"&&Mh.test(String(A.content??"")),L={role:ie(A.role,16)??null,at:Number(A.timestamp)||null,agent:ie(A.agent_slug,64),model:ie(A.model_id,128),error:A.is_error?!0:void 0,text:D?void 0:yt(A.content,n.textChars),relayChars:D?String(A.content??"").length:void 0,reasoning:yt(A.reasoning,n.textChars),tools:C.length?C.map(X=>ie(X?.function?.name??X?.name,80)??"?"):void 0,toolArgChars:C.length?C.reduce((X,K)=>X+String(K?.function?.arguments??"").length,0):void 0,toolResultChars:Number(A.tool_result_chars)||void 0,attachments:Ml(A.attachments).length||void 0},j=Buffer.byteLength(JSON.stringify(L));if(R+j>n.sessionBytes){k=!0;break}R+=j,P.push(L)}let O={id:ie(p.id,64)??null,kind:ie(p.kind,16)??null,parent:ie(p.parent_session_id,64),app:ie(p.app_id,50)??null,title:yt(p.title,200)??null,model:ie(p.model_id,128)??null,project:yt(p.project_name,120),archived:p.archived?!0:void 0,createdAt:ie(p.created_at,40)??null,updatedAt:ie(p.updated_at,40)??null,messages:P.reverse(),...k?{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:Vt(a)}}finally{try{i?.close()}catch{}}}async function Xh(t,e,n=Ph){let r=ae(t,"tangu","state.db"),o=await xt(r).then(i=>i.isFile(),i=>i?.code==="ENOENT"?!1:Vt(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, ${or}) AS error, r.tokens_total, r.created_at, r.updated_at, s.kind
248
+ WHERE s.kind IN (${Ml.map(()=>"?").join(", ")}) AND ${l} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...Ml,...u,n.sessions+1),h=o.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 ?`),p=[],m=0,w=f.length>n.sessions;for(let y of f.slice(0,n.sessions)){let S=h.all(y.id,...u,n.messages+1),g=S.length>n.messages,P=[],x=0;for(let A of S.slice(0,n.messages)){let E=Ul(A.tool_calls),M=y.kind==="teamwork"&&A.role==="user"&&Hh.test(String(A.content??"")),W={role:ce(A.role,16)??null,at:Number(A.timestamp)||null,agent:ce(A.agent_slug,64),model:ce(A.model_id,128),error:A.is_error?!0:void 0,text:M?void 0:wt(A.content,n.textChars),relayChars:M?String(A.content??"").length:void 0,reasoning:wt(A.reasoning,n.textChars),tools:E.length?E.map(B=>ce(B?.function?.name??B?.name,80)??"?"):void 0,toolArgChars:E.length?E.reduce((B,ie)=>B+String(ie?.function?.arguments??"").length,0):void 0,toolResultChars:Number(A.tool_result_chars)||void 0,attachments:Ul(A.attachments).length||void 0},j=Buffer.byteLength(JSON.stringify(W));if(x+j>n.sessionBytes){g=!0;break}x+=j,P.push(W)}let D={id:ce(y.id,64)??null,kind:ce(y.kind,16)??null,parent:ce(y.parent_session_id,64),app:ce(y.app_id,50)??null,title:wt(y.title,200)??null,model:ce(y.model_id,128)??null,project:wt(y.project_name,120),archived:y.archived?!0:void 0,createdAt:ce(y.created_at,40)??null,updatedAt:ce(y.updated_at,40)??null,messages:P.reverse(),...g?{olderMessagesDropped:!0}:{}},k=Buffer.byteLength(JSON.stringify(D));if(m+k>n.totalBytes){w=!0;break}m+=k,p.push(D)}return{sessions:p,...w?{sessionsTruncated:!0}:{}}}catch(a){return{sessions:[],sessionsError:Xt(a)}}finally{try{o?.close()}catch{}}}async function sg(t,e,n=zh){let r=le(t,"tangu","state.db"),i=await Rt(r).then(o=>o.isFile(),o=>o?.code==="ENOENT"?!1:Xt(o));if(i!==!0)return i===!1?{runs:[]}:{runs:[],runsError:i};let s;try{let{DatabaseSync:o}=await import("node:sqlite");s=new o(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, ${dr}) 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(wn(ht(e)),wn(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,
251
+ WHERE r.updated_at >= ? AND r.updated_at < ? ORDER BY r.updated_at DESC, r.id LIMIT ?`).all(kn(gt(e)),kn(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
- json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${or}) AS error
255
- FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),u=y=>typeof y=="number"&&Number.isFinite(y)&&y>0?y:0,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},S=new Map,k=[],P=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=ie(C.name,80)??"?",L=S.get(D)??(S.size<n.tools?{name:D,n:0,ms:0,maxMs:0}:void 0);if(!L){O=!0;continue}S.set(D,L),L.n++,C.failed&&(L.errors=(L.errors??0)+1),L.ms+=u(C.ms),L.maxMs=Math.max(L.maxMs,u(C.ms))}else if(C.type==="error"){let D=fo(C.error,n.errorChars);D&&!k.includes(D)&&k.length<3&&k.push(D)}else C.phase==="llm_retry"&&P++;let w={id:ie(y.id,64)??null,session:ie(y.session_id,64)??null,kind:ie(y.kind,16),app:ie(y.app_id,50),model:ie(y.model_id,128),status:ie(y.status,16)??null,error:fo(y.error,n.errorChars),createdAt:ie(y.created_at,40)??null,updatedAt:ie(y.updated_at,40)??null,steps:d(u(y.current_step)),tokens:d(u(y.tokens_total)),retries:d(P),...Object.fromEntries(Object.entries(p).map(([C,D])=>[C,d(D)])),errors:k.length?k:void 0,tools:S.size?[...S.values()]:void 0,partial:O||void 0},A=Buffer.byteLength(JSON.stringify(w));if(h+A>n.totalBytes){m=!0;break}h+=A,g.push(w)}return{runs:g,...m?{runsTruncated:!0}:{}}}catch(i){return{runs:[],runsError:Vt(i)}}finally{try{s?.close()}catch{}}}async function Zh(t){let e=o=>Math.round(o/1048576),n=o=>xt(o).then(s=>s.isFile()?s.size:0,()=>0),r=ae(t,"tangu","state.db");return{cpus:_h().length,memTotalMB:e(xh()),memFreeMB:e(Ch()),diskFreeMB:await Eh(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 Pl=t=>typeof t.diagnosticLogs=="function";function Qh(t,e=$h){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=>fo(c,Vs)??""),s=o.some((c,l)=>c.length>Vs||r[l].length>or),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:ie(n.state,32)??null,lastError:fo(n.lastError,Vs)??null,log:o.slice(i).join(`
256
- `),...s?{logTruncated:!0}:{}}}var Js={errors:20,errorChars:300,agents:100},eg=t=>ql(Bl(t,!1).replace(/[^\s"'`<>()[\]{},;]*\/[^\s"'`<>()[\]{},;]*/g,e=>Ys.test(e)?e:"[path]")),tg=(t,e=[],n=Js.errorChars)=>yt(eg(bl(wt(t),e.map(r=>wt(r)))),n)??"",Le=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?Math.round(t):0,uo=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?new Date(t).toISOString():null,Vl=t=>{let e=t&&typeof t=="object"?t:{};return Object.fromEntries(wl.flatMap(n=>Le(e[n])?[[n,Le(e[n])]]:[]))},$l=t=>{let e=t;return e&&typeof e=="object"?{at:uo(e.at),ms:Le(e.ms),completed:e.completed===!0,...Vl(e.counts)}:null},ng=Object.fromEntries(At.map(t=>[t.path,t.id])),rg=new Set(["idle","scanning","syncing","paused"]),og=new Set(["queued","active","done","failed","paused","conflict"]);function sg(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 At)o[a.id]=r(pn(a.path,n)?.target);let s={},i={};for(let a of n){if(a.source===""||ng[a.source])continue;let c=er(a.source);if(c&&Object.keys(s).length<Js.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 ig(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])=>og.has(i)&&Le(a)).map(([i,a])=>[i,Le(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"&&rg.has(e.phase)?e.phase:null,revision:Le(e.revision),rules:sg(e.rules,n),backlog:r?{jobs:o,blocked:Le(r.blocked),pendingUploads:Le(r.pendingUploads),unconfirmed:Le(r.unconfirmed),trash:Le(r.trash),awaitingBytes:Le(r.awaitingBytes),dirty:Le(r.dirty)}:null,archive:e.archive==="running"||e.archive==="done"?e.archive:null,since:uo(e.since),lastRun:$l(e.lastRun),runs:(Array.isArray(e.runs)?e.runs:[]).slice(-20).map($l).filter(Boolean),totals:{runs:Le(s.runs),completedRuns:Le(s.completedRuns),idleRuns:Le(s.idleRuns),...Vl(s)},errors:(Array.isArray(e.errors)?e.errors:[]).slice(-Js.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:uo(i.first),at:uo(i.at),n:Le(i.n)||1,kind:Wr(i.text)??"other",text:tg(i.text,a)}]})}}function ag(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 cg(t,e=Fh){let n;try{n=oo(t)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof n[r]=="string"&&n[r]?[[r,n[r]]]:[]))}async function Yl(t,e=jh){try{if(!(await xt(t)).isFile())return null;let n=await jl(t,El.O_RDONLY|(El.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 nr=async(t,e)=>{let n=await Yl(t);return n?yt(wt(n),e):void 0};async function lg(t,e){let n=await Yl(ae(t,"config.toml")),r=Object.entries(n?cg(n):{}).map(([o,s])=>[o,yt(wt(s),e)??""]);return r.length?Object.fromEntries(r):void 0}async function Nl(t){let e=await yn(ae(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 ug(t,e,n=Nh){let r=ae(t,"tangu"),o=h=>xt(h).then(m=>m.isFile()?m.mtimeMs:0,()=>0),s=Ct(new Date(ht(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 nr(ae(r,"USER.md"),n.fileChars);l&&c([],l)&&(i.user=l);let u=ae(r,"state.db"),d=await xt(u).then(h=>h.isFile(),h=>h?.code==="ENOENT"?!1:Vt(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, ${or}) AS detail, session_ref, created_at FROM special_agent_log
257
- WHERE created_at >= ? AND created_at < ? AND (${Lh.map(S=>`action GLOB '${S}*'`).join(" OR ")})
258
- ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(wn(ht(e)),wn(e.getTime()),n.activity+1);p.length>n.activity&&(i.truncated=!0);for(let S of p.slice(0,n.activity))if(!c(i.activity,{at:ie(S.created_at,40)??null,agent:ie(S.agent,64)??null,action:ie(S.action,64)??null,detail:typeof S.detail=="string"&&S.detail?yt(wt(S.detail),n.detailChars):void 0,session:ie(S.session_ref,64)}))break}catch(m){i.activityError=Vt(m)}finally{try{h?.close()}catch{}}}for(let h of await mt(ae(r,"project-memory"),100)){let m=ae(r,"project-memory",h);if(!await rr(m))continue;let y=await nr(ae(m,"MEMORY.md"),n.fileChars),p=await Nl(m);if(!y&&!p)continue;let S=(await yn(ae(m,"PROJECT.json")))?.project;if(!c(i.projects,{id:ie(h,64)??null,name:typeof S=="string"?ie(Ul(S.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:p,memory:y}))break}for(let h of await mt(ae(r,"teams"),100)){if(!await rr(ae(r,"teams",h)))continue;let m=await nr(ae(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 mt(ae(r,"agents"),100)){let m=ae(r,"agents",h);await rr(m)&&g.push({id:h,dir:m,at:Math.max(0,...await Promise.all([...xl,".memory-state.json"].map(y=>o(ae(m,y)))))})}for(let{id:h,dir:m,at:y}of g.sort((p,S)=>S.at-p.at||p.id.localeCompare(S.id))){let p={};for(let O of xl){let w=await nr(ae(m,O),n.fileChars);w&&(p[O]=w)}let S=[];if(await rr(ae(m,"LOG")))for(let O of(await mt(ae(m,"LOG"),400)).filter(w=>/^\d{4}-\d{2}-\d{2}\.md$/.test(w)&&w.slice(0,10)>=s&&w.slice(0,10)<=Ct(e))){let w=await nr(ae(m,"LOG",O),n.logChars);w&&S.push({date:O.slice(0,10),text:w})}let k=(await yn(ae(m,".memory-dream.json")))?.last,P=await Nl(m),R=await lg(m,n.fileChars);!Object.keys(p).length&&!S.length&&!P&&!R||c(i.agents,{id:h,updatedAt:y?new Date(y).toISOString():null,config:R,state:P,dream:k&&typeof k=="object"?{state:ie(k.state,32),startedAt:ie(k.startedAt,40),finishedAt:ie(k.finishedAt,40),calls:typeof k.calls=="number"?k.calls:void 0,detail:typeof k.detail=="string"?yt(wt(k.detail),n.detailChars):void 0}:void 0,files:Object.keys(p).length?p:void 0,log:S.length?S:void 0})}return i}async function Gl(t){let e=(await yn(ae(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${yh("sha256").update(Ll()).digest("hex").slice(0,8)}`}async function dg(t){let{home:e}=t,n=ae(e,"tangu"),r=t.now??new Date,o=i=>t.since?.[i]??ht(r),s=Qh(t.engineLogs);return wt({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:Ul(e),cloudUrl:t.cloudUrl},device:{id:await Gl(e),name:Ll()},system:await Zh(e),config:Yh(await yn(ae(e,"config.json"))),agents:await Dl(ae(n,"agents")),teams:await Dl(ae(n,"teams")),plugins:{desktop:await Ol(ae(e,"plugins")),engine:await Ol(ae(n,"plugins"))},inventory:{skills:await mt(ae(n,"skills")),spaces:await mt(ae(e,"spaces")),themes:await mt(ae(e,"themes"))},...t.activity?{...await Jh(ae(e,"activity"),r,o("activity")),activitySince:new Date(o("activity")).toISOString()}:{},...t.sessions?{...await Kh(e,r,zl,o("sessions")),sessionsSince:new Date(o("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await ug(e,r)}:{},...await Xh(e,r),runsSince:new Date(ht(r)).toISOString(),...s?{engine:s}:{},sync:{content:ig(t.contentSync),legacy:ag(t.engineLogs)}})}function Jl(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(R=>Fr({baseUrl:R.cloudUrl,vault:Lr,getToken:()=>R.token})),o=e.policyFor??Hs,s=()=>ae(t.homeDir(),"extend-diagnostics.json"),i=()=>{let R=O=>O&&typeof O=="object"?O:{};try{let O=JSON.parse(bh(s(),"utf8"));return{accounts:R(O?.accounts),sent:R(O?.sent)}}catch{return{accounts:{},sent:{}}}},a=()=>i().accounts,c=(R,O,w)=>{let A=i();A.accounts[R]={...A.accounts[R],...O},Object.assign(A.sent,w),wh(t.homeDir(),{recursive:!0});let C=`${s()}.${process.pid}.tmp`;vh(C,JSON.stringify(A,null,2),{encoding:"utf8",mode:384}),Sh(C,s())},l=()=>{let R=t.readCreds();return R.token&&R.cloudUrl?t.accountId():null},u=()=>{let R=l(),O=R?a()[R]??{}:{},w=Zn(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:io,mode:w.mode,intervalHours:w.intervalHours}},d=()=>{try{return Pl(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(),A=i(),C=A.accounts[R],D=O.cloudUrl.replace(/\/+$/,""),L=js(C?.file,A.sent[D]??{},w),j=(async()=>{try{let X=await dg({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:O.cloudUrl,activity:C?.activity!==!1,sessions:C?.sessions===!0,now:w,since:L,engineLogs:d(),contentSync:kl(),memory:()=>{let ge=l()===R?a()[R]:void 0;return ge?.enabled===!0&&ge.memory===!0}}),K=await Gl(t.homeDir()),te=a()[R];if(l()!==R||te?.enabled!==!0)return!1;if(te.activity===!1)for(let ge of["activity","activityTruncated","activityError","activitySince"])delete X[ge];if(te.sessions!==!0)for(let ge of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete X[ge];te.memory!==!0&&delete X.memory;let ne=[],Q=Th(X,ne);if(!Q)throw new Error("snapshot too large");await Ls(r(O),K,Q,w),h.delete(R);let ee=Fs(i().sent[D]??{},C?.file,L,w,X,ne);return c(R,{lastUploadAt:n().getTime(),lastError:void 0,file:ee.file},{[D]:ee.sent}),t.log(`[forsion-extend] diagnostics uploaded (${Q.length} bytes)`),!0}catch(X){h.set(R,n().getTime());let K=String(X?.message||X).slice(0,300);try{c(R,{lastError:K})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${K}`),!1}finally{g=null}})();return g={id:R,done:j},j},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 A=O??{...Zn(w.policy),requestedAt:0},C=A.requestedAt>(w.requestSeen??A.requestedAt),D=w.lastUploadAt??0,L=!D||A.mode==="scheduled"&&n().getTime()-D>=A.intervalHours*Hl;if(!C&&!L||n().getTime()-(h.get(R)??-Cl)<Cl)return;await m()&&C&&c(R,{requestSeen:A.requestedAt})}catch(R){t.log(`[forsion-extend] diagnostics tick failed: ${String(R?.message||R)}`)}},p=Promise.resolve(),S={ok:!1,error:"untrusted"};t.handle("diagnostics:get",R=>t.isTrustedSender(R)?u():S),t.handle("diagnostics:set",(R,O)=>{if(!t.isTrustedSender(R))return S;let w=l();if(!w)return u();let A={};typeof O?.enabled=="boolean"&&(A.enabled=O.enabled),A.enabled&&(A.requestSeen=void 0),typeof O?.activity=="boolean"&&(A.activity=O.activity),typeof O?.sessions=="boolean"&&(A.sessions=O.sessions),typeof O?.memory=="boolean"&&(A.memory=O.memory);let C=a()[w];for(let D of["sessions","memory"])A[D]!==void 0||C?.[D]!==void 0||(C?.enabled===!0?A[D]=!1:A.enabled&&(A[D]=!0));return c(w,A),A.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()):S);let k=setTimeout(()=>void y(),Ih),P=setInterval(()=>void y(),Rh);return k.unref?.(),P.unref?.(),t.log(`[forsion-extend] diagnostics registered${Pl(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(k),clearInterval(P)},{tick:y,settled:()=>p})}import{randomUUID as iu}from"node:crypto";import{appendFileSync as Eg,existsSync as _g,mkdirSync as ti,readFileSync as au,renameSync as cu,rmSync as ni,statSync as Cg,writeFileSync as lu}from"node:fs";import{lstat as pu}from"node:fs/promises";import{homedir as Ag,release as xg}from"node:os";import{join as Sn}from"node:path";var sr={$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 pg=sr.events,hg=sr.envelope,Xs=sr.limits,Zl=sr.version,gg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,mg=/^[A-Za-z0-9._:/@+-]+$/,Ql=t=>typeof t=="string"&&gg.test(t),Kl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,yg=[[/\/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]"]],eu=t=>yg.reduce((e,[n,r])=>e.replace(n,r),t);function Xl(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(Kl,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=eu(r),(r.length>e?r.slice(0,e):r).replace(Kl,"\uFFFD")}var wg=/^pr-[a-f0-9]{48}$/,bg=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Sg=t=>wg.test(t)||bg.test(t)||eu(t)===t;function vg(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function Ks(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 Ql(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&&mg.test(e)&&Sg(e)?e:void 0;case"text":return typeof e=="string"&&e?Xl(e,t.max,n):void 0;case"stack":{let r=vg(e);return r?Xl(r,t.max,n):void 0}}}function Yt(t,e){let n=typeof t?.event=="string"?pg[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=Ks(a,o[i],e);c!==void 0&&(r[i]=c)}let s=Ks({type:"iso-time"},t.ts);return{event:t.event,ts:s??new Date().toISOString(),...Ql(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function tu(t){let e={};for(let[n,r]of Object.entries(hg)){if(n==="installId")continue;let o=Ks(r,t[n]);e[n]=typeof o=="string"?o:null}return e}function nu(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 ru(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function Zs(t){return t?/^pr-/.test(t)?"forsion":/^codex\//.test(t)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(t)?"local":"byok":"other"}var kg=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function ou(t){if(typeof t!="string"||!t)return;let e=Zs(t);if(e==="forsion"||e==="codex")return t;let n=t.slice(t.lastIndexOf("/")+1);return kg.test(n)?n:void 0}function Qs(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function ei(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}function su(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var Tg=10*6e4,Ig=6e4,Rg=50,uu=1024*1024,Dg=168*36e5,du=15e3,Og=200,Mg=2e3,ri=7,Pg=5e3,fu=864e5,$g=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts"]),oi={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},Ng=new Set(["custom-ask","escalate","mode","protected","control","always"]),jg=new Set(["readonly","auto-edit","full-auto","custom"]),hu=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),si=t=>({at:hu(t),id:"~"}),bn=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function Fg(t,e,n,r){let o=Sn(t,"tangu","state.db");if(!await pu(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
254
+ json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${dr}) 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=w=>typeof w=="number"&&Number.isFinite(w)&&w>0?w:0,f=w=>w||void 0,h=[],p=0,m=c.length>n.runs;for(let w of c.slice(0,n.runs)){let y={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},S=new Map,g=[],P=0,x=l.all(w.id,n.events+1),D=x.length>n.events;for(let E of x.slice(0,n.events))if(E.type==="usage")y.llmCalls++,y.prompt+=u(E.prompt),y.completion+=u(E.completion),y.cached+=u(E.cached),y.reasoning+=u(E.reasoning),y.llmMs+=u(E.llm_ms),y.ttftMaxMs=Math.max(y.ttftMaxMs,u(E.ttft_ms)),y.requestMaxBytes=Math.max(y.requestMaxBytes,u(E.request_bytes));else if(E.type==="tool_result"){let M=ce(E.name,80)??"?",W=S.get(M)??(S.size<n.tools?{name:M,n:0,ms:0,maxMs:0}:void 0);if(!W){D=!0;continue}S.set(M,W),W.n++,E.failed&&(W.errors=(W.errors??0)+1),W.ms+=u(E.ms),W.maxMs=Math.max(W.maxMs,u(E.ms))}else if(E.type==="error"){let M=mi(E.error,n.errorChars);M&&!g.includes(M)&&g.length<3&&g.push(M)}else E.phase==="llm_retry"&&P++;let k={id:ce(w.id,64)??null,session:ce(w.session_id,64)??null,kind:ce(w.kind,16),app:ce(w.app_id,50),model:ce(w.model_id,128),status:ce(w.status,16)??null,error:mi(w.error,n.errorChars),createdAt:ce(w.created_at,40)??null,updatedAt:ce(w.updated_at,40)??null,steps:f(u(w.current_step)),tokens:f(u(w.tokens_total)),retries:f(P),...Object.fromEntries(Object.entries(y).map(([E,M])=>[E,f(M)])),errors:g.length?g:void 0,tools:S.size?[...S.values()]:void 0,partial:D||void 0},A=Buffer.byteLength(JSON.stringify(k));if(p+A>n.totalBytes){m=!0;break}p+=A,h.push(k)}return{runs:h,...m?{runsTruncated:!0}:{}}}catch(o){return{runs:[],runsError:Xt(o)}}finally{try{s?.close()}catch{}}}async function og(t){let e=i=>Math.round(i/1048576),n=i=>Rt(i).then(s=>s.isFile()?s.size:0,()=>0),r=le(t,"tangu","state.db");return{cpus:Oh().length,memTotalMB:e($h()),memFreeMB:e(Mh()),diskFreeMB:await Dh(t).then(i=>e(i.bavail*i.bsize),()=>null),stateDbMB:e(await n(r)+await n(`${r}-wal`)),uptimeMin:Math.round(process.uptime()/60)}}var Hl=t=>typeof t.diagnosticLogs=="function";function ag(t,e=Bh){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),i=r.map(c=>mi(c,Qs)??""),s=i.some((c,l)=>c.length>Qs||r[l].length>dr),o=i.length,a=e;for(;o>0&&Buffer.byteLength(i[o-1])+1<=a;)a-=Buffer.byteLength(i[--o])+1;return o>0&&(s=!0),{state:ce(n.state,32)??null,lastError:mi(n.lastError,Qs)??null,log:i.slice(o).join(`
256
+ `),...s?{logTruncated:!0}:{}}}var no={errors:20,errorChars:300,agents:100},cg=t=>Xl(Kl(t,!1).replace(/[^\s"'`<>()[\]{},;]*\/[^\s"'`<>()[\]{},;]*/g,e=>eo.test(e)?e:"[path]")),lg=(t,e=[],n=no.errorChars)=>wt(cg(Al(bt(t),e.map(r=>bt(r)))),n)??"",He=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?Math.round(t):0,gi=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?new Date(t).toISOString():null,Ql=t=>{let e=t&&typeof t=="object"?t:{};return Object.fromEntries(Cl.flatMap(n=>He(e[n])?[[n,He(e[n])]]:[]))},zl=t=>{let e=t;return e&&typeof e=="object"?{at:gi(e.at),ms:He(e.ms),completed:e.completed===!0,...Ql(e.counts)}:null},ug=Object.fromEntries(It.map(t=>[t.path,t.id])),dg=new Set(["idle","scanning","syncing","paused"]),fg=new Set(["queued","active","done","failed","paused","conflict"]);function pg(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",i={other:r(n.find(a=>a.source==="")?.target)};for(let a of It)i[a.id]=r(yn(a.path,n)?.target);let s={},o={};for(let a of n){if(a.source===""||ug[a.source])continue;let c=ar(a.source);if(c&&Object.keys(s).length<no.agents)s[c]=r(a.target);else if(!c){let l=r(a.target)??"unknown";o[l]=(o[l]??0)+1}}return{...i,agentRules:s,folderRules:o,count:n.length}}function hg(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,i=r?.jobs&&typeof r.jobs=="object"?Object.fromEntries(Object.entries(r.jobs).filter(([o,a])=>fg.has(o)&&He(a)).map(([o,a])=>[o,He(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"&&dg.has(e.phase)?e.phase:null,revision:He(e.revision),rules:pg(e.rules,n),backlog:r?{jobs:i,blocked:He(r.blocked),pendingUploads:He(r.pendingUploads),unconfirmed:He(r.unconfirmed),trash:He(r.trash),awaitingBytes:He(r.awaitingBytes),dirty:He(r.dirty)}:null,archive:e.archive==="running"||e.archive==="done"?e.archive:null,since:gi(e.since),lastRun:zl(e.lastRun),runs:(Array.isArray(e.runs)?e.runs:[]).slice(-20).map(zl).filter(Boolean),totals:{runs:He(s.runs),completedRuns:He(s.completedRuns),idleRuns:He(s.idleRuns),...Ql(s)},errors:(Array.isArray(e.errors)?e.errors:[]).slice(-no.errors).flatMap(o=>{if(!o||typeof o!="object"||typeof o.text!="string"||!o.text)return[];let a=Array.isArray(o.paths)?o.paths.filter(c=>typeof c=="string"):[];return[{first:gi(o.first),at:gi(o.at),n:He(o.n)||1,kind:Zr(o.text)??"other",text:lg(o.text,a)}]})}}function gg(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 i=/已从云端拉取(覆盖|新文件)/.exec(r);if(i){i[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 mg(t,e=Vh){let n;try{n=li(t)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof n[r]=="string"&&n[r]?[[r,n[r]]]:[]))}async function eu(t,e=Wh){try{if(!(await Rt(t)).isFile())return null;let n=await ql(t,Rl.O_RDONLY|(Rl.O_NOFOLLOW??0));try{let r=await n.stat();if(!r.isFile())return null;let i=Buffer.alloc(Math.min(e,r.size)),{bytesRead:s}=await n.read(i,0,i.length,0);return i.subarray(0,s).toString("utf8")}finally{await n.close()}}catch{return null}}var lr=async(t,e)=>{let n=await eu(t);return n?wt(bt(n),e):void 0};async function yg(t,e){let n=await eu(le(t,"config.toml")),r=Object.entries(n?mg(n):{}).map(([i,s])=>[i,wt(bt(s),e)??""]);return r.length?Object.fromEntries(r):void 0}async function Bl(t){let e=await vn(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 wg(t,e,n=qh){let r=le(t,"tangu"),i=p=>Rt(p).then(m=>m.isFile()?m.mtimeMs:0,()=>0),s=Tt(new Date(gt(e))),o={agents:[],teams:[],projects:[],activity:[]},a=n.totalBytes,c=(p,m)=>{let w=Buffer.byteLength(JSON.stringify(m))+1;return w>a?(o.truncated=!0,!1):(a-=w,p.push(m),!0)},l=await lr(le(r,"USER.md"),n.fileChars);l&&c([],l)&&(o.user=l);let u=le(r,"state.db"),f=await Rt(u).then(p=>p.isFile(),p=>p?.code==="ENOENT"?!1:Xt(p));if(typeof f=="string")o.activityError=f;else if(f){let p;try{let{DatabaseSync:m}=await import("node:sqlite");p=new m(u,{readOnly:!0}),p.exec("PRAGMA busy_timeout = 1500");let y=p.prepare(`SELECT agent, action, substr(detail, 1, ${dr}) AS detail, session_ref, created_at FROM special_agent_log
257
+ WHERE created_at >= ? AND created_at < ? AND (${Yh.map(S=>`action GLOB '${S}*'`).join(" OR ")})
258
+ ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(kn(gt(e)),kn(e.getTime()),n.activity+1);y.length>n.activity&&(o.truncated=!0);for(let S of y.slice(0,n.activity))if(!c(o.activity,{at:ce(S.created_at,40)??null,agent:ce(S.agent,64)??null,action:ce(S.action,64)??null,detail:typeof S.detail=="string"&&S.detail?wt(bt(S.detail),n.detailChars):void 0,session:ce(S.session_ref,64)}))break}catch(m){o.activityError=Xt(m)}finally{try{p?.close()}catch{}}}for(let p of await yt(le(r,"project-memory"),100)){let m=le(r,"project-memory",p);if(!await ur(m))continue;let w=await lr(le(m,"MEMORY.md"),n.fileChars),y=await Bl(m);if(!w&&!y)continue;let S=(await vn(le(m,"PROJECT.json")))?.project;if(!c(o.projects,{id:ce(p,64)??null,name:typeof S=="string"?ce(Yl(S.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:y,memory:w}))break}for(let p of await yt(le(r,"teams"),100)){if(!await ur(le(r,"teams",p)))continue;let m=await lr(le(r,"teams",p,"TEAM.md"),n.fileChars);if(m&&!c(o.teams,{id:p,files:{"TEAM.md":m}}))break}let h=[];for(let p of await yt(le(r,"agents"),100)){let m=le(r,"agents",p);await ur(m)&&h.push({id:p,dir:m,at:Math.max(0,...await Promise.all([...Pl,".memory-state.json"].map(w=>i(le(m,w)))))})}for(let{id:p,dir:m,at:w}of h.sort((y,S)=>S.at-y.at||y.id.localeCompare(S.id))){let y={};for(let D of Pl){let k=await lr(le(m,D),n.fileChars);k&&(y[D]=k)}let S=[];if(await ur(le(m,"LOG")))for(let D of(await yt(le(m,"LOG"),400)).filter(k=>/^\d{4}-\d{2}-\d{2}\.md$/.test(k)&&k.slice(0,10)>=s&&k.slice(0,10)<=Tt(e))){let k=await lr(le(m,"LOG",D),n.logChars);k&&S.push({date:D.slice(0,10),text:k})}let g=(await vn(le(m,".memory-dream.json")))?.last,P=await Bl(m),x=await yg(m,n.fileChars);!Object.keys(y).length&&!S.length&&!P&&!x||c(o.agents,{id:p,updatedAt:w?new Date(w).toISOString():null,config:x,state:P,dream:g&&typeof g=="object"?{state:ce(g.state,32),startedAt:ce(g.startedAt,40),finishedAt:ce(g.finishedAt,40),calls:typeof g.calls=="number"?g.calls:void 0,detail:typeof g.detail=="string"?wt(bt(g.detail),n.detailChars):void 0}:void 0,files:Object.keys(y).length?y:void 0,log:S.length?S:void 0})}return o}async function tu(t){let e=(await vn(le(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Ch("sha256").update(Vl()).digest("hex").slice(0,8)}`}async function bg(t){let{home:e}=t,n=le(e,"tangu"),r=t.now??new Date,i=o=>t.since?.[o]??gt(r),s=ag(t.engineLogs);return bt({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:Ph(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:Yl(e),cloudUrl:t.cloudUrl},device:{id:await tu(e),name:Vl()},system:await og(e),config:tg(await vn(le(e,"config.json"))),agents:await Fl(le(n,"agents")),teams:await Fl(le(n,"teams")),plugins:{desktop:await Ll(le(e,"plugins")),engine:await Ll(le(n,"plugins"))},inventory:{skills:await yt(le(n,"skills")),spaces:await yt(le(e,"spaces")),themes:await yt(le(e,"themes"))},...t.activity?{...await rg(le(e,"activity"),r,i("activity")),activitySince:new Date(i("activity")).toISOString()}:{},...t.sessions?{...await ig(e,r,Jl,i("sessions")),sessionsSince:new Date(i("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await wg(e,r)}:{},...await sg(e,r),runsSince:new Date(gt(r)).toISOString(),...s?{engine:s}:{},sync:{content:hg(t.contentSync),legacy:gg(t.engineLogs)}})}function nu(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(x=>Wr({baseUrl:x.cloudUrl,vault:Vr,getToken:()=>x.token})),i=e.policyFor??Gs,s=()=>le(t.homeDir(),"extend-diagnostics.json"),o=()=>{let x=D=>D&&typeof D=="object"?D:{};try{let D=JSON.parse(xh(s(),"utf8"));return{accounts:x(D?.accounts),sent:x(D?.sent)}}catch{return{accounts:{},sent:{}}}},a=()=>o().accounts,c=(x,D,k)=>{let A=o();A.accounts[x]={...A.accounts[x],...D},Object.assign(A.sent,k),Ah(t.homeDir(),{recursive:!0});let E=`${s()}.${process.pid}.tmp`;Ih(E,JSON.stringify(A,null,2),{encoding:"utf8",mode:384}),Th(E,s())},l=()=>{let x=t.readCreds();return x.token&&x.cloudUrl?t.accountId():null},u=()=>{let x=l(),D=x?a()[x]??{}:{},k=sr(D.policy);return{signedIn:!!x,enabled:D.enabled===!0,activity:D.activity!==!1,sessions:D.sessions??D.enabled!==!0,memory:D.memory??D.enabled!==!0,lastUploadAt:D.lastUploadAt??null,lastError:D.lastError??null,retainDays:di,mode:k.mode,intervalHours:k.intervalHours}},f=()=>{try{return Hl(t)?t.diagnosticLogs():null}catch{return null}},h=null,p=new Map,m=async()=>{let x=l();if(!x)return!1;if(h)return h.id===x?h.done:(await h.done,m());let D={...t.readCreds()},k=n(),A=o(),E=A.accounts[x],M=D.cloudUrl.replace(/\/+$/,""),W=qs(E?.file,A.sent[M]??{},k),j=(async()=>{try{let B=await bg({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:D.cloudUrl,activity:E?.activity!==!1,sessions:E?.sessions===!0,now:k,since:W,engineLogs:f(),contentSync:Il(),memory:()=>{let fe=l()===x?a()[x]:void 0;return fe?.enabled===!0&&fe.memory===!0}}),ie=await tu(t.homeDir()),se=a()[x];if(l()!==x||se?.enabled!==!0)return!1;if(se.activity===!1)for(let fe of["activity","activityTruncated","activityError","activitySince"])delete B[fe];if(se.sessions!==!0)for(let fe of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete B[fe];se.memory!==!0&&delete B.memory;let X=[],ee=Nh(B,X);if(!ee)throw new Error("snapshot too large");await Vs(r(D),ie,ee,k),p.delete(x);let ne=Ws(o().sent[M]??{},E?.file,W,k,B,X);return c(x,{lastUploadAt:n().getTime(),lastError:void 0,file:ne.file},{[M]:ne.sent}),t.log(`[forsion-extend] diagnostics uploaded (${ee.length} bytes)`),!0}catch(B){p.set(x,n().getTime());let ie=String(B?.message||B).slice(0,300);try{c(x,{lastError:ie})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${ie}`),!1}finally{h=null}})();return h={id:x,done:j},j},w=async()=>{try{let x=l();if(!x||a()[x]?.enabled!==!0)return;let D=await i({...t.readCreds()}),k=l()===x?a()[x]:void 0;if(k?.enabled!==!0)return;D&&(D.mode!==k.policy?.mode||D.intervalHours!==k.policy?.intervalHours)&&c(x,{policy:{mode:D.mode,intervalHours:D.intervalHours}}),D&&k.requestSeen===void 0&&c(x,{requestSeen:D.requestedAt});let A=D??{...sr(k.policy),requestedAt:0},E=A.requestedAt>(k.requestSeen??A.requestedAt),M=k.lastUploadAt??0,W=!M||A.mode==="scheduled"&&n().getTime()-M>=A.intervalHours*Gl;if(!E&&!W||n().getTime()-(p.get(x)??-Ol)<Ol)return;await m()&&E&&c(x,{requestSeen:A.requestedAt})}catch(x){t.log(`[forsion-extend] diagnostics tick failed: ${String(x?.message||x)}`)}},y=Promise.resolve(),S={ok:!1,error:"untrusted"};t.handle("diagnostics:get",x=>t.isTrustedSender(x)?u():S),t.handle("diagnostics:set",(x,D)=>{if(!t.isTrustedSender(x))return S;let k=l();if(!k)return u();let A={};typeof D?.enabled=="boolean"&&(A.enabled=D.enabled),A.enabled&&(A.requestSeen=void 0),typeof D?.activity=="boolean"&&(A.activity=D.activity),typeof D?.sessions=="boolean"&&(A.sessions=D.sessions),typeof D?.memory=="boolean"&&(A.memory=D.memory);let E=a()[k];for(let M of["sessions","memory"])A[M]!==void 0||E?.[M]!==void 0||(E?.enabled===!0?A[M]=!1:A.enabled&&(A[M]=!0));return c(k,A),A.enabled&&(p.delete(k),y=Promise.all([y,w()]).then(()=>{})),u()}),t.handle("diagnostics:uploadNow",async x=>t.isTrustedSender(x)?(u().enabled&&await m(),u()):S);let g=setTimeout(()=>void w(),jh),P=setInterval(()=>void w(),Fh);return g.unref?.(),P.unref?.(),t.log(`[forsion-extend] diagnostics registered${Hl(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(g),clearInterval(P)},{tick:w,settled:()=>y})}import{randomUUID as pu}from"node:crypto";import{appendFileSync as Dg,existsSync as Og,mkdirSync as co,readFileSync as hu,renameSync as gu,rmSync as lo,statSync as Mg,writeFileSync as mu}from"node:fs";import{lstat as Su}from"node:fs/promises";import{homedir as Pg,release as $g}from"node:os";import{join as _n}from"node:path";var fr={$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 vg=fr.events,kg=fr.envelope,io=fr.limits,su=fr.version,Eg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,_g=/^[A-Za-z0-9._:/@+-]+$/,ou=t=>typeof t=="string"&&Eg.test(t),ru=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Cg=[[/\/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]"]],au=t=>Cg.reduce((e,[n,r])=>e.replace(n,r),t);function iu(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(ru,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=au(r),(r.length>e?r.slice(0,e):r).replace(ru,"\uFFFD")}var Ag=/^pr-[a-f0-9]{48}$/,xg=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Tg=t=>Ag.test(t)||xg.test(t)||au(t)===t;function Ig(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function ro(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 ou(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&&_g.test(e)&&Tg(e)?e:void 0;case"text":return typeof e=="string"&&e?iu(e,t.max,n):void 0;case"stack":{let r=Ig(e);return r?iu(r,t.max,n):void 0}}}function Zt(t,e){let n=typeof t?.event=="string"?vg[t.event]:void 0;if(!n)return null;let r={},i=t.props&&typeof t.props=="object"?t.props:{};for(let[o,a]of Object.entries(n)){let c=ro(a,i[o],e);c!==void 0&&(r[o]=c)}let s=ro({type:"iso-time"},t.ts);return{event:t.event,ts:s??new Date().toISOString(),...ou(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function cu(t){let e={};for(let[n,r]of Object.entries(kg)){if(n==="installId")continue;let i=ro(r,t[n]);e[n]=typeof i=="string"?i:null}return e}function lu(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 uu(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function so(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 du(t){if(typeof t!="string"||!t)return;let e=so(t);if(e==="forsion"||e==="codex")return t;let n=t.slice(t.lastIndexOf("/")+1);return Rg.test(n)?n:void 0}function oo(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function ao(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}function fu(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var Ng=10*6e4,jg=6e4,Fg=50,yu=1024*1024,Lg=168*36e5,wu=15e3,Ug=200,Hg=2e3,uo=7,zg=5e3,bu=864e5,Bg=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts"]),fo={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},qg=new Set(["custom-ask","escalate","mode","protected","control","always"]),Wg=new Set(["readonly","auto-edit","full-auto","custom"]),vu=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),po=t=>({at:vu(t),id:"~"}),En=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function Vg(t,e,n,r){let i=_n(t,"tangu","state.db");if(!await Su(i).then(o=>o.isFile(),()=>!1))return{events:[],cursor:e};let s;try{let{DatabaseSync:o}=await import("node:sqlite");s=new o(i,{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",Og),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,
261
+ ORDER BY r.updated_at, r.id LIMIT ?`).all(e.at,e.at,e.id,r??"9999-12-31 23:59:59",Ug),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 @@ ${s}`,n),this.line=r,this.column=o,this.codeblock=s}};var th=/^((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=s.prepare(`SELECT json_extract(e.payload, '$.telemetry.agentRole') AS agentRole, json_extract(e.payload, '$.telemetry.recallEntries') AS recallEntries,
270
+ ORDER BY e.seq LIMIT ?`),l=w=>`(SELECT total(json_extract(s.value, '$.tokens')) FROM json_each(e.payload, '$.sections') s WHERE json_extract(s.value, '$.k') = '${w}')`,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},S=new Map,k=new Map,P=[],R=new Map;for(let j of c.all(y.id,Mg))if(j.type==="usage")p.llmCalls++,p.tokensIn+=d(j.prompt),p.tokensOut+=d(j.completion),p.tokensCached+=d(j.cached);else if(j.type==="tool_call"||j.type==="tool_result"){if(typeof j.id=="string"&&j.source!=null&&k.set(j.id,j.source),j.type!=="tool_result"||typeof j.name!="string")continue;let X=j.source??(typeof j.id=="string"?k.get(j.id):void 0),K=ei(j.name,X),te=Qs(X),ne=`${K}\0${te}`,Q=S.get(ne)??{tool:K,toolSource:te,calls:0,failures:0,totalMs:0,maxMs:0};S.set(ne,Q),Q.calls++,j.failed&&Q.failures++,Q.totalMs+=d(j.ms),Q.maxMs=Math.max(Q.maxMs,d(j.ms))}else if(j.type==="approval_request")P.push({approvalId:g(j.approvalId),name:g(j.name),toolCallId:g(j.toolCallId),reasonKind:Ng.has(j.reasonKind)?j.reasonKind:"other",mode:jg.has(j.reasonMode)?j.reasonMode:"other",at:bn(j.at)});else if(j.type==="approval_result"){let X=g(j.approvalId);X&&!R.has(X)&&R.set(X,{action:g(j.action),via:g(j.via),at:bn(j.at)})}else j.phase==="llm_retry"&&p.retries++;let O=u.all(y.id)[0],w=ru(y.status),A=bn(y.updated_at)-bn(y.created_at),C=new Date(Number.isNaN(bn(y.updated_at))?Date.now():bn(y.updated_at)).toISOString(),D=Yt({event:"agent_run",ts:C,sessionId:n,props:{modelId:ou(y.model_id),providerKind:Zs(y.model_id),mode:su(y.kind),steps:d(y.current_step),...p,durationMs:Number.isFinite(A)&&A>=0?A:void 0,outcome:w,errorClass:w==="done"?void 0:nu(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 j of S.values()){let X=Yt({event:"tool_call",ts:C,sessionId:n,props:{...j,runOutcome:w}});X&&X.props.tool&&h.push(X)}let L=new Map;for(let j of P){if(!j.name)continue;let X=j.toolCallId?k.get(j.toolCallId):void 0,K=X==null?j.name.startsWith("mcp__")?"mcp":void 0:ei(j.name,X),te=Qs(X),ne=`${K??""}\0${te}\0${j.reasonKind}\0${j.mode}`,Q=L.get(ne)??{tool:K,toolSource:te,reasonKind:j.reasonKind,mode:j.mode,asked:0,approved:0,rejected:0,expired:0,decideSecTotal:0,remoteAnswers:0};L.set(ne,Q),Q.asked++;let ee=j.approvalId?R.get(j.approvalId):void 0;if(!ee){Q.expired++;continue}ee.action==="approve"||ee.action==="approve_always"?Q.approved++:ee.action==="reject"&&Q.rejected++;let ge=Math.round((ee.at-j.at)/1e3);Number.isFinite(ge)&&ge>0&&(Q.decideSecTotal+=ge),ee.via&&ee.via!=="local"&&Q.remoteAnswers++}for(let j of L.values()){let X=Yt({event:"approval",ts:C,sessionId:n,props:j});X&&(X.props.tool||j.tool===void 0)&&h.push(X)}}return{events:h,cursor:m}}catch{return{events:[],cursor:e}}finally{try{s?.close()}catch{}}}async function Lg(t,e,n){let r=Sn(t,"tangu","state.db"),o=await pu(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(oi),c=s.prepare(`SELECT DISTINCT day FROM telemetry_ledger
277
+ ORDER BY e.seq LIMIT 1`),f=w=>typeof w=="number"&&Number.isFinite(w)&&w>0?w:0,h=w=>typeof w=="string"&&w?w:void 0,p=[],m=e;for(let w of a){m={at:String(w.updated_at),id:String(w.id)};let y={llmCalls:0,tokensIn:0,tokensOut:0,tokensCached:0,retries:0},S=new Map,g=new Map,P=[],x=new Map;for(let j of c.all(w.id,Hg))if(j.type==="usage")y.llmCalls++,y.tokensIn+=f(j.prompt),y.tokensOut+=f(j.completion),y.tokensCached+=f(j.cached);else if(j.type==="tool_call"||j.type==="tool_result"){if(typeof j.id=="string"&&j.source!=null&&g.set(j.id,j.source),j.type!=="tool_result"||typeof j.name!="string")continue;let B=j.source??(typeof j.id=="string"?g.get(j.id):void 0),ie=ao(j.name,B),se=oo(B),X=`${ie}\0${se}`,ee=S.get(X)??{tool:ie,toolSource:se,calls:0,failures:0,totalMs:0,maxMs:0};S.set(X,ee),ee.calls++,j.failed&&ee.failures++,ee.totalMs+=f(j.ms),ee.maxMs=Math.max(ee.maxMs,f(j.ms))}else if(j.type==="approval_request")P.push({approvalId:h(j.approvalId),name:h(j.name),toolCallId:h(j.toolCallId),reasonKind:qg.has(j.reasonKind)?j.reasonKind:"other",mode:Wg.has(j.reasonMode)?j.reasonMode:"other",at:En(j.at)});else if(j.type==="approval_result"){let B=h(j.approvalId);B&&!x.has(B)&&x.set(B,{action:h(j.action),via:h(j.via),at:En(j.at)})}else j.phase==="llm_retry"&&y.retries++;let D=u.all(w.id)[0],k=uu(w.status),A=En(w.updated_at)-En(w.created_at),E=new Date(Number.isNaN(En(w.updated_at))?Date.now():En(w.updated_at)).toISOString(),M=Zt({event:"agent_run",ts:E,sessionId:n,props:{modelId:du(w.model_id),providerKind:so(w.model_id),mode:fu(w.kind),steps:f(w.current_step),...y,durationMs:Number.isFinite(A)&&A>=0?A:void 0,outcome:k,errorClass:k==="done"?void 0:lu(w.error,w.status),...D?{agentRole:D.agentRole,recallEntries:D.recallEntries,recallHistory:D.recallHistory,recallTruncated:D.recallTruncated===1?!0:D.recallTruncated===0?!1:void 0,...D.sectionsType==="array"?{memoryTokens:D.memoryTokens,humanTokens:D.humanTokens,profileTokens:D.profileTokens,projectTokens:D.projectTokens}:{}}:{}}});M&&p.push(M);for(let j of S.values()){let B=Zt({event:"tool_call",ts:E,sessionId:n,props:{...j,runOutcome:k}});B&&B.props.tool&&p.push(B)}let W=new Map;for(let j of P){if(!j.name)continue;let B=j.toolCallId?g.get(j.toolCallId):void 0,ie=B==null?j.name.startsWith("mcp__")?"mcp":void 0:ao(j.name,B),se=oo(B),X=`${ie??""}\0${se}\0${j.reasonKind}\0${j.mode}`,ee=W.get(X)??{tool:ie,toolSource:se,reasonKind:j.reasonKind,mode:j.mode,asked:0,approved:0,rejected:0,expired:0,decideSecTotal:0,remoteAnswers:0};W.set(X,ee),ee.asked++;let ne=j.approvalId?x.get(j.approvalId):void 0;if(!ne){ee.expired++;continue}ne.action==="approve"||ne.action==="approve_always"?ee.approved++:ne.action==="reject"&&ee.rejected++;let fe=Math.round((ne.at-j.at)/1e3);Number.isFinite(fe)&&fe>0&&(ee.decideSecTotal+=fe),ne.via&&ne.via!=="local"&&ee.remoteAnswers++}for(let j of W.values()){let B=Zt({event:"approval",ts:E,sessionId:n,props:j});B&&(B.props.tool||j.tool===void 0)&&p.push(B)}}return{events:p,cursor:m}}catch{return{events:[],cursor:e}}finally{try{s?.close()}catch{}}}async function Yg(t,e,n){let r=_n(t,"tangu","state.db"),i=await Su(r).then(o=>o.isFile(),o=>o?.code==="ENOENT"||o?.code==="ENOTDIR"?!1:null);if(i===null)return null;if(!i)return{days:[],complete:!0};let s;try{let{DatabaseSync:o}=await import("node:sqlite");if(s=new o(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(fo),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,ri+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,ri)){if(!Yn(d))continue;let g=new Map;for(let m of l.all(d,Pg)){if(typeof m.event!="string"||!Object.hasOwn(oi,m.event))continue;let y=oi[m.event],p=typeof m.dim=="string"?m.dim:"";if((y?!p:p!=="")||typeof m.field!="string"||typeof m.n!="number")continue;let S=`${m.event}\0${p}`,k=g.get(S)??{event:m.event,dimKey:y,dim:p,fields:new Map};g.set(S,k),k.fields.set(m.field,(k.fields.get(m.field)??0)+m.n)}let h=[];for(let m of g.values()){let y=Yt({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<=ri}}catch{return null}finally{try{s?.close()}catch{}}}var Ug=(t,e,n)=>Yt({event:"sync_health",ts:`${t}T23:59:59.000Z`,props:{...n,system:e,day:t}}),Hg=t=>["darwin","win32","linux"].includes(t)?t:"other",zg=t=>["arm64","x64","ia32"].includes(t)?t:"other",Bg=()=>/^zh\b/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en";function gu(t,e={}){let n=e.now??(()=>new Date),r=e.fetch??fetch,o=()=>t.homeDir(),s=()=>Sn(o(),"extend-telemetry.json"),i=()=>Sn(o(),"telemetry"),a=()=>Sn(i(),"queue.jsonl"),c=()=>Sn(i(),"sent.jsonl"),l=t.telemetry,u=()=>ln(n().getTime()-fu);Gc(()=>n().getTime());let d=()=>g()??{},g=()=>{let z;try{z=au(s(),"utf8")}catch(G){return G?.code==="ENOENT"?{}:null}try{let G=JSON.parse(z);return G&&typeof G=="object"&&!Array.isArray(G)?G:null}catch{return null}},h=(z,G=d())=>{let _={...G,...z};ti(o(),{recursive:!0});let x=`${s()}.${process.pid}.tmp`;return lu(x,JSON.stringify(_,null,2),{encoding:"utf8",mode:384}),cu(x,s()),_},m=()=>d().installId??h({installId:iu()}).installId,y=()=>{try{return!!t.readCreds().token}catch{return!1}},p=(z=d())=>z.enabled!==!1&&z.noticeSeen===!0&&l?.packaged===!0&&y(),S=z=>{try{return au(z,"utf8").split(`
280
- `).filter(Boolean)}catch{return[]}},k=()=>S(a()).flatMap(z=>{try{return[JSON.parse(z)]}catch{return[]}}),P=(z,G)=>{if(ti(i(),{recursive:!0}),!G.length){ni(z,{force:!0});return}let _=`${z}.${process.pid}.tmp`;lu(_,G.map(x=>JSON.stringify(x)).join(`
279
+ ORDER BY day LIMIT ?`).all(e,n,...a,uo+1),l=s.prepare("SELECT event, dim, field, n FROM telemetry_ledger WHERE day = ? ORDER BY event, dim, field LIMIT ?"),u=[];for(let{day:f}of c.slice(0,uo)){if(!er(f))continue;let h=new Map;for(let m of l.all(f,zg)){if(typeof m.event!="string"||!Object.hasOwn(fo,m.event))continue;let w=fo[m.event],y=typeof m.dim=="string"?m.dim:"";if((w?!y:y!=="")||typeof m.field!="string"||typeof m.n!="number")continue;let S=`${m.event}\0${y}`,g=h.get(S)??{event:m.event,dimKey:w,dim:y,fields:new Map};h.set(S,g),g.fields.set(m.field,(g.fields.get(m.field)??0)+m.n)}let p=[];for(let m of h.values()){let w=Zt({event:m.event,ts:`${f}T23:59:59.000Z`,props:{...Object.fromEntries(m.fields),day:f,...m.dimKey?{[m.dimKey]:m.dim}:{}}});!w||w.props.day!==f||m.dimKey&&w.props[m.dimKey]===void 0||Object.keys(w.props).some(y=>y!=="day"&&y!==m.dimKey)&&p.push(w)}u.push({day:f,events:p})}return{days:u,complete:c.length<=uo}}catch{return null}finally{try{s?.close()}catch{}}}var Gg=(t,e,n)=>Zt({event:"sync_health",ts:`${t}T23:59:59.000Z`,props:{...n,system:e,day:t}}),Jg=t=>["darwin","win32","linux"].includes(t)?t:"other",Kg=t=>["arm64","x64","ia32"].includes(t)?t:"other",Xg=()=>/^zh\b/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en";function ku(t,e={}){let n=e.now??(()=>new Date),r=e.fetch??fetch,i=()=>t.homeDir(),s=()=>_n(i(),"extend-telemetry.json"),o=()=>_n(i(),"telemetry"),a=()=>_n(o(),"queue.jsonl"),c=()=>_n(o(),"sent.jsonl"),l=t.telemetry,u=()=>pn(n().getTime()-bu);tl(()=>n().getTime());let f=()=>h()??{},h=()=>{let q;try{q=hu(s(),"utf8")}catch(J){return J?.code==="ENOENT"?{}:null}try{let J=JSON.parse(q);return J&&typeof J=="object"&&!Array.isArray(J)?J:null}catch{return null}},p=(q,J=f())=>{let C={...J,...q};co(i(),{recursive:!0});let I=`${s()}.${process.pid}.tmp`;return mu(I,JSON.stringify(C,null,2),{encoding:"utf8",mode:384}),gu(I,s()),C},m=()=>f().installId??p({installId:pu()}).installId,w=()=>{try{return!!t.readCreds().token}catch{return!1}},y=(q=f())=>q.enabled!==!1&&q.noticeSeen===!0&&l?.packaged===!0&&w(),S=q=>{try{return hu(q,"utf8").split(`
280
+ `).filter(Boolean)}catch{return[]}},g=()=>S(a()).flatMap(q=>{try{return[JSON.parse(q)]}catch{return[]}}),P=(q,J)=>{if(co(o(),{recursive:!0}),!J.length){lo(q,{force:!0});return}let C=`${q}.${process.pid}.tmp`;mu(C,J.map(I=>JSON.stringify(I)).join(`
281
281
  `)+`
282
- `,{encoding:"utf8",mode:384}),cu(_,z)},R=0,O=()=>{R++,ni(a(),{force:!0}),ni(c(),{force:!0}),Yc()},w=()=>{let z=n().getTime(),G=S(c()).flatMap(x=>{try{return[JSON.parse(x)]}catch{return[]}}),_=G.filter(x=>z-x.at<Dg);return _.length!==G.length&&P(c(),_),_},A=0,C=!1,D=0,L=()=>{let z=g();if(!z)return Is(!1),!1;let G=p(z);return G&&z.closed?h({closed:void 0,cursor:si(n().getTime()),ledgerCursor:u()},z):G&&!Yn(z.ledgerCursor)?h({ledgerCursor:u()},z):!G&&!z.closed&&(A++,h({closed:!0},z)),Is(G),G},j=()=>{let z=g();if(!z){t.log("[forsion-extend] telemetry state unreadable; skipping the signed-in migration");return}if(z.signedInGate)return;let G={signedInGate:1};!y()&&z.enabled===void 0&&z.noticeSeen===!0&&(G.enabled=!1,G.syncHealth=void 0,A++,O(),t.log("[forsion-extend] telemetry turned off: not signed in (sending now needs a Forsion account)")),h(G,z)},X=z=>{if(!(!z.length||!p())){ti(i(),{recursive:!0}),Eg(a(),z.map(G=>JSON.stringify(G)).join(`
282
+ `,{encoding:"utf8",mode:384}),gu(C,q)},x=0,D=()=>{x++,lo(a(),{force:!0}),lo(c(),{force:!0}),el()},k=()=>{let q=n().getTime(),J=S(c()).flatMap(I=>{try{return[JSON.parse(I)]}catch{return[]}}),C=J.filter(I=>q-I.at<Lg);return C.length!==J.length&&P(c(),C),C},A=0,E=!1,M=0,W=()=>{let q=h();if(!q)return Ns(!1),!1;let J=y(q);return J&&q.closed?p({closed:void 0,cursor:po(n().getTime()),ledgerCursor:u()},q):J&&!er(q.ledgerCursor)?p({ledgerCursor:u()},q):!J&&!q.closed&&(A++,p({closed:!0},q)),Ns(J),J},j=()=>{let q=h();if(!q){t.log("[forsion-extend] telemetry state unreadable; skipping the signed-in migration");return}if(q.signedInGate)return;let J={signedInGate:1};!w()&&q.enabled===void 0&&q.noticeSeen===!0&&(J.enabled=!1,J.syncHealth=void 0,A++,D(),t.log("[forsion-extend] telemetry turned off: not signed in (sending now needs a Forsion account)")),p(J,q)},B=q=>{if(!(!q.length||!y())){co(o(),{recursive:!0}),Dg(a(),q.map(J=>JSON.stringify(J)).join(`
283
283
  `)+`
284
- `,{encoding:"utf8",mode:384});try{if(Cg(a()).size>uu){let G=k(),_=G.length,x=0;for(;_>0&&x+Buffer.byteLength(JSON.stringify(G[_-1]))+1<=uu/2;)x+=Buffer.byteLength(JSON.stringify(G[--_]))+1;P(a(),G.slice(_))}}catch{}k().length>=Rg&&Q()}},K=()=>{let z=d();return{available:!!l,enabled:z.enabled!==!1,noticeSeen:z.noticeSeen===!0,signedIn:y(),active:p(z),packaged:l?.packaged===!0,installId:m(),queued:_g(a())?k().length:0,lastSentAt:z.lastSentAt??null,lastError:z.lastError??null}},te=()=>tu({app:"desktop",appVersion:t.appVersion(),coreVersion:l?.coreVersion()??void 0,channel:l?.channel(),os:Hg(process.platform),osVersion:xg(),arch:zg(process.arch),locale:Bg()}),ne=null,Q=()=>{if(ne)return ne;if(C||n().getTime()<D)return Promise.resolve();let z=A,G=R,_=(async()=>{try{for(let x=0;x<5;x++){let T=k();if(!T.length)return;let I=m(),M={v:Zl,installId:I,...te()},H=[],W=Buffer.byteLength(JSON.stringify({...M,events:[]}));for(let re of T){let de=Buffer.byteLength(JSON.stringify(re))+1;if(H.length>=Xs.maxEvents||W+de>Xs.maxBatchBytes)break;H.push(re),W+=de}if(!H.length){P(a(),T.slice(1));continue}let{base:B}=await t.getCloud(),q={...M,events:H};if(!L()||z!==A)return;let J=await r(`${B.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(q),signal:AbortSignal.timeout(du)}).catch(re=>({ok:!1,status:0,error:String(re?.message||re)})),Z=J.status;if(Z>=200&&Z<300||Z===400||Z===413){let re=new Set(H.map(de=>JSON.stringify(de)));P(a(),k().filter(de=>!re.has(JSON.stringify(de))))}if(Z>=200&&Z<300){let re=n().getTime();G===R&&P(c(),[...w(),{at:re,body:q}]),h({lastSentAt:re,lastError:void 0});continue}if(Z!==400&&Z!==413){let re=Number(J.headers?.get?.("retry-after"));D=n().getTime()+(Number.isFinite(re)&&re>0?Math.min(re,3600)*1e3:5*6e4)}h({lastError:Z?`HTTP ${Z}`:String(J.error??"network error").slice(0,200)});return}}catch(x){try{h({lastError:String(x?.message||x).slice(0,200)})}catch{}}})();return ne=_,_.finally(()=>{ne===_&&(ne=null)}),_},ee=async()=>{try{if(w(),!L())return;let z=d(),G=A,_=z.cursor??si(n().getTime()),x=await Fg(o(),_,l?.sessionId,hu(n().getTime()));if(!L()||G!==A)return;X(x.events),x.cursor!==_&&h({cursor:x.cursor}),await ge(G),await Q()}catch(z){t.log(`[forsion-extend] telemetry tick failed: ${String(z?.message||z)}`)}},ge=async z=>{let G=n().getTime(),_=ln(G),x=ln(G-fu),T=d().ledgerCursor;if(Yn(T)||(T=x,h({ledgerCursor:T})),Rs(T),T>=x){ue();return}let I=await Lg(o(),T,_);if(!(!L()||z!==A)){if(I){let M=I.complete?x:I.days[I.days.length-1]?.day??T;if(M>T){let H=Vc(T,M),W=[...new Set([...I.days.map(q=>q.day),...H.map(q=>q.day)])].filter(q=>q>T&&q<=M).sort(),B=[];for(let q of W){B.push(...I.days.find(J=>J.day===q)?.events??[]);for(let J of H)if(J.day===q){let Z=Ug(q,J.system,J.counts);Z&&B.push(Z)}}X(B),h({ledgerCursor:M}),Rs(M)}}ue()}},ue=()=>{if(!qc())return;let z=g();if(!z)return;let G=Bc();h({syncHealth:Object.keys(G).length?G:void 0},z),Wc()},Ee=l?.subscribe(z=>{try{if(!$g.has(z?.event)||!L())return;let G=Yt({...z,sessionId:l.sessionId},Ag());G&&X([G])}catch(G){t.log(`[forsion-extend] telemetry event dropped: ${String(G?.message||G)}`)}}),he={ok:!1,error:"untrusted"};t.handle("telemetry:get",z=>t.isTrustedSender(z)?(L(),K()):he),t.handle("telemetry:set",(z,G)=>{if(!t.isTrustedSender(z))return he;let _=d(),x={};typeof G?.enabled=="boolean"&&(x.enabled=G.enabled),G?.noticeSeen===!0&&(x.noticeSeen=!0);let T={..._,...x};return!p(_)&&p(T)&&(x.cursor=si(n().getTime()),x.ledgerCursor=u()),p(_)&&!p(T)&&A++,x.enabled===!1&&(x.syncHealth=void 0),h(x),x.enabled===!1&&O(),L(),K()}),t.handle("telemetry:sent",z=>t.isTrustedSender(z)?{batches:w()}:he),t.handle("telemetry:delete",async z=>{if(!t.isTrustedSender(z))return he;C=!0,A++;try{await ne?.catch(()=>{});let G=m(),{base:_}=await t.getCloud(),T=(await r(`${_.replace(/\/+$/,"")}/api/telemetry/install/${G}`,{method:"DELETE",signal:AbortSignal.timeout(du)}).catch(I=>({ok:!1,status:0,error:String(I?.message||I)}))).status;return T>=200&&T<300?(O(),h({installId:iu(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),K()):{ok:!1,error:T?`HTTP ${T}`:"network error"}}finally{C=!1}});try{zc(d().syncHealth),j(),L()}catch(z){t.log(`[forsion-extend] telemetry startup check failed: ${String(z?.message||z)}`)}let nt=t.addFlushHook?.(z=>{if(z!=="blur")try{ue()}catch{}}),rt=setTimeout(()=>void ee(),Ig),ye=setInterval(()=>void ee(),Tg);return rt.unref?.(),ye.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(rt),clearInterval(ye),Ee?.(),nt?.()},{tick:ee,flush:Q})}import{readFileSync as _n,lstatSync as ym,statSync as wm,renameSync as bm,linkSync as Sm,unlinkSync as mi,readdirSync as vm,rmdirSync as km,writeFileSync as Em,mkdirSync as _m,copyFileSync as Cm,constants as Am}from"node:fs";import{readFile as cr,writeFile as lr,mkdir as yi,rename as Co,readdir as ur,lstat as Tt,stat as wi,unlink as dr}from"node:fs/promises";import{join as De,dirname as Kt,relative as fr,sep as Cn}from"node:path";import{hostname as bi}from"node:os";import{randomUUID as tt}from"node:crypto";import{isUtf8 as Si}from"node:buffer";import{Readable as ju}from"node:stream";import{performance as vi}from"node:perf_hooks";import{setImmediate as xm}from"node:timers/promises";var qg=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],Wg=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],ir=".memory-tombstones.json",yu=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),mu=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),Vg=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,Yg=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function Gg(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===ir)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:qg.includes(t)||yu(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&Vg(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var Jg=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),Kg=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,Xg=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function po(t){let e=t.slice(t.lastIndexOf("/")+1);return Kg.test(e)||Xg.test(e)}function wu(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 ii(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(po(t))return!1;if(n){let l=t.slice(6);return e==="folder"?mu(l):Wg.includes(l)||yu(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(!Yg(i)||Jg(i))return!1;if(e==="file")return Gg(a);if(a===""||a==="LOG"||mu(a))return!0;let c=a.split("/");return c[0]==="Library"&&c.every(l=>l&&!l.startsWith(".")&&!l.endsWith(".")&&!l.endsWith(" "))}import{isAbsolute as Zg}from"node:path";var et=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),bt=t=>typeof t=="string",ci=t=>bt(t)&&t.length>0,Nt=t=>typeof t=="boolean",Gt=t=>typeof t=="number"&&Number.isFinite(t),vn=t=>Gt(t)&&Number.isSafeInteger(t)&&t>=0,bu=t=>Gt(t)&&Number.isInteger(t)&&t>=0,Su=t=>vn(t)&&t>0,kn=t=>bt(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),yo=t=>bt(t)&&/^[a-f0-9]{64}$/.test(t),vu=t=>bt(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),go=(t,e)=>bt(t)&&e.includes(t),ke=(t,e)=>t===void 0||e(t),ku=(t,e,n)=>e.every(r=>ke(t[r],n)),Eu=t=>bt(t)&&!t.includes("\0")&&Zg(t);function jt(t,e=!1){try{return Pt(t,e),!0}catch{return!1}}var _u=t=>jt(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,Cu=t=>t===""||kn(t);function mo(t,e){let n=t.indexOf(":");return n>0&&kn(e)&&t.slice(n+1)===e&&vu(t.slice(0,n))}function Qg(t,e){return et(e)&&mo(t,e.id)&&jt(e.path)&&ci(e.version)&&yo(e.hash)&&ku(e,["base","inode","stat"],bt)&&ke(e.statAt,Gt)&&ke(e.memoryDeleted,Nt)}function em(t,e){return et(e)&&mo(t,e.localId)&&kn(e.id)&&jt(e.path)&&Su(e.revision)&&Cu(e.parentId)&&_u(e.name)}function tm(t){return et(t)&&kn(t.id)&&jt(t.path)&&vu(t.target)&&go(t.direction,["upload","download","merge","rename","delete"])&&go(t.state,["queued","active","done","failed","paused","conflict"])&&vn(t.done)&&(t.size===null||vn(t.size))&&Gt(t.at)&&ke(t.error,bt)&&ke(t.finishedAt,Gt)}function nm(t){return et(t)&&jt(t.path)&&yo(t.hash)&&bt(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&ke(t.parentId,kn)&&ke(t.stageRoot,Eu)&&ke(t.stageIdentity,Bt)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&bu(t.stageDev)&&bu(t.stageIno))}function rm(t){return et(t)&&jt(t.prefix,!0)&&Eu(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Bt(t))}function om(t){return et(t)&&go(t.state,["running","done"])&&Nt(t.seen)&&ku(t,["name","folderId","shelfId","shelfName"],bt)&&ke(t.files,vn)&&ke(t.at,Gt)&&ke(t.rewritten,Nt)}var ho=(t,e)=>et(t)&&Object.entries(t).every(([n,r])=>e(n,r)),ai=(t,e)=>Array.isArray(t)&&t.every(e);function Au(t){if(!et(t)||!et(t.config)||!vn(t.config.revision)||!Nt(t.owned)||!Nt(t.paused)||!ho(t.files,Qg)||!ho(t.folders,em)||!ai(t.jobs,tm)||!ke(t.accountReview,Nt)||!ke(t.agentArchive,om)||!ke(t.roots,e=>ai(e,rm))||!ke(t.trash,e=>ai(e,nm))||!ke(t.unconfirmed,e=>ho(e,(n,r)=>mo(n,n.slice(-36))&&yo(r)))||!ke(t.pendingUploads,e=>ho(e,(n,r)=>et(r)&&mo(n,r.id)&&jt(r.path))))throw Error("Invalid content sync state; original data was retained");$t(t.config,t.config.revision)}function xu(t){return et(t)&&kn(t.id)&&Cu(t.parentId)&&_u(t.name)&&jt(t.path)&&go(t.kind,["file","folder"])&&Su(t.revision)&&Nt(t.deleted)&&ke(t.busy,Nt)&&ke(t.version,ci)&&ke(t.hash,yo)&&ke(t.size,vn)&&ke(t.mtime,Gt)&&t.version===void 0==(t.hash===void 0)}function Tu(t){return xu(t)&&t.deleted===!0}function wo(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!et(t)||t.schemaVersion!==1||t.namespace!==e||!ci(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,o=new Set;for(let s of t.nodes){if(!xu(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 Iu,lstatSync as Jt,readdirSync as sm,readFileSync as im,renameSync as bo,unlinkSync as am,linkSync as cm,mkdirSync as vo,realpathSync as li,rmdirSync as lm}from"node:fs";import{open as Ru,lstat as ui,readdir as um,realpath as Du,readFile as di,writeFile as dm,mkdir as Ou,unlink as fm}from"node:fs/promises";import{join as Ft,dirname as So,relative as fi,sep as ko}from"node:path";import{randomUUID as Mu,createHash as pm}from"node:crypto";var ar=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,Eo=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),Pu=".forsion-sync-id.json",hm=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),gm=t=>!hm.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),Ae=t=>pm("sha256").update(t).digest("hex");function $u(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 Pt(e,!0);$u(e);let r=await Du(t),o=Ft(r,...e.split("/").filter(Boolean)),s=fi(r,o);if(s===".."||s.startsWith(".."+ko))throw Error("Content path escapes root");let i=r;for(let a of s.split(ko).filter(Boolean)){i=Ft(i,a);try{if((await ui(i)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(c){if(c.code!=="ENOENT")throw c}}return o}function ct(t,e,n=!1){if(n||Pt(e,!0),$u(e),e.split("/").some(s=>s===".."||s===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let o=li(t);for(let s of e.split("/").filter(Boolean)){o=Ft(o,s);try{if(Jt(o).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(i){if(i.code!=="ENOENT")throw i}}return o}async function _o(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 Du(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 ui(s)).isDirectory())throw Error(`Sync root is not a directory: ${o.prefix||"Forsion"}`);let i=async(a,c)=>{let l=await ui(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){Pt(c);let u;if(l.isDirectory())try{let d=JSON.parse(await di(Ft(a,Pu),"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,...Eo(l),size:l.isFile()?l.size:0})}if(l.isDirectory())for(let u of await um(a,{withFileTypes:!0}))!gm(u.name)||!u.isDirectory()&&!u.isFile()||await i(Ft(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 pi(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await Je(t.root,fi(t.root,Ft(t.physical,Pu)).split(ko).join("/"),!0),n=Mu();try{let r=await Ru(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 di(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 En(t){let e=await Je(t.root,fi(t.root,t.physical).split(ko).join("/")),n=await Ru(e,Iu.O_RDONLY|(Iu.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 Ue(t,e){Pt(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 hi(t,e,n,r,o=async(s,i)=>i()){let s=Ue(t,e);await Ou(s.root,{recursive:!0});let i=await Je(s.root,s.relative),a=await di(i).catch(l=>{if(l.code==="ENOENT")return null;throw l});if((a?Ae(a):null)!==r)throw Error("Local file changed during download");let c=Ft(s.root,`.forsion-sync-${Mu()}.tmp`);try{await dm(c,n,{flag:"wx",mode:384}),await Je(s.root,s.relative),await o(i,()=>{ct(s.root,s.relative),vo(So(i),{recursive:!0}),ct(s.root,s.relative);let l=null;try{l=im(i)}catch(u){if(u.code!=="ENOENT")throw u}if((l?Ae(l):null)!==r)throw Error("Local file changed during download");bo(c,i)})}finally{await fm(c).catch(()=>{})}}async function Nu(t,e,n=async(r,o)=>o()){let r=Ue(t,e);await Ou(r.root,{recursive:!0});let o=await Je(r.root,r.relative);await n([o],()=>{ct(r.root,r.relative),vo(o,{recursive:!0})})}async function gi(t,e,n,r=async(o,s)=>s()){let o=Ue(t,e),s=Ue(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(ct(o.root,o.relative),ct(s.root,s.relative),mm(a)){let l=Jt(i),u=Jt(a),d=li(So(i));if((l.dev===u.dev&&l.ino===u.ino&&d===li(So(a))?sm(d).filter(m=>{let y=Jt(Ft(d,m));return y.dev===l.dev&&y.ino===l.ino}):[]).length!==1)throw Error("Local rename destination exists");bo(i,a);return}vo(So(a),{recursive:!0});let c=Jt(i);if(c.isDirectory()){if(process.platform==="win32"){bo(i,a);return}vo(a,{mode:448});try{bo(i,a)}catch(l){try{lm(a)}catch{}throw l}}else{cm(i,a);let l=Jt(i);if(l.ino!==c.ino||l.dev!==c.dev)throw Error("Source changed during rename");am(i)}})}function mm(t){try{return Jt(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Fu=(t,e)=>t.length===e.length&&t.every(n=>e.some(r=>n.prefix===r.prefix&&n.root===r.root&&(n.dev===void 0||rn(n,r)))),Tm=()=>({config:structuredClone(ll),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),An=50*1024*1024,Im=10*6e4,Lu=1024*1024,Me=(t,e)=>`${t}:${e}`,It=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",Xt=t=>t.slice(t.lastIndexOf("/")+1),pr=Ae(""),ki=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),Lt=t=>t.split("/").length,Pe=t=>t instanceof Error?t.message:String(t),Rm={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},Ei=t=>t.file.replace(/\.json$/,".bases"),Bu=5e3,Dm=3e4,Uu=3e4,Om=3e3,Ao=10*6e4,Mm=60*6e4,Pm=10*6e4,$m=3*6e4,Hu=2e3,Nm=1440*6e4,_i=t=>/^(agents|human)\//.test(t)?Dm:Bu,jm=t=>Math.max(t.mtime,t.ctime);async function*Ut(t){let e=vi.now()+8;for(let n of t)vi.now()>=e&&(await xm(),e=vi.now()+8),yield n}function qu(t){if(!t.contentSync)return;let e=new Ci(t);for(let[n,r]of Object.entries({[gt.get]:(o,s)=>e.snapshot(o,s),[gt.preview]:o=>e.preview(o),[gt.apply]:(o,s)=>e.apply(typeof o=="string"?o:"",s),[gt.run]:()=>{e.touch(),e.kick()},[gt.pause]:o=>e.pause(o===!0),[gt.retry]:()=>{e.touch(),e.kick()},[gt.rename]:o=>e.rename(o),[gt.setup]:o=>e.setup(o),[gt.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:Pe(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)),vl(()=>e.stats()),e.start()}var Ci=class{session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;activeAt=Date.now();lastRunAt=0;focused=!1;devices=[];others;deviceId="";customName="";serial=Promise.resolve();scheduled=null;tick=null;first=null;blocked=new Map;phase="idle";lastError;get error(){return this.lastError}set error(e){this.lastError=e,e&&this.fault(e)}runLog=new tr;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=Vr((e,n,r)=>at("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=nc(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{this.idleSkip()||this.run()},3e4)).unref?.(),(this.first=setTimeout(()=>{this.run()},5e3)).unref?.()}locale(){if(this.uiLocale)return this.uiLocale;try{return/^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en"}catch{return"zh"}}archiveStep(e){if(e.stored.accountReview||e.stored.agentArchive?.state==="done"||this.archiveRetry.account===e.account&&Date.now()<this.archiveRetry.at)return Promise.resolve();let n=()=>{this.archiveRetry={account:e.account,at:Date.now()+Ao}};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(Pe(r)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${Pe(r)}`)}finally{this.archiving=null}})()}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=yl(n);if(!r)return;e.stored.config=$t(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=Ln(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(ps(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 yi(Kt(e.file),{recursive:!0,mode:448});let o=e.file+".tmp-"+tt();try{await lr(o,r,{mode:384,flag:"wx"}),this.guard(e,!1),await Co(o,e.file),e.persisted=r}finally{await dr(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 ps(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=De(this.host.homeDir(),"content-sync"),o=De(r,Ae(e)+".json"),s=Tm();try{let d=JSON.parse(await cr(o,"utf8"));Au(d),s={...s,...d,config:$t(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=De(this.host.homeDir(),"content-sync-device.json"),c=async()=>{let d=JSON.parse(await cr(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 yi(Kt(a),{recursive:!0});try{await lr(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,tombstones: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=Pe(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=Kt(e.file),r=ds(this.host.homeDir()),o=Ae(e.account),s=Ln(r),i=!s?.account&&(await ur(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=Ln(r);if(c?.account!==s?.account||c?.epoch!==s?.epoch||c?.pending!==s?.pending)throw Error("account_changed");fs(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 wi(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!s.isDirectory()||!ft(r,s))throw Error("Sync root changed; preview before rebinding");return r}let o=await $n(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&&!rn(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)&&Ue(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),_o(n)}async write(e,n,r,o){this.guard(e),await hi(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 wi(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=wm(i)}catch{throw Error("Sync root unavailable: "+i)}if(!c.isDirectory()||!ft(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 Tt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return _o(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Wo(e.roots.map(n=>n.root),{ignoreInitial:!0,ignored:n=>{let r=n.split(/[\\/]/).at(-1)??"";return r.startsWith(".")&&r!==".memory-tombstones.json"||r==="node_modules"||r==="__pycache__"}}),this.watcher.on("all",(n,r)=>{let o=this.logical(e,r),s=Date.now();if(this.activeAt=s,o){let i=this.dirty.get(o);i?i.last=s:this.dirty.set(o,{first:s,last:s})}this.schedule(o?void 0:s+Bu)}))}logical(e,n){let r=null;for(let i of e.roots)(n===i.root||n.startsWith(i.root+Cn))&&(!r||i.root.length>r.root.length)&&(r=i);if(!r)return null;let o=fr(r.root,n).split(Cn).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+_i(e),n.first+Uu)}schedule(e){let n=e??1/0;for(let[r,o]of this.dirty)n=Math.min(n,this.dueAt(r,o));this.due&&clearTimeout(this.due),this.due=null,!(n===1/0||this.closed)&&(this.due=setTimeout(()=>{this.due=null;let r=this.session;r?.stored.config.enabled&&!r.stored.paused&&this.kick()},Math.max(0,n-Date.now())+50),this.due.unref?.())}kick(){if(this.running){this.again=!0;return}this.run()}touch(){this.activeAt=Date.now()}idleSkip(e=Date.now()){return e-this.activeAt>=Pm&&e-this.lastRunAt<$m-5e3}flush(e){let n=this.session;if(!(this.closed||!this.host.accountId()||n&&(!n.stored.config.enabled||n.stored.paused)))return this.flushRequest++,this.flushThrough=Math.max(this.flushThrough,Date.now()),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=ju.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));wo(i,s),await this.knownTombstones(e,s,i),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&&Qn.test(i))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),o=r&&Date.now()-r.at<Mm?r:void 0,s=await this.request(e,n,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...o?{"If-None-Match":o.etag}:{}});if(s.status===304)return await s.body?.cancel(),o?o.text:(e.manifests.delete(n),this.manifestText(e,n));let i=await s.text();this.guard(e),wo(JSON.parse(i),n);let a=s.headers.get("etag");return r?.text!==i&&this.touch(),a?e.manifests.set(n,{etag:a,text:i,at:Date.now()}):e.manifests.delete(n),i}async knownTombstones(e,n,r){if(typeof r.tombstonesSince!="string")return;let o=new Set(r.nodes.map(l=>l.id)),s=new Set;for(let[l,u]of Object.entries(e.stored.files))l.startsWith(n+":")&&s.add(u.id);for(let[l,u]of Object.entries(e.stored.folders))l.startsWith(n+":")&&s.add(u.id);for(let[l,u]of Object.entries(e.stored.pendingUploads??{}))l.startsWith(n+":")&&s.add(u.id);let i=e.tombstones.get(n);i||e.tombstones.set(n,i=new Map);for(let l of[...i.keys()])o.has(l)&&i.delete(l);let a=Date.now(),c=[...s].filter(l=>{if(o.has(l))return!1;let u=i.get(l);return!u||!u.node&&a-u.at>=Nm});for(let l=0;l<c.length;l+=Hu){let u=c.slice(l,l+Hu),d=new Set(u),g=await this.json(e,n,"/tombstones","POST",{ids:u}),h=new Map((Array.isArray(g?.nodes)?g.nodes:[]).filter(m=>Tu(m)&&d.has(m.id)).map(m=>[m.id,m]));for(let m of u)i.set(m,{node:h.get(m)??null,at:a})}for(let l of s)if(!o.has(l)){let u=i.get(l)?.node;u&&r.nodes.push(structuredClone(u))}}route(e,n,r="file"){if(po(e)||ii(e,r)===!1)return null;let o=pn(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||ao(bi())}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"){ul.some(i=>s.path.startsWith(i+"/"))||(r.files++,r.size+=s.size);for(let i=It(s.path);i;i=It(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])=>Lt(s)-Lt(i)||(s<i?-1:1)).slice(0,2e3).map(([s,i])=>({path:s,kind:"folder",size:i.size,files:i.files,...er(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,...dl((await En(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||ao(bi()),s=zs(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=De(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+tt();try{await lr(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await Co(r,n)}finally{await dr(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<Ao){r-this.devicesAt>=Ao&&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(Pe(a));try{await o(this.deviceName(),!0)}catch(a){if(!i(a))throw a;let c=!1;if(!this.customName){let l=ao(bi());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}`;zs(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=De(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let a=JSON.parse(await cr(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 lr(i,s,{mode:384,flag:"wx"}),await Co(i,e),this.cachedDevices=s}catch(a){this.error=Pe(a)}finally{await dr(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=gn(gl(n.stored.config),"","off");for(let a of At)a.id!=="agents"&&r[a.id]===!1&&(o=gn(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(ml(o,i))}async snapshot(e,n){(e==="zh"||e==="en")&&(this.uiLocale=e);let r=await this.getSession(),o=n&&typeof n=="object"?n:{};if(o.focused===!0){let s=!this.focused;this.focused=!0,this.touch(),s&&r.stored.config.enabled&&!r.stored.paused&&Date.now()-this.lastRunAt>3e4&&this.kick()}else o.focused===!1&&(this.focused=!1);return!r.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(r).then(s=>{this.session===r&&this.setSources(s)},()=>{})),o.devices===!0&&Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(r).catch(()=>{})),{available:!0,account:Ae(r.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(r.stored.config),running:this.running,paused:r.stored.paused,phase:this.phase,jobs:structuredClone(r.stored.jobs),devices:this.devices,sources:this.sources.map(s=>{let i=s.agent&&this.agentNames.get(s.path);return i?{...s,...i.name?{name:i.name}:{},...i.nameEn?{nameEn:i.nameEn}:{}}:s}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...r.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...r.stored.agentArchive?{agentArchive:(({rewritten:s,...i})=>i)(r.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 tr().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=$t(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(S=>S.kind==="file"&&S.path.startsWith("agents/")&&this.route(S.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 await(let S of Ut(i.filter(k=>k.kind==="file"))){let k=this.route(S.path,a);if(!k)continue;let P=c.get(k)?.nodes.find(O=>!O.deleted&&O.kind==="file"&&O.path===S.path);if(S.size>An){l++,g+=S.size;continue}let R=Ae(await En(S));this.guard(n),h.set(S.path,R),R!==P?.hash&&(l++,g+=S.size,P?.version&&d++)}let m=o.enabled?this.agentAsks(n,i,a,c,h):[];for(let[S,k]of c)for await(let P of Ut(k.nodes))!P.deleted&&P.kind==="file"&&P.version&&this.route(P.path,a)===S&&!i.some(R=>R.path===P.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 Ae(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=Fm(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 wi(p.root).catch(k=>{if(k.code==="ENOENT")return null;throw k})&&g.push({...p,...await $n(p.root)});let h=structuredClone(i.value.config);for(let p of h.rules){let S=u.find(k=>k.kind==="folder"&&k.path===p.source);S&&(p.sourceId=await pi(S))}let m=a.length?$t(a.reduce((p,S)=>gn(p,`agents/${S.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,S]of Object.entries(s.stored.files))(y.config.enabled!==s.stored.config.enabled||!Fu(y.roots??g,g)||this.route(S.path,y.config)!==this.route(S.path,s.stored.config))&&delete s.stored.files[p];for(let[p,S]of Object.entries(s.stored.folders))(y.config.enabled!==s.stored.config.enabled||!Fu(y.roots??g,g)||this.route(S.path,y.config,"folder")!==this.route(S.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,S=>this.host.contentSync.claim(y.owned,S)).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(Pe(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");this.activeAt=Date.now();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"?at("content","uploads"):o==="download"&&at("content","downloads");let l=Rm[o];return l&&this.tally(l),c}catch(c){throw a.state=e.stored.paused?"paused":"failed",a.error=Pe(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.lastRunAt=n,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=Pe(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("/"+ir),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,S]of u)for await(let k of Ut(S.nodes.filter(P=>P.kind==="file"&&!P.busy&&d(P.path)))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.route(k.path,l)!==p||c.some(P=>P.path===k.path))){if(this.isBlocked(p,k.path)){h.add(m(k.path)??"");continue}g.add(k.id);try{await this.missing(o,k,p,c,l)}catch(P){this.error=Pe(P),h.add(m(k.path)??"")}}}for await(let p of Ut(c.filter(S=>S.kind==="file").sort((S,k)=>+!d(S.path)-+!d(k.path)))){if(this.guard(o),o.stored.paused)throw Error("paused");let S=this.route(p.path,l);if(!(!S||y(p.path))){if(this.isBlocked(S,p.path)){d(p.path)&&h.add(m(p.path)??"");continue}try{await this.file(o,l,p,S,u.get(S))==="held"&&r.add(p.path)}catch(k){this.error=Pe(k),d(p.path)&&h.add(m(p.path)??"")}}}for(let[p,S]of u)for await(let k of Ut(S.nodes.filter(P=>P.kind==="file"&&!P.busy&&!g.has(P.id)))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.isBlocked(p,k.path)||this.route(k.path,l)!==p||c.some(P=>P.path===k.path)||y(k.path))){if(this.holdGone(k.path)){r.add(k.path);continue}try{await this.missing(o,k,p,c,l)}catch(P){this.error=Pe(P)}}}await this.cleanupFolders(o,l,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(o).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=Ao)&&(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=Pe(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&&(at("content","cycles"),at("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?Wr(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<_i(e)&&r-n.first<Uu}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=Pe(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(Pe(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 await(let l of Ut(c.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,d)=>Lt(u.path)-Lt(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,()=>gi(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=Ue(e.roots,h.path);h.physical=De(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 Nu(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 await(let l of Ut(s.sort((u,d)=>Lt(u.path)-Lt(d.path))))if(!this.isBlocked(a,l.path))try{let u=this.route(l.path,n,"folder"),d=n.rules.some(S=>S.target===a&&S.source.startsWith(l.path+"/"));if(u!==a&&!d||ii(l.path,"folder")===!1)continue;let g=await pi(l),h=e.stored.folders[Me(a,g)],m=h?c.nodes.find(S=>S.id===h.id):c.nodes.find(S=>S.path===l.path&&!S.deleted);if(m?.deleted){if(h){let S=!1;for(let k of r.filter(P=>P.kind==="file"&&P.path.startsWith(l.path+"/")&&this.route(P.path,n)===a)){let P=Object.entries(e.stored.files).find(([R,O])=>R.startsWith(a+":")&&O.path===k.path)?.[1];if(!P){S=!0;break}if(!this.sameAsShadow(P,k)){let R=Ae(await En(k));if(R!==P.hash&&!(P.memoryDeleted&&ki(k.path)&&R===pr)){S=!0;break}}}if(!S)continue}m=void 0}let y=It(l.path),p=y?c.nodes.find(S=>S.path===y&&S.kind==="folder"&&!S.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:Xt(l.path),kind:"folder"}),e.tombstones.get(a)?.delete(m.id),c.nodes.push(m);else if(h&&m.path!==l.path){if(m.revision!==h.revision)throw Error(`Concurrent folder rename: ${l.path}`);let S=m.path,k=await this.operation(e,l.path,a,"rename",null,()=>this.json(e,a,`/nodes/${m.id}`,"PATCH",{parentId:p,name:Xt(l.path),revision:m.revision}));for(let P of c.nodes)P.path.startsWith(S+"/")&&(P.path=l.path+P.path.slice(S.length));Object.assign(m,k);for(let[P,R]of Object.entries(e.stored.files))P.startsWith(a+":")&&R.path.startsWith(S+"/")&&(R.path=l.path+R.path.slice(S.length))}e.stored.folders[Me(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[Me(a,l.localId)]:void 0;d&&this.block(a,d.path,u),at("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,l.path,a,"rename",null);g.state="conflict",g.error=Pe(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let o=await this.scan(e);for(let[s,i]of r)for await(let a of Ut(i.nodes.filter(c=>c.kind==="folder"&&!c.busy).sort((c,l)=>Lt(l.path)-Lt(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 ur(l.physical)).some(d=>d!==".forsion-sync-id.json"))continue;await this.operation(e,a.path,s,"delete",null,()=>this.lock(e,l.physical,()=>{ct(l.root,fr(l.root,l.physical).split(Cn).join("/"));let d=vm(l.physical);if(d.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let g=De(l.physical,".forsion-sync-id.json"),h=d.length?_n(g):null;h&&mi(g);try{km(l.physical)}catch(m){if(h)try{Em(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>An)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>An)throw await l.cancel(),Error("Content too large");i.push(u.value),o.done=a}}let c=Buffer.concat(i);if(n.hash&&Ae(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[Me(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,()=>gi(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>An)throw Error("File exceeds 50 MB content limit");this.guard(e);let i=this.host.readCreds(),a=ju.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=Me(n,r.id),c=Ae(o),l=Si(o);l&&o.length>=Lu&&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<Lu?{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=Ue(e.roots,n),s=await Tt(De(o.root,...o.relative.split("/"))).catch(()=>null);if(!s?.isFile())return;let i=Eo(s);return{key:ar(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===ar(n)&&jm(n)<=e.statAt-Om}unchanged(e,n,r,o,s){let i=Me(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("/"+ir)||n?.stat===ar(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>=_i(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=Ei(e),s=De(o,n);if(await Tt(s).then(()=>!0,()=>!1))return;await yi(o,{recursive:!0,mode:448});let i=s+".tmp-"+tt();try{await lr(i,r,{mode:384,flag:"wx"}),await Co(i,s)}finally{await dr(i).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await cr(De(Ei(e),n.hash)).catch(o=>{if(o.code==="ENOENT")return null;throw o});return r&&Ae(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(o=>o.hash)),r=Ei(e);for(let o of await ur(r).catch(()=>[]))n.has(o)||await dr(De(r,o)).catch(()=>{})}async file(e,n,r,o,s){if(r.size>An){at("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(S=>S.kind==="file"&&!S.deleted&&S.path===r.path);if(!i){let S=Object.entries(e.stored.files).find(([k,P])=>k.startsWith(o+":")&&P.inode===r.inode&&P.path!==r.path)?.[1];if(S){let k=Ue(e.roots,S.path),P=await Tt(De(k.root,k.relative)).then(async O=>Eo(O).inode!==r.inode||It(S.path)!==It(r.path)?!0:(await ur(Kt(r.physical))).includes(Xt(S.path)),O=>O.code==="ENOENT"?!1:Promise.reject(O)),R=s.nodes.find(O=>O.id===S.id&&!O.deleted);if(!P&&R)try{if(R.path!==S.path)throw Error(`Concurrent file rename: ${r.path}`);let O=It(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 A=await this.operation(e,r.path,o,"rename",null,()=>this.json(e,o,`/nodes/${R.id}`,"PATCH",{name:Xt(r.path),parentId:w,revision:R.revision}));Object.assign(R,A),S.path=r.path,i=R}catch(O){for(let w of new Set([S.path,R.path,r.path]))this.block(o,w,O);throw O}}}let a=i?e.stored.files[Me(o,i.id)]:Object.entries(e.stored.files).find(([S,k])=>S.startsWith(o+":")&&k.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 En(r),u=Ae(l),d={key:ar(r),at:c,inode:r.inode};if(this.guard(e),this.settled(r.path,c),!i){if((a?s.nodes.find(A=>A.id===a.id&&A.deleted):null)&&a&&(a.hash===u||a.memoryDeleted&&ki(r.path)&&u===pr)){ki(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[Me(o,a.id)]);return}let k=It(r.path),P=k?s.nodes.find(A=>A.path===k&&!A.deleted&&A.kind==="folder")?.id:"";if(k&&!P)throw Error("Parent folder is unavailable");let R=Object.entries(e.stored.pendingUploads??{}).find(([A,C])=>A.startsWith(o+":")&&C.path===r.path&&!s.nodes.some(D=>D.id===C.id))?.[1];for(let[A,C]of Object.entries(e.stored.pendingUploads??{}))A.startsWith(o+":")&&C.path===r.path&&s.nodes.some(D=>D.id===C.id&&D.deleted)&&delete e.stored.pendingUploads[A];let O=R?.id??tt(),w=Me(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:P,name:Xt(r.path),kind:"file"}),e.tombstones.get(o)?.delete(i.id),i.id!==O&&delete e.stored.pendingUploads[w],s.nodes.push(i),a=void 0}if(i.busy)return;let g=Me(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,S=>this.download(e,i,o,S)),r),a=e.stored.files[g]),!i.version&&a&&a.hash===u&&!e.stored.pendingUploads?.[g]){let S=this.awaitingBytes.get(g)??Date.now();if(this.awaitingBytes.set(g,S),Date.now()-S<Im)return}if(this.awaitingBytes.delete(g),!i.version||a&&i.version===a.version){(e.stored.unconfirmed??={})[g]=u,await this.persist(e);let S=await this.operation(e,r.path,o,"upload",l.length,k=>this.upload(e,i,o,l,k));Object.assign(i,S),await this.shadow(e,o,i,l,r,d);return}let h=await this.operation(e,r.path,o,"download",i.size??null,S=>this.download(e,i,o,S)),m=h,y=!1;if(!a||a.hash!==u){let S=l.toString("utf8"),k=h.toString("utf8"),P=a?await this.readBase(e,a):null,R=Buffer.from(S).equals(l)&&Buffer.from(k).equals(h)?this.host.contentSync.merge(r.path,S,P,k):null;if(R?(m=Buffer.from(R.content),y=R.conflict):y=!0,y){await this.preserveConflict(e,r.path,l)&&(at("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=Ue(e.roots,n),s=await Je(o.root,o.relative),i=Xt(n),a=Ae(r);for(let c of await ur(Kt(s))){if(c.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==i||!po(c))continue;let l=It(n)?It(n)+"/"+c:c,u=Ue(e.roots,l),d=await Je(u.root,u.relative),g=await Tt(d);if(g.isFile()&&g.size===r.length&&Ae(await cr(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=wu(n,r,o),i=Ue(e.roots,s);if(!await Tt(De(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"?er(c.path):null;if(!l||co.has(l))continue;let u=`agents/${l}/`,d=this.route(u+"config.toml",r);if(!d||Object.entries(e.stored.files).some(([p,S])=>p.startsWith(d+":")&&S.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 S=m.get(p.path);return!!S&&s.get(p.path)!==S.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: ${Pe(l)}`)}let i=`agents/${s.slug}`,a=o.rules.find(l=>l.source===i),c=gn(e.stored.config,i,fl(o,i));a&&(c={...c,rules:c.rules.map(l=>l.source===i?{...a,target:l.target}:l)}),e.stored.config=$t(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),wo(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("/"+ir),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=Ue(e.roots,h);if(zu(De(y.root,y.relative)))continue;let p=await this.operation(e,h,s,"download",m.size??null,S=>this.download(e,m,s,S));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<=An).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 En(h),y=Ae(m),p=c.get(h.path),S=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}/${S}`,m),p){let w=await this.operation(e,h.path,s,"download",p.size??null,A=>this.download(e,p,s,A));await this.shadow(e,s,p,w,h,await u(h.path,w,y))}else S==="MEMORY.md"?await this.write(e,h.path,Buffer.alloc(0),y):await this.removeLocal(e,h,y);continue}if(!p)continue;let k=await this.operation(e,h.path,s,"download",p.size??null,w=>this.download(e,p,s,w)),P=s==="default"?await this.legacyBaseline(h.path,p):void 0;if(P?.hash===y){await this.shadow(e,s,p,k,h,await u(h.path,k,y));continue}let R=P?await this.readBase(e,P):null,O=Si(m)&&Si(k)?this.host.contentSync.merge(h.path,m.toString("utf8"),R,k.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,k)}else(p.mtime??0)>h.mtime?(await this.keep(e,`${g}/${S}`,m),await this.shadow(e,s,p,k,h,await u(h.path,k,y))):(await this.keep(e,`${g}/${S}`,k),await this.shadow(e,s,p,k))}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=Ue(e.roots,c);if(!await Tt(De(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 hi(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(ct(n.root,fr(n.root,n.physical).split(Cn).join("/")),Ae(_n(n.physical))!==r)throw Error("Local file changed before replacing");mi(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=Ue(e.roots,n),o=await Je(r.root,r.relative);try{return await Tt(o),!1}catch(s){if(s.code==="ENOENT")return!0;throw s}}async missing(e,n,r,o,s){let i=e.stored.files[Me(r,n.id)],a=e.stored.pendingUploads?.[Me(r,n.id)];if(n.deleted){i&&delete e.stored.files[Me(r,n.id)],a&&delete e.stored.pendingUploads[Me(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[Me(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[Me(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 _o(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);l&&(n.path=l.path+"/"+Xt(n.path))}let r=Ue(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&&!rn(a,i))throw Error("Sync recovery root changed; journal retained");let c=De(s,n.stage);await Tt(c).then(()=>!0,l=>l.code==="ENOENT"?!1:Promise.reject(l))&&await this.lock(e,o,()=>{if(ct(s,n.stage,!0),Ae(_n(c))!==n.hash)throw Error("Sync recovery content changed");ct(r.root,r.relative),_m(Kt(o),{recursive:!0});let l=zu(o)?o+` (sync recovery ${tt().slice(0,8)})`:o;try{Sm(c,l)}catch(u){if(u.code!=="EXDEV")throw u;if(Cm(c,l,Am.COPYFILE_EXCL),Ae(_n(l))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}mi(c)},!0),e.stored.trash=e.stored.trash.filter(l=>l!==n)}}async clearDeletedMemory(e,n,r,o,s,i){o.memoryDeleted&&o.hash===pr&&i===pr||(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[Me(n,o.id)]={...o,hash:pr,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,fr(n.root,n.physical).split(Cn).join("/")),s={path:n.path,stage:".forsion-sync-trash-"+tt(),hash:r},i=De(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(_n(De(Kt(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(ct(n.root,fr(n.root,o).split(Cn).join("/")),Ae(_n(o))!==r)throw Error("Local file changed before deletion");bm(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 Fm(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))Qn.test(n)&&cl.includes(r)&&(e[n]=r);return e}function zu(t){try{return ym(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}Yi(Ia);function Rv(t){Ta(t.contentSync?.withWriteLock?.bind(t.contentSync)),ra(t),as(t),qu(t),t.log("[forsion-extend] cloud account handlers registered"),Zo(t)?Qo(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),ts(t)?ns(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),hs(t)?gs(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),Ds(t)?Os(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),Ps(t)?$s(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Gs(t)?Jl(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),Gs(t)&&gu(t)}export{sc as ACCOUNT_SEAM,Jc as AMADEUS_SEAM,Xo as CONNECT_MAX_FILES,Oa as CONNECT_MAX_FILE_BYTES,Ma as CONNECT_MAX_TOTAL_BYTES,Lr as DIAGNOSTICS_VAULT,za as FORSION_CONNECT_LOCAL_SDK,na as PAY_PERIODS,ta as PAY_TABS,Wa as PENZOR_MAX_FILE,Re as SYNC_IPC,Zc as UNIT_SEAM,jn as UPLOAD_MAX_FILE,Jn as UnitCapsReporter,Gn as UnitHost,He as cloudJson,$a as collectProjectFiles,Br as conflictCopyPath,hp as conflictCopyVariant,Ua as connectMetaOf,oc as createAccountCloud,Kc as createAmadeusCloud,Fr as createPenzorRemote,Qc as createUnitHub,jr as deviceHeader,es as expectedPartsOf,Ne as forsionAccountId,xr as forsionRefreshToken,Nn as forsionWhoami,hs as hasAccountHost,Ds as hasAmadeusHost,Zo as hasConnectHost,ts as hasRemoteSyncHost,Ps as hasUnitHost,Ha as makePreviewProxy,ec as multipartFrame,ja as readConnectMeta,gs as registerAccount,Os as registerAmadeus,Rv as registerCloud,Qo as registerConnect,ns as registerPenzor,as as registerPenzorTransfers,$s as registerUnit,Ur as safeDownloadName,La as scanSdkUsage,Ar as shouldRefreshToken,rs as speedOf,Xc as streamWorthy,Pc as stripConflictSuffix,gp as textFingerprint,Po as tokenAgeMs,Xi as tokenRemainingMs,os as uploadError,Fa as writeConnectMeta};
284
+ `,{encoding:"utf8",mode:384});try{if(Mg(a()).size>yu){let J=g(),C=J.length,I=0;for(;C>0&&I+Buffer.byteLength(JSON.stringify(J[C-1]))+1<=yu/2;)I+=Buffer.byteLength(JSON.stringify(J[--C]))+1;P(a(),J.slice(C))}}catch{}g().length>=Fg&&ee()}},ie=()=>{let q=f();return{available:!!l,enabled:q.enabled!==!1,noticeSeen:q.noticeSeen===!0,signedIn:w(),active:y(q),packaged:l?.packaged===!0,installId:m(),queued:Og(a())?g().length:0,lastSentAt:q.lastSentAt??null,lastError:q.lastError??null}},se=()=>cu({app:"desktop",appVersion:t.appVersion(),coreVersion:l?.coreVersion()??void 0,channel:l?.channel(),os:Jg(process.platform),osVersion:$g(),arch:Kg(process.arch),locale:Xg()}),X=null,ee=()=>{if(X)return X;if(E||n().getTime()<M)return Promise.resolve();let q=A,J=x,C=(async()=>{try{for(let I=0;I<5;I++){let T=g();if(!T.length)return;let R=m(),H={v:su,installId:R,...se()},V=[],N=Buffer.byteLength(JSON.stringify({...H,events:[]}));for(let re of T){let pe=Buffer.byteLength(JSON.stringify(re))+1;if(V.length>=io.maxEvents||N+pe>io.maxBatchBytes)break;V.push(re),N+=pe}if(!V.length){P(a(),T.slice(1));continue}let{base:U}=await t.getCloud(),Q={...H,events:V};if(!W()||q!==A)return;let K=await r(`${U.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q),signal:AbortSignal.timeout(wu)}).catch(re=>({ok:!1,status:0,error:String(re?.message||re)})),z=K.status;if(z>=200&&z<300||z===400||z===413){let re=new Set(V.map(pe=>JSON.stringify(pe)));P(a(),g().filter(pe=>!re.has(JSON.stringify(pe))))}if(z>=200&&z<300){let re=n().getTime();J===x&&P(c(),[...k(),{at:re,body:Q}]),p({lastSentAt:re,lastError:void 0});continue}if(z!==400&&z!==413){let re=Number(K.headers?.get?.("retry-after"));M=n().getTime()+(Number.isFinite(re)&&re>0?Math.min(re,3600)*1e3:5*6e4)}p({lastError:z?`HTTP ${z}`:String(K.error??"network error").slice(0,200)});return}}catch(I){try{p({lastError:String(I?.message||I).slice(0,200)})}catch{}}})();return X=C,C.finally(()=>{X===C&&(X=null)}),C},ne=async()=>{try{if(k(),!W())return;let q=f(),J=A,C=q.cursor??po(n().getTime()),I=await Vg(i(),C,l?.sessionId,vu(n().getTime()));if(!W()||J!==A)return;B(I.events),I.cursor!==C&&p({cursor:I.cursor}),await fe(J),await ee()}catch(q){t.log(`[forsion-extend] telemetry tick failed: ${String(q?.message||q)}`)}},fe=async q=>{let J=n().getTime(),C=pn(J),I=pn(J-bu),T=f().ledgerCursor;if(er(T)||(T=I,p({ledgerCursor:T})),js(T),T>=I){oe();return}let R=await Yg(i(),T,C);if(!(!W()||q!==A)){if(R){let H=R.complete?I:R.days[R.days.length-1]?.day??T;if(H>T){let V=Qc(T,H),N=[...new Set([...R.days.map(Q=>Q.day),...V.map(Q=>Q.day)])].filter(Q=>Q>T&&Q<=H).sort(),U=[];for(let Q of N){U.push(...R.days.find(K=>K.day===Q)?.events??[]);for(let K of V)if(K.day===Q){let z=Gg(Q,K.system,K.counts);z&&U.push(z)}}B(U),p({ledgerCursor:H}),js(H)}}oe()}},oe=()=>{if(!Xc())return;let q=h();if(!q)return;let J=Kc();p({syncHealth:Object.keys(J).length?J:void 0},q),Zc()},Te=l?.subscribe(q=>{try{if(!Bg.has(q?.event)||!W())return;let J=Zt({...q,sessionId:l.sessionId},Pg());J&&B([J])}catch(J){t.log(`[forsion-extend] telemetry event dropped: ${String(J?.message||J)}`)}}),we={ok:!1,error:"untrusted"};t.handle("telemetry:get",q=>t.isTrustedSender(q)?(W(),ie()):we),t.handle("telemetry:set",(q,J)=>{if(!t.isTrustedSender(q))return we;let C=f(),I={};typeof J?.enabled=="boolean"&&(I.enabled=J.enabled),J?.noticeSeen===!0&&(I.noticeSeen=!0);let T={...C,...I};return!y(C)&&y(T)&&(I.cursor=po(n().getTime()),I.ledgerCursor=u()),y(C)&&!y(T)&&A++,I.enabled===!1&&(I.syncHealth=void 0),p(I),I.enabled===!1&&D(),W(),ie()}),t.handle("telemetry:sent",q=>t.isTrustedSender(q)?{batches:k()}:we),t.handle("telemetry:delete",async q=>{if(!t.isTrustedSender(q))return we;E=!0,A++;try{await X?.catch(()=>{});let J=m(),{base:C}=await t.getCloud(),T=(await r(`${C.replace(/\/+$/,"")}/api/telemetry/install/${J}`,{method:"DELETE",signal:AbortSignal.timeout(wu)}).catch(R=>({ok:!1,status:0,error:String(R?.message||R)}))).status;return T>=200&&T<300?(D(),p({installId:pu(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),ie()):{ok:!1,error:T?`HTTP ${T}`:"network error"}}finally{E=!1}});try{Jc(f().syncHealth),j(),W()}catch(q){t.log(`[forsion-extend] telemetry startup check failed: ${String(q?.message||q)}`)}let Je=t.addFlushHook?.(q=>{if(q!=="blur")try{oe()}catch{}}),Be=setTimeout(()=>void ne(),jg),Oe=setInterval(()=>void ne(),Ng);return Be.unref?.(),Oe.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(Be),clearInterval(Oe),Te?.(),Je?.()},{tick:ne,flush:ee})}import{readFileSync as Tn,lstatSync as Cm,statSync as Am,renameSync as xm,linkSync as Tm,unlinkSync as _o,readdirSync as Im,rmdirSync as Rm,writeFileSync as Dm,mkdirSync as Om,copyFileSync as Mm,constants as Pm}from"node:fs";import{readFile as gr,writeFile as mr,mkdir as Co,rename as Ii,readdir as yr,lstat as Dt,stat as Ao,unlink as wr}from"node:fs/promises";import{join as De,dirname as tn,relative as br,sep as In}from"node:path";import{hostname as xo}from"node:os";import{randomUUID as ot}from"node:crypto";import{isUtf8 as To}from"node:buffer";import{Readable as qu}from"node:stream";import{performance as Io}from"node:perf_hooks";import{setImmediate as $m}from"node:timers/promises";var Zg=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],Qg=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],pr=".memory-tombstones.json",_u=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),Eu=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),em=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,tm=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function nm(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===pr)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:Zg.includes(t)||_u(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&em(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var rm=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),im=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,sm=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function yi(t){let e=t.slice(t.lastIndexOf("/")+1);return im.test(e)||sm.test(e)}function Cu(t,e,n=1){let r=t.lastIndexOf("/"),i=r<0?"":t.slice(0,r+1),s=r<0?t:t.slice(r+1),o=s.lastIndexOf("."),a=o>0?s.slice(0,o):s,c=o>0?s.slice(o):"",l=f=>String(f).padStart(2,"0"),u=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}${n>1?` ${n}`:""}`;return`${i}${a} (conflict ${u})${c}`}function ho(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(yi(t))return!1;if(n){let l=t.slice(6);return e==="folder"?Eu(l):Qg.includes(l)||_u(l)}let i=t.slice(7),s=i.indexOf("/"),o=s<0?i:i.slice(0,s),a=s<0?"":i.slice(s+1);if(!tm(o)||rm(o))return!1;if(e==="file")return nm(a);if(a===""||a==="LOG"||Eu(a))return!0;let c=a.split("/");return c[0]==="Library"&&c.every(l=>l&&!l.startsWith(".")&&!l.endsWith(".")&&!l.endsWith(" "))}import{isAbsolute as om}from"node:path";var st=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),St=t=>typeof t=="string",mo=t=>St(t)&&t.length>0,Ht=t=>typeof t=="boolean",Qt=t=>typeof t=="number"&&Number.isFinite(t),Cn=t=>Qt(t)&&Number.isSafeInteger(t)&&t>=0,Au=t=>Qt(t)&&Number.isInteger(t)&&t>=0,xu=t=>Cn(t)&&t>0,An=t=>St(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),vi=t=>St(t)&&/^[a-f0-9]{64}$/.test(t),Tu=t=>St(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),bi=(t,e)=>St(t)&&e.includes(t),ke=(t,e)=>t===void 0||e(t),Iu=(t,e,n)=>e.every(r=>ke(t[r],n)),Ru=t=>St(t)&&!t.includes("\0")&&om(t);function zt(t,e=!1){try{return Lt(t,e),!0}catch{return!1}}var Du=t=>zt(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,Ou=t=>t===""||An(t);function Si(t,e){let n=t.indexOf(":");return n>0&&An(e)&&t.slice(n+1)===e&&Tu(t.slice(0,n))}function am(t,e){return st(e)&&Si(t,e.id)&&zt(e.path)&&mo(e.version)&&vi(e.hash)&&Iu(e,["base","inode","stat"],St)&&ke(e.statAt,Qt)&&ke(e.memoryDeleted,Ht)}function cm(t,e){return st(e)&&Si(t,e.localId)&&An(e.id)&&zt(e.path)&&xu(e.revision)&&Ou(e.parentId)&&Du(e.name)}function lm(t){return st(t)&&An(t.id)&&zt(t.path)&&Tu(t.target)&&bi(t.direction,["upload","download","merge","rename","delete"])&&bi(t.state,["queued","active","done","failed","paused","conflict"])&&Cn(t.done)&&(t.size===null||Cn(t.size))&&Qt(t.at)&&ke(t.error,St)&&ke(t.finishedAt,Qt)}function um(t){return st(t)&&zt(t.path)&&vi(t.hash)&&St(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&ke(t.parentId,An)&&ke(t.stageRoot,Ru)&&ke(t.stageIdentity,Gt)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&Au(t.stageDev)&&Au(t.stageIno))}function dm(t){return st(t)&&zt(t.prefix,!0)&&Ru(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Gt(t))}function fm(t){return st(t)&&bi(t.state,["running","done"])&&Ht(t.seen)&&Iu(t,["name","folderId","shelfId","shelfName"],St)&&ke(t.files,Cn)&&ke(t.at,Qt)&&ke(t.rewritten,Ht)}var wi=(t,e)=>st(t)&&Object.entries(t).every(([n,r])=>e(n,r)),go=(t,e)=>Array.isArray(t)&&t.every(e);function Mu(t){if(!st(t)||!st(t.config)||!Cn(t.config.revision)||!Ht(t.owned)||!Ht(t.paused)||!wi(t.files,am)||!wi(t.folders,cm)||!go(t.jobs,lm)||!ke(t.accountReview,Ht)||!ke(t.agentArchive,fm)||!ke(t.roots,e=>go(e,dm))||!ke(t.trash,e=>go(e,um))||!ke(t.unconfirmed,e=>wi(e,(n,r)=>Si(n,n.slice(-36))&&vi(r)))||!ke(t.pendingUploads,e=>wi(e,(n,r)=>st(r)&&Si(n,r.id)&&zt(r.path))))throw Error("Invalid content sync state; original data was retained");Ut(t.config,t.config.revision)}function Pu(t){return st(t)&&An(t.id)&&Ou(t.parentId)&&Du(t.name)&&zt(t.path)&&bi(t.kind,["file","folder"])&&xu(t.revision)&&Ht(t.deleted)&&ke(t.busy,Ht)&&ke(t.version,mo)&&ke(t.hash,vi)&&ke(t.size,Cn)&&ke(t.mtime,Qt)&&t.version===void 0==(t.hash===void 0)}function $u(t){return Pu(t)&&t.deleted===!0}function ki(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!st(t)||t.schemaVersion!==1||t.namespace!==e||!mo(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,i=new Set;for(let s of t.nodes){if(!Pu(s)||r.has(s.id)||!s.deleted&&i.has(s.path))throw n();r.set(s.id,s),s.deleted||i.add(s.path)}for(let s of r.values()){let o=s.parentId?r.get(s.parentId):void 0;if(s.parentId&&(!o||o.kind!=="folder"||o.deleted&&!s.deleted)||s.path!==(o?o.path+"/"+s.name:s.name))throw n()}}import{constants as Nu,lstatSync as en,readdirSync as pm,readFileSync as hm,renameSync as Ei,unlinkSync as gm,linkSync as mm,mkdirSync as Ci,realpathSync as yo,rmdirSync as ym}from"node:fs";import{open as ju,lstat as wo,readdir as wm,realpath as Fu,readFile as bo,writeFile as bm,mkdir as Lu,unlink as Sm}from"node:fs/promises";import{join as Bt,dirname as _i,relative as So,sep as Ai}from"node:path";import{randomUUID as Uu,createHash as vm}from"node:crypto";var hr=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,xi=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),Hu=".forsion-sync-id.json",km=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),Em=t=>!km.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),Ce=t=>vm("sha256").update(t).digest("hex");function zu(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 et(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 Lt(e,!0);zu(e);let r=await Fu(t),i=Bt(r,...e.split("/").filter(Boolean)),s=So(r,i);if(s===".."||s.startsWith(".."+Ai))throw Error("Content path escapes root");let o=r;for(let a of s.split(Ai).filter(Boolean)){o=Bt(o,a);try{if((await wo(o)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(c){if(c.code!=="ENOENT")throw c}}return i}function ut(t,e,n=!1){if(n||Lt(e,!0),zu(e),e.split("/").some(s=>s===".."||s===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let i=yo(t);for(let s of e.split("/").filter(Boolean)){i=Bt(i,s);try{if(en(i).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(o){if(o.code!=="ENOENT")throw o}}return i}async function Ti(t){let e=new Map,n=t.filter(i=>i.prefix).map(i=>i.prefix),r=[];for(let i of t)try{r.push({...i,root:await Fu(i.root)})}catch(s){if(s.code!=="ENOENT")throw s}if(new Set(r.map(i=>i.root)).size!==r.length)throw Error("Managed roots refer to the same directory; choose a separate vault folder");for(let i of r){let s=i.root;if(!(await wo(s)).isDirectory())throw Error(`Sync root is not a directory: ${i.prefix||"Forsion"}`);let o=async(a,c)=>{let l=await wo(a);if(!l.isSymbolicLink()&&!(a!==s&&r.some(u=>u!==i&&u.root===a))&&!(c&&i.prefix===""&&n.some(u=>c===u||c.startsWith(u+"/")))){if(c){Lt(c);let u;if(l.isDirectory())try{let f=JSON.parse(await bo(Bt(a,Hu),"utf8"));/^[a-f0-9-]{36}$/i.test(f.id)&&(u=f.id)}catch(f){if(f.code!=="ENOENT"&&!(f instanceof SyntaxError))throw f}e.set(c,{path:c,physical:a,root:s,kind:l.isDirectory()?"folder":"file",localId:u,...xi(l),size:l.isFile()?l.size:0})}if(l.isDirectory())for(let u of await wm(a,{withFileTypes:!0}))!Em(u.name)||!u.isDirectory()&&!u.isFile()||await o(Bt(a,u.name),c?`${c}/${u.name}`:u.name)}};await o(s,i.prefix)}return[...e.values()].sort((i,s)=>i.path.split("/").length-s.path.split("/").length||i.path.localeCompare(s.path))}async function vo(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await et(t.root,So(t.root,Bt(t.physical,Hu)).split(Ai).join("/"),!0),n=Uu();try{let r=await ju(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 i=JSON.parse(await bo(e,"utf8"));if(!/^[a-f0-9-]{36}$/i.test(i.id))throw Error("Invalid folder sync identity");return t.localId=i.id,i.id}}async function xn(t){let e=await et(t.root,So(t.root,t.physical).split(Ai).join("/")),n=await ju(e,Nu.O_RDONLY|(Nu.O_NOFOLLOW||0));try{if((await n.stat()).size>50*1024*1024)throw Error("File exceeds 50 MB content limit");return await n.readFile()}finally{await n.close()}}function ze(t,e){Lt(e);let n=[...t].sort((r,i)=>i.prefix.length-r.prefix.length).find(r=>!r.prefix||e===r.prefix||e.startsWith(r.prefix+"/"));if(!n)throw Error("Content root unavailable");return{root:n.root,relative:n.prefix?e.slice(n.prefix.length).replace(/^\//,""):e}}async function ko(t,e,n,r,i=async(s,o)=>o()){let s=ze(t,e);await Lu(s.root,{recursive:!0});let o=await et(s.root,s.relative),a=await bo(o).catch(l=>{if(l.code==="ENOENT")return null;throw l});if((a?Ce(a):null)!==r)throw Error("Local file changed during download");let c=Bt(s.root,`.forsion-sync-${Uu()}.tmp`);try{await bm(c,n,{flag:"wx",mode:384}),await et(s.root,s.relative),await i(o,()=>{ut(s.root,s.relative),Ci(_i(o),{recursive:!0}),ut(s.root,s.relative);let l=null;try{l=hm(o)}catch(u){if(u.code!=="ENOENT")throw u}if((l?Ce(l):null)!==r)throw Error("Local file changed during download");Ei(c,o)})}finally{await Sm(c).catch(()=>{})}}async function Bu(t,e,n=async(r,i)=>i()){let r=ze(t,e);await Lu(r.root,{recursive:!0});let i=await et(r.root,r.relative);await n([i],()=>{ut(r.root,r.relative),Ci(i,{recursive:!0})})}async function Eo(t,e,n,r=async(i,s)=>s()){let i=ze(t,e),s=ze(t,n);if(i.root!==s.root)throw Error("Folder move crosses a managed source");let o=await et(i.root,i.relative),a=await et(s.root,s.relative);await r([o,a],()=>{if(ut(i.root,i.relative),ut(s.root,s.relative),_m(a)){let l=en(o),u=en(a),f=yo(_i(o));if((l.dev===u.dev&&l.ino===u.ino&&f===yo(_i(a))?pm(f).filter(m=>{let w=en(Bt(f,m));return w.dev===l.dev&&w.ino===l.ino}):[]).length!==1)throw Error("Local rename destination exists");Ei(o,a);return}Ci(_i(a),{recursive:!0});let c=en(o);if(c.isDirectory()){if(process.platform==="win32"){Ei(o,a);return}Ci(a,{mode:448});try{Ei(o,a)}catch(l){try{ym(a)}catch{}throw l}}else{mm(o,a);let l=en(o);if(l.ino!==c.ino||l.dev!==c.dev)throw Error("Source changed during rename");gm(o)}})}function _m(t){try{return en(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Wu=(t,e)=>t.length===e.length&&t.every(n=>e.some(r=>n.prefix===r.prefix&&n.root===r.root&&(n.dev===void 0||ln(n,r)))),Nm=()=>({config:structuredClone(ml),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),Rn=50*1024*1024,jm=10*6e4,Vu=1024*1024,$e=(t,e)=>`${t}:${e}`,Ot=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",nn=t=>t.slice(t.lastIndexOf("/")+1),Sr=Ce(""),Ro=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),qt=t=>t.split("/").length,Ne=t=>t instanceof Error?t.message:String(t),Fm={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},Do=t=>t.file.replace(/\.json$/,".bases"),Ku=5e3,Lm=3e4,Yu=3e4,Um=3e3,Ri=10*6e4,Hm=60*6e4,zm=10*6e4,Bm=3*6e4,Gu=2e3,qm=1440*6e4,Oo=t=>/^(agents|human)\//.test(t)?Lm:Ku,Wm=t=>Math.max(t.mtime,t.ctime);async function*Wt(t){let e=Io.now()+8;for(let n of t)Io.now()>=e&&(await $m(),e=Io.now()+8),yield n}function Xu(t){if(!t.contentSync)return;let e=new Mo(t);for(let[n,r]of Object.entries({[mt.get]:(i,s)=>e.snapshot(i,s),[mt.preview]:i=>e.preview(i),[mt.apply]:(i,s)=>e.apply(typeof i=="string"?i:"",s),[mt.run]:()=>{e.touch(),e.kick()},[mt.pause]:i=>e.pause(i===!0),[mt.retry]:()=>{e.touch(),e.kick()},[mt.rename]:i=>e.rename(i),[mt.setup]:i=>e.setup(i),[mt.archiveSeen]:()=>e.archiveSeen()}))t.handle(n,async(i,...s)=>{if(!t.isTrustedSender(i))return{ok:!1,error:"untrusted"};try{return{ok:!0,value:await r(...s)}}catch(o){return{ok:!1,error:Ne(o)}}});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)),Tl(()=>e.stats()),e.start()}var Mo=class{session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;activeAt=Date.now();lastRunAt=0;focused=!1;devices=[];others;deviceId="";customName="";serial=Promise.resolve();scheduled=null;tick=null;first=null;blocked=new Map;phase="idle";lastError;get error(){return this.lastError}set error(e){this.lastError=e,e&&this.fault(e)}runLog=new cr;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)=>lt("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=uc(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{this.idleSkip()||this.run()},3e4)).unref?.(),(this.first=setTimeout(()=>{this.run()},5e3)).unref?.()}locale(){if(this.uiLocale)return this.uiLocale;try{return/^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en"}catch{return"zh"}}archiveStep(e){if(e.stored.accountReview||e.stored.agentArchive?.state==="done"||this.archiveRetry.account===e.account&&Date.now()<this.archiveRetry.at)return Promise.resolve();let n=()=>{this.archiveRetry={account:e.account,at:Date.now()+Ri}};return this.archiving??=(async()=>{try{let r=this.host.readCreds();if(!r.token)return;let i=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),!i.ok){n();return}let s=await i.json();if(this.guard(e),s.state!=="done"&&s.state!=="running"){n();return}let o=e.stored.agentArchive,a=s.archive;o?.rewritten||this.turnAgentsOff(e);let c={rewritten:!0,seen:o?.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(Ne(r)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${Ne(r)}`)}finally{this.archiving=null}})()}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=_l(n);if(!r)return;e.stored.config=Ut(r,n.revision+1);let i=s=>s==="agents"||s.startsWith("agents/");for(let[s,o]of Object.entries(e.stored.files))i(o.path)&&(delete e.stored.files[s],delete e.stored.unconfirmed?.[s]);for(let[s,o]of Object.entries(e.stored.folders))i(o.path)&&delete e.stored.folders[s];for(let[s,o]of Object.entries(e.stored.pendingUploads??{}))i(o.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=qn(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(bs(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 Co(tn(e.file),{recursive:!0,mode:448});let i=e.file+".tmp-"+ot();try{await mr(i,r,{mode:384,flag:"wx"}),this.guard(e,!1),await Ii(i,e.file),e.persisted=r}finally{await wr(i).catch(()=>{})}});return e.writes=n,n}async getSession(){let e=this.host.accountId();if(!e)throw this.logAccount&&(this.runLog.reset(),this.logAccount=null),this.session?.abort.abort(),this.session=null,Error("not_signed_in");let n=this.accountGeneration;return bs(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=De(this.host.homeDir(),"content-sync"),i=De(r,Ce(e)+".json"),s=Nm();try{let f=JSON.parse(await gr(i,"utf8"));Mu(f),s={...s,...f,config:Ut(f.config,f.config.revision)},s.jobs=Array.isArray(f.jobs)?f.jobs.slice(-200):[]}catch(f){if(f.code!=="ENOENT")throw Error("Invalid content sync state; original data was retained")}let o,a=De(this.host.homeDir(),"content-sync-device.json"),c=async()=>{let f=JSON.parse(await gr(a,"utf8"));if(typeof f?.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(f.id))throw Error("Invalid device sync ID");return f};try{o=await c()}catch(f){if(f.code!=="ENOENT")throw f;o={id:ot()},await Co(tn(a),{recursive:!0});try{await mr(a,JSON.stringify(o),{flag:"wx",mode:384})}catch(h){if(h.code!=="EEXIST")throw h;o=await c()}}if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=o.id,this.customName=typeof o.name=="string"?o.name:"";let l=await this.host.contentSync.roots();if(this.host.accountId()!==e)throw Error("account_changed");let u={account:e,generation:n,file:i,stored:s,roots:l,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map,tombstones:new Map};return this.session=u,await this.bindAccount(u),await this.recoverTrash(u),this.guard(u),s.owned&&await this.accountWrite(u,f=>this.host.contentSync.claim(!0,f)),this.setSources(await this.scan(u,l).catch(f=>(this.error=Ne(f),[]))),await this.register(u,!0),await this.watchRoots(u),u})().catch(r=>{throw this.session?.account===e&&(this.session.abort.abort(),this.session=null),r}).finally(()=>{this.initializing=null}),this.initializing)}async bindAccount(e){let n=tn(e.file),r=ys(this.host.homeDir()),i=Ce(e.account),s=qn(r),o=!s?.account&&(await yr(n).catch(c=>{if(c.code==="ENOENT")return[];throw c})).some(c=>/^[a-f0-9]{64}\.json$/.test(c)&&c!==i+".json"),a=s?.pending&&(e.stored.owned||e.stored.config.revision>0);if((s?.account&&s.account!==i||o||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!==i||s.pending){this.guard(e,!1);let c=qn(r);if(c?.account!==s?.account||c?.epoch!==s?.epoch||c?.pending!==s?.pending)throw Error("account_changed");ws(r,{version:1,account:i,...s?.epoch?{epoch:s.epoch}:{}})}e.binding={file:r,account:i,epoch:s?.epoch},this.guard(e,!1)}async rootIdentity(e,n){let r=e.rootIdentities.get(n);if(r){let s=await Ao(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 i=await Un(n).catch(s=>{throw s.code==="ENOENT"?Error("Sync root unavailable: "+n):s});return this.guard(e),e.rootIdentities.set(n,i),i}async scan(e,n=e.roots){let r=!1;for(let i of e.stored.roots??[]){let s=n.find(a=>a.prefix===i.prefix);if(!s||s.root!==i.root)throw Error("content_roots_changed_preview_required");let o=await this.rootIdentity(e,i.root);if(i.dev!==void 0&&!ln(i,o))throw Error("Sync root changed; preview before rebinding");if(i.dev!==void 0&&i.dev!==o.dev){let a=String(i.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(a)&&ze(n,c.path).root===i.root&&(c.inode=String(o.dev)+":"+c.inode.slice(a.length),delete c.stat,delete c.statAt)}JSON.stringify(i)!==JSON.stringify({...i,...o})&&(Object.assign(i,o),r=!0)}return r&&await this.persist(e),Ti(n)}async write(e,n,r,i){this.guard(e),await ko(e.roots,n,r,i,(s,o)=>this.lock(e,s,o)),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 Ao(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&((e.stored.roots??=[]).push({...r,...await this.rootIdentity(e,r.root)}),n=!0)}n&&await this.persist(e)}lock(e,n,r,i=!1){let s=()=>{if(this.guard(e),e.stored.paused&&!i)throw Error("paused");for(let[o,a]of e.rootIdentities){let c;try{c=Am(o)}catch{throw Error("Sync root unavailable: "+o)}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(i=>i.prefix===r.prefix&&i.root===r.root)&&await Dt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return Ti(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Xi(e.roots.map(n=>n.root),{ignoreInitial:!0,ignored:n=>{let r=n.split(/[\\/]/).at(-1)??"";return r.startsWith(".")&&r!==".memory-tombstones.json"||r==="node_modules"||r==="__pycache__"}}),this.watcher.on("all",(n,r)=>{let i=this.logical(e,r),s=Date.now();if(this.activeAt=s,i){let o=this.dirty.get(i);o?o.last=s:this.dirty.set(i,{first:s,last:s})}this.schedule(i?void 0:s+Ku)}))}logical(e,n){let r=null;for(let o of e.roots)(n===o.root||n.startsWith(o.root+In))&&(!r||o.root.length>r.root.length)&&(r=o);if(!r)return null;let i=br(r.root,n).split(In).join("/");return(r.prefix?i?`${r.prefix}/${i}`:r.prefix:i)||null}dueAt(e,n){return n.last<=this.flushAt?0:Math.min(n.last+Oo(e),n.first+Yu)}schedule(e){let n=e??1/0;for(let[r,i]of this.dirty)n=Math.min(n,this.dueAt(r,i));this.due&&clearTimeout(this.due),this.due=null,!(n===1/0||this.closed)&&(this.due=setTimeout(()=>{this.due=null;let r=this.session;r?.stored.config.enabled&&!r.stored.paused&&this.kick()},Math.max(0,n-Date.now())+50),this.due.unref?.())}kick(){if(this.running){this.again=!0;return}this.run()}touch(){this.activeAt=Date.now()}idleSkip(e=Date.now()){return e-this.activeAt>=zm&&e-this.lastRunAt<Bm-5e3}flush(e){let n=this.session;if(!(this.closed||!this.host.accountId()||n&&(!n.stored.config.enabled||n.stored.paused)))return this.flushRequest++,this.flushThrough=Math.max(this.flushThrough,Date.now()),e==="quit"&&(this.quitting=!0),this.flushAt=this.quitting?1/0:this.flushThrough,this.flushing?this.flushing:this.flushing=(async()=>{try{for(;!this.closed;){let r=this.serial;if(await r,r!==this.serial)continue;if(this.running){await this.runFinished;continue}let i=this.flushRequest;if(await this.run(),i===this.flushRequest)return}}finally{this.flushing=null,this.quitting=!1,this.flushAt=this.flushThrough}})()}async request(e,n,r="",i="GET",s,o,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},f;if(s instanceof Buffer){u["Content-Type"]="application/octet-stream",u["Content-Length"]=String(s.length);let m=async function*(){for(let w=0;w<s.length;w+=64*1024)e.abort.signal.throwIfAborted(),yield s.subarray(w,w+64*1024),o?.(Math.min(s.length,w+64*1024))};f=qu.from(m())}else s!==void 0&&(u["Content-Type"]="application/json",f=JSON.stringify(s));let h={method:i,headers:u,body:f,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...s instanceof Buffer?{duplex:"half"}:{}},p=await fetch(l,h);if(this.guard(e),!p.ok&&!(p.status===304&&a?.["If-None-Match"])){this.httpStatus=p.status;let m=await p.json().catch(()=>({}));throw Object.assign(new Error(typeof m.detail=="string"?m.detail:`content_http_${p.status}`),{status:p.status})}return i==="DELETE"&&this.tally("deletesSent"),p}async json(e,n,r="",i="GET",s){let o=await(await this.request(e,n,r,i,s)).json();return this.guard(e),o}async manifests(e,n){let r=new Map;for(let s of new Set(n.rules.filter(o=>o.target!=="off").map(o=>o.target))){let o=JSON.parse(await this.manifestText(e,s));ki(o,s),await this.knownTombstones(e,s,o),r.set(s,o)}let i=[r.get("default"),r.get(`device-${this.deviceId}`)].filter(Boolean);return i.length&&(this.cloudAgents=[...new Set(i.flatMap(s=>s.nodes.filter(o=>!o.deleted&&o.kind==="file").map(o=>/^agents\/([^/]+)\/config\.toml$/.exec(o.path)?.[1]).filter(o=>!!o&&or.test(o))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),i=r&&Date.now()-r.at<Hm?r:void 0,s=await this.request(e,n,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...i?{"If-None-Match":i.etag}:{}});if(s.status===304)return await s.body?.cancel(),i?i.text:(e.manifests.delete(n),this.manifestText(e,n));let o=await s.text();this.guard(e),ki(JSON.parse(o),n);let a=s.headers.get("etag");return r?.text!==o&&this.touch(),a?e.manifests.set(n,{etag:a,text:o,at:Date.now()}):e.manifests.delete(n),o}async knownTombstones(e,n,r){if(typeof r.tombstonesSince!="string")return;let i=new Set(r.nodes.map(l=>l.id)),s=new Set;for(let[l,u]of Object.entries(e.stored.files))l.startsWith(n+":")&&s.add(u.id);for(let[l,u]of Object.entries(e.stored.folders))l.startsWith(n+":")&&s.add(u.id);for(let[l,u]of Object.entries(e.stored.pendingUploads??{}))l.startsWith(n+":")&&s.add(u.id);let o=e.tombstones.get(n);o||e.tombstones.set(n,o=new Map);for(let l of[...o.keys()])i.has(l)&&o.delete(l);let a=Date.now(),c=[...s].filter(l=>{if(i.has(l))return!1;let u=o.get(l);return!u||!u.node&&a-u.at>=qm});for(let l=0;l<c.length;l+=Gu){let u=c.slice(l,l+Gu),f=new Set(u),h=await this.json(e,n,"/tombstones","POST",{ids:u}),p=new Map((Array.isArray(h?.nodes)?h.nodes:[]).filter(m=>$u(m)&&f.has(m.id)).map(m=>[m.id,m]));for(let m of u)o.set(m,{node:p.get(m)??null,at:a})}for(let l of s)if(!i.has(l)){let u=o.get(l)?.node;u&&r.nodes.push(structuredClone(u))}}route(e,n,r="file"){if(yi(e)||ho(e,r)===!1)return null;let i=yn(e,n.rules);return i&&i.target!=="off"?i.target:null}effective(e,n){let r=new Map(n.filter(i=>i.localId).map(i=>[i.localId,i.path]));return{...e,rules:e.rules.map(i=>i.sourceId&&r.has(i.sourceId)?{...i,source:r.get(i.sourceId)}:i)}}deviceName(){return this.customName||fi(xo())}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"){yl.some(o=>s.path.startsWith(o+"/"))||(r.files++,r.size+=s.size);for(let o=Ot(s.path);o;o=Ot(o)){let a=n.get(o);a&&(a.size+=s.size,a.files++)}}let i=new Map(e.filter(s=>s.kind==="file"&&/^agents\/[^/]+\/config\.toml$/.test(s.path)).map(s=>[s.path.slice(0,-12),s]));this.others=r,this.sources=[...n].sort(([s],[o])=>qt(s)-qt(o)||(s<o?-1:1)).slice(0,2e3).map(([s,o])=>({path:s,kind:"folder",size:o.size,files:o.files,...ar(s)&&i.has(s)?{agent:!0}:{}})),this.sourcesAt=Date.now(),this.readAgentNames(i)}async readAgentNames(e){for(let n of this.agentNames.keys())e.has(n)||this.agentNames.delete(n);for(let[n,r]of e){let i=`${r.mtime}:${r.size}`;if(!(this.agentNames.get(n)?.key===i||r.size>256*1024))try{this.agentNames.set(n,{key:i,...wl((await xn(r)).toString("utf8"))})}catch{this.agentNames.set(n,{key:i})}}}async rename(e){let n=typeof e=="string"?e.trim():"";if(n.length>64||/[\u0000-\u001f\u007f]/.test(n))throw Error("Invalid device name");let r=await this.getSession(),i=n||fi(xo()),s=Js(i,this.devices,this.deviceId);if(s)throw Error(s==="taken"?"device_name_taken":s==="reserved"?"device_name_reserved":"device_name_invalid");return await this.json(r,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:i,unique:!0}),await this.saveName(n),await this.register(r,!0),this.deviceName()}async saveName(e){let n=De(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+ot();try{await mr(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await Ii(r,n)}finally{await wr(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<Ri){r-this.devicesAt>=Ri&&await this.refreshDevices(e);return}let i=(a,c)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:a,...c?{unique:!0}:{}}),s=async()=>(await this.json(e,"devices")).devices,o=a=>/device_name_(taken|reserved|invalid)/.test(Ne(a));try{await i(this.deviceName(),!0)}catch(a){if(!o(a))throw a;let c=!1;if(!this.customName){let l=fi(xo());for(let u=0;u<5&&!c;u++){let f=await s(),h=null;for(let p=2;p<100&&!h;p++){let m=`${l} ${p}`;Js(m,f,this.deviceId)||(h=m)}if(!h)break;try{await i(h,!0),await this.saveName(h),c=!0}catch(p){if(!o(p))throw p}}}c||await i(this.deviceName(),!1)}this.registered={name:this.deviceName(),at:r},await this.refreshDevices(e)}async refreshDevices(e){this.devicesAt=Date.now(),this.devices=(await this.json(e,"devices")).devices,await this.cacheDevices()}cachedDevices="";async cacheDevices(){let e=De(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let a=JSON.parse(await gr(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])),i=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((f,h)=>typeof f=="string"&&f!==a.name&&l.lastIndexOf(f)===h).slice(-5);return{id:a.id,name:a.name,...u.length?{aliases:u}:{}}}),s=JSON.stringify({devices:i});if(s===this.cachedDevices)return;let o=e+".tmp-"+ot();try{await mr(o,s,{mode:384,flag:"wx"}),await Ii(o,e),this.cachedDevices=s}catch(a){this.error=Ne(a)}finally{await wr(o).catch(()=>{})}}async setup(e){let n=await this.getSession(),r=e&&typeof e=="object"?e:{};if(n.stored.config.enabled||n.stored.config.revision>0)return null;let i=bn(kl(n.stored.config),"","off");for(let a of It)a.id!=="agents"&&r[a.id]===!1&&(i=bn(i,a.path,"off"));let s=new Set(this.sources.filter(a=>a.agent).map(a=>a.path.slice(7))),o=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(a=>typeof a=="string"&&s.has(a)):[];return this.preview(El(i,o))}async snapshot(e,n){(e==="zh"||e==="en")&&(this.uiLocale=e);let r=await this.getSession(),i=n&&typeof n=="object"?n:{};if(i.focused===!0){let s=!this.focused;this.focused=!0,this.touch(),s&&r.stored.config.enabled&&!r.stored.paused&&Date.now()-this.lastRunAt>3e4&&this.kick()}else i.focused===!1&&(this.focused=!1);return!r.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(r).then(s=>{this.session===r&&this.setSources(s)},()=>{})),i.devices===!0&&Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(r).catch(()=>{})),{available:!0,account:Ce(r.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(r.stored.config),running:this.running,paused:r.stored.paused,phase:this.phase,jobs:structuredClone(r.stored.jobs),devices:this.devices,sources:this.sources.map(s=>{let o=s.agent&&this.agentNames.get(s.path);return o?{...s,...o.name?{name:o.name}:{},...o.nameEn?{nameEn:o.nameEn}:{}}:s}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...r.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...r.stored.agentArchive?{agentArchive:(({rewritten:s,...o})=>o)(r.stored.agentArchive)}:{}}}stats(){let e=this.host.accountId(),n=e&&this.session?.account===e?this.session:null,r=n?.stored,i={},s=e&&e===this.logAccount?this.runLog.snapshot():new cr().snapshot();for(let o of r?.jobs??[])i[o.state]=(i[o.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(o=>({source:o.source,target:o.target})),backlog:r?{jobs:i,blocked:[...this.blocked.values()].reduce((o,a)=>o+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 i=Ut(e,n.stored.config.revision+1),s=await this.host.contentSync.roots();this.guard(n);let o=await this.previewScan(n,s),a=this.effective(i,o);if(n.stored.agentArchive?.state==="running"&&o.some(S=>S.kind==="file"&&S.path.startsWith("agents/")&&this.route(S.path,a)))throw Error("agent_archive_running");let c=await this.manifests(n,a);this.guard(n),this.setSources(o);let l=0,u=0,f=0,h=0,p=new Map;for await(let S of Wt(o.filter(g=>g.kind==="file"))){let g=this.route(S.path,a);if(!g)continue;let P=c.get(g)?.nodes.find(D=>!D.deleted&&D.kind==="file"&&D.path===S.path);if(S.size>Rn){l++,h+=S.size;continue}let x=Ce(await xn(S));this.guard(n),p.set(S.path,x),x!==P?.hash&&(l++,h+=S.size,P?.version&&f++)}let m=i.enabled?this.agentAsks(n,o,a,c,p):[];for(let[S,g]of c)for await(let P of Wt(g.nodes))!P.deleted&&P.kind==="file"&&P.version&&this.route(P.path,a)===S&&!o.some(x=>x.path===P.path)&&u++;let w=this.signature(o,c,s),y={token:ot(),config:a,upload:i.enabled?l:0,download:i.enabled?u:0,conflicts:i.enabled?f:0,bytes:i.enabled?h:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,...m.length?{agentAsks:m}:{}};return this.previewValue={value:y,account:n.account,signature:w},y}signature(e,n,r){return Ce(JSON.stringify([r,e.map(i=>[i.path,i.size,i.mtime,i.inode]),[...n].map(([i,s])=>[i,s.nodes.map(o=>[o.id,o.revision,o.version,o.deleted])])]))}async apply(e,n){let r=this.serial,i;this.serial=new Promise(s=>{i=s}),await r;try{let s=await this.getSession(),o=this.previewValue;if(!o||o.value.token!==e||o.account!==s.account||o.value.expiresAt<Date.now()||o.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let a=o.value.agentAsks??[],c=Vm(n);this.resolving=!0;try{let l=await this.host.contentSync.roots(),u=await this.previewScan(s,l),f=await this.manifests(s,o.value.config);if(this.signature(u,f,l)!==o.signature)throw Error("preview_changed");let h=[];for(let y of l)await Ao(y.root).catch(g=>{if(g.code==="ENOENT")return null;throw g})&&h.push({...y,...await Un(y.root)});let p=structuredClone(o.value.config);for(let y of p.rules){let S=u.find(g=>g.kind==="folder"&&g.path===y.source);S&&(y.sourceId=await vo(S))}let m=a.length?Ut(a.reduce((y,S)=>bn(y,`agents/${S.slug}`,"off"),p),p.revision):p;if(this.guard(s),this.previewValue!==o||o.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");let w=structuredClone(s.stored);s.stored.config=m,s.stored.owned=!0,s.stored.paused=!1,delete s.stored.unconfirmed;for(let[y,S]of Object.entries(s.stored.files))(w.config.enabled!==s.stored.config.enabled||!Wu(w.roots??h,h)||this.route(S.path,w.config)!==this.route(S.path,s.stored.config))&&delete s.stored.files[y];for(let[y,S]of Object.entries(s.stored.folders))(w.config.enabled!==s.stored.config.enabled||!Wu(w.roots??h,h)||this.route(S.path,w.config,"folder")!==this.route(S.path,s.stored.config,"folder"))&&delete s.stored.folders[y];s.stored.roots=h,s.rootIdentities=new Map(h.map(y=>[y.root,y])),await this.persist(s);try{await this.accountWrite(s,y=>this.host.contentSync.claim(!0,y))}catch(y){throw s.stored=w,await this.persist(s),await this.accountWrite(s,S=>this.host.contentSync.claim(w.owned,S)).catch(()=>{}),y}if(this.previewValue=null,s.roots=l,await this.watchRoots(s),a.length)try{await this.resolveAsks(s,a,c,p)}catch(y){throw this.fault(Ne(y)),y}s.stored.accountReview&&(delete s.stored.accountReview,await this.persist(s))}finally{this.resolving=!1}}finally{i()}this.run()}async pause(e){let n=await this.getSession();if(!e&&n.stored.accountReview)throw Error("content_account_changed_preview_required");n.stored.paused=e,e?(n.abort.abort(new Error("paused")),this.phase="paused"):this.running||(n.abort=new AbortController),await this.persist(n),e||this.run()}job(e,n,r,i,s){let o=e.stored.jobs.findLast(c=>c.path===n&&c.target===r&&c.direction===i&&["failed","paused","queued"].includes(c.state));if(o)return Object.assign(o,{state:"active",done:0,size:s,at:Date.now(),error:void 0,finishedAt:void 0}),o;let a={id:ot(),path:n,target:r,direction:i,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,i,s,o){if(this.guard(e),e.stored.paused)throw Error("paused");this.activeAt=Date.now();let a=this.job(e,n,r,i,s);try{let c=await o(a);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(a),i==="upload"?lt("content","uploads"):i==="download"&&lt("content","downloads");let l=Fm[i];return l&&this.tally(l),c}catch(c){throw a.state=e.stored.paused?"paused":"failed",a.error=Ne(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.lastRunAt=n,this.wroteLocal=!1;let r=new Set,i,s=!1,o=!1;try{if(i=await this.getSession(),this.runAccount=i.account,i.stored.accountReview){this.error="content_account_changed_preview_required";return}if(await this.archiveStep(i),!i.stored.config.enabled||i.stored.paused)return;i.abort.signal.aborted&&(i.abort=new AbortController),this.blocked.clear(),this.phase="scanning",this.error=void 0,s=!0,this.httpStatus=0,this.live()&&this.runLog.begin(n);let a=await this.host.contentSync.roots();this.guard(i),i.roots=a,await this.host.contentSync.agentFiles?.prepare().catch(y=>{this.error=Ne(y)}),this.guard(i);let c=await this.scan(i,a);await this.recordRoots(i);let l=this.effective(i.stored.config,c),u=await this.manifests(i,l);this.guard(i),await this.register(i),this.openJobs=new Set(i.stored.jobs.filter(y=>["failed","paused","active"].includes(y.state)&&["upload","download","merge"].includes(y.direction)).map(y=>y.target+"\0"+y.path)),await this.folders(i,l,c,u),await this.recordRoots(i),await this.fileRenames(i,l,c,u),c=await this.scan(i,a),l=this.effective(l,c),i.stored.config=l,this.setSources(c),this.phase="syncing";let f=y=>y.endsWith("/"+pr),h=new Set,p=new Set,m=y=>y.startsWith("agents/")?y.slice(0,y.lastIndexOf("/")+1):null,w=y=>y.endsWith("/MEMORY.md")&&p.has(m(y)??"");for(let[y,S]of u)for await(let g of Wt(S.nodes.filter(P=>P.kind==="file"&&!P.busy&&f(P.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(g.path,l)!==y||c.some(P=>P.path===g.path))){if(this.isBlocked(y,g.path)){p.add(m(g.path)??"");continue}h.add(g.id);try{await this.missing(i,g,y,c,l)}catch(P){this.error=Ne(P),p.add(m(g.path)??"")}}}for await(let y of Wt(c.filter(S=>S.kind==="file").sort((S,g)=>+!f(S.path)-+!f(g.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");let S=this.route(y.path,l);if(!(!S||w(y.path))){if(this.isBlocked(S,y.path)){f(y.path)&&p.add(m(y.path)??"");continue}try{await this.file(i,l,y,S,u.get(S))==="held"&&r.add(y.path)}catch(g){this.error=Ne(g),f(y.path)&&p.add(m(y.path)??"")}}}for(let[y,S]of u)for await(let g of Wt(S.nodes.filter(P=>P.kind==="file"&&!P.busy&&!h.has(P.id)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.isBlocked(y,g.path)||this.route(g.path,l)!==y||c.some(P=>P.path===g.path)||w(g.path))){if(this.holdGone(g.path)){r.add(g.path);continue}try{await this.missing(i,g,y,c,l)}catch(P){this.error=Ne(P)}}}await this.cleanupFolders(i,l,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(i).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=Ri)&&(await this.accountWrite(i,y=>this.host.contentSync.changed(y)),this.changedAt=Date.now()),this.guard(i),await this.persist(i),await this.pruneBases(i),o=!0}catch(a){this.error=Ne(a)}finally{this.phase=i?.stored.paused?"paused":"idle",s&&(this.noteHealth(n,o),this.live()&&this.runLog.end(o));for(let[a,c]of this.dirty)!r.has(a)&&c.last<n&&this.dirty.delete(a);i&&this.host.accountId()===i.account&&(await this.persist(i).catch(()=>{}),!this.closed&&i.abort.signal.aborted&&!i.stored.paused&&i.stored.config.enabled&&(i.abort=new AbortController,this.again=!0)),this.running=!1,this.runAccount=null,this.again&&!this.closed?(this.again=!1,queueMicrotask(()=>void this.run())):this.schedule(),e()}}noteHealth(e,n){n&&(lt("content","cycles"),lt("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?Zr(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<Oo(e)&&r-n.first<Yu}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=Ne(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(Ne(r),[n])}async folders(e,n,r,i){let s=r.filter(a=>a.kind==="folder"),o=new Map;for(let a of s)if(a.localId){if(o.has(a.localId))throw Error(`Duplicate folder sync identity: ${a.path}`);o.set(a.localId,a.path)}for(let[a,c]of i){for await(let l of Wt(c.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,f)=>qt(u.path)-qt(f.path))))if(!this.isBlocked(a,l.path))try{let u=Object.entries(e.stored.folders).find(([h,p])=>h.startsWith(a+":")&&p.id===l.id)?.[1],f=(u?s.find(h=>h.localId===u.localId):null)??s.find(h=>h.path===l.path);if(u&&f&&l.path!==u.path&&f.path!==u.path&&l.path!==f.path)throw Error(`Concurrent folder rename: ${f.path}`);if(u&&f&&l.path!==u.path&&f.path===u.path){if(this.route(f.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,f.path,a,"rename",null,()=>Eo(e.roots,f.path,l.path,(p,m)=>this.lock(e,p,m)));let h=f.path;for(let p of r)if(p.path===h||p.path.startsWith(h+"/")){let m=p.path;p.path=l.path+m.slice(h.length);let w=ze(e.roots,p.path);p.physical=De(w.root,w.relative)}for(let[p,m]of Object.entries(e.stored.files))p.startsWith(a+":")&&m.path.startsWith(u.path+"/")&&(m.path=l.path+m.path.slice(u.path.length));for(let p of n.rules)(p.source===u.path||p.source.startsWith(u.path+"/"))&&(p.source=l.path+p.source.slice(u.path.length))}if(!f&&this.route(l.path,n,"folder")===a&&!u){await Bu(e.roots,l.path,(p,m)=>this.lock(e,p,m));let h=(await this.scan(e)).find(p=>p.path===l.path);h&&(r.push(h),s.push(h))}}catch(u){this.block(a,l.path,u),this.tally("folderConflicts");let f=Object.entries(e.stored.folders).find(([h,p])=>h.startsWith(a+":")&&p.id===l.id)?.[1];f&&this.block(a,f.path,u)}for await(let l of Wt(s.sort((u,f)=>qt(u.path)-qt(f.path))))if(!this.isBlocked(a,l.path))try{let u=this.route(l.path,n,"folder"),f=n.rules.some(S=>S.target===a&&S.source.startsWith(l.path+"/"));if(u!==a&&!f||ho(l.path,"folder")===!1)continue;let h=await vo(l),p=e.stored.folders[$e(a,h)],m=p?c.nodes.find(S=>S.id===p.id):c.nodes.find(S=>S.path===l.path&&!S.deleted);if(m?.deleted){if(p){let S=!1;for(let g of r.filter(P=>P.kind==="file"&&P.path.startsWith(l.path+"/")&&this.route(P.path,n)===a)){let P=Object.entries(e.stored.files).find(([x,D])=>x.startsWith(a+":")&&D.path===g.path)?.[1];if(!P){S=!0;break}if(!this.sameAsShadow(P,g)){let x=Ce(await xn(g));if(x!==P.hash&&!(P.memoryDeleted&&Ro(g.path)&&x===Sr)){S=!0;break}}}if(!S)continue}m=void 0}let w=Ot(l.path),y=w?c.nodes.find(S=>S.path===w&&S.kind==="folder"&&!S.deleted)?.id:"";if(w&&!y)throw Error("Cloud parent is unavailable");if(!m)m=await this.json(e,a,"/nodes","POST",{id:p?ot():h,parentId:y,name:nn(l.path),kind:"folder"}),e.tombstones.get(a)?.delete(m.id),c.nodes.push(m);else if(p&&m.path!==l.path){if(m.revision!==p.revision)throw Error(`Concurrent folder rename: ${l.path}`);let S=m.path,g=await this.operation(e,l.path,a,"rename",null,()=>this.json(e,a,`/nodes/${m.id}`,"PATCH",{parentId:y,name:nn(l.path),revision:m.revision}));for(let P of c.nodes)P.path.startsWith(S+"/")&&(P.path=l.path+P.path.slice(S.length));Object.assign(m,g);for(let[P,x]of Object.entries(e.stored.files))P.startsWith(a+":")&&x.path.startsWith(S+"/")&&(x.path=l.path+x.path.slice(S.length))}e.stored.folders[$e(a,h)]={id:m.id,localId:h,path:l.path,revision:m.revision,parentId:m.parentId,name:m.name}}catch(u){this.block(a,l.path,u);let f=l.localId?e.stored.folders[$e(a,l.localId)]:void 0;f&&this.block(a,f.path,u),lt("content","conflicts"),this.tally("folderConflicts");let h=this.job(e,l.path,a,"rename",null);h.state="conflict",h.error=Ne(u),h.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let i=await this.scan(e);for(let[s,o]of r)for await(let a of Wt(o.nodes.filter(c=>c.kind==="folder"&&!c.busy).sort((c,l)=>qt(l.path)-qt(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,f])=>u.startsWith(s+":")&&f.id===a.id);if(!c)continue;let l=i.find(u=>u.path===a.path&&u.kind==="folder");if(a.deleted&&l){if(i.some(f=>f.path.startsWith(a.path+"/"))||(await yr(l.physical)).some(f=>f!==".forsion-sync-id.json"))continue;await this.operation(e,a.path,s,"delete",null,()=>this.lock(e,l.physical,()=>{ut(l.root,br(l.root,l.physical).split(In).join("/"));let f=Im(l.physical);if(f.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let h=De(l.physical,".forsion-sync-id.json"),p=f.length?Tn(h):null;p&&_o(h);try{Rm(l.physical)}catch(m){if(p)try{Dm(h,p,{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)||o.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,i){if(n.size!==void 0&&n.size>Rn)throw Error("File exceeds 50 MB content limit");let s=await this.request(e,r,`/nodes/${n.id}/content`),o=[],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>Rn)throw await l.cancel(),Error("Content too large");o.push(u.value),i.done=a}}let c=Buffer.concat(o);if(n.hash&&Ce(c)!==n.hash)throw Error("Cloud file changed during download");return c}async fileRenames(e,n,r,i){for(let[s,o]of i)for(let a of o.nodes.filter(c=>c.kind==="file"&&!c.deleted&&!c.busy)){let c=e.stored.files[$e(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,()=>Eo(e.roots,l.path,a.path,(u,f)=>this.lock(e,u,f))),c.path=a.path}catch(u){this.block(s,l.path,u),this.block(s,a.path,u)}}}async upload(e,n,r,i,s){if(i.length>Rn)throw Error("File exceeds 50 MB content limit");this.guard(e);let o=this.host.readCreds(),a=qu.from((async function*(){for(let l=0;l<i.length;l+=64*1024)e.abort.signal.throwIfAborted(),yield i.subarray(l,l+64*1024),s.done=Math.min(i.length,l+64*1024)})()),c=await fetch(o.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(r)}/nodes/${n.id}/content`,{method:"PUT",headers:{Authorization:`Bearer ${o.token}`,"X-Content-Device":this.deviceId,"Content-Type":"application/octet-stream","Content-Length":String(i.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,i,s,o){let a=$e(n,r.id),c=Ce(i),l=To(i);l&&i.length>=Vu&&await this.keepBase(e,c,i);for(let u of e.stored.jobs)u.path===r.path&&u.target===n&&["failed","paused","active"].includes(u.state)&&["upload","download","merge"].includes(u.direction)&&this.done(u);e.stored.pendingUploads&&delete e.stored.pendingUploads[a],delete e.stored.unconfirmed?.[a],e.stored.files[a]={id:r.id,path:r.path,version:r.version,hash:c,...l&&i.length<Vu?{base:i.toString("utf8")}:{},...o?{inode:o.inode,stat:o.key,statAt:o.at}:s?{inode:s.inode}:{}}}async seen(e,n,r){let i=ze(e.roots,n),s=await Dt(De(i.root,...i.relative.split("/"))).catch(()=>null);if(!s?.isFile())return;let o=xi(s);return{key:hr(o),at:r,inode:o.inode}}sameAsShadow(e,n){return!this.dirty.has(n.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===hr(n)&&Wm(n)<=e.statAt-Um}unchanged(e,n,r,i,s){let o=$e(n,r.id);return this.sameAsShadow(i,s)&&i.id===r.id&&i.path===s.path&&!r.busy&&!r.deleted&&r.version===i.version&&r.hash===i.hash&&!e.stored.unconfirmed?.[o]&&!e.stored.pendingUploads?.[o]&&!this.openJobs.has(n+"\0"+s.path)}hold(e,n){if(e.path.endsWith("/"+pr)||n?.stat===hr(e))return!1;let r=e.mtime,i=Date.now(),s=this.dirty.get(e.path);if(Math.floor(r)<=this.flushAt)return!1;if(s)s.last=Math.max(s.last,r);else{if(i-r>=Oo(e.path))return!1;s={first:Math.min(i,r),last:r},this.dirty.set(e.path,s)}return this.dueAt(e.path,s)>i}settled(e,n){let r=this.dirty.get(e);r&&(r.last<n?this.dirty.delete(e):r.first=n)}async keepBase(e,n,r){let i=Do(e),s=De(i,n);if(await Dt(s).then(()=>!0,()=>!1))return;await Co(i,{recursive:!0,mode:448});let o=s+".tmp-"+ot();try{await mr(o,r,{mode:384,flag:"wx"}),await Ii(o,s)}finally{await wr(o).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await gr(De(Do(e),n.hash)).catch(i=>{if(i.code==="ENOENT")return null;throw i});return r&&Ce(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(i=>i.hash)),r=Do(e);for(let i of await yr(r).catch(()=>[]))n.has(i)||await wr(De(r,i)).catch(()=>{})}async file(e,n,r,i,s){if(r.size>Rn){lt("content","skippedTooLarge",1,r.path),await this.operation(e,r.path,i,"upload",r.size,async()=>{throw Error("File exceeds 50 MB content limit")});return}let o=s.nodes.find(S=>S.kind==="file"&&!S.deleted&&S.path===r.path);if(!o){let S=Object.entries(e.stored.files).find(([g,P])=>g.startsWith(i+":")&&P.inode===r.inode&&P.path!==r.path)?.[1];if(S){let g=ze(e.roots,S.path),P=await Dt(De(g.root,g.relative)).then(async D=>xi(D).inode!==r.inode||Ot(S.path)!==Ot(r.path)?!0:(await yr(tn(r.physical))).includes(nn(S.path)),D=>D.code==="ENOENT"?!1:Promise.reject(D)),x=s.nodes.find(D=>D.id===S.id&&!D.deleted);if(!P&&x)try{if(x.path!==S.path)throw Error(`Concurrent file rename: ${r.path}`);let D=Ot(r.path),k=D?s.nodes.find(E=>E.path===D&&E.kind==="folder"&&!E.deleted)?.id:"";if(D&&!k)throw Error("Rename parent unavailable");let A=await this.operation(e,r.path,i,"rename",null,()=>this.json(e,i,`/nodes/${x.id}`,"PATCH",{name:nn(r.path),parentId:k,revision:x.revision}));Object.assign(x,A),S.path=r.path,o=x}catch(D){for(let k of new Set([S.path,x.path,r.path]))this.block(i,k,D);throw D}}}let a=o?e.stored.files[$e(i,o.id)]:Object.entries(e.stored.files).find(([S,g])=>S.startsWith(i+":")&&g.path===r.path)?.[1];if(!a&&o?.version&&i==="default"&&(a=await this.legacyBaseline(r.path,o)),o&&a&&this.unchanged(e,i,o,a,r))return;if(this.hold(r,a))return"held";let c=Date.now(),l=await xn(r),u=Ce(l),f={key:hr(r),at:c,inode:r.inode};if(this.guard(e),this.settled(r.path,c),!o){if((a?s.nodes.find(A=>A.id===a.id&&A.deleted):null)&&a&&(a.hash===u||a.memoryDeleted&&Ro(r.path)&&u===Sr)){Ro(r.path)?await this.clearDeletedMemory(e,i,r,a,l,u):(await this.operation(e,r.path,i,"delete",r.size,()=>this.trashFile(e,r,u)),this.tally("deletesLocal"),delete e.stored.files[$e(i,a.id)]);return}let g=Ot(r.path),P=g?s.nodes.find(A=>A.path===g&&!A.deleted&&A.kind==="folder")?.id:"";if(g&&!P)throw Error("Parent folder is unavailable");let x=Object.entries(e.stored.pendingUploads??{}).find(([A,E])=>A.startsWith(i+":")&&E.path===r.path&&!s.nodes.some(M=>M.id===E.id))?.[1];for(let[A,E]of Object.entries(e.stored.pendingUploads??{}))A.startsWith(i+":")&&E.path===r.path&&s.nodes.some(M=>M.id===E.id&&M.deleted)&&delete e.stored.pendingUploads[A];let D=x?.id??ot(),k=$e(i,D);(e.stored.pendingUploads??={})[k]={id:D,path:r.path},await this.persist(e),o=await this.json(e,i,"/nodes","POST",{id:D,parentId:P,name:nn(r.path),kind:"file"}),e.tombstones.get(i)?.delete(o.id),o.id!==D&&delete e.stored.pendingUploads[k],s.nodes.push(o),a=void 0}if(o.busy)return;let h=$e(i,o.id);if(o.version&&this.awaitingBytes.delete(h),o.hash===u){await this.shadow(e,i,o,l,r,f);return}if(o.hash&&e.stored.unconfirmed?.[h]===o.hash&&(await this.shadow(e,i,o,await this.operation(e,r.path,i,"download",o.size??null,S=>this.download(e,o,i,S)),r),a=e.stored.files[h]),!o.version&&a&&a.hash===u&&!e.stored.pendingUploads?.[h]){let S=this.awaitingBytes.get(h)??Date.now();if(this.awaitingBytes.set(h,S),Date.now()-S<jm)return}if(this.awaitingBytes.delete(h),!o.version||a&&o.version===a.version){(e.stored.unconfirmed??={})[h]=u,await this.persist(e);let S=await this.operation(e,r.path,i,"upload",l.length,g=>this.upload(e,o,i,l,g));Object.assign(o,S),await this.shadow(e,i,o,l,r,f);return}let p=await this.operation(e,r.path,i,"download",o.size??null,S=>this.download(e,o,i,S)),m=p,w=!1;if(!a||a.hash!==u){let S=l.toString("utf8"),g=p.toString("utf8"),P=a?await this.readBase(e,a):null,x=Buffer.from(S).equals(l)&&Buffer.from(g).equals(p)?this.host.contentSync.merge(r.path,S,P,g):null;if(x?(m=Buffer.from(x.content),w=x.conflict):w=!0,w){await this.preserveConflict(e,r.path,l)&&(lt("content","conflicts"),this.tally("conflictCopies"));let D=this.job(e,r.path,i,"merge",l.length);D.state="conflict",D.error="Both versions preserved",D.finishedAt=Date.now()}if(!m.equals(p)){let D=await this.operation(e,r.path,i,"merge",m.length,k=>this.upload(e,o,i,m,k));Object.assign(o,D)}}let y=Date.now();await this.write(e,r.path,m,u),await this.shadow(e,i,o,m,r,await this.seen(e,r.path,y))}async preserveConflict(e,n,r){let i=ze(e.roots,n),s=await et(i.root,i.relative),o=nn(n),a=Ce(r);for(let c of await yr(tn(s))){if(c.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==o||!yi(c))continue;let l=Ot(n)?Ot(n)+"/"+c:c,u=ze(e.roots,l),f=await et(u.root,u.relative),h=await Dt(f);if(h.isFile()&&h.size===r.length&&Ce(await gr(f))===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 i=1;;i++){let s=Cu(n,r,i),o=ze(e.roots,s);if(!await Dt(De(o.root,...o.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,i,s){let o=[],a=c=>c.length?Math.max(...c):null;for(let c of n){let l=c.kind==="folder"?ar(c.path):null;if(!l||pi.has(l))continue;let u=`agents/${l}/`,f=this.route(u+"config.toml",r);if(!f||Object.entries(e.stored.files).some(([y,S])=>y.startsWith(f+":")&&S.path.startsWith(u)))continue;let h=(i.get(f)?.nodes??[]).filter(y=>!y.deleted&&y.kind==="file"&&y.version&&y.path.startsWith(u)&&this.route(y.path,r)===f),p=n.filter(y=>y.kind==="file"&&y.path.startsWith(u)&&this.route(y.path,r)===f);if(!h.length||!p.length)continue;let m=new Map(h.map(y=>[y.path,y])),w=p.filter(y=>{let S=m.get(y.path);return!!S&&s.get(y.path)!==S.hash}).length;!w&&p.length===h.length&&p.every(y=>m.has(y.path))||o.push({slug:l,namespace:f,cloudFiles:h.length,localFiles:p.length,differ:w,cloudMtime:a(h.map(y=>y.mtime??0)),localMtime:a(p.map(y=>y.mtime))})}return o}async resolveAsks(e,n,r,i){for(let s of n){try{await this.resolveAsk(e,s,r[s.slug]??"merge",i)}catch(l){throw this.dropShadows(e,s.namespace,`agents/${s.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Ne(l)}`)}let o=`agents/${s.slug}`,a=i.rules.find(l=>l.source===o),c=bn(e.stored.config,o,bl(i,o));a&&(c={...c,rules:c.rules.map(l=>l.source===o?{...a,target:l.target}:l)}),e.stored.config=Ut(c,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,i){let s=n.namespace,o=`agents/${n.slug}/`;if(this.dropShadows(e,s,o),r==="local"){await this.archiveAgent(e,s,n.slug),await this.persist(e);return}let a=await this.json(e,s);this.guard(e),ki(a,s);let c=new Map(a.nodes.filter(p=>!p.deleted&&!p.busy&&p.kind==="file"&&p.version&&p.path.startsWith(o)&&this.route(p.path,i)===s).map(p=>[p.path,p])),l=p=>p.endsWith("/"+pr),u=async(p,m,w)=>{let y=Date.now();return await this.write(e,p,m,w),this.seen(e,p,y)};for(let[p,m]of c){if(!l(p))continue;let w=ze(e.roots,p);if(Ju(De(w.root,w.relative)))continue;let y=await this.operation(e,p,s,"download",m.size??null,S=>this.download(e,m,s,S));await this.shadow(e,s,m,y,void 0,await u(p,y,null))}let f=(await this.scan(e)).filter(p=>p.kind==="file"&&p.path.startsWith(o)&&this.route(p.path,i)===s&&p.size<=Rn).sort((p,m)=>+!l(p.path)-+!l(m.path)),h=await this.removedDir(e,n.slug);for(let p of f){this.guard(e);let m=await xn(p),w=Ce(m),y=c.get(p.path),S=p.path.slice(o.length);if(y&&y.hash===w){await this.shadow(e,s,y,m,p);continue}if(r==="cloud"){if(await this.keep(e,`${h}/${S}`,m),y){let k=await this.operation(e,p.path,s,"download",y.size??null,A=>this.download(e,y,s,A));await this.shadow(e,s,y,k,p,await u(p.path,k,w))}else S==="MEMORY.md"?await this.write(e,p.path,Buffer.alloc(0),w):await this.removeLocal(e,p,w);continue}if(!y)continue;let g=await this.operation(e,p.path,s,"download",y.size??null,k=>this.download(e,y,s,k)),P=s==="default"?await this.legacyBaseline(p.path,y):void 0;if(P?.hash===w){await this.shadow(e,s,y,g,p,await u(p.path,g,w));continue}let x=P?await this.readBase(e,P):null,D=To(m)&&To(g)?this.host.contentSync.merge(p.path,m.toString("utf8"),x,g.toString("utf8")):null;if(D&&!D.conflict){let k=Buffer.from(D.content);k.equals(m)||await this.write(e,p.path,k,w),await this.shadow(e,s,y,g)}else(y.mtime??0)>p.mtime?(await this.keep(e,`${h}/${S}`,m),await this.shadow(e,s,y,g,p,await u(p.path,g,w))):(await this.keep(e,`${h}/${S}`,g),await this.shadow(e,s,y,g))}await this.persist(e)}dropShadows(e,n,r){for(let[i,s]of Object.entries(e.stored.files))i.startsWith(n+":")&&s.path.startsWith(r)&&(delete e.stored.files[i],delete e.stored.unconfirmed?.[i])}async removedDir(e,n,r="agents"){let i=new Date,s=a=>String(a).padStart(2,"0"),o=`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())} ${s(i.getHours())}${s(i.getMinutes())}`;for(let a=1;;a++){let c=`${r}/.removed/${n} ${o}${a>1?` ${a}`:""}`,l=ze(e.roots,c);if(!await Dt(De(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 ko(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(ut(n.root,br(n.root,n.physical).split(In).join("/")),Ce(Tn(n.physical))!==r)throw Error("Local file changed before replacing");_o(n.physical)})}async archiveAgent(e,n,r){let i=this.host.readCreds();if(!i.token)throw Error("not_signed_in");let s=await fetch(i.cloudUrl.replace(/\/+$/,"")+"/api/remotesync/agent-archive/agent",{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({namespace:n,slug:r,opId:ot(),locale:this.locale()}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)])});this.guard(e);let o=await s.json().catch(()=>({}));if(this.guard(e),!s.ok||o?.state!=="done")throw Error(typeof o?.detail=="string"?o.detail:`agent_archive_http_${s.status}`)}async absent(e,n){this.guard(e);let r=ze(e.roots,n),i=await et(r.root,r.relative);try{return await Dt(i),!1}catch(s){if(s.code==="ENOENT")return!0;throw s}}async missing(e,n,r,i,s){let o=e.stored.files[$e(r,n.id)],a=e.stored.pendingUploads?.[$e(r,n.id)];if(n.deleted){o&&delete e.stored.files[$e(r,n.id)],a&&delete e.stored.pendingUploads[$e(r,n.id)];return}if(n.busy||o?.inode&&this.blocked.has(r)&&i.some(u=>u.kind==="file"&&u.inode===o.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[$e(r,n.id)],n.deleted=!0);return}if(o&&o.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[$e(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 Ti(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);l&&(n.path=l.path+"/"+nn(n.path))}let r=ze(e.roots,n.path),i=await et(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,o=await this.rootIdentity(e,s),a=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(a&&!ln(a,o))throw Error("Sync recovery root changed; journal retained");let c=De(s,n.stage);await Dt(c).then(()=>!0,l=>l.code==="ENOENT"?!1:Promise.reject(l))&&await this.lock(e,i,()=>{if(ut(s,n.stage,!0),Ce(Tn(c))!==n.hash)throw Error("Sync recovery content changed");ut(r.root,r.relative),Om(tn(i),{recursive:!0});let l=Ju(i)?i+` (sync recovery ${ot().slice(0,8)})`:i;try{Tm(c,l)}catch(u){if(u.code!=="EXDEV")throw u;if(Mm(c,l,Pm.COPYFILE_EXCL),Ce(Tn(l))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}_o(c)},!0),e.stored.trash=e.stored.trash.filter(l=>l!==n)}}async clearDeletedMemory(e,n,r,i,s,o){i.memoryDeleted&&i.hash===Sr&&o===Sr||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!i.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)}i.memoryDeleted=!0,await this.persist(e);let a=Date.now();s.length&&await this.write(e,r.path,Buffer.alloc(0),o);let c=await this.seen(e,r.path,a);e.stored.files[$e(n,i.id)]={...i,hash:Sr,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 i=await et(n.root,br(n.root,n.physical).split(In).join("/")),s={path:n.path,stage:".forsion-sync-trash-"+ot(),hash:r},o=De(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(Tn(De(tn(i),".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,i,()=>{if(ut(n.root,br(n.root,i).split(In).join("/")),Ce(Tn(i))!==r)throw Error("Local file changed before deletion");xm(i,o)}),await this.host.contentSync.trash(o),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 Vm(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))or.test(n)&&gl.includes(r)&&(e[n]=r);return e}function Ju(t){try{return Cm(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}na(ja);function Lv(t){Na(t.contentSync?.withWriteLock?.bind(t.contentSync)),da(t),ps(t),Xu(t),t.log("[forsion-extend] cloud account handlers registered"),is(t)?ss(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),as(t)?cs(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),Ss(t)?vs(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),Fs(t)?Ls(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),Hs(t)?zs(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),to(t)?nu(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),to(t)&&ku(t)}export{pc as ACCOUNT_SEAM,nl as AMADEUS_SEAM,rs as CONNECT_MAX_FILES,Ua as CONNECT_MAX_FILE_BYTES,Ha as CONNECT_MAX_TOTAL_BYTES,Vr as DIAGNOSTICS_VAULT,Ka as FORSION_CONNECT_LOCAL_SDK,ua as PAY_PERIODS,la as PAY_TABS,Qa as PENZOR_MAX_FILE,Re as SYNC_IPC,sl as UNIT_SEAM,zn as UPLOAD_MAX_FILE,nr as UnitCapsReporter,tr as UnitHost,qe as cloudJson,Ba as collectProjectFiles,Kr as conflictCopyPath,kp as conflictCopyVariant,Ga as connectMetaOf,fc as createAccountCloud,rl as createAmadeusCloud,Wr as createPenzorRemote,ol as createUnitHub,qr as deviceHeader,os as expectedPartsOf,Fe as forsionAccountId,Pr as forsionRefreshToken,Hn as forsionWhoami,Ss as hasAccountHost,Fs as hasAmadeusHost,is as hasConnectHost,as as hasRemoteSyncHost,Hs as hasUnitHost,Ja as makePreviewProxy,cc as multipartFrame,Wa as readConnectMeta,vs as registerAccount,Ls as registerAmadeus,Lv as registerCloud,ss as registerConnect,cs as registerPenzor,ps as registerPenzorTransfers,zs as registerUnit,Yr as safeDownloadName,Ya as scanSdkUsage,Mr as shouldRefreshToken,ls as speedOf,il as streamWorthy,Hc as stripConflictSuffix,Ep as textFingerprint,Li as tokenAgeMs,oa as tokenRemainingMs,us as uploadError,Va as writeConnectMeta};
286
286
  /*! Bundled license information:
287
287
 
288
288
  chokidar/index.js: