@forsion/extend 0.10.12 → 0.10.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/SIGNATURE +6 -6
- package/dist/desktop.mjs +60 -59
- package/dist/main.js +43 -43
- package/manifest.json +1 -1
- package/package.json +1 -1
package/dist/desktop.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var Ho=null;function aa(t){Ho=t}function Ee(){if(!Ho)throw new Error("core host not set (call setCoreHost first)");return Ho}var ca=new TextEncoder,Sd=new TextDecoder("utf-8",{ignoreBOM:!0}),jn=t=>ca.encode(t),Et=t=>Sd.decode(t),Or=t=>typeof t=="string"?ca.encode(t).length:t.length;function la(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Mr(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 ua(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ue(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,"/"),i=Uint8Array.from(atob(o),c=>c.charCodeAt(0)),s=JSON.parse(new TextDecoder().decode(i)),a=s.userId??s.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function zo(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Et(Mr(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Bo(t,e=Date.now()){let n=zo(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function da(t,e=Date.now()){let n=zo(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var vd=36e5;function Pr(t,e=Date.now()){return!!t&&Bo(t,e)>=vd}async function $r(t,e,n=8e3,r){if(!t||!e)return null;let o=t.replace(/\/+$/,"");try{let i=await fetch(`${o}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!i.ok)return null;let s=await i.json().catch(()=>null),a=typeof s?.token=="string"?s.token:"";return a&&a!==e?a:null}catch{return null}}var Fn=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,kd=(t,e)=>new Promise((n,r)=>{let o=()=>{clearTimeout(i),r(new Error("Sign-in cancelled."))},i=setTimeout(()=>{e.removeEventListener("abort",o),n()},t);e.aborted?o():e.addEventListener("abort",o,{once:!0})});function fa(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===Ue(p.cloudUrl,p.token)):null}catch{return null}},o=(f,h)=>{let p=Ue(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=zo(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]})},i=()=>{let f=t.readCreds();o(f);let h=Ue(f.cloudUrl,f.token);return(r()??[]).map(({token:p,...m})=>({...m,active:m.id===h}))},s=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=Ue(f.cloudUrl||"",f.token||""),p=r();h&&p&&n({version:1,accounts:p.filter(m=>m.id!==h)})},c=null;return{rememberForsionAccount:o,forsionAccounts:i,savedForsionAccount:s,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(T=>T.json())}catch(T){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${y}:${T?.message||T}`)}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}`,j=new URL(`${y}/auth`);j.searchParams.set("logout","1"),j.searchParams.set("app","forsion-desktop"),j.searchParams.set("redirect",g);let x=j.toString();h?.({url:x,userCode:String(S.user_code||"")}),t.openExternal(x);let M=Date.now()+(S.expires_in||600)*1e3,E=(S.interval||2)*1e3;for(;Date.now()<M;){await kd(E,m.signal),w();let T=null;try{T=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(),T.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let _=await T.json().catch(()=>({status:"pending"}));if(w(),_.status==="approved"&&_.token){let P={cloudUrl:y,token:_.token};return await p(P,w),w(),{token:_.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,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 Ln(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function Ve(t,e,n,r,o=6e4){let i=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)}),s=await i.json().catch(()=>({}));return{status:i.status,json:s}}var Ed=50*1024*1024,_d=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,i]of Object.entries(e.fields)){if(!_d.has(o)||typeof i!="string"||(r+=i.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(o))return null;n.append(o,i)}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>Ed)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 pa(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 i=_t(o.base,r.path);if(!i)return{status:0,error:"no_cloud_url"};try{let s=await Ln(o,i,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:s.status,json:await s.json().catch(()=>null)}}catch(s){return{status:0,error:String(s?.message||s)}}})}async function qo(t){if(!t.token)return"";try{let e=await Ve(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 ha=["membership","credits","storefront"],ga=["monthly","quarterly","yearly","autorenew","autorenew-quarterly"],Ad=t=>t==="autorenew-quarterly"?"autorenew&cycle=quarterly":t,xd=/^[A-Za-z0-9_-]{1,64}$/,Td=["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","agent-tool","backpack","other"],ma=t=>Td.includes(t)?t:void 0,Nr=(t,e)=>{let n=ma(e);return n?{...t,entry:n}:t};function ya(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(o,i)=>{if(!t.isTrustedSender(o))return n;let s=await t.getCloud(),a=s.base;if(!a)return{ok:!1};let c=i&&/^[a-z0-9-]+$/i.test(i)?`#${i}`:"",l=await qo(s),u=`${a}/account${l?`?${l}`:""}${c}`;return s.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(o,...i)=>{if(!t.isTrustedSender(o))return n;let s=i.length>=4,[a,c,l]=i.slice(0,3).map(y=>s&&y===null?void 0:y),u=ma(i[3]);if(a!==void 0&&!ha.includes(a))return{ok:!1,error:"invalid_tab"};if(c!==void 0&&(typeof c!="string"||!xd.test(c)))return{ok:!1,error:"invalid_plan"};if(l!==void 0&&!ga.includes(l))return{ok:!1,error:"invalid_period"};let f=(a??"membership")==="membership"&&c?`&plan=${encodeURIComponent(c)}${l?`&period=${Ad(l)}`:""}`:"",h=await t.getCloud(),p=h.base;if(!p)return{ok:!1};let m=await qo(h),w=`${p}/pay?tab=${a??"membership"}${f}${u?`&from=${u}`:""}${m?`&${m}`:""}&redirect=${encodeURIComponent(`${p}/account`)}`;return h.signal?.throwIfAborted(),await t.openExternal(w),{ok:!0}}),t.handle("auth:resumeAutoRenew",async o=>{if(!t.isTrustedSender(o))return n;let i=await t.getCloud(),s=i.base;if(!s)return{ok:!1};let a=await qo(i);if(!a.startsWith("code="))return{ok:!1,error:"handoff_unavailable"};let c=`${s}/pay?tab=membership&action=resume_autorenew&${a}&redirect=${encodeURIComponent(`${s}/account`)}`;return i.signal?.throwIfAborted(),await t.openExternal(c),{ok:!0}}),t.handle("profile:publicOrigin",async o=>{if(!t.isTrustedSender(o))return n;let{base:i}=await t.getCloud();if(!i)return{ok:!1};try{let s=await fetch(`${i}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});s.body?.cancel().catch(()=>{});let a=s.status>=300&&s.status<400?s.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 i=await r();if(!i.token)return{status:401,json:null};try{return await Ve(i,"GET","/api/token-quota/my",void 0,15e3)}catch(s){return{status:0,json:{detail:String(s?.message||s)}}}}),t.handle("account:useResetCard",async(o,...i)=>{if(!t.isTrustedSender(o))return e;let s=await r();if(!s.token)return{status:401,json:null};let a=i[0];if(a!==void 0&&a!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${String(a)}`}};let c=a??"both";try{return await Ve(s,"POST","/api/token-quota/reset-card/use",Nr({type:c},i[1]),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgConvert",async(o,i,s)=>{if(!t.isTrustedSender(o))return e;let a=await r();if(!a.token)return{status:401,json:null};if(!Number.isInteger(i)||i<1||i>100)return{status:400,json:{error:"invalid_percent"}};try{return await Ve(a,"POST","/api/token-quota/background/convert",Nr({percent:i},s),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:pointsAutoDeduct",async(o,i,s)=>{if(!t.isTrustedSender(o))return e;let a=await r();if(!a.token)return{status:401,json:null};if(typeof i!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ve(a,"POST","/api/token-quota/auto-deduct",Nr({enabled:i},s),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgAutoMain",async(o,i,s)=>{if(!t.isTrustedSender(o))return e;let a=await r();if(!a.token)return{status:401,json:null};if(typeof i!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ve(a,"POST","/api/token-quota/background/auto-main",Nr({enabled:i},s),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("feedback:submit",async(o,i)=>{if(!t.isTrustedSender(o))return n;let s=await t.getCloud();if(!s.base||!s.token)return{ok:!1,error:"not-logged-in"};if(i?.expectedAccountId!==void 0){let u=i.expectedAccountId;if(typeof u!="string"||!u||Ue(s.base,s.token)!==u)return{ok:!1,error:"account-changed"}}let a=(i?.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(i?.sessionLogJson){let u=jn(i.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};c.push({filename:i.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:la(u)})}try{let u=await Ln(s,`${s.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(o,i)=>{if(!t.isTrustedSender(o))return{status:0,error:"untrusted"};let s=i??{},a=typeof s.path=="string"?s.path:"",c=s.projectSource===void 0?null:s.projectSource;if(c!==null&&(typeof c!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(c)))return{status:0,error:"bad_project_source"};let l=Math.min(12e4,Math.max(1e3,Number(s.timeoutMs)||15e3)),u=typeof s.method=="string"?s.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=s.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,w=setTimeout(()=>m.abort(),l);try{let y=await Ln(f,h,{method:u,headers:{...p?{"Content-Type":"application/json"}:{},...c?{"X-Project-Source":c}:{}},body:p?JSON.stringify(s.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)}}),pa(t)}import{createHash as Ha}from"node:crypto";import{existsSync as Af,promises as xf,readFileSync as Tf,renameSync as If,statSync as Rf}from"node:fs";import Df from"node:path";import{setTimeout as Of}from"node:timers/promises";import{EventEmitter as rf}from"node:events";import{stat as of}from"node:fs";import{readdir as sf,stat as af}from"node:fs/promises";import*as de from"node:path";import{lstat as wa,readdir as Id,realpath as Rd,stat as Dd}from"node:fs/promises";import{join as Od,resolve as Md,sep as ba}from"node:path";import{Readable as Pd}from"node:stream";var Qe={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},an={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Qe.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(an);var Ea="READDIRP_RECURSIVE_ERROR",$d=new Set(["ENOENT","EPERM","EACCES","ELOOP",Ea]),Sa=[Qe.DIR_TYPE,Qe.EVERYTHING_TYPE,Qe.FILE_DIR_TYPE,Qe.FILE_TYPE],Nd=new Set([Qe.DIR_TYPE,Qe.EVERYTHING_TYPE,Qe.FILE_DIR_TYPE]),jd=new Set([Qe.EVERYTHING_TYPE,Qe.FILE_DIR_TYPE,Qe.FILE_TYPE]),Fd=t=>$d.has(t.code),Ld=process.platform==="win32",va=t=>!0,ka=t=>{if(t===void 0)return va;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 va},Wo=class extends Pd{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,o=n.type??an.type;this._fileFilter=ka(n.fileFilter),this._directoryFilter=ka(n.directoryFilter);let i=n.lstat?wa:Dd;Ld?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:an.depth,this._wantsDir=Nd.has(o),this._wantsFile=jd.has(o),this._wantsEverything=o===Qe.EVERYTHING_TYPE,this._root=Md(r),this._relStart=this._root.endsWith(ba)?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 s={path:this._root,depth:1};s.pending=this._exploreDir(this._root,1),this.parents=[s],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:i}=n,s=r.splice(0,e).map(c=>this._formatEntry(c,o)),a=this._isDirent?s:await Promise.all(s);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)?(i<=this._maxDepth&&this.parents.push({path:c.fullPath,depth:i+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 i=o.pending??this._exploreDir(o.path,o.depth),s=this.parents[this.parents.length-1];if(s&&!s.pending&&(s.pending=this._exploreDir(s.path,s.depth)),this.parent=await i,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await Id(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=Od(n,r),i={path:o.slice(this._relStart),fullPath:o,basename:r};return this._isDirent?(i.dirent=e,i):this._stat(o).then(s=>(i.stats=s,i),s=>{this._onError(s)})}_onError(e){Fd(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 Rd(n),o=await wa(r);if(o.isFile())return"file";if(o.isDirectory()){let i=r.length;if(n.startsWith(r)&&n[i]===ba){let s=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return s.code=Ea,this._onError(s),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function _a(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Qe.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!Sa.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${Sa.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 Wo(r)}import{watch as Ud,unwatchFile as Ca,watchFile as Hd}from"node:fs";import{realpath as Vo,lstat as zd,open as Bd,stat as xa}from"node:fs/promises";import{type as qd}from"node:os";import*as ye from"node:path";var Wd="data",Jo="end",Ta="close",Hr=()=>{};var zr=process.platform,Ko=zr==="win32",Vd=zr==="darwin",Yd=zr==="linux",Gd=zr==="freebsd",Ia=qd()==="OS400",be={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},ct=be,Jd="watch",Kd={lstat:zd,stat:xa},Jt="listeners",jr="errHandlers",cn="rawEmitters",Xd=[Jt,jr,cn],Zd=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"]),Qd=t=>Zd.has(ye.extname(t).slice(1).toLowerCase()),Go=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Un=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},ef=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Hn=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},Ra=t=>t instanceof Set?t.size===0:!t,Fr=new Map;function Aa(t,e,n,r,o){let i=(s,a)=>{n(t),o(s,a,{watchedPath:t}),a&&t!==a&&Lr(ye.resolve(t,a),Jt,ye.join(t,a))};try{return Ud(t,{persistent:e.persistent},i)}catch(s){r(s);return}}var Lr=(t,e,n,r,o)=>{let i=Fr.get(t);i&&Go(i[e],s=>{s(n,r,o)})},tf=(t,e,n,r)=>{let{listener:o,errHandler:i,rawEmitter:s}=r,a=Fr.get(e),c;if(!n.persistent)return c=Aa(t,n,o,i,s),c?c.close.bind(c):void 0;if(a)Un(a,Jt,o),Un(a,jr,i),Un(a,cn,s);else{if(c=Aa(t,n,Lr.bind(null,e,Jt),i,Lr.bind(null,e,cn)),!c)return;c.on(ct.ERROR,async l=>{let u=Lr.bind(null,e,jr);if(a&&(a.watcherUnusable=!0),Ko&&l.code==="EPERM")try{await(await Bd(t,"r")).close(),u(l)}catch{}else u(l)}),a={listeners:o,errHandlers:i,rawEmitters:s,watcher:c},Fr.set(e,a)}return()=>{Hn(a,Jt,o),Hn(a,jr,i),Hn(a,cn,s),Ra(a.listeners)&&(a.watcher.close(),Fr.delete(e),Xd.forEach(ef(a)),a.watcher=void 0,Object.freeze(a))}},Yo=new Map,nf=(t,e,n,r)=>{let{listener:o,rawEmitter:i}=r,s=Yo.get(e),a=s&&s.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(Ca(e),s=void 0),s?(Un(s,Jt,o),Un(s,cn,i)):(s={listeners:o,rawEmitters:i,options:n,watcher:Hd(e,n,(c,l)=>{Go(s.rawEmitters,f=>{f(ct.CHANGE,e,{curr:c,prev:l})});let u=c.mtimeMs;(c.size!==l.size||u>l.mtimeMs||u===0)&&Go(s.listeners,f=>f(t,c))})},Yo.set(e,s)),()=>{Hn(s,Jt,o),Hn(s,cn,i),Ra(s.listeners)&&(Yo.delete(e),Ca(e),s.options=s.watcher=void 0,Object.freeze(s))}},Ur=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,o=ye.dirname(e),i=ye.basename(e);this.fsw._getWatchedDir(o).add(i);let a=ye.resolve(e),c={persistent:r.persistent};n||(n=Hr);let l;if(r.usePolling){let u=r.interval!==r.binaryInterval;c.interval=u&&Qd(i)?r.binaryInterval:r.interval,l=nf(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})}else l=tf(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=ye.dirname(e),i=ye.basename(e),s=this.fsw._getWatchedDir(o),a=n;if(s.has(i))return;let c=async(u,f)=>{if(this.fsw._throttle(Jd,e,5)){if(!f||f.mtimeMs===0)try{let h=await xa(e);if(this.fsw.closed)return;let p=h.atimeMs,m=h.mtimeMs;if((!p||p<=m||m!==a.mtimeMs)&&this.fsw._emit(ct.CHANGE,e,h),(Vd||Yd||Gd)&&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(o,i)}else if(s.has(i)){let h=f.atimeMs,p=f.mtimeMs;(!h||h<=p||p!==a.mtimeMs)&&this.fsw._emit(ct.CHANGE,e,f),a=f}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ct.ADD,e,0))return;this.fsw._emit(ct.ADD,e,n)}return l}async _handleSymlink(e,n,r,o){if(this.fsw.closed)return;let i=e.fullPath,s=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Vo(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(s.has(o)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(ct.CHANGE,r,e.stats)):(s.add(o),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(ct.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,n,r,o,i,s,a){e=ye.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,f=this.fsw._readdirp(e,{fileFilter:h=>r.filterPath(h),directoryFilter:h=>r.filterDir(h)});if(f)return f.on(Wd,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===o||!o&&!l.has(p))&&(this.fsw._incrReadyCount(),m=ye.join(i,ye.relative(i,m)),this._addToNodeFs(m,n,r,s+1))}}).on(ct.ERROR,this._boundHandleError),new Promise((h,p)=>{if(!f)return p();f.once(Jo,()=>{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,o,i,s,a)})})}async _handleDir(e,n,r,o,i,s,a){let c=this.fsw._getWatchedDir(ye.dirname(e)),l=c.has(ye.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(ct.ADD_DIR,e,n),c.add(ye.basename(e)),this.fsw._getWatchedDir(e);let u,f,h=this.fsw.options.depth;if((h==null||o<=h)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,r,s,i,e,o,u),this.fsw.closed))return;f=this._watchWithNodeFs(e,(p,m)=>{m&&m.mtimeMs===0||this._handleRead(p,!1,s,i,e,o,u)})}return f}async _addToNodeFs(e,n,r,o,i){let s=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return s(),!1;let a=this.fsw._getWatchHelpers(e);r&&(a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await Kd[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return s(),!1;let l=this.fsw.options.followSymlinks,u;if(c.isDirectory()){let f=ye.resolve(e),h=l?await Vo(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,o,i,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 Vo(e):e;if(this.fsw.closed)return;let h=ye.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(ct.ADD,a.watchPath,c),u=await this._handleDir(h,c,n,o,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 s(),u&&this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return s(),e}}};var Xo="/",cf="//",$a=".",lf="..",uf="string",df=/\\/g,Na=/\/\//g,ff=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,pf=/^\.[/\\]/;function Br(t){return Array.isArray(t)?t:[t]}var Zo=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function hf(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=de.relative(t.path,e);return n?!n.startsWith("..")&&!de.isAbsolute(n):!1}return!1}:()=>!1}function gf(t){if(typeof t!="string")throw new Error("string expected");t=de.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(Na,"/"),e&&(t="/"+t),t}function Da(t,e,n){let r=gf(e);for(let o=0;o<t.length;o++){let i=t[o];if(i(r,n))return!0}return!1}function mf(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Br(t).map(o=>hf(o));return e==null?(o,i)=>Da(r,o,i):Da(r,e)}var Oa=t=>{let e=Br(t).flat();if(!e.every(n=>typeof n===uf))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(ja)},Ma=t=>{let e=t.replace(df,Xo),n=!1;return e.startsWith(cf)&&(n=!0),e=e.replace(Na,Xo),n&&(e=Xo+e),e},ja=t=>Ma(de.normalize(Ma(t))),Pa=(t="")=>e=>typeof e=="string"?ja(de.isAbsolute(e)?e:de.join(t,e)):e,yf=(t,e)=>de.isAbsolute(t)?t:de.join(e,t),wf=Object.freeze(new Set),Qo=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!==$a&&e!==lf&&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 sf(r)}catch{this._removeWatcher&&this._removeWatcher(de.dirname(r),de.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=Hr,this.items=wf,Object.freeze(this)}},bf="stat",Sf="lstat",ei=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let o=e;this.path=e=e.replace(pf,""),this.watchPath=o,this.fullWatchPath=de.resolve(o),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=n,this.statMethod=n?bf:Sf}entryPath(e){return de.join(this.watchPath,de.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)}},qr=class extends rf{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?Br(e.ignored):Br([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};Ia&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?o.usePolling=!1:c==="true"||c==="1"?o.usePolling=!0:o.usePolling=!!c}let s=process.env.CHOKIDAR_INTERVAL;s&&(o.interval=Number.parseInt(s,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Hr,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=o,this._nodeFsHandler=new Ur(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 i=Oa(e);return o&&(i=i.map(s=>yf(s,o))),i.forEach(s=>{this._removeIgnoredPath(s)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async s=>{let a=await this._nodeFsHandler._addToNodeFs(s,!r,void 0,0,n);return a&&this._emitReady(),a})).then(s=>{this.closed||s.forEach(a=>{a&&this.add(de.dirname(a),de.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=Oa(e),{cwd:r}=this.options;return n.forEach(o=>{!de.isAbsolute(o)&&!this._closers.has(o)&&(r&&(o=de.join(r,o)),o=de.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 i=(this.options.cwd?de.relative(this.options.cwd,r):r)||$a;e[i]=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 o=this.options;Ko&&(n=de.normalize(n)),o.cwd&&(n=de.relative(o.cwd,n));let i=[n];r!=null&&i.push(r);let s=o.awaitWriteFinish,a;if(s&&(a=this._pendingWrites.get(n)))return a.lastChange=new Date,this;if(o.atomic){if(e===be.UNLINK)return this._pendingUnlinks.set(n,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(be.ALL,...c),this._pendingUnlinks.delete(l)})},typeof o.atomic=="number"?o.atomic:100),this;e===be.ADD&&this._pendingUnlinks.has(n)&&(e=be.CHANGE,this._pendingUnlinks.delete(n))}if(s&&(e===be.ADD||e===be.CHANGE)&&this._readyEmitted){let c=(l,u)=>{l?(e=be.ERROR,i[0]=l,this.emitWithAll(e,i)):u&&(i.length>1?i[1]=u:i.push(u),this.emitWithAll(e,i))};return this._awaitWriteFinish(n,s.stabilityThreshold,e,c),this}if(e===be.CHANGE&&!this._throttle(be.CHANGE,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===be.ADD||e===be.ADD_DIR||e===be.CHANGE)){let c=o.cwd?de.join(o.cwd,n):n,l;try{l=await af(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(e,i),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 o=this._throttled.get(e);if(!o)throw new Error("invalid throttle");let i=o.get(n);if(i)return i.count++,!1;let s,a=()=>{let l=o.get(n),u=l?l.count:0;return o.delete(n),clearTimeout(s),l&&clearTimeout(l.timeoutObject),u};s=setTimeout(a,r);let c={timeoutObject:s,clear:a,count:0};return o.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,o){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let s=i.pollInterval,a,c=e;this.options.cwd&&!de.isAbsolute(e)&&(c=de.join(this.options.cwd,e));let l=new Date,u=this._pendingWrites;function f(h){of(c,(p,m)=>{if(p||!u.has(e)){p&&p.code!=="ENOENT"&&o(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),o(void 0,m)):a=setTimeout(f,s,m)})}u.has(e)||(u.set(e,{lastChange:l,cancelWait:()=>(u.delete(e),clearTimeout(a),r)}),a=setTimeout(f,s))}_isIgnored(e,n){if(this.options.atomic&&ff.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,i=(this.options.ignored||[]).map(Pa(r)),a=[...[...this._ignoredPaths].map(Pa(r)),...i];this._userIgnored=mf(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new ei(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=de.resolve(e);return this._watched.has(n)||this._watched.set(n,new Qo(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let o=de.join(e,n),i=de.resolve(o);if(r=r??(this._watched.has(o)||this._watched.has(i)),!this._throttle("remove",o,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(o).getChildren().forEach(h=>this._remove(o,h));let c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let u=o;if(this.options.cwd&&(u=de.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===be.ADD)return;this._watched.delete(o),this._watched.delete(i);let f=r?be.UNLINK_DIR:be.UNLINK;l&&!this._isIgnored(o)&&this._emit(f,o),this._closePath(o)}_closePath(e){this._closeFile(e);let n=de.dirname(e);this._getWatchedDir(n).remove(de.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},o=_a(e,r);return this._streams.add(o),o.once(Ta,()=>{o=void 0}),o.once(Jo,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function ti(t,e={}){let n=new qr(e);return n.add(t),n}var Fa={watch:ti,FSWatcher:qr};import{execFile as vf}from"node:child_process";import{stat as La}from"node:fs/promises";import{resolve as kf}from"node:path";import{promisify as Ef}from"node:util";function Kt(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 lt(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Ua=Ef(vf);function _f(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 Cf(t){if(process.platform!=="darwin")return;let{stdout:e}=await Ua("/bin/df",["-P",kf(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
|
|
2
|
-
`).slice(1).map(
|
|
3
|
-
`,"utf8")}catch{}}var
|
|
1
|
+
var ms=null;function Ha(t){ms=t}function Ee(){if(!ms)throw new Error("core host not set (call setCoreHost first)");return ms}var za=new TextEncoder,wf=new TextDecoder("utf-8",{ignoreBOM:!0}),nr=t=>za.encode(t),Ct=t=>wf.decode(t),ei=t=>typeof t=="string"?za.encode(t).length:t.length;function Ba(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function ti(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),n=>n.charCodeAt(0))}async function qa(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ve(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let i=r.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(i),l=>l.charCodeAt(0)),a=JSON.parse(new TextDecoder().decode(s)),o=a.userId??a.sub;return typeof o!="string"&&typeof o!="number"||!String(o).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(o)}`}catch{return null}}function ys(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Ct(ti(e)));return n&&typeof n=="object"?n:null}catch{return null}}function ws(t,e=Date.now()){let n=ys(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Wa(t,e=Date.now()){let n=ys(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var bf=36e5;function ni(t,e=Date.now()){return!!t&&ws(t,e)>=bf}async function ri(t,e,n=8e3,r){if(!t||!e)return null;let i=t.replace(/\/+$/,"");try{let s=await fetch(`${i}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!s.ok)return null;let a=await s.json().catch(()=>null),o=typeof a?.token=="string"?a.token:"";return o&&o!==e?o:null}catch{return null}}var rr=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,Sf=(t,e)=>new Promise((n,r)=>{let i=()=>{clearTimeout(s),r(new Error("Sign-in cancelled."))},s=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);e.aborted?i():e.addEventListener("abort",i,{once:!0})});function Ga(t,e){let n=f=>e.write(JSON.stringify(f,null,2)),r=()=>{let f;try{f=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(f===null)return[];try{let g=JSON.parse(f);return Array.isArray(g.accounts)?g.accounts.filter(p=>p&&typeof p.token=="string"&&p.id===Ve(p.cloudUrl,p.token)):null}catch{return null}},i=(f,g)=>{let p=Ve(f.cloudUrl||"",f.token||"");if(!p||!f.token||!f.cloudUrl)return;let m=r();if(!m)return;let y=m.find(h=>h.id===p),b=ys(f.token),_={...y,id:p,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:g?.username||y?.username||b?.username,nickname:g?.nickname||y?.nickname};JSON.stringify(y)!==JSON.stringify(_)&&n({version:1,accounts:[...m.filter(h=>h.id!==p),_]})},s=()=>{let f=t.readCreds();i(f);let g=Ve(f.cloudUrl,f.token);return(r()??[]).map(({token:p,...m})=>({...m,active:m.id===g}))},a=f=>{let g=r()?.find(p=>p.id===f);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},o=f=>{let g=Ve(f.cloudUrl||"",f.token||""),p=r();g&&p&&n({version:1,accounts:p.filter(m=>m.id!==g)})},l=null;return{rememberForsionAccount:i,forsionAccounts:s,savedForsionAccount:a,forgetForsionAccount:o,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(f,g,p)=>{if(l)throw new Error("A sign-in is already in progress.");if(!f)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;l=m;let y=()=>{if(m.signal.aborted||l!==m)throw new Error("Sign-in cancelled.")};try{let b=f.replace(/\/+$/,""),_;try{_=await fetch(`${b}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(D=>D.json())}catch(D){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${b}:${D?.message||D}`)}if(y(),!_?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let h=_.verification_uri_complete||`${_.verification_uri}?code=${_.user_code}`,T=new URL(`${b}/auth`);T.searchParams.set("logout","1"),T.searchParams.set("app","forsion-desktop"),T.searchParams.set("redirect",h);let v=T.toString();g?.({url:v,userCode:String(_.user_code||"")}),t.openExternal(v);let I=Date.now()+(_.expires_in||600)*1e3,E=(_.interval||2)*1e3;for(;Date.now()<I;){await Sf(E,m.signal),y();let D=null;try{D=await fetch(`${b}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:_.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),D.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let x=await D.json().catch(()=>({status:"pending"}));if(y(),x.status==="approved"&&x.token){let L={cloudUrl:b,token:x.token};return await p(L,y),y(),{token:x.token,cloudUrl:b}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===m&&(l=null)}},readAccounts:()=>r()??[]}}function Nt(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,i;try{r=new URL(n),i=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||i.origin!==r.origin||!i.pathname.startsWith("/api/")?null:i.toString()}function ir(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function Ze(t,e,n,r,i=6e4){let s=await(t.fetch??fetch)(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token&&!t.fetch?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(i)}),a=await s.json().catch(()=>({}));return{status:s.status,json:a}}var vf=50*1024*1024,kf=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function Ef(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[i,s]of Object.entries(e.fields)){if(!kf.has(i)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(i))return null;n.append(i,s)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>vf)return null;n.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:`${e.id?`/market/mine/${e.id}/update`:"/market/submit"}${e.dryRun===!0?"?dryRun=1":""}`,body:n}}function Va(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=Ef(n);if(!r)return{status:400,json:{error:"invalid_request"}};let i=await t.getCloud();if(!i.token)return{status:401,error:"not_signed_in"};let s=Nt(i.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let a=await ir(i,s,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,error:String(a?.message||a)}}})}async function bs(t){if(!t.token)return"";try{let e=await Ze(t,"POST","/api/auth/handoff",{},5e3);if(e.status===200&&typeof e.json?.code=="string"&&e.json.code)return`code=${encodeURIComponent(e.json.code)}`;if((e.status===404||e.status===405)&&!t.fetch)return`token=${encodeURIComponent(t.token)}`}catch{}return""}var Ya=["membership","credits","storefront"],Ja=["monthly","quarterly","yearly","autorenew","autorenew-quarterly"],_f=t=>t==="autorenew-quarterly"?"autorenew&cycle=quarterly":t,Cf=/^[A-Za-z0-9_-]{1,64}$/,Af=["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","agent-tool","backpack","other"],Ka=t=>Af.includes(t)?t:void 0,ii=(t,e)=>{let n=Ka(e);return n?{...t,entry:n}:t};function Xa(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(i,s)=>{if(!t.isTrustedSender(i))return n;let a=await t.getCloud(),o=a.base;if(!o)return{ok:!1};let l=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",c=await bs(a),u=`${o}/account${c?`?${c}`:""}${l}`;return a.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(i,...s)=>{if(!t.isTrustedSender(i))return n;let a=s.length>=4,[o,l,c]=s.slice(0,3).map(b=>a&&b===null?void 0:b),u=Ka(s[3]);if(o!==void 0&&!Ya.includes(o))return{ok:!1,error:"invalid_tab"};if(l!==void 0&&(typeof l!="string"||!Cf.test(l)))return{ok:!1,error:"invalid_plan"};if(c!==void 0&&!Ja.includes(c))return{ok:!1,error:"invalid_period"};let f=(o??"membership")==="membership"&&l?`&plan=${encodeURIComponent(l)}${c?`&period=${_f(c)}`:""}`:"",g=await t.getCloud(),p=g.base;if(!p)return{ok:!1};let m=await bs(g),y=`${p}/pay?tab=${o??"membership"}${f}${u?`&from=${u}`:""}${m?`&${m}`:""}&redirect=${encodeURIComponent(`${p}/account`)}`;return g.signal?.throwIfAborted(),await t.openExternal(y),{ok:!0}}),t.handle("auth:resumeAutoRenew",async i=>{if(!t.isTrustedSender(i))return n;let s=await t.getCloud(),a=s.base;if(!a)return{ok:!1};let o=await bs(s);if(!o.startsWith("code="))return{ok:!1,error:"handoff_unavailable"};let l=`${a}/pay?tab=membership&action=resume_autorenew&${o}&redirect=${encodeURIComponent(`${a}/account`)}`;return s.signal?.throwIfAborted(),await t.openExternal(l),{ok:!0}}),t.handle("profile:publicOrigin",async i=>{if(!t.isTrustedSender(i))return n;let{base:s}=await t.getCloud();if(!s)return{ok:!1};try{let a=await fetch(`${s}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});a.body?.cancel().catch(()=>{});let o=a.status>=300&&a.status<400?a.headers.get("location"):null;return o&&/^https?:\/\//i.test(o)?{ok:!0,origin:new URL(o).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async i=>{if(!t.isTrustedSender(i))return e;let s=await r();if(!s.token)return{status:401,json:null};try{return await Ze(s,"GET","/api/token-quota/my",void 0,15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:useResetCard",async(i,...s)=>{if(!t.isTrustedSender(i))return e;let a=await r();if(!a.token)return{status:401,json:null};let o=s[0];if(o!==void 0&&o!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${String(o)}`}};let l=o??"both";try{return await Ze(a,"POST","/api/token-quota/reset-card/use",ii({type:l},s[1]),15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(!Number.isInteger(s)||s<1||s>100)return{status:400,json:{error:"invalid_percent"}};try{return await Ze(o,"POST","/api/token-quota/background/convert",ii({percent:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:pointsAutoDeduct",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ze(o,"POST","/api/token-quota/auto-deduct",ii({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgAutoMain",async(i,s,a)=>{if(!t.isTrustedSender(i))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ze(o,"POST","/api/token-quota/background/auto-main",ii({enabled:s},a),15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("feedback:submit",async(i,s)=>{if(!t.isTrustedSender(i))return n;let a=await t.getCloud();if(!a.base||!a.token)return{ok:!1,error:"not-logged-in"};if(s?.expectedAccountId!==void 0){let u=s.expectedAccountId;if(typeof u!="string"||!u||Ve(a.base,a.token)!==u)return{ok:!1,error:"account-changed"}}let o=(s?.description||"").trim();if(!o)return{ok:!1,error:"empty"};if(o.length>1e4)return{ok:!1,error:"description-too-long"};let l=[],c=!1;if(s?.sessionLogJson){let u=nr(s.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};l.push({filename:s.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:Ba(u)})}try{let u=await ir(a,`${a.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:o,attachments:l}),signal:AbortSignal.timeout(2e4)});if(!u.ok){let g=`HTTP ${u.status}`;try{g=(await u.json())?.detail||g}catch{}return{ok:!1,error:g}}return{ok:!0,id:(await u.json().catch(()=>({})))?.id??null,attachmentSkipped:c}}catch(u){return{ok:!1,error:u?.message||String(u)}}}),t.handle("cloud:fetch",async(i,s)=>{if(!t.isTrustedSender(i))return{status:0,error:"untrusted"};let a=s??{},o=typeof a.path=="string"?a.path:"",l=a.projectSource===void 0?null:a.projectSource;if(l!==null&&(typeof l!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(l)))return{status:0,error:"bad_project_source"};let c=Math.min(12e4,Math.max(1e3,Number(a.timeoutMs)||15e3)),u=typeof a.method=="string"?a.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(u))return{status:0,error:"bad_method"};if(!o.startsWith("/"))return{status:0,error:"bad_path"};let f=await t.getCloud();if(!String(f.base||""))return{status:0,error:"no_cloud_url"};let g=Nt(f.base,o);if(!g)return{status:0,error:"bad_path"};if(!f.token)return{status:401,error:"not_signed_in"};let p=a.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,y=setTimeout(()=>m.abort(),c);try{let b=await ir(f,g,{method:u,headers:{...p?{"Content-Type":"application/json"}:{},...l?{"X-Project-Source":l}:{}},body:p?JSON.stringify(a.body):void 0,signal:m.signal});return{status:b.status,json:await b.json().catch(()=>null)}}catch(b){return{status:0,error:String(b?.message||b)}}finally{clearTimeout(y)}}),Va(t)}import{createHash as vl}from"node:crypto";import{existsSync as Ep,promises as _p,readFileSync as Cp,renameSync as Ap,statSync as xp}from"node:fs";import Tp from"node:path";import{setTimeout as Ip}from"node:timers/promises";import{EventEmitter as tp}from"node:events";import{stat as np}from"node:fs";import{readdir as rp,stat as ip}from"node:fs/promises";import*as fe from"node:path";import{lstat as Za,readdir as xf,realpath as Tf,stat as If}from"node:fs/promises";import{join as Rf,resolve as Df,sep as Qa}from"node:path";import{Readable as Of}from"node:stream";var st={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},vn={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:st.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(vn);var rl="READDIRP_RECURSIVE_ERROR",Mf=new Set(["ENOENT","EPERM","EACCES","ELOOP",rl]),el=[st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE],Nf=new Set([st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE]),Pf=new Set([st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE]),$f=t=>Mf.has(t.code),jf=process.platform==="win32",tl=t=>!0,nl=t=>{if(t===void 0)return tl;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return tl},Ss=class extends Of{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??vn.highWaterMark});let n={...vn,...e},r=n.root??vn.root,i=n.type??vn.type;this._fileFilter=nl(n.fileFilter),this._directoryFilter=nl(n.directoryFilter);let s=n.lstat?Za:If;jf?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:vn.depth,this._wantsDir=Nf.has(i),this._wantsFile=Pf.has(i),this._wantsEverything=i===st.EVERYTHING_TYPE,this._root=Df(r),this._relStart=this._root.endsWith(Qa)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let a={path:this._root,depth:1};a.pending=this._exploreDir(this._root,1),this.parents=[a],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:i,depth:s}=n,a=r.splice(0,e).map(l=>this._formatEntry(l,i)),o=this._isDirent?a:await Promise.all(a);for(let l of o){if(!l)continue;if(this.destroyed)return;let c=this._getEntryType(l);typeof c!="string"&&(c=await c),c==="directory"&&this._directoryFilter(l)?(s<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:s+1}),this._wantsDir&&(this.push(l),e--)):(c==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}let s=i.pending??this._exploreDir(i.path,i.depth),a=this.parents[this.parents.length-1];if(a&&!a.pending&&(a.pending=this._exploreDir(a.path,a.depth)),this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await xf(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,i=Rf(n,r),s={path:i.slice(this._relStart),fullPath:i,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(i).then(a=>(s.stats=a,s),a=>{this._onError(a)})}_onError(e){$f(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await Tf(n),i=await Za(r);if(i.isFile())return"file";if(i.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===Qa){let a=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return a.code=rl,this._onError(a),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function il(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=st.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!el.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${el.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new Ss(r)}import{watch as Lf,unwatchFile as sl,watchFile as Ff}from"node:fs";import{realpath as vs,lstat as Uf,open as Hf,stat as al}from"node:fs/promises";import{type as zf}from"node:os";import*as _e from"node:path";var Bf="data",_s="end",ll="close",ci=()=>{};var ui=process.platform,Cs=ui==="win32",qf=ui==="darwin",Wf=ui==="linux",Gf=ui==="freebsd",cl=zf()==="OS400",Te={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},wt=Te,Vf="watch",Yf={lstat:Uf,stat:al},on="listeners",si="errHandlers",kn="rawEmitters",Jf=[on,si,kn],Kf=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Xf=t=>Kf.has(_e.extname(t).slice(1).toLowerCase()),Es=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},sr=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},Zf=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},or=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ul=t=>t instanceof Set?t.size===0:!t,oi=new Map;function ol(t,e,n,r,i){let s=(a,o)=>{n(t),i(a,o,{watchedPath:t}),o&&t!==o&&ai(_e.resolve(t,o),on,_e.join(t,o))};try{return Lf(t,{persistent:e.persistent},s)}catch(a){r(a);return}}var ai=(t,e,n,r,i)=>{let s=oi.get(t);s&&Es(s[e],a=>{a(n,r,i)})},Qf=(t,e,n,r)=>{let{listener:i,errHandler:s,rawEmitter:a}=r,o=oi.get(e),l;if(!n.persistent)return l=ol(t,n,i,s,a),l?l.close.bind(l):void 0;if(o)sr(o,on,i),sr(o,si,s),sr(o,kn,a);else{if(l=ol(t,n,ai.bind(null,e,on),s,ai.bind(null,e,kn)),!l)return;l.on(wt.ERROR,async c=>{let u=ai.bind(null,e,si);if(o&&(o.watcherUnusable=!0),Cs&&c.code==="EPERM")try{await(await Hf(t,"r")).close(),u(c)}catch{}else u(c)}),o={listeners:i,errHandlers:s,rawEmitters:a,watcher:l},oi.set(e,o)}return()=>{or(o,on,i),or(o,si,s),or(o,kn,a),ul(o.listeners)&&(o.watcher.close(),oi.delete(e),Jf.forEach(Zf(o)),o.watcher=void 0,Object.freeze(o))}},ks=new Map,ep=(t,e,n,r)=>{let{listener:i,rawEmitter:s}=r,a=ks.get(e),o=a&&a.options;return o&&(o.persistent<n.persistent||o.interval>n.interval)&&(sl(e),a=void 0),a?(sr(a,on,i),sr(a,kn,s)):(a={listeners:i,rawEmitters:s,options:n,watcher:Ff(e,n,(l,c)=>{Es(a.rawEmitters,f=>{f(wt.CHANGE,e,{curr:l,prev:c})});let u=l.mtimeMs;(l.size!==c.size||u>c.mtimeMs||u===0)&&Es(a.listeners,f=>f(t,l))})},ks.set(e,a)),()=>{or(a,on,i),or(a,kn,s),ul(a.listeners)&&(ks.delete(e),sl(e),a.options=a.watcher=void 0,Object.freeze(a))}},li=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,i=_e.dirname(e),s=_e.basename(e);this.fsw._getWatchedDir(i).add(s);let o=_e.resolve(e),l={persistent:r.persistent};n||(n=ci);let c;if(r.usePolling){let u=r.interval!==r.binaryInterval;l.interval=u&&Xf(s)?r.binaryInterval:r.interval,c=ep(e,o,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else c=Qf(e,o,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(e,n,r){if(this.fsw.closed)return;let i=_e.dirname(e),s=_e.basename(e),a=this.fsw._getWatchedDir(i),o=n;if(a.has(s))return;let l=async(u,f)=>{if(this.fsw._throttle(Vf,e,5)){if(!f||f.mtimeMs===0)try{let g=await al(e);if(this.fsw.closed)return;let p=g.atimeMs,m=g.mtimeMs;if((!p||p<=m||m!==o.mtimeMs)&&this.fsw._emit(wt.CHANGE,e,g),(qf||Wf||Gf)&&o.ino!==g.ino){this.fsw._closeFile(u),o=g;let y=this._watchWithNodeFs(e,l);y&&this.fsw._addPathCloser(u,y)}else o=g}catch{this.fsw._remove(i,s)}else if(a.has(s)){let g=f.atimeMs,p=f.mtimeMs;(!g||g<=p||p!==o.mtimeMs)&&this.fsw._emit(wt.CHANGE,e,f),o=f}}},c=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(wt.ADD,e,0))return;this.fsw._emit(wt.ADD,e,n)}return c}async _handleSymlink(e,n,r,i){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await vs(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(s)!==o&&(this.fsw._symlinkPaths.set(s,o),this.fsw._emit(wt.CHANGE,r,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(s,o),this.fsw._emit(wt.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,i,s,a,o){e=_e.join(e,"");let l=i?`${e}:${i}`:e;if(o=this.fsw._throttle("readdir",l,1e3),!o)return;let c=this.fsw._getWatchedDir(r.path),u=new Set,f=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(f)return f.on(Bf,async g=>{if(this.fsw.closed){f=void 0;return}let p=g.path,m=_e.join(e,p);if(u.add(p),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,m,p))){if(this.fsw.closed){f=void 0;return}(p===i||!i&&!c.has(p))&&(this.fsw._incrReadyCount(),m=_e.join(s,_e.relative(s,m)),this._addToNodeFs(m,n,r,a+1))}}).on(wt.ERROR,this._boundHandleError),new Promise((g,p)=>{if(!f)return p();f.once(_s,()=>{if(this.fsw.closed){f=void 0;return}let m=o?o.clear():!1;g(void 0),c.getChildren().filter(y=>y!==e&&!u.has(y)).forEach(y=>{this.fsw._remove(e,y)}),f=void 0,m&&this._handleRead(e,!1,r,i,s,a,o)})})}async _handleDir(e,n,r,i,s,a,o){let l=this.fsw._getWatchedDir(_e.dirname(e)),c=l.has(_e.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!c&&this.fsw._emit(wt.ADD_DIR,e,n),l.add(_e.basename(e)),this.fsw._getWatchedDir(e);let u,f,g=this.fsw.options.depth;if((g==null||i<=g)&&!this.fsw._symlinkPaths.has(o)){if(!s&&(await this._handleRead(e,r,a,s,e,i,u),this.fsw.closed))return;f=this._watchWithNodeFs(e,(p,m)=>{m&&m.mtimeMs===0||this._handleRead(p,!1,a,s,e,i,u)})}return f}async _addToNodeFs(e,n,r,i,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);r&&(o.filterPath=l=>r.filterPath(l),o.filterDir=l=>r.filterDir(l));try{let l=await Yf[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,l))return a(),!1;let c=this.fsw.options.followSymlinks,u;if(l.isDirectory()){let f=_e.resolve(e),g=c?await vs(e):e;if(this.fsw.closed||(u=await this._handleDir(o.watchPath,l,n,i,s,o,g),this.fsw.closed))return;f!==g&&g!==void 0&&this.fsw._symlinkPaths.set(f,g)}else if(l.isSymbolicLink()){let f=c?await vs(e):e;if(this.fsw.closed)return;let g=_e.dirname(o.watchPath);if(this.fsw._getWatchedDir(g).add(o.watchPath),this.fsw._emit(wt.ADD,o.watchPath,l),u=await this._handleDir(g,l,n,i,e,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(_e.resolve(e),f)}else u=this._handleFile(o.watchPath,l,n);return a(),u&&this.fsw._addPathCloser(e,u),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var As="/",sp="//",gl=".",op="..",ap="string",lp=/\\/g,ml=/\/\//g,cp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,up=/^\.[/\\]/;function di(t){return Array.isArray(t)?t:[t]}var xs=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function dp(t){return typeof t=="function"?t:typeof t=="string"?e=>t===e:t instanceof RegExp?e=>t.test(e):typeof t=="object"&&t!==null?e=>{if(t.path===e)return!0;if(t.recursive){let n=fe.relative(t.path,e);return n?!n.startsWith("..")&&!fe.isAbsolute(n):!1}return!1}:()=>!1}function fp(t){if(typeof t!="string")throw new Error("string expected");t=fe.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ml,"/"),e&&(t="/"+t),t}function dl(t,e,n){let r=fp(e);for(let i=0;i<t.length;i++){let s=t[i];if(s(r,n))return!0}return!1}function pp(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=di(t).map(i=>dp(i));return e==null?(i,s)=>dl(r,i,s):dl(r,e)}var fl=t=>{let e=di(t).flat();if(!e.every(n=>typeof n===ap))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(yl)},pl=t=>{let e=t.replace(lp,As),n=!1;return e.startsWith(sp)&&(n=!0),e=e.replace(ml,As),n&&(e=As+e),e},yl=t=>pl(fe.normalize(pl(t))),hl=(t="")=>e=>typeof e=="string"?yl(fe.isAbsolute(e)?e:fe.join(t,e)):e,hp=(t,e)=>fe.isAbsolute(t)?t:fe.join(e,t),gp=Object.freeze(new Set),Ts=class{path;_removeWatcher;items;constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==gl&&e!==op&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await rp(r)}catch{this._removeWatcher&&this._removeWatcher(fe.dirname(r),fe.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=ci,this.items=gp,Object.freeze(this)}},mp="stat",yp="lstat",Is=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let i=e;this.path=e=e.replace(up,""),this.watchPath=i,this.fullWatchPath=fe.resolve(i),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?mp:yp}entryPath(e){return fe.join(this.watchPath,fe.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},fi=class extends tp{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?di(e.ignored):di([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};cl&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let l=s.toLowerCase();l==="false"||l==="0"?i.usePolling=!1:l==="true"||l==="1"?i.usePolling=!0:i.usePolling=!!l}let a=process.env.CHOKIDAR_INTERVAL;a&&(i.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=ci,this._readyEmitted=!0,process.nextTick(()=>this.emit(Te.READY)))},this._emitRaw=(...l)=>this.emit(Te.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new li(this),Object.freeze(i)}_addIgnoredPath(e){if(xs(e)){for(let n of this._ignoredPaths)if(xs(n)&&n.path===e.path&&n.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let n of this._ignoredPaths)xs(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let s=fl(e);return i&&(s=s.map(a=>hp(a,i))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!r,void 0,0,n);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(fe.dirname(o),fe.basename(n||o))})}),this}unwatch(e){if(this.closed)return this;let n=fl(e),{cwd:r}=this.options;return n.forEach(i=>{!fe.isAbsolute(i)&&!this._closers.has(i)&&(r&&(i=fe.join(r,i)),i=fe.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let i=r();i instanceof Promise&&e.push(i)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let s=(this.options.cwd?fe.relative(this.options.cwd,r):r)||gl;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==Te.ERROR&&this.emit(Te.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let i=this.options;Cs&&(n=fe.normalize(n)),i.cwd&&(n=fe.relative(i.cwd,n));let s=[n];r!=null&&s.push(r);let a=i.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(n)))return o.lastChange=new Date,this;if(i.atomic){if(e===Te.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((l,c)=>{this.emit(...l),this.emit(Te.ALL,...l),this._pendingUnlinks.delete(c)})},typeof i.atomic=="number"?i.atomic:100),this;e===Te.ADD&&this._pendingUnlinks.has(n)&&(e=Te.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(e===Te.ADD||e===Te.CHANGE)&&this._readyEmitted){let l=(c,u)=>{c?(e=Te.ERROR,s[0]=c,this.emitWithAll(e,s)):u&&(s.length>1?s[1]=u:s.push(u),this.emitWithAll(e,s))};return this._awaitWriteFinish(n,a.stabilityThreshold,e,l),this}if(e===Te.CHANGE&&!this._throttle(Te.CHANGE,n,50))return this;if(i.alwaysStat&&r===void 0&&(e===Te.ADD||e===Te.ADD_DIR||e===Te.CHANGE)){let l=i.cwd?fe.join(i.cwd,n):n,c;try{c=await ip(l)}catch{}if(!c||this.closed)return;s.push(c)}return this.emitWithAll(e,s),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(Te.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let s=i.get(n);if(s)return s.count++,!1;let a,o=()=>{let c=i.get(n),u=c?c.count:0;return i.delete(n),clearTimeout(a),c&&clearTimeout(c.timeoutObject),u};a=setTimeout(o,r);let l={timeoutObject:a,clear:o,count:0};return i.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,i){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,o,l=e;this.options.cwd&&!fe.isAbsolute(e)&&(l=fe.join(this.options.cwd,e));let c=new Date,u=this._pendingWrites;function f(g){np(l,(p,m)=>{if(p||!u.has(e)){p&&p.code!=="ENOENT"&&i(p);return}let y=Number(new Date);g&&m.size!==g.size&&(u.get(e).lastChange=y);let b=u.get(e);y-b.lastChange>=n?(u.delete(e),i(void 0,m)):o=setTimeout(f,a,m)})}u.has(e)||(u.set(e,{lastChange:c,cancelWait:()=>(u.delete(e),clearTimeout(o),r)}),o=setTimeout(f,a))}_isIgnored(e,n){if(this.options.atomic&&cp.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(hl(r)),o=[...[...this._ignoredPaths].map(hl(r)),...s];this._userIgnored=pp(o,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Is(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=fe.resolve(e);return this._watched.has(n)||this._watched.set(n,new Ts(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let i=fe.join(e,n),s=fe.resolve(i);if(r=r??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(i).getChildren().forEach(g=>this._remove(i,g));let l=this._getWatchedDir(e),c=l.has(n);l.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=i;if(this.options.cwd&&(u=fe.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Te.ADD)return;this._watched.delete(i),this._watched.delete(s);let f=r?Te.UNLINK_DIR:Te.UNLINK;c&&!this._isIgnored(i)&&this._emit(f,i),this._closePath(i)}_closePath(e){this._closeFile(e);let n=fe.dirname(e);this._getWatchedDir(n).remove(fe.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:Te.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},i=il(e,r);return this._streams.add(i),i.once(ll,()=>{i=void 0}),i.once(_s,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function Rs(t,e={}){let n=new fi(e);return n.add(t),n}var wl={watch:Rs,FSWatcher:fi};import{execFile as wp}from"node:child_process";import{stat as bl}from"node:fs/promises";import{resolve as bp}from"node:path";import{promisify as Sp}from"node:util";function Vt(t){if(!t||typeof t!="object")return!1;let e=t;return Number.isInteger(e.dev)&&e.dev>=0&&Number.isInteger(e.ino)&&e.ino>0&&(e.birthtimeMs===void 0||Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0)&&(e.volumeId===void 0||typeof e.volumeId=="string"&&e.volumeId.length>0)}function an(t,e){return t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)&&(t.volumeId===void 0?t.dev===e.dev:t.volumeId===e.volumeId)}function bt(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Sl=Sp(wp);function vp(t){let e=t.match(/<key>VolumeUUID<\/key>\s*<string>([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})<\/string>/i)?.[1];return e?`darwin:${e.toLowerCase()}`:void 0}async function kp(t){if(process.platform!=="darwin")return;let{stdout:e}=await Sl("/bin/df",["-P",bp(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
|
|
2
|
+
`).slice(1).map(i=>i.trim().split(/\s+/)[0]).find(i=>/^\/dev\/disk\d+(?:s\d+)*$/.test(i));if(!n)return;let{stdout:r}=await Sl("/usr/sbin/diskutil",["info","-plist",n],{timeout:5e3,maxBuffer:256*1024});return vp(r)}async function ar(t,e=kp,n=process.platform){let r=await bl(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),a=await bl(t);if(!a.isDirectory()||!bt(i,a))throw Error("Sync root changed while reading its identity");return{...i,...s?{volumeId:s}:{}}}var Ds;function kl(t){Ds=t}var El={fs:_p,path:Tp,directoryIdentity:ar,sha256Hex:t=>vl("sha256").update(t).digest("hex"),tmpTag:()=>process.pid,existsSync:Ep,async compareAndReplace(t,e,n,r,i){if(!Ds)throw new Error("This host needs the shared content write lock for safe cloud downloads");let s=!1,a=Ds,o=()=>{if(!r())return;if(i){let c;try{c=xp(i.path)}catch(u){if(u.code==="ENOENT")return;throw u}if(!c.isDirectory()||!bt(i.identity,c))return}let l=null;try{l=vl("sha256").update(Cp(e)).digest("hex")}catch(c){if(c.code!=="ENOENT")throw c}l===n&&(Ap(t,e),s=!0)};for(let l=0;;l++)try{return await a(e,o),s}catch(c){let u=c.code;if(s||process.platform!=="win32"||l>=4||u!=="EPERM"&&u!=="EBUSY")throw c;await Ip(20*2**l)}},watch(t,e,n){let r=wl.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 Rp,lstatSync as Ns,readFileSync as Ps,writeFileSync as Dp,realpathSync as _l,opendirSync as Op,openSync as Mp,fstatSync as Np,readSync as Pp,closeSync as $p,constants as Os}from"node:fs";import{join as pi,extname as Cl,sep as jp}from"node:path";var $s=300,Al=5*1024*1024,xl=20*1024*1024,Lp=50*1024*1024,Tl=new Set(["node_modules"]),Fp=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Il(t,e){let n=[],r=0,i=(s,a)=>{for(let o of Rp(s)){if(o.startsWith("."))continue;let l=pi(s,o),c;try{c=Ns(l)}catch{continue}if(c.isSymbolicLink())continue;let u=a?`${a}/${o}`:o;if(c.isDirectory()){Tl.has(o)||i(l,u);continue}if(!c.isFile()||o.endsWith(".d.ts"))continue;if(n.length>=$s)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${$s}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let f=Cl(o).toLowerCase(),g,p=e.mimeOf(f)??"application/octet-stream";if(Fp.has(f)){let m=e.transpile(Ps(l,"utf8"),f,u);g=Buffer.from(m??"","utf8"),p="text/javascript"}else g=Ps(l);if(g.length>Al)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${u}`);if(r+=g.length,r>xl)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:u,content_b64:g.toString("base64"),content_type:p,size:g.length})}};if(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 Rl=".forsion-connect.json";function Dl(t){try{return JSON.parse(Ps(pi(t,Rl),"utf8"))}catch{return{}}}function Ol(t,e){try{Dp(pi(t,Rl),JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf8")}catch{}}var Up=new Set([".html",".htm",".js",".mjs",".cjs",".ts",".tsx",".jsx",".mts",".cts",".vue",".svelte"]),Hp=400,zp=5e3,Ms=2*1024*1024,Bp=12,qp=/\bforsion\.ai\.(chat|generateImage|agent|status)\b/g;function Ml(t){try{if(!Ns(t).isDirectory())return null}catch{return null}let e=!1,n=new Set,r=0,i=0,s=null,a=l=>{let c;try{c=Mp(l,Os.O_RDONLY|(Os.O_NOFOLLOW||0)|(Os.O_NONBLOCK||0))}catch{return null}try{if(!Np(c).isFile())return null;s??=Buffer.allocUnsafe(Ms+1);let u=0;for(;u<s.length;){let f=Pp(c,s,u,s.length-u,null);if(f<=0)break;u+=f}return u>Ms?null:s.toString("utf8",0,u)}catch{return null}finally{try{$p(c)}catch{}}},o=(l,c)=>{let u;try{u=Op(l)}catch{return}try{for(;;){if(r>=Hp||i>=zp)return;let f;try{f=u.readSync()}catch{return}if(!f)return;i++;let g=f.name;if(g.startsWith(".")||Tl.has(g))continue;let p=pi(l,g),m;try{m=Ns(p)}catch{continue}if(m.isSymbolicLink())continue;if(m.isDirectory()){c<Bp&&o(p,c+1);continue}if(!m.isFile()||m.size>Ms||!Up.has(Cl(g).toLowerCase()))continue;r++;let y=a(p);if(y!==null){!e&&y.includes("forsion-connect.js")&&(e=!0);for(let b of y.matchAll(qp))n.add(`forsion.ai.${b[1]}`)}}}finally{try{u.closeSync()}catch{}}};return o(t,0),{usesSdk:e,sdkMethods:[...n].sort()}}function Nl(t){let e=Dl(t),n=Ml(t);return n?{...e,...n}:e}function Pl(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,a]=(r.url||"").split("?"),o=(m,y)=>{i.headersSent||(i.statusCode=m,i.setHeader("Content-Type","application/json")),i.end(JSON.stringify({detail:y}))},l=n(s);if(!l)return o(404,"unknown connect endpoint");if((r.method||"GET")!==l.method)return o(405,"method not allowed");let c="",u="";try{({base:c,token:u}=await t())}catch{}if(!c)return o(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(l.auth&&!u)return o(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let f;if(l.method==="POST"){let m=[],y=0;try{for await(let b of r){if(y+=b.length,y>Lp)return r.destroy(),o(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");m.push(b)}}catch(b){return o(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${b?.message||String(b)}`)}f=Buffer.concat(m)}if(l.agentRun){let m;try{m=JSON.parse((f||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return o(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}f=Buffer.from(JSON.stringify({session_id:typeof m.session_id=="string"?m.session_id:"",message:typeof m.message=="string"?m.message:"",app_id:"connect",agent_config:{}}))}let g=new AbortController,p=setTimeout(()=>g.abort(new Error("proxy timeout")),l.timeoutMs??3e5);r.on("close",()=>g.abort());try{let m=await fetch(c+l.path+(a?`?${a}`:""),{method:l.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...u?{Authorization:`Bearer ${u}`}:{}},body:f&&f.length?new Uint8Array(f):void 0,signal:g.signal});if(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 y of m.body)i.write(y);i.end()}catch(m){let y=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${m?.message||String(m)}`;if(i.headersSent){try{i.write(`data: ${JSON.stringify({error:y})}
|
|
4
4
|
|
|
5
|
-
`)}catch{}
|
|
5
|
+
`)}catch{}i.end()}else o(502,y)}finally{clearTimeout(p)}}}var $l=`
|
|
6
6
|
(function () {
|
|
7
7
|
'use strict';
|
|
8
8
|
if (window.forsion) return;
|
|
@@ -196,69 +196,69 @@ var Ho=null;function aa(t){Ho=t}function Ee(){if(!Ho)throw new Error("core host
|
|
|
196
196
|
ai: { chat: chat, agent: agentRun, generateImage: generateImage, status: aiStatus }
|
|
197
197
|
};
|
|
198
198
|
})();
|
|
199
|
-
`,Gf=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 ci(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function li(t){t.setPreviewHooks({sdkJs:nc,proxy:tc(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?ec(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 Ve(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=qa(n.dir);let i=null;try{i=qa(t.projectsRoot())}catch{}if(!(!!i&&(r===i||r.startsWith(i+Uf)))&&!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 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:i,totalBytes:s}=Ja(r,Gf(t));if(!i.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 Ve(o,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:i},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};Za(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:s}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),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:i}=await Ve(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:i?.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:i}=await Ve(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:i?.code||"error",detail:i?.detail||`HTTP ${o}`}:{ok:!0,status:i.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:i}=await Ve(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:i?.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 Ve(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 Kf}from"node:crypto";import{hostname as Xf}from"node:os";async function Bn(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 i=o.avatar||o.avatarUrl||o.avatar_url||void 0;return i&&/^\/(?!\/)/.test(i)&&(i=n+i),{status:"ok",user:{username:o.username||o.nickname||void 0,nickname:o.nickname||void 0,avatar:i,membershipTier:o.membershipTier||o.membership_tier||void 0}}}catch{return{status:"offline"}}}var rc=t=>`${t.seq}:${t.hash}`,Vr=(t=Xf())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},Zf=t=>Kf("sha256").update(t).digest("hex");function ui(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 Yr(t){let e=t.baseUrl.replace(/\/+$/,""),n=i=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${i}`,r=Vr(),o=async(i,s)=>{let a=t.getToken();if(!a)throw new Error("penzor-not-logged-in");let c=await fetch(i,{...s,headers:{...s.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 ${s.method??"GET"} ${c.status}: ${l.slice(0,200)}`)}return c};return{kind:"penzor",async walk(i){let s=await o(n("/manifest"),{method:"GET",signal:i}),{files:a}=await s.json();return a.map(c=>({key:c.path,size:c.size,mtimeMs:c.mtimeMs,id:rc(c),hash:c.hash}))},async readFile(i,s){let c=await(await o(n(`/file?path=${encodeURIComponent(i)}`),{method:"GET",signal:s})).json(),l=await fetch(c.url,{signal:s});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${i}`);let u=Buffer.from(await l.arrayBuffer());if(Zf(u)!==c.hash)throw new Error(`penzor hash mismatch: ${i}`);return u},async writeFile(i,s,a,c,l){let u=ui(l),f=new URLSearchParams({path:i,mtimeMs:String(Math.floor(a)||0)});u&&(f.set("baseSeq",String(u.baseSeq)),u.baseHash&&f.set("baseHash",u.baseHash));let p=await(await o(n(`/file?${f.toString()}`),{method:"PUT",body:new Uint8Array(s),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:c})).json();return{key:i,size:p.size,mtimeMs:p.mtimeMs,id:rc(p)}},async rm(i,s,a){let c=ui(a),l=new URLSearchParams({path:i});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:s})},async check(){try{return await o(n("/manifest"),{method:"GET"}),{ok:!0}}catch(i){return{ok:!1,error:String(i?.message||i)}}}}}var Gr="forsion-diagnostics",ic=50*1024*1024,oc=new Map;async function Qf(t,e){let n=oc.get(e);if(n)return{id:n};let r=await Bn(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?(oc.set(e,o),{id:o}):{error:"penzor-auth-unverified"}}var di=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function fi(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===Gr)return{error:"penzor-bad-vault"};let i=await Qf(n.cloudUrl,n.token);if("error"in i)return i;let s=n.token;return{remote:Yr({baseUrl:n.cloudUrl,vault:o,getToken:()=>s}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${i.id}|${o}`,maxFileBytes:ic}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as tp}from"node:fs";import{access as np,link as rp,lstat as op,mkdir as ip,open as sp,readdir as ap,rename as cp,stat as fc,unlink as gi}from"node:fs/promises";import{request as lp}from"node:http";import{request as up}from"node:https";import{homedir as dp}from"node:os";import{basename as pc,extname as fp,isAbsolute as pp,join as Wn}from"node:path";import{randomUUID as Kr}from"node:crypto";var qn=52428800;var sc=["bytes","signed","text"],ac=/^[A-Za-z0-9_-]{1,64}$/,cc=/^[a-z0-9][a-z0-9-]{0,63}$/;function Jr(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 ep={".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 lc(t){let e=t.lastIndexOf(".");return ep[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function uc(t,e,n,r){let o=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",i=encodeURIComponent(n).replace(/['()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),s="";for(let[a,c]of Object.entries(e))s+=`--${t}\r
|
|
200
|
-
Content-Disposition: form-data; name="${
|
|
199
|
+
`,Wp=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function Gp(t,e){let n=t.isAdoptedCreation;if(typeof n!="function")return!1;try{return n.call(t,e)===!0}catch{return!1}}function js(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Ls(t){t.setPreviewHooks({sdkJs:$l,proxy:Pl(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?Nl(n):{}),t.handle("connect:list",async()=>{let e=await t.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:n,json:r}=await Ze(e,"GET","/api/connect/apps");return n===401||n===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:n!==200?{ok:!1,code:"error",detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,...r}}catch(n){return{ok:!1,code:"error",detail:n?.message||String(n)}}}),t.handle("connect:publish",async(e,n)=>{if(!n||typeof n.dir!="string"||!n.dir||!n.name||!n.slug||!n.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r;try{r=_l(n.dir);let s=null;try{s=_l(t.projectsRoot())}catch{}if(!(!!s&&(r===s||r.startsWith(s+jp)))&&!Gp(t,r))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let i=await t.getCloud();if(!i.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:s,totalBytes:a}=Il(r,Wp(t));if(!s.some(u=>u.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:o,json:l}=await Ze(i,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:s},3e5);if(o===401)return{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"};if(o!==200)return{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${o}`,used:l?.used,limit:l?.limit};Ol(r,{slug:String(l.slug)});let c=typeof l.publicUrl=="string"&&/^https?:\/\//i.test(l.publicUrl)?l.publicUrl:`${i.base}${l.url}`;return{ok:!0,slug:l.slug,handle:l.handle,url:c,totalBytes:a}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:unpublish",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return i===401||i===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingApply",async(e,n)=>{if(!n||typeof n.slug!="string"||!n.slug||typeof n.summary!="string"||!n.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200?{ok:!1,code:s?.code||"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0,status:s.status}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:i,json:s}=await Ze(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200&&i!==404?{ok:!1,code:"error",detail:s?.detail||`HTTP ${i}`}:{ok:!0}}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await Ze(e,"GET","/api/connect/store");return n!==200?{ok:!1,detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,items:Array.isArray(r.items)?r.items:[]}}catch(n){return{ok:!1,detail:n?.message||String(n)}}}),t.log("[forsion-extend] connect handlers registered")}import{createHash as Vp}from"node:crypto";import{hostname as Yp}from"node:os";async function lr(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let r=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let i=await r.json();if(!i)return{status:"offline"};let s=i.avatar||i.avatarUrl||i.avatar_url||void 0;return s&&/^\/(?!\/)/.test(s)&&(s=n+s),{status:"ok",user:{username:i.username||i.nickname||void 0,nickname:i.nickname||void 0,avatar:s,membershipTier:i.membershipTier||i.membership_tier||void 0}}}catch{return{status:"offline"}}}var jl=t=>`${t.seq}:${t.hash}`,hi=(t=Yp())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},Jp=t=>Vp("sha256").update(t).digest("hex");function Fs(t){if(t===null)return{baseSeq:0,baseHash:null};if(typeof t!="string")return;let e=t.indexOf(":"),n=Number(e===-1?t:t.slice(0,e));if(!Number.isInteger(n)||n<=0)return;let r=e===-1?"":t.slice(e+1);return{baseSeq:n,baseHash:/^[0-9a-f]{64}$/.test(r)?r:null}}function gi(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=hi(),i=async(s,a)=>{let o=t.getToken();if(!o)throw new Error("penzor-not-logged-in");let l=await fetch(s,{...a,headers:{...a.headers,Authorization:`Bearer ${o}`}});if(l.status===409){let c=await l.json().catch(()=>({}));throw new Error(`cas-conflict ${String(c.code??"")}: seq=${String(c.seq??"?")}`)}if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`penzor ${a.method??"GET"} ${l.status}: ${c.slice(0,200)}`)}return l};return{kind:"penzor",async walk(s){let a=await i(n("/manifest"),{method:"GET",signal:s}),{files:o}=await a.json();return o.map(l=>({key:l.path,size:l.size,mtimeMs:l.mtimeMs,id:jl(l),hash:l.hash}))},async readFile(s,a){let l=await(await i(n(`/file?path=${encodeURIComponent(s)}`),{method:"GET",signal:a})).json(),c=await fetch(l.url,{signal:a});if(!c.ok)throw new Error(`penzor blob GET ${c.status}: ${s}`);let u=Buffer.from(await c.arrayBuffer());if(Jp(u)!==l.hash)throw new Error(`penzor hash mismatch: ${s}`);return u},async writeFile(s,a,o,l,c){let u=Fs(c),f=new URLSearchParams({path:s,mtimeMs:String(Math.floor(o)||0)});u&&(f.set("baseSeq",String(u.baseSeq)),u.baseHash&&f.set("baseHash",u.baseHash));let p=await(await i(n(`/file?${f.toString()}`),{method:"PUT",body:new Uint8Array(a),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:l})).json();return{key:s,size:p.size,mtimeMs:p.mtimeMs,id:jl(p)}},async rm(s,a,o){let l=Fs(o),c=new URLSearchParams({path:s});l&&l.baseSeq>0&&(c.set("baseSeq",String(l.baseSeq)),l.baseHash&&c.set("baseHash",l.baseHash)),await i(n(`/file?${c.toString()}`),{method:"DELETE",signal:a})},async check(){try{return await i(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var mi="forsion-diagnostics",Fl=50*1024*1024,Ll=new Map;async function Kp(t,e){let n=Ll.get(e);if(n)return{id:n};let r=await lr(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let i=r.user?.username?.trim();return i?(Ll.set(e,i),{id:i}):{error:"penzor-auth-unverified"}}var Us=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function Hs(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,i=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(i)||i===mi)return{error:"penzor-bad-vault"};let s=await Kp(n.cloudUrl,n.token);if("error"in s)return s;let a=n.token;return{remote:gi({baseUrl:n.cloudUrl,vault:i,getToken:()=>a}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${s.id}|${i}`,maxFileBytes:Fl}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as Zp}from"node:fs";import{access as Qp,link as eh,lstat as th,mkdir as nh,open as rh,readdir as ih,rename as sh,stat as Gl,unlink as qs}from"node:fs/promises";import{request as oh}from"node:http";import{request as ah}from"node:https";import{homedir as lh}from"node:os";import{basename as Vl,extname as ch,isAbsolute as uh,join as ur}from"node:path";import{randomUUID as wi}from"node:crypto";var cr=52428800;var Ul=["bytes","signed","text"],Hl=/^[A-Za-z0-9_-]{1,64}$/,zl=/^[a-z0-9][a-z0-9-]{0,63}$/;function yi(t){if(typeof t!="string")return null;let n=(t.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f<>:"|?*]/g,"").trim().slice(0,200);return n&&n!=="."&&n!==".."?n:null}var Xp={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".svg":"image/svg+xml",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Bl(t){let e=t.lastIndexOf(".");return Xp[e>0?t.slice(e).toLowerCase():""]??"application/octet-stream"}function ql(t,e,n,r){let i=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",s=encodeURIComponent(n).replace(/['()*]/g,o=>`%${o.charCodeAt(0).toString(16).toUpperCase()}`),a="";for(let[o,l]of Object.entries(e))a+=`--${t}\r
|
|
200
|
+
Content-Disposition: form-data; name="${o}"\r
|
|
201
201
|
\r
|
|
202
|
-
${
|
|
203
|
-
`;return
|
|
204
|
-
Content-Disposition: form-data; name="file"; filename="${
|
|
202
|
+
${l}\r
|
|
203
|
+
`;return a+=`--${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:
|
|
207
|
+
`,{head:a,tail:`\r
|
|
208
208
|
--${t}--\r
|
|
209
|
-
`}}function pi(t,e){let n=t.filter(([a])=>e-a<=3e3);if(n.length<2)return 0;let[r,o]=n[0],[i,s]=n[n.length-1];return i>r?Math.max(0,(s-o)/(i-r)*1e3):0}function hi(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 hp=3,mi=6e4,gp=200,mp=sc;function hc(t,e,n,r){let{head:o,tail:i}=uc(t,e,n,r);return{head:Buffer.from(o,"utf8"),tail:Buffer.from(i,"utf8")}}function yp(t,e,n,r,o,i,s,a){return new Promise((c,l)=>{let u=new URL(t),f=(u.protocol==="https:"?up:lp)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+o+i.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(mi,()=>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 tp(r)){let w=m;if(p+=w.length,p>o)throw new Error("changed");f.write(w)||await new Promise(y=>f.once("drain",y)),s(p)}if(p!==o)throw new Error("changed");f.end(i)}catch(p){f.destroy(p)}})()})}function yi(t,e={}){let n=e.downloadsDir??(()=>Wn(dp(),"Downloads")),r=e.post??yp,o=e.now??Date.now,i=[],s=new Map,a=Promise.resolve(),c=async()=>{let E=await t.getCloud(),T=typeof t.accountId=="function"?t.accountId():null;return{...E,account:T||`${E.base}|${E.token}`}},l=E=>{let{account:T,attempt:_,relDir:P,abort:q,samples:J,dl:R,...Y}=E;return{...Y,speed:E.state==="active"?pi(J,o()):0}},u=(E,T,_=null)=>{E.state=T,E.error=_,E.abort=null,E.finishedAt=o(),E.samples=[];let P=i.filter(q=>q.state==="done"||q.state==="canceled");for(let q of P.slice(0,Math.max(0,P.length-gp)))i.splice(i.indexOf(q),1);f()};function f(){for(let E of["up","down"]){let T=i.filter(_=>_.kind===E&&_.state==="active").length;for(let _ of i){if(T>=hp)break;if(_.kind!==E||_.state!=="queued")continue;T++,_.state="active",_.startedAt=o(),_.done=0,_.samples=[[o(),0]],_.abort=new AbortController;let P=++_.attempt,q=()=>_.attempt===P&&_.state==="active";(E==="up"?S(_,q):j(_,q)).catch(J=>{q()&&u(_,"failed",h(J))})}}}let h=E=>{let T=String(E?.message||E);return T==="changed"||T==="too_large"||T==="quota"||T==="account_changed"||T==="not_signed_in"||T.startsWith("http_")||T==="bad_response"||T==="gone"?T:"network"},p=(E,T)=>{E.done=T;let _=o(),P=E.samples[E.samples.length-1];for((!P||_-P[0]>=200)&&E.samples.push([_,T]);E.samples.length>2&&_-E.samples[0][0]>3500;)E.samples.shift()};async function m(E){let T=await c();if(T.account!==E.account)throw new Error("account_changed");if(!T.token)throw new Error("not_signed_in");return T}async function w(E,T,_,P){let q=_t(E,_);if(!q)throw new Error("bad_path");let J=await fetch(q,{method:P.method??"GET",headers:{Authorization:`Bearer ${T}`,...P.body!==void 0?{"Content-Type":"application/json"}:{},...P.projectSource?{"X-Project-Source":P.projectSource}:{}},body:P.body!==void 0?JSON.stringify(P.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:J.status,json:await J.json().catch(()=>null)}}function y(E,T,_){if(!E.relDir.length)return Promise.resolve(E.targetId);let P=s.get(E.batch);P||s.set(E.batch,P=new Map);let q=P,J=R=>{if(R===0)return Promise.resolve(E.targetId);let Y=E.relDir.slice(0,R).join("/"),re=q.get(Y);return re||(re=J(R-1).then(async X=>{let se=E.relDir[R-1],ee=await w(T,_,"/files",{method:"POST",body:{type:"directory",parentId:X,name:se},projectSource:E.projectSource});if(ee.status===201&&typeof ee.json?.id=="string")return ee.json.id;if(ee.status===409){let oe=await w(T,_,`/files${X==="ROOT"?"":`?parentId=${encodeURIComponent(X)}`}`,{projectSource:E.projectSource}),te=Array.isArray(oe.json)?oe.json.find(Se=>Se?.fileType==="directory"&&Se?.name===se):null;if(te?.id)return String(te.id)}throw new Error(ee.status===401?"not_signed_in":`http_${ee.status}`)}),re.catch(()=>q.delete(Y)),q.set(Y,re)),re};return J(E.relDir.length)}async function S(E,T){let{base:_,token:P}=await m(E),q=await fc(E.localPath).catch(()=>null);if(!q?.isFile())throw new Error("gone");if(q.size>52428800)throw new Error("too_large");E.size=q.size;let J=await y(E,_,P);if(!T())return;E.parentId=J;let R=_t(_,"/files/upload");if(!R)throw new Error("bad_path");let Y=`----penzor${Kr().replace(/-/g,"")}`,{head:re,tail:X}=hc(Y,{parentId:J,autoRename:"true"},E.name,lc(E.name)),se=await r(R,{Authorization:`Bearer ${P}`,"Content-Type":`multipart/form-data; boundary=${Y}`,...E.projectSource?{"X-Project-Source":E.projectSource}:{}},re,E.localPath,q.size,X,ee=>{T()&&p(E,ee)},E.abort.signal);T()&&(se.status===201||se.status===200?(E.fileId=typeof se.body?.id=="string"?se.body.id:null,p(E,E.size),u(E,"done")):u(E,"failed",hi(se.status,se.body)))}function g(E,T,_,P){let q=async()=>{let R=fp(_),Y=R?_.slice(0,-R.length):_;for(let re=0;re<1e3;re++){if(!P())throw new Error("aborted");let X=Wn(T,re===0?_:`${Y} (${re})${R}`);try{await rp(E,X)}catch(se){let ee=se.code;if(ee==="EEXIST")continue;if(ee!=="EPERM"&&ee!=="ENOTSUP"&&ee!=="EOPNOTSUPP"&&ee!=="ENOSYS"&&ee!=="EXDEV")throw se;if(await np(X).then(()=>!0,()=>!1))continue;await cp(E,X)}if(!P())throw await gi(X).catch(()=>{}),new Error("aborted");return await gi(E).catch(()=>{}),X}throw new Error("too many duplicates")},J=a.then(q,q);return a=J.catch(()=>{}),J}async function j(E,T){let _=E.dl,{base:P,token:q}=await m(E);if(!T())return;let J=_t(P,_.path);if(!J)throw new Error("bad_path");let R=E.abort.signal,Y=_.subdir?Wn(n(),_.subdir):n();await ip(Y,{recursive:!0});let re=Wn(Y,`.${E.id}-${E.attempt}.penzor-part`),X=await sp(re,"wx"),se=!1;try{let ee=new AbortController,oe=setTimeout(()=>ee.abort(),mi),te=()=>{clearTimeout(oe),oe=setTimeout(()=>ee.abort(),mi)},Se=AbortSignal.any([R,ee.signal]);try{let ve=await fetch(J,{headers:{Authorization:`Bearer ${q}`},signal:Se});if(!ve.ok)throw new Error(ve.status===401?"not_signed_in":`http_${ve.status}`);let Xe=ve.body,je=Number(ve.headers.get("content-length"))||E.size;if(_.mode!=="bytes"){let Fe=await ve.json().catch(()=>null);if(_.mode==="text"){if(typeof Fe?.content!="string")throw new Error("bad_response");let we=Buffer.from(Fe.content,"utf8");await X.writeFile(we),E.size=we.length,p(E,we.length),Xe=null}else{if(typeof Fe?.url!="string"||!/^https?:\/\//i.test(Fe.url))throw new Error("bad_response");let we=await fetch(Fe.url,{signal:Se});if(!we.ok)throw new Error(`http_${we.status}`);Xe=we.body,je=Number(we.headers.get("content-length"))||E.size}}if(Xe){E.size=je;let Fe=0;for await(let we of Xe){te();for(let Oe=0;Oe<we.length;){let{bytesWritten:I}=await X.write(we,Oe,we.length-Oe);if(I<=0)throw new Error("short_write");Oe+=I}if(Fe+=we.length,!T())throw new Error("aborted");p(E,Fe)}Fe>E.size&&(E.size=Fe)}}finally{clearTimeout(oe)}if(await X.close(),!T()||(E.localPath=await g(re,Y,_.name,T),se=!0,!T()))return;u(E,"done")}finally{se||(await X.close().catch(()=>{}),await gi(re).catch(()=>{}))}}let x=(E,T)=>{let _={...E,id:Kr(),attempt:0,done:0,state:T?"failed":"queued",error:T??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:T?o():null};return i.push(_),_};async function M(E){let T=[],_=async(P,q)=>{if(q.length>32)return!0;let J=await(q.length?op(P):fc(P)).catch(()=>null);if(!J)return!0;if(J.isFile())return T.push({path:P,size:J.size,relDir:q}),T.length<=2e3;if(!J.isDirectory())return!0;let R=(await ap(P).catch(()=>[])).filter(Y=>!Y.startsWith(".")).sort();for(let Y of R)if(!await _(Wn(P,Y),[...q,pc(P)]))return!1;return!0};for(let P of E)if(!await _(P,[]))return"too_many";return T}return t.handle("penzor:device",E=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let T=Vr();return{ok:!0,name:T?decodeURIComponent(T):null}}),t.handle("penzor:upload",async(E,T)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let _=T??{},P=Array.isArray(_.paths)?_.paths.filter(te=>typeof te=="string"&&pp(te)):[],q=typeof _.parentId=="string"&&ac.test(_.parentId)?_.parentId:null,J=typeof _.projectSource=="string"&&cc.test(_.projectSource)?_.projectSource:null;if(!P.length)return{ok:!1,error:"no_files"};if(!q||!J)return{ok:!1,error:"bad_target"};let{base:R,token:Y,account:re}=await c();if(!Y)return{ok:!1,error:"not_signed_in"};let X=await M(P);if(X==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!X.length)return{ok:!1,error:"no_files"};let se=X.filter(te=>te.size<=52428800).reduce((te,Se)=>te+Se.size,0);try{let te=await w(R,Y,"/storage/quota",{}),Se=Number(te.json?.used),ve=Number(te.json?.quota);if(te.status===200&&ve>0&&Se+se>ve)return{ok:!1,error:"quota",short:Se+se-ve}}catch{}if((await c()).account!==re)return{ok:!1,error:"account_changed"};let ee=Kr(),oe=X.map(te=>x({kind:"up",name:pc(te.path),size:te.size,projectSource:J,parentId:te.relDir.length?null:q,targetId:q,fileId:null,localPath:te.path,batch:ee,account:re,relDir:te.relDir},te.size>52428800?"too_large":void 0).id);return f(),{ok:!0,ids:oe,batch:ee}}),t.handle("penzor:download",async(E,T)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let _=T??{},P=mp.includes(_.mode)?_.mode:null,q=Jr(_.name);if(!P)return{ok:!1,error:"bad_mode"};if(!q)return{ok:!1,error:"bad_name"};let{base:J,token:R,account:Y}=await c();if(typeof _.path!="string"||!_t(J,_.path))return{ok:!1,error:"bad_path"};if(!R)return{ok:!1,error:"not_signed_in"};let re=_.subdir==null?null:Jr(_.subdir),X=x({kind:"down",name:q,size:Math.max(0,Number(_.size)||0),localPath:null,batch:typeof _.batch=="string"&&_.batch.length<=64?_.batch:Kr(),account:Y,relDir:[],dl:{path:_.path,mode:P,name:q,subdir:re}});return f(),{ok:!0,id:X.id}}),t.handle("penzor:transfers",E=>t.isTrustedSender(E)?{ok:!0,items:i.map(l)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(E,T)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let _=T??{},P=i.find(J=>J.id===_.id);if(!P)return{ok:!1,error:"not_found"};let q=()=>{P.abort?.abort(),P.abort=null,P.done=0,P.samples=[]};switch(_.op){case"pause":(P.state==="active"||P.state==="queued")&&(q(),P.state="paused",f());break;case"resume":P.state==="paused"&&(P.state="queued",f());break;case"cancel":(P.state==="active"||P.state==="queued"||P.state==="paused")&&(q(),u(P,"canceled"));break;case"retry":(P.state==="failed"||P.state==="canceled")&&(P.state="queued",P.error=null,P.finishedAt=null,P.done=0,f());break;case"dismiss":P.state!=="active"&&P.state!=="queued"&&i.splice(i.indexOf(P),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(E,T)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let _=T?.which==="all";for(let P of[...i])(P.state==="done"||P.state==="canceled"||_&&P.state==="failed")&&i.splice(i.indexOf(P),1);return{ok:!0}}),t.addQuitGuard?.(E=>{let T=i.filter(_=>_.state==="active"||_.state==="queued"||_.state==="paused").length;return T?E==="zh"?{message:`\u8FD8\u6709 ${T} \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:T===1?"1 file hasn't finished transferring":`${T} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>i.map(l)}}import{readFileSync as Cp,writeFileSync as Ap,mkdirSync as xp,chmodSync as Tp,renameSync as Ip}from"node:fs";import{join as Rp}from"node:path";import{mkdirSync as wp,readFileSync as bp,renameSync as Sp,unlinkSync as vp,writeFileSync as kp}from"node:fs";import{dirname as Ep,join as _p}from"node:path";import{randomUUID as gc}from"node:crypto";var vi=t=>_p(t,"content-sync","active-account.json"),wi=()=>Error("Invalid content sync account binding; original data was retained");function Vn(t){try{let e=JSON.parse(bp(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 wi();return e}catch(e){if(e?.code==="ENOENT")return null;throw wi()}}function ki(t,e){wp(Ep(t),{recursive:!0,mode:448});let n=t+".tmp-"+gc();try{kp(n,JSON.stringify(e),{flag:"wx",mode:384}),Sp(n,t)}finally{try{vp(n)}catch{}}}var bi=new WeakMap,Si=new WeakSet;function mc(t,e){let n=bi.get(t);return n||bi.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function Ei(t){if(Si.has(t))throw wi()}function un(t,e,n){if(!t.contentSync||e===n)return;let r=vi(t.homeDir());try{let o=Vn(r);ki(r,{version:1,account:o?.account??null,epoch:gc(),pending:!0}),Si.delete(t)}catch(o){throw Si.add(t),o}finally{for(let o of bi.get(t)??[])o()}}function Dp(t){let e=()=>Rp(t(),"auth-accounts.json");return{read:()=>Cp(e(),"utf8"),write:n=>{xp(t(),{recursive:!0});let r=`${e()}.tmp`;Ap(r,n,{encoding:"utf8",mode:384}),Tp(r,384),Ip(r,e())}}}var wc=t=>fa(t,Dp(()=>t.homeDir())),bc=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],_i=t=>bc.every(e=>typeof t[e]=="function");function Ci(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=wc(t),o=0,i=()=>{let c=t.readCreds();return Fn(c.cloudUrl,c.token)},s=c=>Ue(c.cloudUrl??"",c.token??""),a=null;t.handle("auth:status",async c=>{if(!t.isTrustedSender(c))return n;let l=o,u=i(),{base:f}=await t.getCloud(),h=t.readCreds().token,p=h?await Bn(f,h):null,m=await t.accountBackendState(),{base:w}=await t.getCloud(),y=t.readCreds(),S=Fn(w,y.token)!==Fn(f,h),g=Fn(f,h);!S&&p?.status==="ok"&&p.user&&(a={key:g,user:p.user},r.rememberForsionAccount({...y,cloudUrl:f},p.user));let j=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:Ue(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!==o||i()!==u)return;let M=()=>{if(l!==o||i()!==u)throw yc};try{await t.accountClear(M,()=>{un(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(E){if(E!==yc)throw E}});let x=t.readCreds();return{loggedIn:!!x.token,tokenValid:null,cloudUrl:x.cloudUrl||f,accountId:Ue(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:Ue(f,h),username:j?.username||null,nickname:j?.nickname||null,avatar:j?.avatar||null,membershipTier:j?.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=++o;return r.cancelForsionLogin(),t.accountTransition(async()=>{let f=r.savedForsionAccount(l);return await t.accountCommit(f,()=>{if(u!==o)throw new Error("Account switch cancelled.")},()=>{un(t,t.accountId?.()??null,s(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=++o;r.cancelForsionLogin();let{base:f}=await t.getCloud();if(u!==o)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!==o)throw new Error("Sign-in cancelled.")},()=>{un(t,t.accountId?.()??null,s(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,()=>{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,s(c),s(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=i(),f=t.readCreds().token;if(!Pr(f))return;let{base:h}=await t.getCloud(),p=await $r(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!==o||i()!==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 yc=Symbol("stale-auth-intent");import{promises as mn}from"node:fs";import Zt from"node:path";import{execFile as ah}from"node:child_process";import ch from"node:os";var Ai=null;function Sc(t){Ai=t}var vc=null;function kc(t){vc=t}var Ec=()=>vc;function He(){if(!Ai)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return Ai}var Pe=()=>He().accountId();function Yn(t=Pe()){return t?Ee().sha256Hex(t):"signed-out"}var et=(t=Pe())=>He().readConfig(t),Ct=(t,e=Pe())=>He().writeConfig(t,e),dn=(t,e=Pe())=>He().updateConfig(t,e),At=(t=Pe())=>He().cloudVaultDir(t),Xr=t=>He().isManagedCloudVault(t);function Op(t,e){let n=Object.create(null);for(let i=0;i<e.length;i++){let s=e[i];n[s]?n[s].push(i):n[s]=[i]}let o=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let i=0;i<t.length;i++){let s=t[i],a=n[s]||[],c=0,l=o[0];for(let u of a){let f;for(f=c;f<o.length&&!(o[f].buffer2index<u&&(f===o.length-1||o[f+1].buffer2index>u));f++);if(f<o.length){let h={buffer1index:i,buffer2index:u,chain:o[f]};if(c===o.length?o.push(l):o[c]=l,c=f+1,l=h,c===o.length)break}}o[c]=l}return o[o.length-1]}function _c(t,e){let n=Op(t,e),r=[],o=t.length,i=e.length;for(let s=n;s!==null;s=s.chain){let a=o-s.buffer1index-1,c=i-s.buffer2index-1;o=s.buffer1index,i=s.buffer2index,(a||c)&&r.push({buffer1:[o+1,a],buffer1Content:t.slice(o+1,o+1+a),buffer2:[i+1,c],buffer2Content:e.slice(i+1,i+1+c)})}return r.reverse(),r}function Mp(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]})}_c(e,t).forEach(c=>o(c,"a")),_c(e,n).forEach(c=>o(c,"b")),r.sort((c,l)=>c.oStart-l.oStart);let i=[],s=0;function a(c){c>s&&(i.push({stable:!0,buffer:"o",bufferStart:s,bufferLength:c-s,bufferContent:e.slice(s,c)}),s=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;i.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,j=g+c.oLength,x=c.abStart,M=x+c.abLength,E=h[c.ab];E[0]=Math.min(x,E[0]),E[1]=Math.max(M,E[1]),E[2]=Math.min(g,E[2]),E[3]=Math.max(j,E[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)};i.push(S)}s=u}return a(e.length),i}function Cc(t,e,n,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof t=="string"&&(t=t.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof n=="string"&&(n=n.split(r.stringSeparator));let i=[],s=Mp(t,e,n),a=[];function c(){a.length&&i.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 s.forEach(u=>{u.stable?a.push(...u.bufferContent):r.excludeFalseConflicts&&l(u.aContent,u.bContent)?a.push(...u.aContent):(c(),i.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),c(),i}function Zr(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),o=n<0?t:t.slice(n+1),i=o.lastIndexOf("."),s=i>0?o.slice(0,i):o,a=i>0?o.slice(i):"",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}${s} (conflict ${l})${a}`}function Pp(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,i=r?t.slice(n):"";return`${o}-${e}${i}`}function $p(t){let e=3735928559,n=1103547991;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o);e=Math.imul(e^i,2654435761),n=Math.imul(n^i,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 Ac(t,e,n){let r=Cc(t.split(`
|
|
209
|
+
`}}function zs(t,e){let n=t.filter(([o])=>e-o<=3e3);if(n.length<2)return 0;let[r,i]=n[0],[s,a]=n[n.length-1];return s>r?Math.max(0,(a-i)/(s-r)*1e3):0}function Bs(t,e){let n=e??{};return t===401?"not_signed_in":n.code==="STORAGE_QUOTA_EXCEEDED"?"quota":n.code==="STORAGE_BUSY"||n.code==="STORAGE_RECONCILIATION_REQUIRED"?"storage_unavailable":n.code==="FILE_TOO_LARGE"||t===413?"too_large":typeof n.detail=="string"&&/quota exceeded/i.test(n.detail)?"quota":n.code==="STORAGE_NOT_CONFIGURED"?"storage_unavailable":`http_${t}`}var dh=3,Ws=6e4,fh=200,ph=Ul;function Yl(t,e,n,r){let{head:i,tail:s}=ql(t,e,n,r);return{head:Buffer.from(i,"utf8"),tail:Buffer.from(s,"utf8")}}function hh(t,e,n,r,i,s,a,o){return new Promise((l,c)=>{let u=new URL(t),f=(u.protocol==="https:"?ah:oh)(u,{method:"POST",headers:{...e,"Content-Length":String(n.length+i+s.length)}},p=>{let m=[];p.on("data",y=>m.push(y)),p.on("end",()=>{let y=null;try{y=JSON.parse(Buffer.concat(m).toString("utf8"))}catch{}l({status:p.statusCode??0,body:y})}),p.on("error",c)}),g=()=>{f.destroy(new Error("aborted"))};if(o.aborted)return g();o.addEventListener("abort",g,{once:!0}),f.setTimeout(Ws,()=>f.destroy(new Error("timeout"))),f.on("error",p=>{o.removeEventListener("abort",g),c(p)}),(async()=>{try{f.write(n);let p=0;for await(let m of Zp(r)){let y=m;if(p+=y.length,p>i)throw new Error("changed");f.write(y)||await new Promise(b=>f.once("drain",b)),a(p)}if(p!==i)throw new Error("changed");f.end(s)}catch(p){f.destroy(p)}})()})}function Gs(t,e={}){let n=e.downloadsDir??(()=>ur(lh(),"Downloads")),r=e.post??hh,i=e.now??Date.now,s=[],a=new Map,o=Promise.resolve(),l=async()=>{let E=await t.getCloud(),D=typeof t.accountId=="function"?t.accountId():null;return{...E,account:D||`${E.base}|${E.token}`}},c=E=>{let{account:D,attempt:x,relDir:L,abort:V,samples:H,dl:N,...Y}=E;return{...Y,speed:E.state==="active"?zs(H,i()):0}},u=(E,D,x=null)=>{E.state=D,E.error=x,E.abort=null,E.finishedAt=i(),E.samples=[];let L=s.filter(V=>V.state==="done"||V.state==="canceled");for(let V of L.slice(0,Math.max(0,L.length-fh)))s.splice(s.indexOf(V),1);f()};function f(){for(let E of["up","down"]){let D=s.filter(x=>x.kind===E&&x.state==="active").length;for(let x of s){if(D>=dh)break;if(x.kind!==E||x.state!=="queued")continue;D++,x.state="active",x.startedAt=i(),x.done=0,x.samples=[[i(),0]],x.abort=new AbortController;let L=++x.attempt,V=()=>x.attempt===L&&x.state==="active";(E==="up"?_(x,V):T(x,V)).catch(H=>{V()&&u(x,"failed",g(H))})}}}let g=E=>{let D=String(E?.message||E);return D==="changed"||D==="too_large"||D==="quota"||D==="account_changed"||D==="not_signed_in"||D.startsWith("http_")||D==="bad_response"||D==="gone"?D:"network"},p=(E,D)=>{E.done=D;let x=i(),L=E.samples[E.samples.length-1];for((!L||x-L[0]>=200)&&E.samples.push([x,D]);E.samples.length>2&&x-E.samples[0][0]>3500;)E.samples.shift()};async function m(E){let D=await l();if(D.account!==E.account)throw new Error("account_changed");if(!D.token)throw new Error("not_signed_in");return D}async function y(E,D,x,L){let V=Nt(E,x);if(!V)throw new Error("bad_path");let H=await fetch(V,{method:L.method??"GET",headers:{Authorization:`Bearer ${D}`,...L.body!==void 0?{"Content-Type":"application/json"}:{},...L.projectSource?{"X-Project-Source":L.projectSource}:{}},body:L.body!==void 0?JSON.stringify(L.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:H.status,json:await H.json().catch(()=>null)}}function b(E,D,x){if(!E.relDir.length)return Promise.resolve(E.targetId);let L=a.get(E.batch);L||a.set(E.batch,L=new Map);let V=L,H=N=>{if(N===0)return Promise.resolve(E.targetId);let Y=E.relDir.slice(0,N).join("/"),ee=V.get(Y);return ee||(ee=H(N-1).then(async J=>{let se=E.relDir[N-1],te=await y(D,x,"/files",{method:"POST",body:{type:"directory",parentId:J,name:se},projectSource:E.projectSource});if(te.status===201&&typeof te.json?.id=="string")return te.json.id;if(te.status===409){let ae=await y(D,x,`/files${J==="ROOT"?"":`?parentId=${encodeURIComponent(J)}`}`,{projectSource:E.projectSource}),Q=Array.isArray(ae.json)?ae.json.find(me=>me?.fileType==="directory"&&me?.name===se):null;if(Q?.id)return String(Q.id)}throw new Error(te.status===401?"not_signed_in":`http_${te.status}`)}),ee.catch(()=>V.delete(Y)),V.set(Y,ee)),ee};return H(E.relDir.length)}async function _(E,D){let{base:x,token:L}=await m(E),V=await Gl(E.localPath).catch(()=>null);if(!V?.isFile())throw new Error("gone");if(V.size>52428800)throw new Error("too_large");E.size=V.size;let H=await b(E,x,L);if(!D())return;E.parentId=H;let N=Nt(x,"/files/upload");if(!N)throw new Error("bad_path");let Y=`----penzor${wi().replace(/-/g,"")}`,{head:ee,tail:J}=Yl(Y,{parentId:H,autoRename:"true"},E.name,Bl(E.name)),se=await r(N,{Authorization:`Bearer ${L}`,"Content-Type":`multipart/form-data; boundary=${Y}`,...E.projectSource?{"X-Project-Source":E.projectSource}:{}},ee,E.localPath,V.size,J,te=>{D()&&p(E,te)},E.abort.signal);D()&&(se.status===201||se.status===200?(E.fileId=typeof se.body?.id=="string"?se.body.id:null,p(E,E.size),u(E,"done")):u(E,"failed",Bs(se.status,se.body)))}function h(E,D,x,L){let V=async()=>{let N=ch(x),Y=N?x.slice(0,-N.length):x;for(let ee=0;ee<1e3;ee++){if(!L())throw new Error("aborted");let J=ur(D,ee===0?x:`${Y} (${ee})${N}`);try{await eh(E,J)}catch(se){let te=se.code;if(te==="EEXIST")continue;if(te!=="EPERM"&&te!=="ENOTSUP"&&te!=="EOPNOTSUPP"&&te!=="ENOSYS"&&te!=="EXDEV")throw se;if(await Qp(J).then(()=>!0,()=>!1))continue;await sh(E,J)}if(!L())throw await qs(J).catch(()=>{}),new Error("aborted");return await qs(E).catch(()=>{}),J}throw new Error("too many duplicates")},H=o.then(V,V);return o=H.catch(()=>{}),H}async function T(E,D){let x=E.dl,{base:L,token:V}=await m(E);if(!D())return;let H=Nt(L,x.path);if(!H)throw new Error("bad_path");let N=E.abort.signal,Y=x.subdir?ur(n(),x.subdir):n();await nh(Y,{recursive:!0});let ee=ur(Y,`.${E.id}-${E.attempt}.penzor-part`),J=await rh(ee,"wx"),se=!1;try{let te=new AbortController,ae=setTimeout(()=>te.abort(),Ws),Q=()=>{clearTimeout(ae),ae=setTimeout(()=>te.abort(),Ws)},me=AbortSignal.any([N,te.signal]);try{let ge=await fetch(H,{headers:{Authorization:`Bearer ${V}`},signal:me});if(!ge.ok)throw new Error(ge.status===401?"not_signed_in":`http_${ge.status}`);let Pe=ge.body,Ce=Number(ge.headers.get("content-length"))||E.size;if(x.mode!=="bytes"){let He=await ge.json().catch(()=>null);if(x.mode==="text"){if(typeof He?.content!="string")throw new Error("bad_response");let Ae=Buffer.from(He.content,"utf8");await J.writeFile(Ae),E.size=Ae.length,p(E,Ae.length),Pe=null}else{if(typeof He?.url!="string"||!/^https?:\/\//i.test(He.url))throw new Error("bad_response");let Ae=await fetch(He.url,{signal:me});if(!Ae.ok)throw new Error(`http_${Ae.status}`);Pe=Ae.body,Ce=Number(Ae.headers.get("content-length"))||E.size}}if(Pe){E.size=Ce;let He=0;for await(let Ae of Pe){Q();for(let ut=0;ut<Ae.length;){let{bytesWritten:M}=await J.write(Ae,ut,Ae.length-ut);if(M<=0)throw new Error("short_write");ut+=M}if(He+=Ae.length,!D())throw new Error("aborted");p(E,He)}He>E.size&&(E.size=He)}}finally{clearTimeout(ae)}if(await J.close(),!D()||(E.localPath=await h(ee,Y,x.name,D),se=!0,!D()))return;u(E,"done")}finally{se||(await J.close().catch(()=>{}),await qs(ee).catch(()=>{}))}}let v=(E,D)=>{let x={...E,id:wi(),attempt:0,done:0,state:D?"failed":"queued",error:D??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:D?i():null};return s.push(x),x};async function I(E){let D=[],x=async(L,V)=>{if(V.length>32)return!0;let H=await(V.length?th(L):Gl(L)).catch(()=>null);if(!H)return!0;if(H.isFile())return D.push({path:L,size:H.size,relDir:V}),D.length<=2e3;if(!H.isDirectory())return!0;let N=(await ih(L).catch(()=>[])).filter(Y=>!Y.startsWith(".")).sort();for(let Y of N)if(!await x(ur(L,Y),[...V,Vl(L)]))return!1;return!0};for(let L of E)if(!await x(L,[]))return"too_many";return D}return t.handle("penzor:device",E=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let D=hi();return{ok:!0,name:D?decodeURIComponent(D):null}}),t.handle("penzor:upload",async(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=Array.isArray(x.paths)?x.paths.filter(Q=>typeof Q=="string"&&uh(Q)):[],V=typeof x.parentId=="string"&&Hl.test(x.parentId)?x.parentId:null,H=typeof x.projectSource=="string"&&zl.test(x.projectSource)?x.projectSource:null;if(!L.length)return{ok:!1,error:"no_files"};if(!V||!H)return{ok:!1,error:"bad_target"};let{base:N,token:Y,account:ee}=await l();if(!Y)return{ok:!1,error:"not_signed_in"};let J=await I(L);if(J==="too_many")return{ok:!1,error:"too_many",max:2e3};if(!J.length)return{ok:!1,error:"no_files"};let se=J.filter(Q=>Q.size<=52428800).reduce((Q,me)=>Q+me.size,0);try{let Q=await y(N,Y,"/storage/quota",{}),me=Number(Q.json?.used),ge=Number(Q.json?.quota);if(Q.status===200&&ge>0&&me+se>ge)return{ok:!1,error:"quota",short:me+se-ge}}catch{}if((await l()).account!==ee)return{ok:!1,error:"account_changed"};let te=wi(),ae=J.map(Q=>v({kind:"up",name:Vl(Q.path),size:Q.size,projectSource:H,parentId:Q.relDir.length?null:V,targetId:V,fileId:null,localPath:Q.path,batch:te,account:ee,relDir:Q.relDir},Q.size>52428800?"too_large":void 0).id);return f(),{ok:!0,ids:ae,batch:te}}),t.handle("penzor:download",async(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=ph.includes(x.mode)?x.mode:null,V=yi(x.name);if(!L)return{ok:!1,error:"bad_mode"};if(!V)return{ok:!1,error:"bad_name"};let{base:H,token:N,account:Y}=await l();if(typeof x.path!="string"||!Nt(H,x.path))return{ok:!1,error:"bad_path"};if(!N)return{ok:!1,error:"not_signed_in"};let ee=x.subdir==null?null:yi(x.subdir),J=v({kind:"down",name:V,size:Math.max(0,Number(x.size)||0),localPath:null,batch:typeof x.batch=="string"&&x.batch.length<=64?x.batch:wi(),account:Y,relDir:[],dl:{path:x.path,mode:L,name:V,subdir:ee}});return f(),{ok:!0,id:J.id}}),t.handle("penzor:transfers",E=>t.isTrustedSender(E)?{ok:!0,items:s.map(c)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D??{},L=s.find(H=>H.id===x.id);if(!L)return{ok:!1,error:"not_found"};let V=()=>{L.abort?.abort(),L.abort=null,L.done=0,L.samples=[]};switch(x.op){case"pause":(L.state==="active"||L.state==="queued")&&(V(),L.state="paused",f());break;case"resume":L.state==="paused"&&(L.state="queued",f());break;case"cancel":(L.state==="active"||L.state==="queued"||L.state==="paused")&&(V(),u(L,"canceled"));break;case"retry":(L.state==="failed"||L.state==="canceled")&&(L.state="queued",L.error=null,L.finishedAt=null,L.done=0,f());break;case"dismiss":L.state!=="active"&&L.state!=="queued"&&s.splice(s.indexOf(L),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(E,D)=>{if(!t.isTrustedSender(E))return{ok:!1,error:"untrusted"};let x=D?.which==="all";for(let L of[...s])(L.state==="done"||L.state==="canceled"||x&&L.state==="failed")&&s.splice(s.indexOf(L),1);return{ok:!0}}),t.addQuitGuard?.(E=>{let D=s.filter(x=>x.state==="active"||x.state==="queued"||x.state==="paused").length;return D?E==="zh"?{message:`\u8FD8\u6709 ${D} \u4E2A\u6587\u4EF6\u6CA1\u4F20\u5B8C`,detail:"\u73B0\u5728\u9000\u51FA\u4F1A\u4E2D\u65AD\uFF0C\u4E0B\u6B21\u6253\u5F00\u8981\u91CD\u65B0\u4F20\u3002"}:{message:D===1?"1 file hasn't finished transferring":`${D} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>s.map(c)}}import{readFileSync as kh,writeFileSync as Eh,mkdirSync as _h,chmodSync as Ch,renameSync as Ah}from"node:fs";import{join as xh}from"node:path";import{mkdirSync as gh,readFileSync as mh,renameSync as yh,unlinkSync as wh,writeFileSync as bh}from"node:fs";import{dirname as Sh,join as vh}from"node:path";import{randomUUID as Jl}from"node:crypto";var Ks=t=>vh(t,"content-sync","active-account.json"),Vs=()=>Error("Invalid content sync account binding; original data was retained");function dr(t){try{let e=JSON.parse(mh(t,"utf8"));if(e?.version!==1||!(e.account===null&&e.pending===!0||typeof e.account=="string"&&/^[a-f0-9]{64}$/.test(e.account))||e.epoch!==void 0&&(typeof e.epoch!="string"||!/^[a-f0-9-]{36}$/i.test(e.epoch))||e.pending!==void 0&&typeof e.pending!="boolean"||e.pending&&!e.epoch)throw Vs();return e}catch(e){if(e?.code==="ENOENT")return null;throw Vs()}}function Xs(t,e){gh(Sh(t),{recursive:!0,mode:448});let n=t+".tmp-"+Jl();try{bh(n,JSON.stringify(e),{flag:"wx",mode:384}),yh(n,t)}finally{try{wh(n)}catch{}}}var Ys=new WeakMap,Js=new WeakSet;function Kl(t,e){let n=Ys.get(t);return n||Ys.set(t,n=new Set),n.add(e),()=>{n.delete(e)}}function Zs(t){if(Js.has(t))throw Vs()}function En(t,e,n){if(!t.contentSync||e===n)return;let r=Ks(t.homeDir());try{let i=dr(r);Xs(r,{version:1,account:i?.account??null,epoch:Jl(),pending:!0}),Js.delete(t)}catch(i){throw Js.add(t),i}finally{for(let i of Ys.get(t)??[])i()}}function Th(t){let e=()=>xh(t(),"auth-accounts.json");return{read:()=>kh(e(),"utf8"),write:n=>{_h(t(),{recursive:!0});let r=`${e()}.tmp`;Eh(r,n,{encoding:"utf8",mode:384}),Ch(r,384),Ah(r,e())}}}var Zl=t=>Ga(t,Th(()=>t.homeDir())),Ql=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],Qs=t=>Ql.every(e=>typeof t[e]=="function");function eo(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=Zl(t),i=0,s=()=>{let l=t.readCreds();return rr(l.cloudUrl,l.token)},a=l=>Ve(l.cloudUrl??"",l.token??""),o=null;t.handle("auth:status",async l=>{if(!t.isTrustedSender(l))return n;let c=i,u=s(),{base:f}=await t.getCloud(),g=t.readCreds().token,p=g?await lr(f,g):null,m=await t.accountBackendState(),{base:y}=await t.getCloud(),b=t.readCreds(),_=rr(y,b.token)!==rr(f,g),h=rr(f,g);!_&&p?.status==="ok"&&p.user&&(o={key:h,user:p.user},r.rememberForsionAccount({...b,cloudUrl:f},p.user));let T=_?void 0:p?.status==="ok"?p.user:p?.status==="offline"&&o?.key===h?o.user:void 0;if(_)return{loggedIn:!!b.token,tokenValid:null,cloudUrl:y,accountId:Ve(y,b.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:b.token?"tangu-login":null,backendState:m};if(p?.status==="expired"){await t.accountTransition(async()=>{if(c!==i||s()!==u)return;let I=()=>{if(c!==i||s()!==u)throw Xl};try{await t.accountClear(I,()=>{En(t,t.accountId?.()??null,null),t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++i,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),o=null})}catch(E){if(E!==Xl)throw E}});let v=t.readCreds();return{loggedIn:!!v.token,tokenValid:null,cloudUrl:v.cloudUrl||f,accountId:Ve(v.cloudUrl||f,v.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:v.token?"tangu-login":null,backendState:m}}return{loggedIn:!!g,tokenValid:p&&p.status==="ok"?!0:null,cloudUrl:f,accountId:Ve(f,g),username:T?.username||null,nickname:T?.nickname||null,avatar:T?.avatar||null,membershipTier:T?.membershipTier||null,tokenSource:g?"tangu-login":null,backendState:m}}),t.handle("auth:accounts",l=>t.isTrustedSender(l)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(l,c)=>{if(!t.isTrustedSender(l))return e;if(typeof c!="string")throw new Error("Invalid account.");let u=++i;return r.cancelForsionLogin(),t.accountTransition(async()=>{let f=r.savedForsionAccount(c);return await t.accountCommit(f,()=>{if(u!==i)throw new Error("Account switch cancelled.")},()=>{En(t,t.accountId?.()??null,a(f)),r.rememberForsionAccount(f),o=null}),{ok:!0,cloudUrl:f.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(l,c)=>{if(!t.isTrustedSender(l))return e;let u=++i;r.cancelForsionLogin();let{base:f}=await t.getCloud();if(u!==i)throw new Error("Sign-in cancelled.");let g=(c||f||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(g,m=>t.broadcast("auth:device",m),(m,y)=>t.accountTransition(()=>t.accountCommit(m,()=>{if(y(),u!==i)throw new Error("Sign-in cancelled.")},()=>{En(t,t.accountId?.()??null,a(m)),r.rememberForsionAccount(m),o=null})))).cloudUrl}}),t.handle("auth:logout",async l=>t.isTrustedSender(l)?(++i,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:c}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{En(t,t.accountId?.()??null,null),r.forgetForsionAccount(u),o=null,c&&u.token&&fetch(`${c}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${u.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:l,current:c})=>{try{En(t,a(l),a(c))}catch{t.log("[content-sync] account transition could not be recorded; sync is stopped")}++i,r.cancelForsionLogin(),l.token&&!c.token&&r.forgetForsionAccount(l),o=null,r.rememberForsionAccount(c)}),t.setTokenRefresher(async l=>{let c=i,u=s(),f=t.readCreds().token;if(!ni(f))return;let{base:g}=await t.getCloud(),p=await ri(g,f,l,`desktop/${t.appVersion()}`);if(!p){t.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}c!==i||s()!==u||(r.rememberForsionAccount({cloudUrl:g,token:p}),t.writeCreds({cloudUrl:g,token:p}),t.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),t.log("[forsion-extend] account core registered")}var Xl=Symbol("stale-auth-intent");import{promises as Dn}from"node:fs";import dn from"node:path";import{execFile as dg}from"node:child_process";import fg from"node:os";var to=null;function ec(t){to=t}var tc=null;function nc(t){tc=t}var rc=()=>tc;function Le(){if(!to)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return to}var Be=()=>Le().accountId();function _n(t=Be()){return t?Ee().sha256Hex(t):"signed-out"}var ot=(t=Be())=>Le().readConfig(t),Pt=(t,e=Be())=>Le().writeConfig(t,e),Cn=(t,e=Be())=>Le().updateConfig(t,e),$t=(t=Be())=>Le().cloudVaultDir(t),bi=t=>Le().isManagedCloudVault(t);function Ih(t,e){let n=Object.create(null);for(let s=0;s<e.length;s++){let a=e[s];n[a]?n[a].push(s):n[a]=[s]}let i=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let s=0;s<t.length;s++){let a=t[s],o=n[a]||[],l=0,c=i[0];for(let u of o){let f;for(f=l;f<i.length&&!(i[f].buffer2index<u&&(f===i.length-1||i[f+1].buffer2index>u));f++);if(f<i.length){let g={buffer1index:s,buffer2index:u,chain:i[f]};if(l===i.length?i.push(c):i[l]=c,l=f+1,c=g,l===i.length)break}}i[l]=c}return i[i.length-1]}function ic(t,e){let n=Ih(t,e),r=[],i=t.length,s=e.length;for(let a=n;a!==null;a=a.chain){let o=i-a.buffer1index-1,l=s-a.buffer2index-1;i=a.buffer1index,s=a.buffer2index,(o||l)&&r.push({buffer1:[i+1,o],buffer1Content:t.slice(i+1,i+1+o),buffer2:[s+1,l],buffer2Content:e.slice(s+1,s+1+l)})}return r.reverse(),r}function Rh(t,e,n){let r=[];function i(l,c){r.push({ab:c,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}ic(e,t).forEach(l=>i(l,"a")),ic(e,n).forEach(l=>i(l,"b")),r.sort((l,c)=>l.oStart-c.oStart);let s=[],a=0;function o(l){l>a&&(s.push({stable:!0,buffer:"o",bufferStart:a,bufferLength:l-a,bufferContent:e.slice(a,l)}),a=l)}for(;r.length;){let l=r.shift(),c=l.oStart,u=l.oStart+l.oLength,f=[l];for(o(c);r.length;){let g=r[0],p=g.oStart;if(p>u)break;u=Math.max(u,p+g.oLength),f.push(r.shift())}if(f.length===1){if(l.abLength>0){let g=l.ab==="a"?t:n;s.push({stable:!0,buffer:l.ab,bufferStart:l.abStart,bufferLength:l.abLength,bufferContent:g.slice(l.abStart,l.abStart+l.abLength)})}}else{let g={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;f.length;){l=f.shift();let h=l.oStart,T=h+l.oLength,v=l.abStart,I=v+l.abLength,E=g[l.ab];E[0]=Math.min(v,E[0]),E[1]=Math.max(I,E[1]),E[2]=Math.min(h,E[2]),E[3]=Math.max(T,E[3])}let p=g.a[0]+(c-g.a[2]),m=g.a[1]+(u-g.a[3]),y=g.b[0]+(c-g.b[2]),b=g.b[1]+(u-g.b[3]),_={stable:!1,aStart:p,aLength:m-p,aContent:t.slice(p,m),oStart:c,oLength:u-c,oContent:e.slice(c,u),bStart:y,bLength:b-y,bContent:n.slice(y,b)};s.push(_)}a=u}return o(e.length),s}function sc(t,e,n,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof t=="string"&&(t=t.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof n=="string"&&(n=n.split(r.stringSeparator));let s=[],a=Rh(t,e,n),o=[];function l(){o.length&&s.push({ok:o}),o=[]}function c(u,f){if(u.length!==f.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==f[g])return!1;return!0}return a.forEach(u=>{u.stable?o.push(...u.bufferContent):r.excludeFalseConflicts&&c(u.aContent,u.bContent)?o.push(...u.aContent):(l(),s.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),l(),s}function Si(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),i=n<0?t:t.slice(n+1),s=i.lastIndexOf("."),a=s>0?i.slice(0,s):i,o=s>0?i.slice(s):"",l=u=>String(u).padStart(2,"0"),c=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${r}${a} (conflict ${c})${o}`}function Dh(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),i=r?t.slice(0,n):t,s=r?t.slice(n):"";return`${i}-${e}${s}`}function Oh(t){let e=3735928559,n=1103547991;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=Math.imul(e^s,2654435761),n=Math.imul(n^s,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let r=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${r.toString(36)}`}var An=(t,e)=>e.seq===t.seq&&e.hash!==null&&e.hash!==t.hash,oc=(t,e)=>e.seq!==t.seq||An(t,e);function vi(t,e,n){if(t===null&&e===null&&n===null)return{kind:"none"};if(n===null)return t===null?e?{kind:"dropShadow"}:{kind:"none"}:e?t===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(t===null)return e?oc(e,n)?{kind:"pull"}:{kind:"pushDelete"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"hold"};if(An(e,n))return t===n.hash?{kind:"adopt"}:t===e.hash?{kind:"pull"}:{kind:"hold"};let r=t!==e.hash,i=oc(e,n);return!r&&!i?{kind:"none"}:r?i?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function ac(t,e,n){let r=sc(t.split(`
|
|
210
210
|
`),e.split(`
|
|
211
211
|
`),n.split(`
|
|
212
|
-
`),{excludeFalseConflicts:!0}),
|
|
213
|
-
`)}function xi(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var xc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function Tc(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function Ti(t){let e=t??"";if(/^(?:ENOENT|EACCES|EPERM|EBUSY|EISDIR|ENOTDIR|EEXIST|EMFILE|ENFILE|ENOSPC|EROFS|EIO|ENAMETOOLONG)\b/.test(e))return"errOther";let n=/^(?:cloud|sse) http (\d{3})\b/i.exec(e);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|etimedout/i.test(e)?"errTimeout":!e||/fetch failed|econn|enotfound|eai_again|enetunreach|ehostunreach|enetdown|network|socket|terminated|other side closed|und_err|^cloud http 0\b/i.test(e)?"errOffline":"errOther"}function Ic(t){if(!(t instanceof Error))return;let e=t.cause,n=e&&typeof e=="object"?[e.code,e.message].filter(r=>typeof r=="string"&&r).join(" "):"";return n?`${t.message} (${n})`:t.message}function Rc(t,e){if(t==="offline")return Ti(e);if(t==="auth-required")return e==="not-logged-in"?null:"errAuth";if(t!=="error")return null;let n=e??"";return n.startsWith("vault-missing")?"errVaultMissing":n.startsWith("scan-failed")?"errScan":n.startsWith("mirror-missing")?"errMirrorMissing":"errOther"}function eo(t,e=0){if(/^(account_changed|content_sync_closed|paused)$/.test(t)||/^File exceeds \d+ MB/.test(t))return null;if(t==="not_signed_in"||e===401||e===403)return"errAuth";let n=/^content_http_(\d{3})$/.exec(t);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|aborted due to timeout/i.test(t)?"errTimeout":/fetch failed|econn|enotfound|eai_again|network|socket/i.test(t)?"errOffline":/^Sync root (unavailable|changed|is not a directory)|^content_roots_changed/.test(t)?"errVaultMissing":e?"errHttp":"errOther"}function to(t){let e=null;return{error(n){n!==e&&(e=n,t?.(n))},ok(){e=null}}}var Np=/[\u0000-\u001f\u007f]/;function Nt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||Np.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function Ii(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Nt(n):n.startsWith(`${e}/`)?Nt(n.slice(e.length+1)):null}function Dc(t,e){return e===""?t:`${e}/${t}`}function Gn(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function ze(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var ot=t=>t==="page"||t==="db";var jp=1024,Te=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},Oc=t=>12e4+Math.ceil(t/256);function Fp(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 Mc(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=()=>t.getToken?.()??t.token,r=async(s,a)=>{let c=n();for(let l=0;;l++){let u={...a.headers,Authorization:`Bearer ${c}`},f=await fetch(s,{...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}},o=async(s,a,c)=>{let l={Authorization:`Bearer ${t.token}`,...c?.headers};s!=="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>=jp&&(l["Content-Encoding"]="gzip",u=await ua(u))):c?.form&&(u=c.form);let f=await r(a,{method:s,headers:l,body:u,signal:Fp(c?.timeoutMs??3e4,c?.signal)});if(!f.ok){let p=null;try{p=await f.json()}catch{}throw n(),new Te(f.status,p,a)}let h=await f.json();return n(),h},i=s=>new URLSearchParams(s).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(s){let a=await o("GET",`${e}/vaults/${s}/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(s,a){let c=await o("GET",`${e}/vaults/${s}/file?${i({path:a})}`);return{content:String(c.content??""),seq:Number(c.seq??0),hash:c.hash??null}},putFile(s,a,c,l,u=!1){return o("PUT",`${e}/vaults/${s}/file`,{json:{path:a,content:c,baseSeq:l,...u?{force:!0}:{}}})},async deleteFile(s,a,c,l){let u={path:a};c!==void 0&&(u.baseSeq=String(c)),await o("DELETE",`${e}/vaults/${s}/file?${i(u)}`,l?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(s,a,c){return o("POST",`${e}/vaults/${s}/move`,{json:{from:a,to:c}})},renameFolder(s,a,c){return o("POST",`${e}/vaults/${s}/folders/rename`,{json:{path:a,newName:c}})},moveFolder(s,a,c){return o("POST",`${e}/vaults/${s}/folders/move`,{json:{path:a,dest:c}})},async deleteFolder(s,a){await o("DELETE",`${e}/vaults/${s}/folders?${i({path:a})}`)},putBinary(s,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/${s}/binary`,{form:u,timeoutMs:Oc(c.length),signal:l?.signal})},async listVersions(s,a){return((await o("GET",`${e}/vaults/${s}/file/versions?${i({path:a})}`)).versions??[]).map(l=>({id:String(l.id),seq:Number(l.seq??0)}))},async getVersion(s,a){let c=await o("GET",`${e}/vaults/${s}/file/versions/${a}`);return String(c.content??"")},async getAsset(s,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/${s}/asset?${i({ref:a})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:l.signal});if(!h.ok)throw new Te(h.redirected&&(h.status===401||h.status===403)?502:h.status,null,"asset:"+a);clearTimeout(f),f=setTimeout(u,Oc(Number(h.headers.get("content-length"))||0));let p=new Uint8Array(await h.arrayBuffer());return n(),p}finally{clearTimeout(f)}},async changes(s,a){let c=await o("GET",`${e}/vaults/${s}/changes?${i({since:String(a)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function Pc(t,e){let n=!1,r=0,o=null,i=null,s=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,a=(l,u=!1)=>{if(n)return;o?.abort(),e.onDown(l,u);let f=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,i=setTimeout(()=>void c(),f)},c=async()=>{if(n)return;o=new AbortController;let l;try{if(l=await fetch(s(),{headers:{Authorization:`Bearer ${t.getToken?.()??t.token}`,Accept:"text/event-stream"},signal:o.signal}),n){await l.body?.cancel();return}t.getToken?.()}catch(S){a(S);return}if(!l.ok||!l.body){a(new Error(`sse http ${l.status}`));return}r=0;let u=Date.now();e.onOpen();let f=l.body.getReader(),h=new TextDecoder,p="",m="",w=[],y=()=>{if(t.getToken?.(),!w.length&&!m)return;let S=w.join(`
|
|
214
|
-
`),
|
|
215
|
-
`);if(j<0)break;let x=p.slice(0,j).replace(/\r$/,"");if(p=p.slice(j+1),x==="")y();else{if(x.startsWith(":"))continue;x.startsWith("event:")?m=x.slice(6).trim():x.startsWith("data:")&&w.push(x.slice(5).replace(/^ /,""))}}}}catch(S){n||a(S,Date.now()-u>=1e4);return}a(new Error("sse stream ended"),Date.now()-u>=1e4)};return c(),{stop:()=>{n=!0,i&&clearTimeout(i),o?.abort()}}}var Xt=t=>Ee().path.join(He().userDataDir(),He().isDevMode()?`${t}.dev.json`:`${t}.json`),Ri=Xt,jt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Jn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Kn=t=>typeof t=="string"&&Nt(t)===t,Di=t=>typeof t=="string"&&t.length>0,Lp=t=>jt(t)&&Jn(t.seq)&&Di(t.hash)&&Jn(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),Up=t=>jt(t)&&Kn(t.from)&&Kn(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||jt(t.hashes)&&Object.values(t.hashes).every(Di));async function Oi(t){let e;try{e=await Ee().fs.readFile(Ri(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&&!Kt(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,o])=>Kn(r)&&jt(o)&&Jn(o.seq)&&(o.hash===null||Di(o.hash))))||!jt(n.files)||!Object.entries(n.files).every(([r,o])=>Kn(r)&&Lp(o))||n.cursor!==void 0&&!Jn(n.cursor)||n.lastSyncAt!=null&&!Jn(n.lastSyncAt)||n.pending!==void 0&&(!jt(n.pending)||!Object.entries(n.pending).every(([r,o])=>Kn(r)&&(o==="local"||o==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(Up)))throw Error("Invalid cloud vault sync state; original data was retained");return{...n,cursor:n.cursor??0,lastSyncAt:n.lastSyncAt??null}}function $c(t){let e=null,n=null,r=Promise.resolve(),o=null,i=()=>{if(!e)return r;let s=e,a=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let c=Ri(t),l=`${c}.tmp-${Ee().tmpTag()}-${Date.now()}-0`;await Ee().fs.writeFile(l,a,"utf8"),await Ee().fs.rename(l,c),o=null}catch(c){e??=s,o=c}}),r};return{save(s){e=s,!n&&(n=setTimeout(()=>{n=null,i()},500))},async flush(s=!1){if(n&&(clearTimeout(n),n=null),await i(),s&&o)throw o}}}async function Nc(t){try{await Ee().fs.unlink(Ri(t))}catch{}}var Xn=/^[0-9a-f]{64}$/;function jc(t){let e=Ee(),n=()=>Xt(t).replace(/\.json$/,".bases"),r=a=>e.path.join(n(),a),o=a=>e.fs.access(r(a)).then(()=>!0,()=>!1),i=new Map,s=(a,c)=>{let l=(i.get(a)??Promise.resolve()).then(c,c);return i.set(a,l),l.finally(()=>{i.get(a)===l&&i.delete(a)}),l};return{put(a,c){return Xn.test(a)?s(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(!Xn.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 Xn.test(a)?s(a,async()=>{if(!(c&&!c()))try{await e.fs.rm(r(a),{force:!0})}catch{}}):Promise.resolve()},async has(a){return Xn.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)&&!(!Xn.test(l)&&!/^[0-9a-f]{64}\.tmp-/.test(l)))try{await e.fs.rm(e.path.join(n(),l),{force:!0})}catch{}}}}var Hp=5*1024*1024,zp=5*1024*1024,Bp=3e4,qp=5e3,Wp=5*6e4,Vp=2500,Yp=3e3,Gp=5,Jp=256*1024,Kp=5,no=1024*1024,Fc=200,Xp=6e4,Zp=50,Qp=".sync-trash",xt=t=>Ee().sha256Hex(t);function Zn(t,e){let n=e??{localRoot:At(),shadowName:`amadeus-sync-${Yn()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]},r=d=>{let b=Ii(d,"");if(!b)return null;for(let A of n.excludePrefixes??[])if(b===A.replace(/\/$/,"")||b.startsWith(A))return null;if(n.ignoreNames?.length&&b.split("/").some(A=>n.ignoreNames.includes(A)))return null;let k=n.serverDir?`${n.serverDir}/${b}`:b;return n.inScope&&!n.inScope(k,ze(k))?null:k},o=d=>{let b;if(n.serverDir){if(!d.startsWith(`${n.serverDir}/`))return null;b=d.slice(n.serverDir.length+1)}else{for(let k of n.excludePrefixes??[])if(d.startsWith(k))return null;b=d}return b.split("/").some(k=>Gn(k)||!!n.ignoreNames?.includes(k))?null:b},i=(d,b)=>!n.inScope||n.inScope(d,b),s=n.accountId??Pe(),{fs:a,path:c,directoryIdentity:l}=Ee(),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,j=null,x=null,M=null,E=null,T=()=>{let d=t.loadCreds();if(!E||s!==Pe()||!d.token||d.cloudUrl?.replace(/\/+$/,"")!==E.cloudUrl.replace(/\/+$/,""))throw new Te(401,{code:"ACCOUNT_CHANGED"},"sync-session");return d.token},_=null,P=0,q=new Map,J=null,R=$c(n.shadowName),Y=jc(n.shadowName),re=!1,X=new Map,se=!1,ee=!1,oe=[],te=(d,b,k)=>{try{t.onHealth?.(d,b,k)}catch{}},Se=to(te),ve=0,Xe=()=>{ee||te("massDeleteGuard"),ee=!0},je=()=>{g&&(g.pending=X.size?Object.fromEntries(X):void 0,R.save(g))},Fe=()=>{ee=!1,oe.length=0},we=()=>{if(ee)return!0;let d=Date.now();for(;oe.length&&d-oe[0]>Xp;)oe.shift();return oe.length>=Zp?(Xe(),!0):!1},Oe=[],I=new Set,F=!1,v=null,C=null,D=null,N=null,O=()=>{!f||N||(N=setTimeout(()=>{N=null,t.onStatus($t())},200))},L=(d,b,k)=>{let A=y;y=d,b!==void 0&&(S=b),Z(A,d,k),O()},K=!1,Z=(d,b,k)=>{if(b==="syncing"&&d!=="syncing"&&(ve=Date.now()),b==="idle"&&d==="syncing"&&(te("cycles"),te("cycleMsTotal",Math.max(0,Date.now()-ve))),b==="idle"||b==="disabled"){K=!1,Se.ok();return}if(k===null)return;let A=k??Rc(b,S);A&&Se.error(A)},Q=(d,b)=>{q.set(d,b),te(Tc(b),1,d)},V=(d,b=!1)=>{if(!(!f||!h)){if(d.key){if(I.has(d.key))return;I.add(d.key)}b?Oe.unshift(d):Oe.push(d),On()}},ie=new Map,pe=d=>{if(!f)return;let b=(g?.files[d]?.size??0)>Jp,k=(n.pushQuietMs??Yp)*(b?Kp:1),A=Date.now(),$=ie.get(d);$&&clearTimeout($.timer);let H=$?.since??A,B=Math.max(0,Math.min(k,H+k*Gp-A)),U=setTimeout(()=>{ie.delete(d),V({key:d,run:()=>xe(d,!0)})},B);ie.set(d,{timer:U,since:H}),O()},fe=()=>{for(let{timer:d}of ie.values())clearTimeout(d);ie.clear()},le=d=>!(d instanceof Te)||d.status>=500||d.status===0,Ae=d=>d instanceof Te&&(d.status===401||d.status===403),Yt=(d,b)=>{Q(d,b?.body?.code||`http ${b?.status}`),O()},On=async()=>{if(!F){F=!0;try{for(;Oe.length;){(y==="idle"||y==="starting")&&L("syncing");let d=Oe.shift();d.key&&I.delete(d.key);try{await d.run()}catch(b){if(!f)return;if(Ae(b)){Oe.length=0,I.clear(),$n(),L("auth-required","login-expired");return}if(le(b)){V(d,!0),$n(),L("offline",b?.message||"network error"),We();return}Yt(d.key??"(op)",b)}}f&&y==="syncing"&&(g&&(g.lastSyncAt=Date.now(),R.save(g)),L("idle",null))}finally{F=!1;for(let d of w)d();w.clear()}}},We=()=>{!f||v||(v=setTimeout(()=>{v=null,Nn()},Bp))},ge=new Map,Gt=0,Ie=null,$o=()=>!!C||!!Ie||!f,Ls=d=>d instanceof Te&&d.status>=500||d?.name==="TimeoutError",Us=n.pushRetryMs??qp,Mn=(d,b)=>{(b||!ge.has(d))&&ge.set(d,b)},Hs=(d,b,k)=>{Q(d,b instanceof Te?`http ${b.status}`:"timeout"),Mn(d,k),Gt=Math.min(Gt*2||Us,Wp),C=setTimeout(kr,Gt),O()},zs=(d,b,k)=>{let A=new AbortController,$=b(A.signal).then(B=>()=>B,B=>()=>{throw B}),H={path:d,abort:A,after:[],settle:async()=>{let B=await $;if(Ie===H){Ie=null;try{await k(B)}catch(U){if(Ae(U)||le(U))throw U;Yt(d,U)}finally{for(let U of H.after)V(U);Bs(d)}}}};Ie=H,$.then(()=>V({run:H.settle}))},on=(d,b)=>{for(let[k,A]of[...ge])!A||!Ze(k,d)||(ge.delete(k),q.delete(k),b!==null&&ge.set(b+k.slice(d.length),A));O()},kr=()=>{C=null;let[d]=ge;if(d===void 0)return;let[b]=d;I.delete(b),V({key:b,run:async()=>{if(Ie?.path===b)return;let k=ge.get(b),A=!k&&ge.delete(b);(k||A)&&q.delete(b);try{k?await pt(b,k.seq):A&&await xe(b,!0)}finally{A&&Je(b)&&Mn(b),Bs(b)}}})},Bs=d=>{if(!$o())if(ge.has(d)){let b=ge.get(d);ge.delete(d),ge.set(d,b),C=setTimeout(kr,Gt||Us)}else kr()},Me=d=>{if(!_||!g)throw new Error("engine not bound");let b=o(d);if(b===null)throw new Error("path outside binding: "+d);let k=c.resolve(_,Dc(b,g.folder)),A=c.relative(_,k);if(A.startsWith("..")||c.isAbsolute(A))throw new Error("path escapes vault: "+d);return k},Er=d=>({size:d,mtimeMs:-1}),qs=async d=>{try{let b=await a.stat(d);return b.isFile()?{size:b.size,mtimeMs:Math.floor(b.mtimeMs)}:null}catch{return null}},cd=async d=>{if(!a.lstat||!_)return qs(d);let b=c.relative(_,d).split(c.sep),k=_;for(let[A,$]of b.entries()){k=c.join(k,$);let H=await a.lstat(k).catch(B=>{if(B?.code==="ENOENT")return null;throw B});if(!H)return null;if(H.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(A===b.length-1&&H.isFile())return{size:H.size,mtimeMs:Math.floor(H.mtimeMs)};if(A===b.length-1||!H.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},ld=0,Ws=async(d,b,k,A)=>{if(!await Ye())throw Error("Cloud vault sync root is unavailable or changed");let $=_&&j?{path:_,identity:j}:void 0;await a.mkdir(c.dirname(d),{recursive:!0});let H=`${d}.tmp-${Ee().tmpTag()}-${Date.now()}-${ld++}`;await a.writeFile(H,b);let B=await qs(H)??Er(Or(b));try{if(!A())return null;let U=Ee().compareAndReplace;if(!U)throw new Error("Host does not support safe cloud download commits");let G=await U(H,d,k,A,$);if(!G&&!await Ye())throw Error("Cloud vault sync root is unavailable or changed");return G?B:null}finally{await Ye()&&await a.rm(H,{force:!0})}},Vs=async d=>{let b;try{b=await a.readdir(d,{withFileTypes:!0})}catch{return}for(let k of b)k.isDirectory()&&await Vs(c.join(d,k.name));try{await a.rmdir(d)}catch{}},ft=async d=>{let b=Me(d),k=await cd(b);if(!await Ye())throw Error("Cloud vault sync root is unavailable or changed");if(a.lstat&&!k)return null;let A;try{A=await a.readFile(b)}catch(H){if(H?.code!=="ENOENT")throw H;if(!await Ye())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:ot(ze(d))?xt(Et(A)):xt(A),size:k?.size??A.length,mtimeMs:k?.mtimeMs??-1,buf:A}},Mt=async(d,b,k,A,$)=>{if(!g)return;let H=g.files[d]?.hash;g.files[d]={seq:b,hash:k,size:A.size,mtimeMs:A.mtimeMs},g.mirrorRestore&&g.mirrorRestore!=="list"&&delete g.mirrorRestore[d],R.save(g),$!==void 0&&await Ys(d,k,$),H&&H!==k&&await Gs(H)},Ys=async(d,b,k)=>{if(!ot(ze(d))||Or(k)>no)return;let A=typeof k=="string"?k:Et(k);xt(A)===b&&await Y.put(b,A)},Gs=async d=>{let b=()=>!!g&&!Object.values(g.files).some(k=>k.hash===d);b()&&await Y.drop(d,b)},rt=d=>{if(g&&d in g.files){let b=g.files[d].hash;delete g.files[d],R.save(g),Gs(b)}},pt=async(d,b)=>{if(!x||!g||Je(d))return;let k=ke,A=ze(d);if(ot(A)){let U;try{U=await x.getFile(g.vaultId,d),te("downloads")}catch(G){if(G instanceof Te&&G.status===404){await No(d);return}throw G}await Js(d,A,U.content,U.seq,U.hash??xt(U.content),k);return}if($o()){Mn(d,{seq:b}),O();return}let{vaultId:$}=g,H=x,B={seq:b};ge.set(d,B),zs(d,U=>H.getAsset($,d,U),async U=>{let G=ge.get(d)===B,ne;try{ne=U(),Gt=0,te("downloads")}catch(z){if(!G)return;if(ge.delete(d),z instanceof Te&&z.status===404){Q(d,"ASSET_404"),O();return}if(Ls(z)){Hs(d,z,{seq:b});return}throw z}G&&await Js(d,A,ne,b??0,xt(ne),k)}),O()},Js=async(d,b,k,A,$,H)=>{if(!g)return;let B=async me=>{await Mt(d,A,$,me,k),ge.get(d)&&(ge.delete(d),q.delete(d))},U=await ft(d);if(H!==ke||Je(d))return;let G=g.mirrorRestore,ne=G&&G!=="list"&&Object.hasOwn(G,d)?G[d]:void 0;if(ne&&(ne.hash!==$||ne.seq!==A)){let me={...ne};Object.assign(ne,{hash:$,seq:A}),R.save(g);try{await R.flush(!0)}catch(Ke){throw Object.assign(ne,me),R.save(g),Ke}if(!f||H!==ke||Je(d))return}if(U&&U.hash===$){await B(U);return}let z=g.files[d];if(U&&z&&$===z.hash&&U.hash!==z.hash){await B(Er(z.size)),V({key:d,run:()=>xe(d)});return}let W=U?xt(U.buf):null;if(U&&(!z||U.hash!==z.hash)){if(z&&ot(b)&&typeof k=="string"&&await ud(d,z,U,k,A,$,()=>H===ke&&!Je(d))||H!==ke||Je(d)||!await dd(d,()=>H===ke&&!Je(d)))return;W=null}let he=await Ws(Me(d),k,W,()=>f&&H===ke&&!Je(d));if(!he){V({key:d,run:()=>xe(d)});return}await B(he)},ud=async(d,b,k,A,$,H,B)=>{try{if(!x||!g||k.buf.length>no||A.length>no)return!1;let U=await Y.get(b.hash);if(U===null){let W=(await x.listVersions(g.vaultId,d)).find(me=>me.seq===b.seq);if(!W)return!1;let he=await x.getVersion(g.vaultId,W.id);if(xt(he)!==b.hash)return!1;U=he}let G=Et(k.buf),ne;if(ze(d)==="db"){let z=Ec(),W=z?z(d,G,U,A):null;ne=W&&!W.conflict?W.content:null}else ne=Ac(G,U,A);return ne===null?!1:await Ws(Me(d),ne,xt(k.buf),()=>f&&B())?(await Mt(d,$,H,Er(Or(ne)),A),V({key:d,run:()=>xe(d)}),!0):(V({key:d,run:()=>xe(d)}),!0)}catch{return!1}},dd=async(d,b)=>{let k=Nt(Zr(d,new Date));if(!k)return!0;let A=k.lastIndexOf("."),$=A>k.lastIndexOf("/"),H=$?k.slice(0,A):k,B=$?k.slice(A):"",U=k,G=Ee().existsSync;if(G)for(let ne=2;G(Me(U));ne++)U=`${H}-${ne}${B}`;else for(let ne=2;await u(Me(U));ne++)U=`${H}-${ne}${B}`;if(!b())return!1;try{await a.rename(Me(d),Me(U))}catch(ne){if(ne?.code==="ENOENT")return!0;throw ne}return P++,te("conflicts"),V({key:U,run:()=>xe(U)}),O(),!0},Ks=async d=>{if(!_)return;let b=Me(d),k=o(d)??d,A=c.join(_,Qp,new Date().toISOString().slice(0,10),...k.split("/")),$=await u(A)?`${A}.${Date.now()}`:A;try{await a.mkdir(c.dirname($),{recursive:!0}),await a.rename(b,$)}catch(H){if(H?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${b}: ${H?.message??String(H)}`)}},No=async d=>{if(!g)return;on(d,null);let b=await ft(d);if(Je(d))return;let k=g.files[d]??null,A=Qr(b?.hash??null,k,null);if(A.kind==="deleteLocal"){if(!se&&we()){X.set(d,"local"),je(),O();return}oe.push(Date.now()),await Ks(d),rt(d)}else A.kind==="pushCreate"?(rt(d),V({key:d,run:()=>xe(d)})):rt(d)},Xs=(d,b)=>{if(g){on(d,b);for(let k of Object.keys(g.files))if(k===d||k.startsWith(`${d}/`)){let A=b+k.slice(d.length);g.files[A]=g.files[k],delete g.files[k]}R.save(g)}},Zs=async d=>{if(!x||!g||d.seq<=g.cursor||!await Ye())return;if(d.origin.client&&x.clientId===d.origin.client){g.cursor=d.seq,R.save(g);return}let b=d.type==="structure"?"folder":d.type,k=$=>o($)!==null&&i($,b);if(!k(d.path)&&!(d.newPath&&k(d.newPath))){g.cursor=d.seq,R.save(g);return}let A=d.path;if(d.op!=="write"&&d.op!=="mkdir"){for(;Ie&&(Ze(Ie.path,A)||d.newPath&&Ze(Ie.path,d.newPath));)await Ie.settle();if(!f)return}switch(d.op){case"write":await pt(A,d.fileSeq);break;case"delete":await No(A);break;case"move":{let $=d.newPath;if(!$)break;let H=g.files[A],B=await ft(A),U=!!ge.get(A);if(on(A,$),U&&Mn($,{seq:d.fileSeq}),B&&H)try{await a.mkdir(c.dirname(Me($)),{recursive:!0}),await a.rename(Me(A),Me($)),g.files[$]={...H,seq:U?H.seq:d.fileSeq??H.seq},delete g.files[A],R.save(g)}catch{await pt($,d.fileSeq)}else rt(A),await pt($,d.fileSeq);break}case"mkdir":await a.mkdir(Me(A),{recursive:!0});break;case"rename-folder":case"move-folder":{let $=d.newPath;if(!$)break;try{await a.mkdir(c.dirname(Me($)),{recursive:!0}),await a.rename(Me(A),Me($))}catch{}Xs(A,$);break}case"delete-folder":{let $=`${A}/`;for(let H of Object.keys(g.files))(H===A||H.startsWith($))&&await No(H);on(A,null),await Vs(Me(A));break}}if(g.cursor=d.seq,R.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{}},fd=async(d,b,k)=>{let A=Number(b?.seq??0),$=b?.content??null;if($!==null&&xt($)===k.hash){await Mt(d,A,k.hash,k,$);return}if($===null&&A===0){if(!g?.files[d]){Q(d,b?.code||"EXISTS"),O();return}rt(d),V({key:d,run:()=>xe(d)});return}await pt(d,A)},_r=async(d,b)=>{if(!x||!g)return;let k=await ft(d);if(!k){V({key:d,run:()=>xe(d)});return}if(k.size>Hp){Q(d,"TOO_LARGE"),O();return}let A=Et(k.buf);try{let $=await x.putFile(g.vaultId,d,A,b);te("uploads"),q.delete(d),await Mt(d,$.seq,$.hash??k.hash,k,k.buf)}catch($){if($ instanceof Te&&$.status===409){await fd(d,$.body,k);return}throw $}},Cr=async(d,b)=>{if(!x||!g)return;let k=await ft(d);if(!k){V({key:d,run:()=>xe(d)});return}if(k.size>(J??zp)){Q(d,"TOO_LARGE"),O();return}if(Mn(d),O(),$o())return;let{vaultId:A}=g,$=x;zs(d,H=>$.putBinary(A,d,k.buf,{baseSeq:b,signal:H}),async H=>{if(g){ge.get(d)||ge.delete(d);try{let B=H();Gt=0,te("uploads"),q.delete(d),await Mt(d,B.seq,k.hash,k)}catch(B){if(Ls(B)){Hs(d,B);return}if(!(B instanceof Te)||B.status!==409)throw B;let U=Number(B.body?.seq??0),G=B.body?.hash??null;if(G!==null&&G===k.hash){await Mt(d,U,k.hash,k);return}if(U===0){if(!g.files[d]){Q(d,B.body?.code||"EXISTS"),O();return}rt(d),V({key:d,run:()=>xe(d)});return}await pt(d,U)}}})},Qs=async d=>{if(!x||!g||Je(d))return;let b=ke,k=g.files[d];if(k){if(ot(ze(d)))try{let A=await x.getFile(g.vaultId,d);if(A.seq!==k.seq){await pt(d,A.seq);return}}catch(A){if(A instanceof Te&&A.status===404){rt(d);return}throw A}if(!(!await Ye()||b!==ke||Je(d))){try{await x.deleteFile(g.vaultId,d,k.seq,{confirmed:se})}catch(A){if(A instanceof Te&&A.status===409){await pt(d,Number(A.body?.seq??0)||null);return}if(A instanceof Te&&A.status===429&&A.body?.code==="MASS_DELETE_BLOCKED"){X.set(d,"remote"),Xe(),je(),O();return}throw A}rt(d)}}},Ar=d=>a.stat(d).catch(b=>{if(b?.code==="ENOENT")return null;throw b}),jo=async d=>{let b=He();if(e||!s||s!==Pe()||d!==At(s)||!b.isManagedCloudVault(d)||!a.lstat)return!1;let k=b.homeDir(),A=c.relative(k,d);if(!A||A.startsWith("..")||c.isAbsolute(A))return!1;let $=k;for(let H of A.split(c.sep)){$=c.join($,H);let B=await a.lstat($).catch(U=>{if(U.code==="ENOENT")return null;throw U});if(B&&(!B.isDirectory()||B.isSymbolicLink()))return!1}return!0},Pt=d=>(h=!1,se=!1,Oe.length=0,I.clear(),Uo(),$n(),L("error",`${d}: ${_}`),We(),!1),Fo=d=>{let b=j??g?.rootIdentity,k=d!==null&&d.isDirectory();return k&&(!b||lt(b,d))?!0:Pt(k?"vault-changed":"vault-missing")},Ye=async()=>!!_&&Fo(await Ar(_)),ke=0,xr=new Set,Tr=new Map,Ge=d=>JSON.stringify([d.from,d.to]),Ze=(d,b)=>d===b||d.startsWith(`${b}/`),Je=d=>[...g?.moves??[],...xr].some(b=>Ze(d,b.from)||Ze(d,b.to)),ht=()=>!!(g?.moves?.length||xr.size),Ir=async d=>{if(!x||!g)return;let{from:b,to:k,kind:A}=d;if(o(b)===null||o(k)===null)throw new Error("Invalid queued cloud move");if(Ie&&(Ze(Ie.path,b)||Ze(Ie.path,k))){Ie.after.push({key:`move:${Ge(d)}`,run:()=>Ir(d)});return}if(d.hashes??=Object.fromEntries(Object.entries(g.files).filter(([U])=>Ze(U,b)).map(([U,G])=>[U.slice(b.length),G.hash])),R.save(g),await R.flush(!0),!await Ye())return;let $,H=!1;try{if(A==="folder"){let U=c.posix.dirname(b)==="."?"":c.posix.dirname(b),G=c.posix.dirname(k)==="."?"":c.posix.dirname(k);U===G?await x.renameFolder(g.vaultId,b,c.posix.basename(k)):await x.moveFolder(g.vaultId,b,G)}else{let U=await x.move(g.vaultId,b,k);$=Number(U.seq)}}catch(U){if(!(U instanceof Te)||U.status!==404)throw U;let G=await x.tree(g.vaultId);if(G.entries.some(W=>Ze(W.path,b))||G.folders.some(W=>Ze(W,b)))throw U;let z=G.entries.find(W=>W.path===k);if($=z?.seq,H=!z&&!G.entries.some(W=>Ze(W.path,k))&&!G.folders.some(W=>Ze(W,k)),!H){let W=Object.entries(d.hashes);if(!(W.length>0&&W.every(([me,Ke])=>G.entries.some(Le=>Le.path===k+me&&Le.hash===Ke))))throw new Te(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(H){for(let U of Object.keys(g.files))Ze(U,b)&&delete g.files[U];on(b,null)}else Xs(b,k),$!==void 0&&g.files[k]&&!ge.get(k)&&(g.files[k].seq=$);g.moves=(g.moves??[]).filter(U=>Ge(U)!==Ge(d)),R.save(g);try{await R.flush(!0)}catch(U){throw g.moves.unshift(d),R.save(g),U}let B=Tr.get(Ge(d));Tr.delete(Ge(d)),B?.(),Je(k)||(A==="folder"?await Lo():await xe(k))},xe=async(d,b=!1)=>{if(!g||Je(d))return;if(Ie?.path===d){Ie.after.push({key:d,run:()=>xe(d,b)});return}if(!i(d,ze(d))){rt(d);return}if(!await Ye())return;let k=await ft(d);if(Je(d))return;let A=g.files[d]??null,$=Qr(k?.hash??null,A,A?{seq:A.seq,hash:A.hash}:null);switch($.kind){case"push":ot(ze(d))?await _r(d,$.baseSeq):await Cr(d,$.baseSeq);break;case"pushCreate":ot(ze(d))?await _r(d,0):await Cr(d,0);break;case"pushDelete":if(b){Dr();break}if(!se&&(X.has(d)||we())){X.set(d,"remote"),je(),O();break}oe.push(Date.now()),await Qs(d);break;case"dropShadow":rt(d);break;default:k&&A&&k.hash===A.hash&&k.mtimeMs>=0&&(A.size!==k.size||A.mtimeMs!==k.mtimeMs)&&await Mt(d,A.seq,A.hash,k,k.buf);break}},ea=async()=>{let d=new Map;if(!_||!g)return d;let b=_,k=null,A=async $=>{if(k)return;let H;try{H=await a.readdir($,{withFileTypes:!0})}catch(B){k=`${$}: ${B?.message??String(B)}`;return}for(let B of H){if(Gn(B.name)||B.isDirectory()&&n.ignoreNames?.includes(B.name))continue;let U=c.join($,B.name);if(B.isDirectory())await A(U);else if(B.isFile()){let G=c.relative(b,U).split(c.sep).join("/"),ne=r(G);if(!ne)continue;try{let z=await a.stat(U);if(!z.isFile())continue;d.set(ne,{size:z.size,mtimeMs:Math.floor(z.mtimeMs)})}catch(z){if(z?.code==="ENOENT")continue;k=`${U}: ${z?.message??String(z)}`;return}}}};return await A(b),k?(L("error",`scan-failed: ${k}`),We(),null):d},Lo=async()=>{let d=ke;if(ht()||d!==ke||!g||!await Ye())return;let b=await ea();if(!b||ht()||d!==ke||!await Ye())return;let k=!1;for(let[H,B]of[...X])(B==="remote"&&b.has(H)||B==="local"&&!b.has(H))&&(X.delete(H),k=!0);X.size||Fe();for(let[H,B]of b){let U=g.files[H];U&&U.size===B.size&&U.mtimeMs===B.mtimeMs||V({key:H,run:()=>xe(H)})}let A=Object.keys(g.files),$=A.filter(H=>!b.has(H));if($.length&&!se&&(ee||xi($.length,A.length,Fc))){Xe();for(let H of $)X.set(H,"remote");je(),O();return}k&&(je(),O());for(let H of $)X.has(H)||V({key:H,run:()=>xe(H)})},pd=async d=>{if(!g)return;let b=new Set;for(let[k,A]of Object.entries(g.files)){if(!ot(ze(k))||A.size>no)continue;b.add(A.hash);let $=d.get(k);if(!(!$||$.size!==A.size||$.mtimeMs!==A.mtimeMs||await Y.has(A.hash)))try{let H=await ft(k);H&&H.hash===A.hash&&await Ys(k,A.hash,H.buf)}catch{}}await Y.prune(b)},sn=async()=>{if(Ie){Ie.after.push({run:sn});return}let d=ke;if(ht()||d!==ke||!x||!g||!_||!await Ye())return;let b=await x.tree(g.vaultId);if(b.maxFileBytes!==void 0&&b.maxFileBytes!==J&&(J=b.maxFileBytes,O()),ht()||d!==ke)return;let k=new Map;for(let z of b.entries)o(z.path)===null||!i(z.path,z.kind)||k.set(z.path,z);for(let[z,W]of[...ge])W&&!k.has(z)&&on(z,null);let A=await ea();if(!A||ht()||d!==ke||!await Ye())return;if(g.mirrorRestore==="list"){for(let W of Object.keys(g.files))!A.has(W)&&!X.has(W)&&delete g.files[W];let z=Object.create(null);for(let[W,{seq:he,hash:me}]of k)Object.hasOwn(g.files,W)||(z[W]={seq:he,hash:me});g.mirrorRestore=z,R.save(g);try{await R.flush(!0)}catch(W){throw g.mirrorRestore="list",R.save(g),W}}let $=g.mirrorRestore;re||(re=!0,await pd(A));let H=new Set([...k.keys(),...A.keys(),...Object.keys(g.files),...Object.keys($??{})]),B=Object.keys(g.files).length,U=[];for(let z of H){if(ht()||d!==ke)return;let W=g.files[z]??null,he=k.get(z)??null,me=A.get(z)??null,Ke=null,Le=Er(me?.size??0);if(me)if(W&&W.size===me.size&&W.mtimeMs===me.mtimeMs)Ke=W.hash,Le=me;else{let kt=await ft(z);kt&&(Ke=kt.hash,Le=kt)}if($&&Object.hasOwn($,z)){let kt=$[z];!W&&Ke!==null&&kt.hash===Ke&&(W=g.files[z]={seq:kt.seq,hash:Ke,size:Le.size,mtimeMs:Le.mtimeMs}),(W||!he)&&delete $[z]}U.push({sp:z,d:Qr(Ke,W,he?{seq:he.seq,hash:he.hash}:null),rSeq:he?.seq??null,localHash:Ke,localStat:Le})}if(ht()||d!==ke)return;let G=U.filter(z=>z.d.kind==="deleteLocal"||z.d.kind==="pushDelete").length,ne=!se&&(ee||xi(G,B,Fc));ne&&G&&Xe(),X.clear();for(let{sp:z,d:W,rSeq:he,localHash:me,localStat:Ke}of U){if(ht()||d!==ke)return;if(ne&&(W.kind==="deleteLocal"||W.kind==="pushDelete")){X.set(z,W.kind==="deleteLocal"?"local":"remote");continue}if((W.kind==="deleteLocal"||W.kind==="pushDelete")&&((await ft(z))?.hash??null)!==me){V({key:z,run:()=>xe(z)});continue}if(ht()||d!==ke)return;switch(W.kind){case"adopt":{let Le=ot(ze(z))?await ft(z):null;await Mt(z,he,me,Ke,Le&&Le.hash===me?Le.buf:void 0);break}case"pull":await pt(z,he);break;case"push":ot(ze(z))?await _r(z,W.baseSeq):await Cr(z,W.baseSeq);break;case"pushCreate":ot(ze(z))?await _r(z,0):await Cr(z,0);break;case"pushDelete":await Qs(z);break;case"deleteLocal":await Ks(z),rt(z);break;case"conflict":await pt(z,he);break;case"dropShadow":rt(z);break;case"none":break}}se&&(se=!1,oe.length=0),X.size||Fe(),je(),ne&&O();for(let z of b.folders)if(!(o(z)===null||!i(z,"folder")))try{await a.mkdir(Me(z),{recursive:!0})}catch{}g.cursor=b.seq,g.lastSyncAt=Date.now(),$&&!Object.keys($).length&&delete g.mirrorRestore,R.save(g)},hd=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 sn();return}for(let A of b.changes)await Zs(A)},Pn=null,ta=[],Uo=()=>{Pn&&ta.push(Pn.close()),Pn=null},gd=()=>{if(!f||Pn||!_)return;let d=Ee();if(!d.watch)return;let b=k=>{if(!_)return;let A=c.relative(_,k);if(!A||A.startsWith(".."))return;let $=r(A);$&&pe($)};Pn=d.watch(_,{depth:12,ignored:k=>{let A=c.basename(k);return Gn(A)||!!n.ignoreNames?.includes(A)}},{change:b,add:b,unlink:()=>Dr(),unlinkDir:()=>Dr()})},$n=()=>{M?.stop(),M=null},md=()=>{if(!f||!x||!g||M)return;let d=E;d&&(M=Pc({baseUrl:d.cloudUrl,vaultId:g.vaultId,token:d.token,getToken:T},{getSince:()=>g?.cursor??0,onHello:b=>{g&&b>g.cursor&&V({run:hd})},onChange:b=>{V({run:()=>Zs(b)})},onReset:()=>{V({run:sn})},onOpen:()=>{(y==="offline"||y==="starting")&&L("idle",null),V({run:Lo})},onDown:(b,k)=>{let A=Ti(Ic(b));y==="idle"||y==="syncing"?(L("offline",void 0,k?null:A),K=!!k):y==="offline"&&K&&!k&&(K=!1,Se.error(A))},onPresence:b=>t.onPresence?.(g?.vaultId??"",b),onPresenceRoster:b=>t.onPresenceRoster?.(g?.vaultId??"",b)}))},yd=async()=>{let d=await et(s);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}},s),b},wd=async d=>{$n(),Uo(),j=null,Oe.length=0,I.clear(),X.clear(),se=!1,ee=!1,oe.length=0;let b=await et(s);if(d!==p)return;let k=b.cloudSync;if(k?.enabled===!1){_=null,x=null,L("disabled",null);return}if(!s||s!==Pe()){L("auth-required","not-logged-in");return}if(_=n.localRoot,n.requireRootExists){let B=await a.stat(_).then(U=>U.isDirectory()).catch(()=>!1);if(d!==p)return;if(!B){L("error",`vault-missing: ${_}`),We();return}}if(d!==p)return;let A=t.loadCreds();if(!A.cloudUrl||!A.token){x=null,L("auth-required","not-logged-in");return}L("starting",null);let $=k?.deviceId??await yd();if(d!==p)return;let H=n.clientIdSuffix?`${$}#${n.clientIdSuffix}`:$;E={cloudUrl:A.cloudUrl,token:A.token},x=Mc({baseUrl:A.cloudUrl,token:A.token,clientId:H,getToken:()=>{if(d!==p)throw new Te(401,{code:"ACCOUNT_CHANGED"},"sync-session");return T()}});try{let B=n.vaultId==="first"?k?.vaultId:n.vaultId;if(!B){let z=await x.listVaults();if(d!==p)return;if(!z.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");B=z[0].id,await Ct({cloudSync:{...k??{},vaultId:B}},s)}if(d!==p)return;let U=await Oi(n.shadowName);if(d!==p||(g=U&&U.vaultRoot===_&&U.vaultId===B&&U.folder===""?U:{vaultRoot:_,folder:"",vaultId:B,cursor:0,lastSyncAt:null,files:{}},d!==p))return;for(let[z,W]of Object.entries(g.pending??{}))X.set(z,W);X.size&&(ee=!0);let G=await Ar(_);if(d!==p)return;let ne=()=>ht()||!!Object.keys(g?.pending??{}).length;if(!G&&!n.requireRootExists){if(g.rootIdentity||Object.keys(g.files).length||g.mirrorMissing||ne()){let z=await jo(_);if(d!==p)return;if(!z||ne()){Pt("vault-missing");return}if(g.mirrorMissing=!0,R.save(g),await R.flush(!0),d!==p)return;let W=await jo(_);if(d!==p)return;if(!W||ne()){Pt("vault-missing");return}}if(await a.mkdir(_,{recursive:!0}),G=await Ar(_),d!==p)return}if(!G?.isDirectory()){Fo(G);return}if(typeof G.dev=="number"&&Number.isInteger(G.dev)&&G.dev>=0&&typeof G.ino=="number"&&Number.isInteger(G.ino)&&G.ino>0){let z=l?await l(_):{dev:G.dev,ino:G.ino,...G.birthtimeMs&&G.birthtimeMs>0?{birthtimeMs:G.birthtimeMs}:{}};if(d!==p)return;if(!Kt(z))throw Error("Invalid sync root identity; original state retained");let W=g.rootIdentity,he=W&&!ln(W,z);if(!lt(z,G)){Pt("vault-changed");return}let me=!W&&!e&&He().isManagedCloudVault(_)&&(Object.keys(g.files).length>0||ne());if(he||g.mirrorMissing||me){let Le=(!W||(W.volumeId?W.volumeId===z.volumeId:W.dev===z.dev))&&await jo(_),kt=Le&&(await a.readdir(_,{withFileTypes:!0})).every(sa=>sa.isDirectory()&&n.excludePrefixes?.includes(sa.name+"/")),ia=kt&&await Ar(_);if(d!==p)return;if(kt){if(!ia||!lt(z,ia)||ne()){Pt("vault-changed");return}g.files={},g.cursor=0,g.lastSyncAt=null,g.mirrorRestore="list"}else if(he||g.mirrorMissing&&!W){Pt("vault-changed");return}else if(me){if(!Le||ne()){Pt("vault-changed");return}g.mirrorRestore="list"}}if(j=z,(g.mirrorMissing||JSON.stringify(W)!==JSON.stringify(z))&&(delete g.mirrorMissing,g.rootIdentity=z,R.save(g),await R.flush(!0)),d!==p||!await Ye())return}else{if(g.mirrorMissing){Pt("vault-changed");return}if(!Fo(G))return}if(d!==p)return;h=!0,gd();for(let z of g.moves??[])V({key:`move:${Ge(z)}`,run:()=>Ir(z)});V({run:sn}),V({run:async()=>{md()}})}catch(B){if(d!==p)return;Ae(B)?L("auth-required","login-expired"):(L("offline",B?.message||String(B)),We())}},na=()=>{f=!1,h=!1,$n(),Uo(),Oe.length=0,I.clear(),fe();for(let d of[v,C,D,N])d&&clearTimeout(d);v=C=D=N=null,Ie?.abort.abort(),Ie=null},ra=async()=>{F&&await new Promise(d=>w.add(d)),await Promise.all(ta.splice(0)),await R.flush(),g=null,j=null,x=null,E=null,_=null,P=0,q.clear(),ge.clear(),Gt=0,J=null,X.clear(),se=!1,ee=!1,oe.length=0,y="disabled",S=null},bd=()=>{oa()},Rr=null,Nn=()=>{re=!1,Rr?.(),Rr=He().onBeforeQuit(bd);let d=++p;na();let b=m.catch(()=>{}).then(async()=>{await ra(),d===p&&(f=!0,await wd(d))});return m=b,b},oa=()=>{Rr?.(),Rr=null,++p,na();let d=m.catch(()=>{}).then(ra);return m=d,d},$t=()=>({enabled:y!=="disabled",state:y==="idle"&&(ie.size||ge.size)?"syncing":y,lastSyncAt:g?.lastSyncAt??null,pending:Oe.length+ie.size+ge.size,conflicts:P,skipped:[...q].map(([d,b])=>({path:d,reason:b})),error:S,pendingDeletions:X.size,maxFileBytes:J});return{getStatus:$t,start(){Nn()},notifyLocal(d,b,k){if(!g||y==="disabled"||y==="auth-required")return;let A=r(d),$=k?r(k):null;if(b==="write"&&A){Gn(A.split("/").pop()||"")||pe(A);return}if(b==="remove"){if(!A)return;let H=`${A}/`,B=!1;for(let U of Object.keys(g.files))(U===A||U.startsWith(H))&&(B=!0,V({key:U,run:()=>xe(U)}));!B&&A&&V({key:A,run:()=>xe(A)})}},holdLocalMove(d,b){let k=$=>n.serverDir?`${n.serverDir}/${$.replace(/\\/g,"/").normalize("NFC")}`:$.replace(/\\/g,"/").normalize("NFC"),A={from:k(d),to:k(b)};return++ke,xr.add(A),()=>{xr.delete(A)}},async notifyLocalMove(d,b,k,A){let $=r(d),H=r(b),B=g??await Oi(n.shadowName),U=Ii(d,""),G=U&&(n.serverDir?`${n.serverDir}/${U}`:U);if(!$&&H&&G&&B&&Object.keys(B.files).some(ne=>ne===G||ne.startsWith(`${G}/`))&&($=G),!$&&!H){k?.();return}if($&&H){let ne=g??B;if(!ne){k?.();return}let z=A??(Object.keys(ne.files).some(he=>he.startsWith(`${$}/`))?"folder":"file"),W={from:$,to:H,kind:z};ne.moves??=[],ne.moves.some(he=>Ge(he)===Ge(W))||(ne.moves.push(W),++ke),k&&Tr.set(Ge(W),k),R.save(ne);try{await R.flush(!0)}catch(he){throw ne.moves=ne.moves.filter(me=>Ge(me)!==Ge(W)),Tr.delete(Ge(W)),R.save(ne),he}g===ne&&f&&y!=="disabled"&&y!=="auth-required"&&V({key:`move:${Ge(W)}`,run:()=>Ir(W)});return}$&&this.notifyLocal(d,"remove"),H&&(V({key:H,run:()=>xe(H)}),Dr()),k?.()},async setEnabled(d){let b=await et(s);return await Ct({cloudSync:{...b.cloudSync??{},enabled:d}},s),await Nn(),$t()},async restart(){return await Nn(),$t()},async syncNow(){if(q.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 Nn();else{C&&(clearTimeout(C),kr());for(let d of g?.moves??[])V({key:`move:${Ge(d)}`,run:()=>Ir(d)});V({run:sn})}return $t()},confirmMassDeletions(){return!h||!X.size||(se=!0,V({run:sn})),$t()},stop:oa};function Dr(){f&&(D&&clearTimeout(D),D=setTimeout(()=>{D=null,V({run:Lo})},Vp))}}function Mi(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function Pi(t){return/\.md$/i.test(t)?Mi(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function Lc(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 eh=t=>Ee().sha256Hex(t).slice(0,8),th=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",ro="\u4E0E\u6211\u5171\u4EAB";function Uc(t,e){let n=eh(`${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:`${ro}/${th(t.title)}-${n}`,serverDir:r,inScope:(o,i)=>e.some(s=>Lc(s,o,i)),scopeKey:e.map(o=>o.root).join("\0")}}function Hc(t){return Uc(t,[Mi(t.path),...(t.items??[]).map(Pi)])}function zc(t){let e=t.map(Hc),n=t.flatMap((o,i)=>{let s=e[i].serverDir?`${e[i].serverDir}/`:"";return(o.items??[]).filter(a=>!a.startsWith(s)).map(a=>Uc({vaultId:o.vaultId,path:a,title:(a.split("/").pop()??a).replace(/\.md$/i,"")},[Pi(a)]))}),r=new Map;for(let o of[...e,...n])r.has(o.key)||r.set(o.key,o);return[...r.values()]}var nh=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 Bc(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 i=r.slice(n(o.localRelDir).length+1),s=nh(o.serverDir?`${o.serverDir}/${i}`:i);if(!s||s===".."||s.startsWith("../"))return null;let a=[o,...t].find(c=>c.vaultId===o.vaultId&&(!c.serverDir||s.startsWith(`${c.serverDir}/`))&&c.inScope(s,ze(s)));return a?`${a.localRelDir}/${a.serverDir?s.slice(a.serverDir.length+1):s}`:null}function $i(){let t=He().readCreds(),e=Ue(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let f=He().readCreds();if(n.signal.aborted||!e||Ue(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},o=()=>{let f=r();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},i=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},s=null,a=async()=>(r(),s||(s=(await i("GET","/vaults")).vaults[0]?.id??"default",s)),c=()=>{try{let f=(r().token??"").split(".")[1],h=JSON.parse(Et(Mr(f)));return typeof h.userId=="string"?h.userId:null}catch{return null}},l=async()=>(await i("GET","/shared-with-me")).items.map(h=>{let p=Hc(h),m=h.path.split("/").pop()??h.path;return{...h,localPath:`${p.localRelDir}/${m}`}}),u=null;return{stop:()=>n.abort(),call:i,ensureOwnVault:a,myUserId:c,sharedWithMe:l,linkBase:async()=>{if(r(),u)return u;try{u=((await i("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||o()}catch{u=o()}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 i("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:w})}}}import{promises as Vc}from"node:fs";import rh from"node:path";var Ni=".forsion-vault.md",qc=t=>`${t}/${Ni}`;function oo(t){let e=/^devices:\s*(\[.*\])\s*$/m.exec(t??"");if(!e)return null;try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(r=>!!r&&typeof r.id=="string"&&typeof r.name=="string").map(r=>({id:r.id,name:r.name,...typeof r.since=="string"?{since:r.since}:{}})):null}catch{return null}}var Wc=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 fr(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var lc=["cycles","cycleMsTotal","errAuth","errOffline","errVaultMissing","errScan","errMirrorMissing","errHttp","errTimeout","errBlocked","errOther","conflicts","skippedTooLarge","skippedNotFound","skippedExists","skippedOther","massDeleteGuard","uploads","downloads"];function cc(t){return t==="TOO_LARGE"?"skippedTooLarge":t==="ASSET_404"?"skippedNotFound":t==="EXISTS"?"skippedExists":/^http \d+$/.test(t)?"errHttp":t==="timeout"?"errTimeout":"skippedOther"}function no(t){let e=t??"";if(/^(?:ENOENT|EACCES|EPERM|EBUSY|EISDIR|ENOTDIR|EEXIST|EMFILE|ENFILE|ENOSPC|EROFS|EIO|ENAMETOOLONG)\b/.test(e))return"errOther";let n=/^(?:cloud|sse) http (\d{3})\b/i.exec(e);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|etimedout/i.test(e)?"errTimeout":!e||/fetch failed|econn|enotfound|eai_again|enetunreach|ehostunreach|enetdown|network|socket|terminated|other side closed|und_err|^cloud http 0\b/i.test(e)?"errOffline":"errOther"}function uc(t){if(!(t instanceof Error))return;let e=t.cause,n=e&&typeof e=="object"?[e.code,e.message].filter(r=>typeof r=="string"&&r).join(" "):"";return n?`${t.message} (${n})`:t.message}function dc(t,e){if(t==="offline")return no(e);if(t==="auth-required")return e==="not-logged-in"?null:"errAuth";if(t!=="error")return null;let n=e??"";return n.startsWith("vault-missing")?"errVaultMissing":n.startsWith("scan-failed")?"errScan":n.startsWith("mirror-missing")?"errMirrorMissing":"errOther"}function ki(t,e=0){if(/^(account_changed|content_sync_closed|paused)$/.test(t)||/^File exceeds \d+ MB/.test(t))return null;if(t==="not_signed_in"||e===401||e===403)return"errAuth";let n=/^content_http_(\d{3})$/.exec(t);return n?n[1]==="401"||n[1]==="403"?"errAuth":"errHttp":/timeout|timed out|aborted due to timeout/i.test(t)?"errTimeout":/fetch failed|econn|enotfound|eai_again|network|socket/i.test(t)?"errOffline":/^Sync root (unavailable|changed|is not a directory)|^content_roots_changed/.test(t)?"errVaultMissing":e?"errHttp":"errOther"}function Ei(t){let e=null;return{error(n){n!==e&&(e=n,t?.(n))},ok(){e=null}}}var Mh=/[\u0000-\u001f\u007f]/;function Yt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||Mh.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function ro(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Yt(n):n.startsWith(`${e}/`)?Yt(n.slice(e.length+1)):null}function fc(t,e){return e===""?t:`${e}/${t}`}function pr(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function De(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var qe=t=>t==="page"||t==="db";var Nh=t=>Math.max(3,Math.ceil(t*.1)),Ph=(t,e)=>t===429&&e!=="MASS_DELETE_BLOCKED";function $h(t,e=Date.now()){if(!t)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:Math.max(0,r-e)}function jh(t){let e=t.get("ratelimit"),n,r,i;if(e){let s=a=>Number(new RegExp(`(?:^|[;,\\s])${a}=(\\d+)`).exec(e)?.[1]??NaN);n=s("limit"),r=s("remaining"),i=s("reset")}else n=Number(t.get("ratelimit-limit")??NaN),r=Number(t.get("ratelimit-remaining")??NaN),i=Number(t.get("ratelimit-reset")??NaN);return![n,r,i].every(s=>Number.isFinite(s)&&s>=0)||n<=0?null:{limit:n,remaining:r,resetMs:i*1e3}}function Lh(t={}){let e=t.now??Date.now,n=0,r=null,i=new Set,s=()=>{for(let o of[...i])try{o()}catch{}},a=o=>{let l=e()+Math.min(Math.max(o,0),6e5);l<=n||(n=l,r&&clearTimeout(r),r=setTimeout(()=>{r=null,s()},n-e()),r.unref?.(),s())};return{until:()=>n>e()?n:null,async ready(o){for(;n>e();)o?.throwIfAborted(),await new Promise((l,c)=>{let u=setTimeout(f,n-e());function f(){o?.removeEventListener("abort",g),l()}function g(){clearTimeout(u),c(o.reason??new DOMException("Aborted","AbortError"))}o?.addEventListener("abort",g,{once:!0})});o?.throwIfAborted()},observe(o,l,c,u){let f=jh(l);if(Ph(o,c)){let g=$h(l.get("retry-after"),e())??(typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null)??(f&&f.remaining===0&&f.resetMs>0?f.resetMs:null);return a(Math.max(g??3e4,1e3)),!0}return f&&f.remaining<=Nh(f.limit)&&f.resetMs>0&&a(f.resetMs),!1},subscribe(o){return i.add(o),()=>{i.delete(o)}}}}var pc=new Map;function Jt(t){let e;try{e=new URL(t).origin}catch{e=t.replace(/\/+$/,"")}let n=pc.get(e);return n||(n=Lh(),pc.set(e,n)),n}var Fh=1024,ye=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},hc=t=>12e4+Math.ceil(t/256);function Uh(t,e){let n=AbortSignal.timeout(t);if(!e)return n;let r=new AbortController;for(let i of[n,e])i.addEventListener("abort",()=>r.abort(i.reason),{once:!0});return r.signal}function gc(t,e){if(!t||!e)return t??e;let n=new AbortController;for(let r of[t,e]){if(r.aborted){n.abort(r.reason);break}r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}function mc(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=t.gate??Jt(t.baseUrl),r=()=>t.getToken?.()??t.token,i=async(o,l)=>{let c=r();for(let u=0;;u++){let f={...l.headers,Authorization:`Bearer ${c}`},g=await fetch(o,{...l,headers:f});if(r(),g.status!==401||g.redirected)return g;let p=await g.text(),m=r();if(m===c||u>0)return new Response(p,{status:g.status,statusText:g.statusText,headers:g.headers});c=m}},s=async(o,l,c)=>{let u={Authorization:`Bearer ${t.token}`,...c?.headers};o!=="GET"&&(u["X-Amadeus-Client"]=t.clientId);let f;for(c?.json!==void 0?(u["Content-Type"]="application/json",f=JSON.stringify(c.json),f.length>=Fh&&(u["Content-Encoding"]="gzip",f=await qa(f))):c?.form&&(f=c.form);;){n.until()!==null&&await n.ready(gc(c?.signal,t.signal));let g=await i(l,{method:o,headers:u,body:f,signal:Uh(c?.timeoutMs??3e4,c?.signal)});if(!g.ok){let m=null;try{m=await g.json()}catch{}if(r(),n.observe(g.status,g.headers,m?.code,m?.retryAfterMs))continue;throw new ye(g.status,m,l)}n.observe(g.status,g.headers);let p=await g.json();return r(),p}},a=o=>new URLSearchParams(o).toString();return{clientId:t.clientId,async listVaults(){return((await s("GET",`${e}/vaults`)).vaults??[]).map(l=>({id:String(l.id),name:String(l.name),lastChangeSeq:Number(l.lastChangeSeq??0)}))},async tree(o){let l=await s("GET",`${e}/vaults/${o}/tree`);if(!Array.isArray(l.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:l.folders??[],seq:Number(l.seq??0),maxFileBytes:Number.isInteger(l.maxFileBytes)&&l.maxFileBytes>0?l.maxFileBytes:void 0,entries:l.entries.map(c=>({path:String(c.path),kind:c.kind,seq:Number(c.seq??0),hash:c.hash??null,size:Number(c.size??0),updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}))}},async getFile(o,l){let c=await s("GET",`${e}/vaults/${o}/file?${a({path:l})}`);return{content:String(c.content??""),seq:Number(c.seq??0),hash:c.hash??null,updatedAt:typeof c.updatedAt=="string"?c.updatedAt:null}},putFile(o,l,c,u,f=!1,g){return s("PUT",`${e}/vaults/${o}/file`,{json:{path:l,content:c,baseSeq:u,...f?{force:!0}:{},...g?{expectedHash:g}:{}}})},async deleteFile(o,l,c,u){let f={path:l};c!==void 0&&(f.baseSeq=String(c)),u?.expectedHash&&(f.expectedHash=u.expectedHash),await s("DELETE",`${e}/vaults/${o}/file?${a(f)}`,u?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(o,l,c){return s("POST",`${e}/vaults/${o}/move`,{json:{from:l,to:c}})},renameFolder(o,l,c){return s("POST",`${e}/vaults/${o}/folders/rename`,{json:{path:l,newName:c}})},moveFolder(o,l,c){return s("POST",`${e}/vaults/${o}/folders/move`,{json:{path:l,dest:c}})},async deleteFolder(o,l){await s("DELETE",`${e}/vaults/${o}/folders?${a({path:l})}`)},putBinary(o,l,c,u){let f=new FormData;return f.set("path",l),u?.ifAbsent&&f.set("ifAbsent","true"),u?.baseSeq!==void 0&&f.set("baseSeq",String(u.baseSeq)),u?.expectedHash&&f.set("expectedHash",u.expectedHash),f.set("file",new Blob([new Uint8Array(c)]),l.split("/").pop()||"file"),s("POST",`${e}/vaults/${o}/binary`,{form:f,timeoutMs:hc(c.length),signal:u?.signal})},async listVersions(o,l){return((await s("GET",`${e}/vaults/${o}/file/versions?${a({path:l})}`)).versions??[]).map(u=>({id:String(u.id),seq:Number(u.seq??0)}))},async getVersion(o,l){let c=await s("GET",`${e}/vaults/${o}/file/versions/${l}`);return String(c.content??"")},async getAsset(o,l,c){let u=new AbortController;c?.addEventListener("abort",()=>u.abort(c.reason),{once:!0});let f=()=>u.abort(new DOMException("Asset download timed out","TimeoutError")),g;try{let p;for(;;){if(clearTimeout(g),n.until()!==null&&await n.ready(gc(c,t.signal)),g=setTimeout(f,12e4),p=await i(`${e}/vaults/${o}/asset?${a({ref:l})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:u.signal}),p.status!==429){n.observe(p.status,p.headers);break}let y=await p.json().catch(()=>null);if(!n.observe(p.status,p.headers,y?.code,y?.retryAfterMs))break}if(!p.ok)throw new ye(p.redirected&&(p.status===401||p.status===403)?502:p.status,null,"asset:"+l);clearTimeout(g),g=setTimeout(f,hc(Number(p.headers.get("content-length"))||0));let m=new Uint8Array(await p.arrayBuffer());return r(),m}finally{clearTimeout(g)}},async changes(o,l){let c=await s("GET",`${e}/vaults/${o}/changes?${a({since:String(l)})}`);return{changes:c.changes??[],seq:Number(c.seq??0)}}}}function yc(t,e){let n=!1,r=0,i=null,s=null,a=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,o=(c,u=!1)=>{if(n)return;i?.abort(),e.onDown(c,u);let f=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,s=setTimeout(()=>void l(),f)},l=async()=>{if(n)return;i=new AbortController;try{await t.gate?.ready(i.signal)}catch{return}if(n)return;let c;try{if(c=await fetch(a(),{headers:{Authorization:`Bearer ${t.getToken?.()??t.token}`,Accept:"text/event-stream"},signal:i.signal}),n){await c.body?.cancel();return}t.getToken?.()}catch(_){o(_);return}if(c.status===429&&t.gate&&(c.body?.cancel().catch(()=>{}),t.gate.observe(c.status,c.headers))){if(n)return;s=setTimeout(()=>void l(),Math.max(0,(t.gate.until()??Date.now())-Date.now()));return}if(!c.ok||!c.body){o(new Error(`sse http ${c.status}`));return}t.gate?.observe(c.status,c.headers),r=0;let u=Date.now();e.onOpen();let f=c.body.getReader(),g=new TextDecoder,p="",m="",y=[],b=()=>{if(t.getToken?.(),!y.length&&!m)return;let _=y.join(`
|
|
214
|
+
`),h=m||"message";m="",y=[];let T=null;try{T=_?JSON.parse(_):null}catch{return}h==="hello"?e.onHello(Number(T?.seq??0)):h==="change"?e.onChange(T):h==="reset"?e.onReset():h==="presence"?e.onPresence?.(T):h==="presence-roster"&&e.onPresenceRoster?.(T)};try{for(;;){let{done:_,value:h}=await f.read();if(_)break;for(p+=g.decode(h,{stream:!0});;){let T=p.indexOf(`
|
|
215
|
+
`);if(T<0)break;let v=p.slice(0,T).replace(/\r$/,"");if(p=p.slice(T+1),v==="")b();else{if(v.startsWith(":"))continue;v.startsWith("event:")?m=v.slice(6).trim():v.startsWith("data:")&&y.push(v.slice(5).replace(/^ /,""))}}}}catch(_){n||o(_,Date.now()-u>=1e4);return}o(new Error("sse stream ended"),Date.now()-u>=1e4)};return l(),{stop:()=>{n=!0,s&&clearTimeout(s),i?.abort()}}}var un=t=>Ee().path.join(Le().userDataDir(),Le().isDevMode()?`${t}.dev.json`:`${t}.json`),io=un,St=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,ln=t=>typeof t=="string"&&Yt(t)===t,hr=t=>typeof t=="string"&&t.length>0,wc=t=>St(t)&&cn(t.seq)&&hr(t.hash)&&cn(t.size)&&typeof t.mtimeMs=="number"&&Number.isFinite(t.mtimeMs),bc=t=>typeof t=="number"&&Number.isFinite(t),Hh=t=>St(t)&&hr(t.localHash)&&cn(t.localSize)&&bc(t.localMtimeMs)&&cn(t.remoteSeq)&&(t.remoteHash===null||hr(t.remoteHash))&&(t.remoteUpdatedAt===null||typeof t.remoteUpdatedAt=="string")&&bc(t.since),zh=t=>St(t)&&ln(t.from)&&ln(t.to)&&(t.kind==="file"||t.kind==="folder")&&(t.hashes===void 0||St(t.hashes)&&Object.values(t.hashes).every(hr));async function so(t){let e;try{e=await Ee().fs.readFile(io(t),"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let n;try{n=JSON.parse(e)}catch{throw Error("Invalid cloud vault sync state; original data was retained")}if(!St(n)||typeof n.vaultRoot!="string"||!n.vaultRoot||typeof n.vaultId!="string"||!n.vaultId||typeof n.folder!="string"||n.rootIdentity!==void 0&&!Vt(n.rootIdentity)||n.mirrorMissing!==void 0&&n.mirrorMissing!==!0||n.mirrorRestore!==void 0&&n.mirrorRestore!=="list"&&(!St(n.mirrorRestore)||!Object.entries(n.mirrorRestore).every(([r,i])=>ln(r)&&St(i)&&cn(i.seq)&&(i.hash===null||hr(i.hash))))||!St(n.files)||!Object.entries(n.files).every(([r,i])=>ln(r)&&wc(i))||n.cursor!==void 0&&!cn(n.cursor)||n.lastSyncAt!=null&&!cn(n.lastSyncAt)||n.pending!==void 0&&(!St(n.pending)||!Object.entries(n.pending).every(([r,i])=>ln(r)&&(i==="local"||i==="remote")))||n.moves!==void 0&&(!Array.isArray(n.moves)||!n.moves.every(zh))||n.held!==void 0&&(!St(n.held)||!Object.entries(n.held).every(([r,i])=>ln(r)&&Hh(i)))||n.dormant!==void 0&&(!St(n.dormant)||!Object.entries(n.dormant).every(([r,i])=>ln(r)&&wc(i)))||n.dormantRoot!==void 0&&!Vt(n.dormantRoot))throw Error("Invalid cloud vault sync state; original data was retained");return{...n,cursor:n.cursor??0,lastSyncAt:n.lastSyncAt??null}}function Sc(t){let e=null,n=null,r=Promise.resolve(),i=null,s=()=>{if(!e)return r;let a=e,o=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let l=io(t),c=`${l}.tmp-${Ee().tmpTag()}-${Date.now()}-0`;await Ee().fs.writeFile(c,o,"utf8"),await Ee().fs.rename(c,l),i=null}catch(l){e??=a,i=l}}),r};return{save(a){e=a,!n&&(n=setTimeout(()=>{n=null,s()},500))},async flush(a=!1){if(n&&(clearTimeout(n),n=null),await s(),a&&i)throw i}}}async function vc(t){try{await Ee().fs.unlink(io(t))}catch{}}var gr=/^[0-9a-f]{64}$/;function kc(t){let e=Ee(),n=()=>un(t).replace(/\.json$/,".bases"),r=o=>e.path.join(n(),o),i=o=>e.fs.access(r(o)).then(()=>!0,()=>!1),s=new Map,a=(o,l)=>{let c=(s.get(o)??Promise.resolve()).then(l,l);return s.set(o,c),c.finally(()=>{s.get(o)===c&&s.delete(o)}),c};return{put(o,l){return gr.test(o)?a(o,async()=>{try{if(await i(o))return;await e.fs.mkdir(n(),{recursive:!0});let c=`${r(o)}.tmp-${e.tmpTag()}-${Date.now()}`;await e.fs.writeFile(c,l,"utf8"),await e.fs.rename(c,r(o))}catch{}}):Promise.resolve()},async get(o){if(!gr.test(o))return null;try{let l=await e.fs.readFile(r(o),"utf8");return e.sha256Hex(l)===o?l:null}catch{return null}},drop(o,l){return gr.test(o)?a(o,async()=>{if(!(l&&!l()))try{await e.fs.rm(r(o),{force:!0})}catch{}}):Promise.resolve()},async has(o){return gr.test(o)&&i(o)},async prune(o){let l;try{l=(await e.fs.readdir(n(),{withFileTypes:!0})).filter(c=>c.isFile()).map(c=>c.name)}catch{return}for(let c of l)if(!o.has(c)&&!(!gr.test(c)&&!/^[0-9a-f]{64}\.tmp-/.test(c)))try{await e.fs.rm(e.path.join(n(),c),{force:!0})}catch{}}}}var Bh=720*60*60*1e3,qh=/^[0-9a-f]{64}$/,_i=new Map,Ec=(t,e)=>{let n=(_i.get(t)??Promise.resolve()).then(e,e),r=n.catch(()=>{});return _i.set(t,r),r.then(()=>{_i.get(t)===r&&_i.delete(t)}),n},oo=class extends Error{constructor(e){super(`sync recovery save failed: ${e?.message??String(e)}`),this.name="RecoveryError"}};function _c(t){let e=Ee(),n=()=>e.path.join(Le().homeDir(),"sync-recovery",t),r=o=>e.fs.access(o).then(()=>!0,()=>!1),i=async(o,l)=>{let c=`${o}.tmp-${e.tmpTag()}-${Date.now()}`;try{await e.fs.writeFile(c,l),await e.fs.rename(c,o)}catch(u){throw await e.fs.rm(c,{force:!0}).catch(()=>{}),u}},s={async save(o,l){let c=n(),u=await Ec(c,async()=>{try{let f=e.path.join(c,e.sha256Hex(o));await e.fs.mkdir(c,{recursive:!0}),await r(f)||await i(f,o);let g=`${f}.json`,p=[];try{let m=JSON.parse(await e.fs.readFile(g,"utf8"));Array.isArray(m)&&(p=m)}catch{}return p.push({...l,savedAt:Date.now()}),await i(g,JSON.stringify(p)),f}catch(f){throw new oo(f)}});return s.prune(),u},prune(o=Date.now()){let l=n();return Ec(l,()=>a(l,o))}},a=async(o,l)=>{let c;try{c=(await e.fs.readdir(o,{withFileTypes:!0})).filter(u=>u.isFile()).map(u=>u.name)}catch{return}for(let u of c){if(!qh.test(u))continue;let f=e.path.join(o,u),g=0;try{let p=JSON.parse(await e.fs.readFile(`${f}.json`,"utf8"));g=Math.max(0,...p.map(m=>Number(m?.savedAt)||0))}catch{try{g=(await e.fs.stat(f)).mtimeMs}catch{continue}}if(!(l-g<=Bh))try{await e.fs.rm(f,{force:!0}),await e.fs.rm(`${f}.json`,{force:!0})}catch{}}};return s}var Wh=5*1024*1024,Gh=5*1024*1024,Vh=3e4,Yh=5e3,Jh=5*6e4,Kh=2500,Xh=3e3,Zh=5,Qh=256*1024,eg=5,Ci=1024*1024,Cc=200,tg=6e4,ng=50,rg=".sync-trash",Ye=t=>Ee().sha256Hex(t);function mr(t,e){let n=e??{localRoot:$t(),shadowName:`amadeus-sync-${_n()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]},r=d=>{let w=ro(d,"");if(!w)return null;for(let k of n.excludePrefixes??[])if(w===k.replace(/\/$/,"")||w.startsWith(k))return null;if(n.ignoreNames?.length&&w.split("/").some(k=>n.ignoreNames.includes(k)))return null;let S=n.serverDir?`${n.serverDir}/${w}`:w;return n.inScope&&!n.inScope(S,De(S))?null:S},i=d=>{let w;if(n.serverDir){if(!d.startsWith(`${n.serverDir}/`))return null;w=d.slice(n.serverDir.length+1)}else{for(let S of n.excludePrefixes??[])if(d.startsWith(S))return null;w=d}return w.split("/").some(S=>pr(S)||!!n.ignoreNames?.includes(S))?null:w},s=(d,w)=>!n.inScope||n.inScope(d,w),a=n.accountId??Be(),{fs:o,path:l,directoryIdentity:c}=Ee(),u=d=>o.access(d).then(()=>!0,()=>!1),f=!1,g=!1,p=0,m=Promise.resolve(),y=new Set,b="disabled",_=null,h=null,T=null,v=null,I=null,E=null,D=null,x=null,L=null,V=()=>{let d=t.loadCreds();if(!E||a!==Be()||!d.token||d.cloudUrl?.replace(/\/+$/,"")!==E.cloudUrl.replace(/\/+$/,""))throw new ye(401,{code:"ACCOUNT_CHANGED"},"sync-session");return d.token},H=null,N=0,Y=new Map,ee=null,J=Sc(n.shadowName),se=kc(n.shadowName),te=_c(_n(a)),ae=!1,Q=new Map,me=!1,ge=!1,Pe=[],Ce=(d,w,S)=>{try{t.onHealth?.(d,w,S)}catch{}},He=Ei(Ce),Ae=0,ut=()=>{ge||Ce("massDeleteGuard"),ge=!0},M=()=>{h&&(h.pending=Q.size?Object.fromEntries(Q):void 0,J.save(h))},U=()=>{ge=!1,Pe.length=0},C=()=>{if(ge)return!0;let d=Date.now();for(;Pe.length&&d-Pe[0]>tg;)Pe.shift();return Pe.length>=ng?(ut(),!0):!1},A=[],j=new Set,F=!1,z=null,q=null,ne=null,re=null,Z=()=>{!f||re||(re=setTimeout(()=>{re=null,t.onStatus(_t())},200))},ie=(d,w,S)=>{let k=b;b=d,w!==void 0&&(_=w),pe(k,d,S),Z()},oe=!1,pe=(d,w,S)=>{if(w==="syncing"&&d!=="syncing"&&(Ae=Date.now()),w==="idle"&&d==="syncing"&&(Ce("cycles"),Ce("cycleMsTotal",Math.max(0,Date.now()-Ae))),w==="idle"||w==="disabled"){oe=!1,He.ok();return}if(S===null)return;let k=S??dc(w,_);k&&He.error(k)},le=(d,w)=>{Y.set(d,w),Ce(cc(w),1,d)},X=(d,w=!1)=>{if(!(!f||!g)){if(d.key){if(j.has(d.key))return;j.add(d.key)}w?A.unshift(d):A.push(d),rf()}},ve=new Map,nn=d=>{if(!f)return;let w=(h?.files[d]?.size??0)>Qh,S=(n.pushQuietMs??Xh)*(w?eg:1),k=Date.now(),R=ve.get(d);R&&clearTimeout(R.timer);let P=R?.since??k,W=Math.max(0,Math.min(S,P+S*Zh-k)),O=setTimeout(()=>{ve.delete(d),X({key:d,run:()=>xe(d,!0)})},W);ve.set(d,{timer:O,since:P}),Z()},Jn=()=>{for(let{timer:d}of ve.values())clearTimeout(d);ve.clear()},yt=new Set(["EACCES","EPERM","EISDIR","ENOTDIR","ENAMETOOLONG","EILSEQ","EINVAL","ELOOP","EBUSY","EFBIG","EIO"]),os=d=>!(d instanceof ye)&&typeof d?.code=="string"&&yt.has(d.code),Ur=d=>!(d instanceof ye)||d.status>=500||d.status===0,tf=d=>!!d&&!d.startsWith("\0"),nf=d=>d instanceof ye?d.body?.code||`http ${d.status}`:d?.code??"error",Kn=d=>d instanceof ye&&(d.status===401||d.status===403),Hr=(d,w)=>{le(d,nf(w)),Z()},rf=async()=>{if(!F){F=!0;try{for(;A.length;){(b==="idle"||b==="starting")&&ie("syncing");let d=A.shift();d.key&&j.delete(d.key);try{await d.run()}catch(w){if(!f)return;if(Kn(w)){A.length=0,j.clear(),er(),ie("auth-required","login-expired");return}if(Ur(w)&&!(os(w)&&tf(d.key))){X(d,!0),er(),ie("offline",w?.message||"network error"),Xn();return}Hr(d.key??"(op)",w)}}f&&b==="syncing"&&(h&&(h.lastSyncAt=Date.now(),J.save(h)),ie("idle",null))}finally{F=!1;for(let d of y)d();y.clear()}}},Xn=()=>{!f||z||(z=setTimeout(()=>{z=null,tr()},Vh))},we=new Map,rn=0,Me=null,zr=()=>!!q||!!Me||!f,as=d=>d instanceof ye&&d.status>=500||d?.name==="TimeoutError",ma=n.pushRetryMs??Yh,ya=d=>{we.get(d)&&(we.delete(d),Y.delete(d))},Zn=(d,w)=>{(w||!we.has(d))&&we.set(d,w)},wa=(d,w,S)=>{le(d,w instanceof ye?`http ${w.status}`:"timeout"),Zn(d,S),rn=Math.min(rn*2||ma,Jh),q=setTimeout(Br,rn),Z()},ba=(d,w,S)=>{let k=new AbortController,R=w(k.signal).then(W=>()=>W,W=>()=>{throw W}),P={path:d,abort:k,after:[],settle:async()=>{let W=await R;if(Me===P){Me=null;try{await S(W)}catch(O){if(Kn(O)||Ur(O))throw O;Hr(d,O)}finally{for(let O of P.after)X(O);Sa(d)}}}};Me=P,R.then(()=>X({run:P.settle}))},Sn=(d,w)=>{for(let[S,k]of[...we])!k||!We(S,d)||(we.delete(S),Y.delete(S),w!==null&&we.set(w+S.slice(d.length),k));Z()},Br=()=>{q=null;let[d]=we;if(d===void 0)return;let[w]=d;j.delete(w),X({key:w,run:async()=>{if(Me?.path===w)return;let S=we.get(w),k=!S&&we.delete(w);(S||k)&&Y.delete(w);try{S?await Xe(w,S.seq):k&&await xe(w,!0)}finally{k&&je(w)&&Zn(w),Sa(w)}}})},Sa=d=>{if(!zr())if(we.has(d)){let w=we.get(d);we.delete(d),we.set(d,w),q=setTimeout(Br,rn||ma)}else Br()},$e=d=>{if(!H||!h)throw new Error("engine not bound");let w=i(d);if(w===null)throw new Error("path outside binding: "+d);let S=l.resolve(H,fc(w,h.folder)),k=l.relative(H,S);if(k.startsWith("..")||l.isAbsolute(k))throw new Error("path escapes vault: "+d);return S},qr=d=>({size:d,mtimeMs:-1}),va=async d=>{try{let w=await o.stat(d);return w.isFile()?{size:w.size,mtimeMs:Math.floor(w.mtimeMs)}:null}catch{return null}},ka=async d=>{if(!o.lstat||!H)return va(d);let w=l.relative(H,d).split(l.sep),S=H;for(let[k,R]of w.entries()){S=l.join(S,R);let P=await o.lstat(S).catch(W=>{if(W?.code==="ENOENT")return null;throw W});if(!P)return null;if(P.isSymbolicLink())throw Error("Cloud vault sync does not follow symbolic links");if(k===w.length-1&&P.isFile())return{size:P.size,mtimeMs:Math.floor(P.mtimeMs)};if(k===w.length-1||!P.isDirectory())throw Error("Cloud vault sync path is not a regular file")}return null},sf=0,ls=async(d,w,S,k)=>{if(!await et())throw Error("Cloud vault sync root is unavailable or changed");let R=H&&T?{path:H,identity:T}:void 0;await o.mkdir(l.dirname(d),{recursive:!0});let P=`${d}.tmp-${Ee().tmpTag()}-${Date.now()}-${sf++}`;await o.writeFile(P,w);let W=await va(P)??qr(ei(w));try{if(!k())return null;let O=Ee().compareAndReplace;if(!O)throw new Error("Host does not support safe cloud download commits");let B=await O(P,d,S,k,R);if(!B&&!await et())throw Error("Cloud vault sync root is unavailable or changed");return B?W:null}finally{await et()&&await o.rm(P,{force:!0})}},Ea=async d=>{let w;try{w=await o.readdir(d,{withFileTypes:!0})}catch{return}for(let S of w)S.isDirectory()&&await Ea(l.join(d,S.name));try{await o.rmdir(d)}catch{}},dt=async d=>{let w=$e(d),S=await ka(w);if(!await et())throw Error("Cloud vault sync root is unavailable or changed");if(o.lstat&&!S)return null;let k;try{k=await o.readFile(w)}catch(P){if(P?.code!=="ENOENT")throw P;if(!await et())throw Error("Cloud vault sync root is unavailable or changed");return null}return{hash:qe(De(d))?Ye(Ct(k)):Ye(k),size:S?.size??k.length,mtimeMs:S?.mtimeMs??-1,buf:k}},Qe=async(d,w,S,k,R)=>{if(!h)return;let P=h.files[d]?.hash;h.files[d]={seq:w,hash:S,size:k.size,mtimeMs:k.mtimeMs},h.mirrorRestore&&h.mirrorRestore!=="list"&&delete h.mirrorRestore[d],J.save(h),R!==void 0&&await _a(d,S,R),P&&P!==S&&await cs(P)},_a=async(d,w,S)=>{if(!qe(De(d))||ei(S)>Ci)return;let k=typeof S=="string"?S:Ct(S);Ye(k)===w&&await se.put(w,k)},cs=async d=>{let w=()=>!!h&&!Object.values(h.files).some(S=>S.hash===d)&&!Object.values(h.dormant??{}).some(S=>S.hash===d);w()&&await se.drop(d,w)},ft=d=>{if(h&&d in h.files){let w=h.files[d].hash;delete h.files[d],J.save(h),cs(w)}},pt=(d,w,S)=>{if(!h)return;let k=h.held?.[d];ft(d),h.held={...h.held,[d]:{localHash:w.hash,localSize:w.size,localMtimeMs:w.mtimeMs,remoteSeq:S.seq,remoteHash:S.hash,remoteUpdatedAt:S.updatedAt!==void 0?S.updatedAt:k&&k.remoteSeq===S.seq?k.remoteUpdatedAt:null,since:k?.since??Date.now()}},J.save(h),Z()},Se=d=>{if(!h?.held||!Object.hasOwn(h.held,d))return;let{[d]:w,...S}=h.held;h.held=Object.keys(S).length?S:void 0,J.save(h),Z()},Mt=d=>h?.held&&Object.hasOwn(h.held,d)?h.held[d]:void 0,kt=d=>i(d)!==null&&s(d,De(d)),us=d=>{!h||!Object.hasOwn(h.files,d)||(h.dormant={...h.dormant,[d]:h.files[d]},T&&(h.dormantRoot??=T),delete h.files[d],J.save(h))},Wr=d=>{if(!h?.dormant||!Object.hasOwn(h.dormant,d))return;let w=h.dormant[d].hash,{[d]:S,...k}=h.dormant;h.dormant=Object.keys(k).length?k:void 0,h.dormant||delete h.dormantRoot,J.save(h),cs(w)},Ca=d=>!!h?.dormant&&Object.hasOwn(h.dormant,d)&&!Object.hasOwn(h.files,d)&&kt(d),Aa=()=>X({key:"\0full",run:sn}),xa=()=>{if(h){for(let d of Object.keys(h.files))!kt(d)&&!je(d)&&us(d);for(let d of Object.keys(h.held??{}))!kt(d)&&!je(d)&&Se(d)}},Xe=async(d,w)=>{if(!v||!h||je(d))return;if(Ca(d)){Aa();return}let S=ke,k=De(d),R=Mt(d);if(R&&!qe(k)){ya(d),w!==null&&w!==R.remoteSeq&&pt(d,{hash:R.localHash,size:R.localSize,mtimeMs:R.localMtimeMs},{seq:w,hash:null,updatedAt:null});return}if(qe(k)){let B;try{B=await v.getFile(h.vaultId,d),Ce("downloads")}catch(K){if(K instanceof ye&&K.status===404){await ds(d);return}throw K}await Ta(d,k,B.content,B.seq,B.hash??Ye(B.content),S);return}if(zr()){Zn(d,{seq:w}),Z();return}let{vaultId:P}=h,W=v,O={seq:w};we.set(d,O),ba(d,B=>W.getAsset(P,d,B),async B=>{let K=we.get(d)===O,$;try{$=B(),rn=0,Ce("downloads")}catch(G){if(!K)return;if(we.delete(d),G instanceof ye&&G.status===404){le(d,"ASSET_404"),Z();return}if(as(G)){wa(d,G,{seq:w});return}throw G}K&&await Ta(d,k,$,w??0,Ye($),S)}),Z()},Ta=async(d,w,S,k,R,P)=>{if(!h)return;let W=async Ie=>{await Qe(d,k,R,Ie,S),we.get(d)&&(we.delete(d),Y.delete(d))},O=await dt(d);if(P!==ke||je(d))return;let B=h.mirrorRestore,K=B&&B!=="list"&&Object.hasOwn(B,d)?B[d]:void 0;if(K&&(K.hash!==R||K.seq!==k)){let Ie={...K};Object.assign(K,{hash:R,seq:k}),J.save(h);try{await J.flush(!0)}catch(nt){throw Object.assign(K,Ie),J.save(h),nt}if(!f||P!==ke||je(d))return}if(O&&O.hash===R){await W(O),Se(d);return}let $=h.files[d];if(O&&(!$||Mt(d)||An($,{seq:k,hash:R})&&O.hash!==$.hash)){ya(d),pt(d,O,{seq:k,hash:R});return}if(Se(d),O&&$&&R===$.hash&&O.hash!==$.hash){await W(qr($.size)),X({key:d,run:()=>xe(d)});return}let G=O?Ye(O.buf):null;if(O&&(!$||O.hash!==$.hash)){if($&&qe(w)&&typeof S=="string"&&await of(d,$,O,S,k,R,()=>P===ke&&!je(d))||P!==ke||je(d)||!await Ia(d,()=>P===ke&&!je(d)))return;G=null}let he=await ls($e(d),S,G,()=>f&&P===ke&&!je(d));if(!he){X({key:d,run:()=>xe(d)});return}await W(he)},of=async(d,w,S,k,R,P,W)=>{try{if(!v||!h||S.buf.length>Ci||k.length>Ci)return!1;let O=await se.get(w.hash);if(O===null){let G=(await v.listVersions(h.vaultId,d)).find(Ie=>Ie.seq===w.seq);if(!G)return!1;let he=await v.getVersion(h.vaultId,G.id);if(Ye(he)!==w.hash)return!1;O=he}let B=Ct(S.buf),K;if(De(d)==="db"){let $=rc(),G=$?$(d,B,O,k):null;K=G&&!G.conflict?G.content:null}else K=ac(B,O,k);return K===null?!1:await ls($e(d),K,Ye(S.buf),()=>f&&W())?(await Qe(d,R,P,qr(ei(K)),k),X({key:d,run:()=>xe(d)}),!0):(X({key:d,run:()=>xe(d)}),!0)}catch{return!1}},Ia=async(d,w)=>{let S=Yt(Si(d,new Date));if(!S)return!0;let k=S.lastIndexOf("."),R=k>S.lastIndexOf("/"),P=R?S.slice(0,k):S,W=R?S.slice(k):"",O=S,B=Ee().existsSync;if(B)for(let K=2;B($e(O));K++)O=`${P}-${K}${W}`;else for(let K=2;await u($e(O));K++)O=`${P}-${K}${W}`;if(!w())return!1;try{await o.rename($e(d),$e(O))}catch(K){if(K?.code==="ENOENT")return!0;throw K}return N++,Ce("conflicts"),X({key:O,run:()=>xe(O)}),Z(),!0},Ra=async d=>{if(!H)return;let w=$e(d),S=i(d)??d,k=l.join(H,rg,new Date().toISOString().slice(0,10),...S.split("/")),R=await u(k)?`${k}.${Date.now()}`:k;try{await o.mkdir(l.dirname(R),{recursive:!0}),await o.rename(w,R)}catch(P){if(P?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${w}: ${P?.message??String(P)}`)}},ds=async d=>{if(!h)return;Sn(d,null),Se(d),Wr(d);let w=await dt(d);if(je(d))return;let S=h.files[d]??null,k=vi(w?.hash??null,S,null);if(k.kind==="deleteLocal"){if(!me&&C()){Q.set(d,"local"),M(),Z();return}Pe.push(Date.now()),await Ra(d),ft(d)}else k.kind==="pushCreate"?(ft(d),X({key:d,run:()=>xe(d)})):ft(d)},Da=(d,w)=>{if(h){Sn(d,w);for(let S of Object.keys(h.files))if(S===d||S.startsWith(`${d}/`)){let k=w+S.slice(d.length);h.files[k]=h.files[S],delete h.files[S]}for(let S of[h.held,h.dormant])if(S)for(let k of Object.keys(S))(k===d||k.startsWith(`${d}/`))&&(S[w+k.slice(d.length)]=S[k],delete S[k]);J.save(h),Z()}},Oa=async d=>{if(!v||!h||d.seq<=h.cursor||!await et())return;if(d.origin.client&&v.clientId===d.origin.client){h.cursor=d.seq,J.save(h);return}let w=d.type==="structure"?"folder":d.type,S=R=>i(R)!==null&&s(R,w);if(!S(d.path)&&!(d.newPath&&S(d.newPath))){h.cursor=d.seq,J.save(h);return}let k=d.path;if(d.op!=="write"&&d.op!=="mkdir"){for(;Me&&(We(Me.path,k)||d.newPath&&We(Me.path,d.newPath));)await Me.settle();if(!f)return}switch(d.op){case"write":await Xe(k,d.fileSeq);break;case"delete":await ds(k);break;case"move":{let R=d.newPath;if(!R)break;let P=h.files[k],W=await dt(k),O=!!we.get(k);Sn(k,R),Wr(k),Mt(k)&&(Se(k),X({key:k,run:()=>xe(k)})),O&&Zn(R,{seq:d.fileSeq});let B=R!==k&&await ka($e(R)).then(K=>K!==null,()=>!0);if(W&&P&&B)await Xe(R,d.fileSeq);else if(W&&P)try{await o.mkdir(l.dirname($e(R)),{recursive:!0}),await o.rename($e(k),$e(R)),h.files[R]={...P,seq:O?P.seq:d.fileSeq??P.seq},delete h.files[k],J.save(h)}catch{await Xe(R,d.fileSeq)}else ft(k),await Xe(R,d.fileSeq);break}case"mkdir":await o.mkdir($e(k),{recursive:!0});break;case"rename-folder":case"move-folder":{let R=d.newPath;if(!R)break;try{await o.mkdir(l.dirname($e(R)),{recursive:!0}),await o.rename($e(k),$e(R))}catch{}Da(k,R);break}case"delete-folder":{let R=`${k}/`;for(let P of[...Object.keys(h.files),...Object.keys(h.held??{}),...Object.keys(h.dormant??{})])(P===k||P.startsWith(R))&&await ds(P);Sn(k,null),await Ea($e(k));break}}if(h.cursor=d.seq,J.save(h),d.op==="move"||d.op==="rename-folder"||d.op==="move-folder"||d.op==="delete"||d.op==="delete-folder")try{await t.onRemoteApplied?.(d)}catch{}},af=async(d,w,S)=>{let k=Number(w?.seq??0),R=w?.content??null,P;if(w?.seq===void 0&&v&&h)try{let B=await v.getFile(h.vaultId,d);k=B.seq,R=B.content,P=B.updatedAt}catch(B){if(!(B instanceof ye)||B.status!==404)throw B;k=0,R=null}if(R!==null&&Ye(R)===S.hash){await Qe(d,k,S.hash,S,R),Se(d);return}if(R===null&&k===0){if(!h?.files[d]){le(d,w?.code||"EXISTS"),Z();return}ft(d),X({key:d,run:()=>xe(d)});return}let W=h?.files[d],O=R===null?null:Ye(R);if(!W||An(W,{seq:k,hash:O})){pt(d,S,{seq:k,hash:O,updatedAt:P});return}await Xe(d,k)},Gr=async(d,w)=>{if(!v||!h)return;let S=await dt(d);if(!S){X({key:d,run:()=>xe(d)});return}if(S.size>Wh){le(d,"TOO_LARGE"),Z();return}let k=Ct(S.buf),R=w>0?h.files[d]?.hash:void 0;try{let P=await v.putFile(h.vaultId,d,k,w,!1,R);Ce("uploads"),Y.delete(d),await Qe(d,P.seq,P.hash??S.hash,S,S.buf),Se(d)}catch(P){if(P instanceof ye&&P.status===409){await af(d,P.body,S);return}throw P}},Vr=async(d,w)=>{if(!v||!h)return;let S=await dt(d);if(!S){X({key:d,run:()=>xe(d)});return}if(S.size>(ee??Gh)){le(d,"TOO_LARGE"),Z();return}if(Zn(d),Z(),zr())return;let{vaultId:k}=h,R=v,P=w>0?h.files[d]?.hash:void 0;ba(d,W=>R.putBinary(k,d,S.buf,{baseSeq:w,signal:W,expectedHash:P}),async W=>{if(h){we.get(d)||we.delete(d);try{let O=W();rn=0,Ce("uploads"),Y.delete(d),await Qe(d,O.seq,S.hash,S),Se(d)}catch(O){if(as(O)){wa(d,O);return}if(!(O instanceof ye)||O.status!==409)throw O;let B=Number(O.body?.seq??0),K=O.body?.hash??null;if(K!==null&&K===S.hash){await Qe(d,B,S.hash,S),Se(d);return}if(B===0){if(!h.files[d]){le(d,O.body?.code||"EXISTS"),Z();return}ft(d),X({key:d,run:()=>xe(d)});return}let $=h.files[d];if(!$||An($,{seq:B,hash:K})){pt(d,S,{seq:B,hash:K});return}await Xe(d,B)}}})},Ma=async d=>{if(!v||!h||je(d))return;let w=ke,S=h.files[d];if(S){if(qe(De(d)))try{let k=await v.getFile(h.vaultId,d);if(k.seq!==S.seq||k.hash!==null&&k.hash!==S.hash){await Xe(d,k.seq);return}}catch(k){if(k instanceof ye&&k.status===404){ft(d);return}throw k}if(!(!await et()||w!==ke||je(d))){try{await v.deleteFile(h.vaultId,d,S.seq,{confirmed:me,expectedHash:S.hash})}catch(k){if(k instanceof ye&&k.status===409){await Xe(d,Number(k.body?.seq??0)||null);return}if(k instanceof ye&&k.status===429&&k.body?.code==="MASS_DELETE_BLOCKED"){Q.set(d,"remote"),ut(),M(),Z();return}throw k}ft(d)}}},Yr=d=>o.stat(d).catch(w=>{if(w?.code==="ENOENT")return null;throw w}),fs=async d=>{let w=Le();if(e||!a||a!==Be()||d!==$t(a)||!w.isManagedCloudVault(d)||!o.lstat)return!1;let S=w.homeDir(),k=l.relative(S,d);if(!k||k.startsWith("..")||l.isAbsolute(k))return!1;let R=S;for(let P of k.split(l.sep)){R=l.join(R,P);let W=await o.lstat(R).catch(O=>{if(O.code==="ENOENT")return null;throw O});if(W&&(!W.isDirectory()||W.isSymbolicLink()))return!1}return!0},Gt=d=>(g=!1,me=!1,A.length=0,j.clear(),gs(),er(),ie("error",`${d}: ${H}`),Xn(),!1),ps=d=>{let w=T??h?.rootIdentity,S=d!==null&&d.isDirectory();return S&&(!w||bt(w,d))?!0:Gt(S?"vault-changed":"vault-missing")},et=async()=>!!H&&ps(await Yr(H)),ke=0,Jr=new Set,Kr=new Map,tt=d=>JSON.stringify([d.from,d.to]),We=(d,w)=>d===w||d.startsWith(`${w}/`),je=d=>[...h?.moves??[],...Jr].some(w=>We(d,w.from)||We(d,w.to)),Et=()=>!!(h?.moves?.length||Jr.size),Xr=async d=>{if(!v||!h)return;let{from:w,to:S,kind:k}=d;if(i(w)===null||i(S)===null)throw new Error("Invalid queued cloud move");if(Me&&(We(Me.path,w)||We(Me.path,S))){Me.after.push({key:`move:${tt(d)}`,run:()=>Xr(d)});return}if(d.hashes??=Object.fromEntries([...Object.entries(h.held??{}).filter(([O,B])=>We(O,w)&&B.remoteHash!==null).map(([O,B])=>[O.slice(w.length),B.remoteHash]),...Object.entries(h.files).filter(([O])=>We(O,w)).map(([O,B])=>[O.slice(w.length),B.hash])]),J.save(h),await J.flush(!0),!await et())return;let R,P=!1;try{if(k==="folder"){let O=l.posix.dirname(w)==="."?"":l.posix.dirname(w),B=l.posix.dirname(S)==="."?"":l.posix.dirname(S);O===B?await v.renameFolder(h.vaultId,w,l.posix.basename(S)):await v.moveFolder(h.vaultId,w,B)}else{let O=await v.move(h.vaultId,w,S);R=Number(O.seq)}}catch(O){if(!(O instanceof ye)||O.status!==404)throw O;let B=await v.tree(h.vaultId);if(B.entries.some(G=>We(G.path,w))||B.folders.some(G=>We(G,w)))throw O;let $=B.entries.find(G=>G.path===S);if(R=$?.seq,P=!$&&!B.entries.some(G=>We(G.path,S))&&!B.folders.some(G=>We(G,S)),!P){let G=Object.entries(d.hashes);if(!(G.length>0&&G.every(([Ie,nt])=>B.entries.some(Ge=>Ge.path===S+Ie&&Ge.hash===nt))))throw new ye(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(P){for(let O of Object.keys(h.files))We(O,w)&&delete h.files[O];for(let O of Object.keys(h.held??{}))We(O,w)&&Se(O);for(let O of Object.keys(h.dormant??{}))We(O,w)&&Wr(O);Sn(w,null)}else Da(w,S),R!==void 0&&h.files[S]&&!we.get(S)&&(h.files[S].seq=R);h.moves=(h.moves??[]).filter(O=>tt(O)!==tt(d)),J.save(h);try{await J.flush(!0)}catch(O){throw h.moves.unshift(d),J.save(h),O}let W=Kr.get(tt(d));Kr.delete(tt(d)),W?.(),je(S)||(k==="folder"?await hs():await xe(S))},xe=async(d,w=!1)=>{if(!h||je(d))return;if(Me?.path===d){Me.after.push({key:d,run:()=>xe(d,w)});return}if(!s(d,De(d))){us(d),Se(d);return}if(!await et())return;let S=await dt(d);if(je(d))return;let k=h.files[d]??null;if(!k&&Ca(d)){Aa();return}let R=Mt(d);if(R){S&&S.hash===R.remoteHash&&qe(De(d))?await Xe(d,null):S&&S.hash===R.remoteHash?(await Qe(d,R.remoteSeq,S.hash,S),Se(d)):S&&S.hash!==R.localHash&&pt(d,S,{seq:R.remoteSeq,hash:R.remoteHash});return}let P=vi(S?.hash??null,k,k?{seq:k.seq,hash:k.hash}:null);switch(P.kind){case"push":qe(De(d))?await Gr(d,P.baseSeq):await Vr(d,P.baseSeq);break;case"pushCreate":qe(De(d))?await Gr(d,0):await Vr(d,0);break;case"pushDelete":if(w){Qr();break}if(!me&&(Q.has(d)||C())){Q.set(d,"remote"),M(),Z();break}Pe.push(Date.now()),await Ma(d);break;case"dropShadow":ft(d);break;default:S&&k&&S.hash===k.hash&&S.mtimeMs>=0&&(k.size!==S.size||k.mtimeMs!==S.mtimeMs)&&await Qe(d,k.seq,k.hash,S,S.buf);break}},lf=async(d,w)=>{if(!v||!h)return;let S=await v.tree(h.vaultId);if(!h)return;let k=new Map(S.entries.map(R=>[R.path,R]));for(let R of d){if(!f||!h||!Mt(R)||je(R)||Me?.path===R)continue;if(!kt(R)){Se(R);continue}let P=await dt(R),W=k.get(R)??null;if(!P||!W){Se(R),P?X({key:R,run:()=>xe(R)}):await Xe(R,W?.seq??null);continue}if(P.hash===W.hash){await Qe(R,W.seq,P.hash,P,qe(De(R))?P.buf:void 0),Se(R);continue}let O;if(w==="newer"){let $=W.updatedAt?Date.parse(W.updatedAt):NaN;if(!Number.isFinite($)||P.mtimeMs<0)continue;O=P.mtimeMs>$?"local":"cloud"}else O=w;let B=ke,K=()=>f&&B===ke&&!je(R)&&kt(R);try{if(O==="both"){if(!await Ia(R,K))continue;Se(R),await Xe(R,W.seq);continue}let $=qe(De(R));if(!$&&zr())continue;O==="local"?await cf(R,P,W,$):await uf(R,P,W,$,K)}catch($){let G=$?.name==="RecoveryError";if(Kn($)||($ instanceof ye?$.status===0:!G&&!as($)&&Ur($)))throw $;le(R,$ instanceof ye?$.body?.code||`http ${$.status}`:$?.name==="TimeoutError"?"timeout":G?"RECOVERY_FAILED":"RESOLVE_FAILED"),Z()}}},cf=async(d,w,S,k)=>{if(!v||!h)return;let{vaultId:R}=h;if(k){let O=await v.getFile(R,d),B=Ye(O.content);if(O.seq!==S.seq||O.hash!==null&&O.hash!==B||S.hash!==null&&B!==S.hash){pt(d,w,{seq:O.seq,hash:O.hash??B,updatedAt:O.updatedAt});return}if(await te.save(O.content,{binding:n.shadowName,path:d,side:"cloud"}),!kt(d)){Se(d);return}try{let K=await v.putFile(R,d,Ct(w.buf),O.seq,!1,B);Ce("uploads"),Y.delete(d),await Qe(d,K.seq,K.hash??w.hash,w,w.buf),Se(d)}catch(K){if(!(K instanceof ye)||K.status!==409)throw K;await Na(d,w)}return}let P=await v.getAsset(R,d),W=Ye(P);if(S.hash!==null&&W!==S.hash){pt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}if(await te.save(P,{binding:n.shadowName,path:d,side:"cloud"}),!kt(d)){Se(d);return}try{let O=await v.putBinary(R,d,w.buf,{baseSeq:S.seq,expectedHash:W});Ce("uploads"),Y.delete(d),await Qe(d,O.seq,w.hash,w),Se(d)}catch(O){if(!(O instanceof ye)||O.status!==409)throw O;pt(d,w,{seq:Number(O.body?.seq??S.seq),hash:O.body?.hash??null,updatedAt:null})}},uf=async(d,w,S,k,R)=>{if(!v||!h)return;let{vaultId:P}=h,W,O,B;if(k){let $=await v.getFile(P,d);W=$.content,O=$.seq,B=Ye($.content)}else if(W=await v.getAsset(P,d),O=S.seq,B=Ye(W),S.hash!==null&&B!==S.hash){pt(d,w,{seq:S.seq,hash:null,updatedAt:S.updatedAt??null});return}await te.save(w.buf,{binding:n.shadowName,path:d,side:"local"});let K=await ls($e(d),W,Ye(w.buf),R);if(!K){if(!kt(d)){Se(d);return}await Na(d,null);return}Ce("downloads"),Y.delete(d),await Qe(d,O,B,K,W),Se(d)},Na=async(d,w)=>{if(!v||!h)return;let S=w??await dt(d);if(!S){Se(d),await Xe(d,null);return}if(!qe(De(d))){let P=Mt(d);pt(d,S,{seq:P?.remoteSeq??0,hash:null});return}let k;try{k=await v.getFile(h.vaultId,d)}catch(P){if(!(P instanceof ye)||P.status!==404)throw P;Se(d),X({key:d,run:()=>xe(d)});return}let R=Ye(k.content);if(R===S.hash){await Qe(d,k.seq,S.hash,S,k.content),Se(d);return}pt(d,S,{seq:k.seq,hash:R,updatedAt:k.updatedAt})},Pa=async()=>{let d=new Map;if(!H||!h)return d;let w=H,S=null,k=async R=>{if(S)return;let P;try{P=await o.readdir(R,{withFileTypes:!0})}catch(W){S=`${R}: ${W?.message??String(W)}`;return}for(let W of P){if(pr(W.name)||W.isDirectory()&&n.ignoreNames?.includes(W.name))continue;let O=l.join(R,W.name);if(W.isDirectory())await k(O);else if(W.isFile()){let B=l.relative(w,O).split(l.sep).join("/"),K=r(B);if(!K)continue;try{let $=await o.stat(O);if(!$.isFile())continue;d.set(K,{size:$.size,mtimeMs:Math.floor($.mtimeMs)})}catch($){if($?.code==="ENOENT")continue;S=`${O}: ${$?.message??String($)}`;return}}}};return await k(w),S?(ie("error",`scan-failed: ${S}`),Xn(),null):d},hs=async()=>{let d=ke;if(Et()||d!==ke||!h||!await et())return;let w=await Pa();if(!w||Et()||d!==ke||!await et())return;let S=!1;for(let[P,W]of[...Q])(W==="remote"&&w.has(P)||W==="local"&&!w.has(P))&&(Q.delete(P),S=!0);Q.size||U();for(let[P,W]of w){let O=h.files[P];if(O&&O.size===W.size&&O.mtimeMs===W.mtimeMs)continue;let B=Mt(P);B&&B.localSize===W.size&&B.localMtimeMs===W.mtimeMs||X({key:P,run:()=>xe(P)})}for(let P of Object.keys(h.files))kt(P)||us(P);let k=Object.keys(h.files),R=k.filter(P=>!w.has(P));if(R.length&&!me&&(ge||fr(R.length,k.length,Cc))){ut();for(let P of R)Q.set(P,"remote");M(),Z();return}S&&(M(),Z());for(let P of R)Q.has(P)||X({key:P,run:()=>xe(P)})},df=async d=>{if(!h)return;let w=new Set;for(let[S,k]of Object.entries(h.files)){if(!qe(De(S))||k.size>Ci)continue;w.add(k.hash);let R=d.get(S);if(!(!R||R.size!==k.size||R.mtimeMs!==k.mtimeMs||await se.has(k.hash)))try{let P=await dt(S);P&&P.hash===k.hash&&await _a(S,k.hash,P.buf)}catch{}}for(let S of Object.values(h.dormant??{}))w.add(S.hash);await se.prune(w)},sn=async()=>{if(Me){Me.after.push({run:sn});return}let d=ke;if(Et()||d!==ke||!v||!h||!H||!await et())return;let w=await v.tree(h.vaultId);if(w.maxFileBytes!==void 0&&w.maxFileBytes!==ee&&(ee=w.maxFileBytes,Z()),Et()||d!==ke)return;let S=new Map;for(let $ of w.entries)i($.path)===null||!s($.path,$.kind)||S.set($.path,$);for(let[$,G]of[...we])G&&!S.has($)&&Sn($,null);let k=await Pa();if(!k||Et()||d!==ke||!await et())return;if(h.mirrorRestore==="list"){for(let G of Object.keys(h.files))!k.has(G)&&!Q.has(G)&&delete h.files[G];let $=Object.create(null);for(let[G,{seq:he,hash:Ie}]of S)Object.hasOwn(h.files,G)||($[G]={seq:he,hash:Ie});h.mirrorRestore=$,J.save(h);try{await J.flush(!0)}catch(G){throw h.mirrorRestore="list",J.save(h),G}}let R=h.mirrorRestore;if(xa(),h.dormant){let $=!h.dormantRoot||!T||an(h.dormantRoot,T);for(let[G,he]of Object.entries(h.dormant))kt(G)&&($&&k.has(G)&&S.has(G)&&!Object.hasOwn(h.files,G)?(h.files[G]=he,delete h.dormant[G]):Wr(G));h.dormant&&!Object.keys(h.dormant).length&&(delete h.dormant,delete h.dormantRoot),J.save(h)}ae||(ae=!0,await df(k));let P=new Set([...S.keys(),...k.keys(),...Object.keys(h.files),...Object.keys(R??{}),...Object.keys(h.held??{})]),W=Object.keys(h.files).length,O=[];for(let $ of P){if(Et()||d!==ke)return;let G=h.files[$]??null,he=S.get($)??null,Ie=k.get($)??null,nt=null,Ge=qr(Ie?.size??0);if(Ie)if(G&&G.size===Ie.size&&G.mtimeMs===Ie.mtimeMs)nt=G.hash,Ge=Ie;else{let rt;try{rt=await dt($)}catch(ze){if(!os(ze))throw ze;Hr($,ze);continue}rt&&(nt=rt.hash,Ge=rt)}if(R&&Object.hasOwn(R,$)){let rt=R[$];!G&&nt!==null&&rt.hash===nt&&(G=h.files[$]={seq:rt.seq,hash:nt,size:Ge.size,mtimeMs:Ge.mtimeMs}),(G||!he)&&delete R[$]}O.push({sp:$,d:vi(nt,G,he?{seq:he.seq,hash:he.hash}:null),rSeq:he?.seq??null,rHash:he?.hash??null,rUpdatedAt:he?.updatedAt??null,localHash:nt,localStat:Ge})}if(Et()||d!==ke)return;let B=O.filter($=>$.d.kind==="deleteLocal"||$.d.kind==="pushDelete").length,K=!me&&(ge||fr(B,W,Cc));K&&B&&ut(),Q.clear();for(let{sp:$,d:G,rSeq:he,rHash:Ie,rUpdatedAt:nt,localHash:Ge,localStat:rt}of O){if(Et()||d!==ke)return;if(G.kind!=="hold"&&Mt($)&&Se($),K&&(G.kind==="deleteLocal"||G.kind==="pushDelete")){Q.set($,G.kind==="deleteLocal"?"local":"remote");continue}try{if((G.kind==="deleteLocal"||G.kind==="pushDelete")&&((await dt($))?.hash??null)!==Ge){X({key:$,run:()=>xe($)});continue}if(Et()||d!==ke)return;switch(G.kind){case"adopt":{let ze=qe(De($))?await dt($):null;await Qe($,he,Ge,rt,ze&&ze.hash===Ge?ze.buf:void 0);break}case"pull":await Xe($,he);break;case"push":qe(De($))?await Gr($,G.baseSeq):await Vr($,G.baseSeq);break;case"pushCreate":qe(De($))?await Gr($,0):await Vr($,0);break;case"pushDelete":await Ma($);break;case"deleteLocal":await Ra($),ft($);break;case"conflict":await Xe($,he);break;case"hold":pt($,{hash:Ge,size:rt.size,mtimeMs:rt.mtimeMs},{seq:he,hash:Ie,updatedAt:nt});break;case"dropShadow":ft($);break;case"none":break}}catch(ze){if(!f||Kn(ze)||Ur(ze)&&!os(ze))throw ze;Hr($,ze)}}me&&(me=!1,Pe.length=0),Q.size||U(),M(),K&&Z();for(let $ of w.folders)if(!(i($)===null||!s($,"folder")))try{await o.mkdir($e($),{recursive:!0})}catch{}h.cursor=w.seq,h.lastSyncAt=Date.now(),R&&!Object.keys(R).length&&delete h.mirrorRestore,J.save(h)},ff=async()=>{if(!v||!h)return;let d=h.cursor,w=await v.changes(h.vaultId,d);if(w.changes.length===0&&w.seq>d||w.changes.length>0&&w.changes[0].seq!==d+1){await sn();return}for(let k of w.changes)await Oa(k)},Qn=null,$a=[],gs=()=>{Qn&&$a.push(Qn.close()),Qn=null},pf=()=>{if(!f||Qn||!H)return;let d=Ee();if(!d.watch)return;let w=S=>{if(!H)return;let k=l.relative(H,S);if(!k||k.startsWith(".."))return;let R=r(k);R&&nn(R)};Qn=d.watch(H,{depth:12,ignored:S=>{let k=l.basename(S);return pr(k)||!!n.ignoreNames?.includes(k)}},{change:w,add:w,unlink:()=>Qr(),unlinkDir:()=>Qr()})},er=()=>{I?.stop(),I=null},hf=()=>{if(!f||!v||!h||I)return;let d=E;d&&(I=yc({baseUrl:d.cloudUrl,vaultId:h.vaultId,token:d.token,getToken:V,gate:D??void 0},{getSince:()=>h?.cursor??0,onHello:w=>{h&&w>h.cursor&&X({run:ff})},onChange:w=>{X({run:()=>Oa(w)})},onReset:()=>{X({run:sn})},onOpen:()=>{(b==="offline"||b==="starting")&&ie("idle",null),X({run:hs})},onDown:(w,S)=>{let k=no(uc(w));b==="idle"||b==="syncing"?(ie("offline",void 0,S?null:k),oe=!!S):b==="offline"&&oe&&!S&&(oe=!1,He.error(k))},onPresence:w=>t.onPresence?.(h?.vaultId??"",w),onPresenceRoster:w=>t.onPresenceRoster?.(h?.vaultId??"",w)}))},gf=async()=>{let d=await ot(a);if(d.cloudSync?.deviceId)return d.cloudSync.deviceId;let w=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Pt({cloudSync:{...d.cloudSync??{},deviceId:w}},a),w},mf=async d=>{er(),gs(),T=null,A.length=0,j.clear(),Q.clear(),me=!1,ge=!1,Pe.length=0;let w=await ot(a);if(d!==p)return;let S=w.cloudSync;if(S?.enabled===!1){H=null,v=null,ie("disabled",null);return}if(!a||a!==Be()){ie("auth-required","not-logged-in");return}if(H=n.localRoot,n.requireRootExists){let W=await o.stat(H).then(O=>O.isDirectory()).catch(()=>!1);if(d!==p)return;if(!W){ie("error",`vault-missing: ${H}`),Xn();return}}if(d!==p)return;let k=t.loadCreds();if(!k.cloudUrl||!k.token){v=null,ie("auth-required","not-logged-in");return}ie("starting",null);let R=S?.deviceId??await gf();if(d!==p)return;let P=n.clientIdSuffix?`${R}#${n.clientIdSuffix}`:R;E={cloudUrl:k.cloudUrl,token:k.token},D=Jt(k.cloudUrl),x=new AbortController,L?.(),L=D.subscribe(Z),v=mc({baseUrl:k.cloudUrl,token:k.token,clientId:P,gate:D,signal:x.signal,getToken:()=>{if(d!==p)throw new ye(401,{code:"ACCOUNT_CHANGED"},"sync-session");return V()}});try{let W=n.vaultId==="first"?S?.vaultId:n.vaultId;if(!W){let $=await v.listVaults();if(d!==p)return;if(!$.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");W=$[0].id,await Pt({cloudSync:{...S??{},vaultId:W}},a)}if(d!==p)return;let O=await so(n.shadowName);if(d!==p||(h=O&&O.vaultRoot===H&&O.vaultId===W&&O.folder===""?O:{vaultRoot:H,folder:"",vaultId:W,cursor:0,lastSyncAt:null,files:{}},d!==p))return;for(let[$,G]of Object.entries(h.pending??{}))Q.set($,G);Q.size&&(ge=!0);let B=await Yr(H);if(d!==p)return;let K=()=>Et()||!!Object.keys(h?.pending??{}).length;if(!B&&!n.requireRootExists){if(h.rootIdentity||Object.keys(h.files).length||h.mirrorMissing||K()){let $=await fs(H);if(d!==p)return;if(!$||K()){Gt("vault-missing");return}if(h.mirrorMissing=!0,J.save(h),await J.flush(!0),d!==p)return;let G=await fs(H);if(d!==p)return;if(!G||K()){Gt("vault-missing");return}}if(await o.mkdir(H,{recursive:!0}),B=await Yr(H),d!==p)return}if(!B?.isDirectory()){ps(B);return}if(typeof B.dev=="number"&&Number.isInteger(B.dev)&&B.dev>=0&&typeof B.ino=="number"&&Number.isInteger(B.ino)&&B.ino>0){let $=c?await c(H):{dev:B.dev,ino:B.ino,...B.birthtimeMs&&B.birthtimeMs>0?{birthtimeMs:B.birthtimeMs}:{}};if(d!==p)return;if(!Vt($))throw Error("Invalid sync root identity; original state retained");let G=h.rootIdentity,he=G&&!an(G,$);if(!bt($,B)){Gt("vault-changed");return}let Ie=!G&&!e&&Le().isManagedCloudVault(H)&&(Object.keys(h.files).length>0||K());if(he||h.mirrorMissing||Ie){let Ge=(!G||(G.volumeId?G.volumeId===$.volumeId:G.dev===$.dev))&&await fs(H),rt=Ge&&(await o.readdir(H,{withFileTypes:!0})).every(Ua=>Ua.isDirectory()&&n.excludePrefixes?.includes(Ua.name+"/")),ze=rt&&await Yr(H);if(d!==p)return;if(rt){if(!ze||!bt($,ze)||K()){Gt("vault-changed");return}h.files={},h.cursor=0,h.lastSyncAt=null,h.mirrorRestore="list"}else if(he||h.mirrorMissing&&!G){Gt("vault-changed");return}else if(Ie){if(!Ge||K()){Gt("vault-changed");return}h.mirrorRestore="list"}}if(T=$,(h.mirrorMissing||JSON.stringify(G)!==JSON.stringify($))&&(delete h.mirrorMissing,h.rootIdentity=$,J.save(h),await J.flush(!0)),d!==p||!await et())return}else{if(h.mirrorMissing){Gt("vault-changed");return}if(!ps(B))return}if(d!==p)return;g=!0,pf();for(let $ of h.moves??[])X({key:`move:${tt($)}`,run:()=>Xr($)});X({run:sn}),X({run:async()=>{hf()}})}catch(W){if(d!==p)return;Kn(W)?ie("auth-required","login-expired"):(ie("offline",W?.message||String(W)),Xn())}},ja=()=>{f=!1,g=!1,er(),gs(),A.length=0,j.clear(),Jn();for(let d of[z,q,ne,re])d&&clearTimeout(d);z=q=ne=re=null,Me?.abort.abort(),Me=null,x?.abort(new DOMException("sync engine stopped","AbortError")),L?.(),L=null},La=async()=>{F&&await new Promise(d=>y.add(d)),await Promise.all($a.splice(0)),await J.flush(),h=null,T=null,v=null,E=null,D=null,x=null,H=null,N=0,Y.clear(),we.clear(),rn=0,ee=null,Q.clear(),me=!1,ge=!1,Pe.length=0,b="disabled",_=null},yf=()=>{Fa()},Zr=null,tr=()=>{ae=!1,Zr?.(),Zr=Le().onBeforeQuit(yf);let d=++p;ja();let w=m.catch(()=>{}).then(async()=>{await La(),d===p&&(f=!0,await mf(d))});return m=w,w},Fa=()=>{Zr?.(),Zr=null,++p,ja();let d=m.catch(()=>{}).then(La);return m=d,d},_t=()=>{let d=Object.entries(h?.held??{}).map(([w,S])=>({...S,path:w,local:i(w)??w}));return{enabled:b!=="disabled",state:b==="idle"&&(ve.size||we.size)?"syncing":b,lastSyncAt:h?.lastSyncAt??null,pending:A.length+ve.size+we.size,conflicts:N,skipped:[...[...Y].map(([w,S])=>({path:w,reason:S})),...d.map(w=>({path:w.path,reason:"HELD"}))],error:_,pendingDeletions:Q.size,maxFileBytes:ee,held:d,heldCount:d.length,rateLimitedUntil:b!=="disabled"?D?.until()??null:null}};return{getStatus:_t,start(){tr()},notifyLocal(d,w,S){if(!h||b==="disabled"||b==="auth-required")return;let k=r(d),R=S?r(S):null;if(w==="write"&&k){pr(k.split("/").pop()||"")||nn(k);return}if(w==="remove"){if(!k)return;let P=`${k}/`,W=!1;for(let O of Object.keys(h.files))(O===k||O.startsWith(P))&&(W=!0,X({key:O,run:()=>xe(O)}));!W&&k&&X({key:k,run:()=>xe(k)})}},holdLocalMove(d,w){let S=R=>n.serverDir?`${n.serverDir}/${R.replace(/\\/g,"/").normalize("NFC")}`:R.replace(/\\/g,"/").normalize("NFC"),k={from:S(d),to:S(w)};return++ke,Jr.add(k),()=>{Jr.delete(k)}},async notifyLocalMove(d,w,S,k){let R=r(d),P=r(w),W=h??await so(n.shadowName),O=ro(d,""),B=O&&(n.serverDir?`${n.serverDir}/${O}`:O);if(!R&&P&&B&&W&&Object.keys(W.files).some(K=>K===B||K.startsWith(`${B}/`))&&(R=B),!R&&!P){S?.();return}if(R&&P){let K=h??W;if(!K){S?.();return}let $=k??(Object.keys(K.files).some(he=>he.startsWith(`${R}/`))?"folder":"file"),G={from:R,to:P,kind:$};K.moves??=[],K.moves.some(he=>tt(he)===tt(G))||(K.moves.push(G),++ke),S&&Kr.set(tt(G),S),J.save(K);try{await J.flush(!0)}catch(he){throw K.moves=K.moves.filter(Ie=>tt(Ie)!==tt(G)),Kr.delete(tt(G)),J.save(K),he}h===K&&f&&b!=="disabled"&&b!=="auth-required"&&X({key:`move:${tt(G)}`,run:()=>Xr(G)});return}R&&this.notifyLocal(d,"remove"),P&&(X({key:P,run:()=>xe(P)}),Qr()),S?.()},async setEnabled(d){let w=await ot(a);return await Pt({cloudSync:{...w.cloudSync??{},enabled:d}},a),await tr(),_t()},async restart(){return await tr(),_t()},async syncNow(){if(Y.clear(),!g){let d=p;if(await m,d!==p)return _t()}if(b==="disabled"||b==="auth-required"||b==="error"||b==="offline"||!g||!v)await tr();else{q&&(clearTimeout(q),Br());for(let d of h?.moves??[])X({key:`move:${tt(d)}`,run:()=>Xr(d)});X({run:sn})}return _t()},resolveHeld(d,w){if(!g||!h?.held||!["local","cloud","both","newer"].includes(w))return _t();let S=[...new Set(d)].filter(k=>typeof k=="string"&&!!Mt(k));return S.length&&X({run:()=>lf(S,w)}),_t()},rescope(){f&&X({key:"\0rescope",run:async()=>xa()})},confirmMassDeletions(){return!g||!Q.size||(me=!0,X({run:sn})),_t()},stop:Fa};function Qr(){f&&(ne&&clearTimeout(ne),ne=setTimeout(()=>{ne=null,X({run:hs})},Kh))}}function ao(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function lo(t){return/\.md$/i.test(t)?ao(t):{root:t,fdPrefix:"\0",assetPrefix:"\0"}}function Ac(t,e,n){return!!(e===t.root||e.startsWith(t.fdPrefix)||`${e}/`===t.fdPrefix||n==="binary"&&e.startsWith(t.assetPrefix)||n==="folder"&&(`${e}/`===t.assetPrefix||e.startsWith(t.assetPrefix)))}var ig=t=>Ee().sha256Hex(t).slice(0,8),sg=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Ai="\u4E0E\u6211\u5171\u4EAB";function xc(t,e){let n=ig(`${t.vaultId}:${t.path}`),r=t.path.includes("/")?t.path.slice(0,t.path.lastIndexOf("/")):"";return{key:n,vaultId:t.vaultId,rootPath:t.path,title:t.title,localRelDir:`${Ai}/${sg(t.title)}-${n}`,serverDir:r,inScope:(i,s)=>e.some(a=>Ac(a,i,s)),scopeKey:e.map(i=>i.root).join("\0")}}function Tc(t){return xc(t,[ao(t.path),...(t.items??[]).map(lo)])}function Ic(t){let e=t.map(Tc),n=t.flatMap((i,s)=>{let a=e[s].serverDir?`${e[s].serverDir}/`:"";return(i.items??[]).filter(o=>!o.startsWith(a)).map(o=>xc({vaultId:i.vaultId,path:o,title:(o.split("/").pop()??o).replace(/\.md$/i,"")},[lo(o)]))}),r=new Map;for(let i of[...e,...n])r.has(i.key)||r.set(i.key,i);return[...r.values()]}var og=t=>{let e=[];for(let n of t.split("/"))!n||n==="."||(n===".."&&e.length&&e[e.length-1]!==".."?e.pop():e.push(n));return e.join("/")};function Rc(t,e){let n=l=>l.normalize("NFC"),r=n(e.replace(/\\/g,"/")),i=t.find(l=>r.startsWith(`${n(l.localRelDir)}/`));if(!i)return null;let s=r.slice(n(i.localRelDir).length+1),a=og(i.serverDir?`${i.serverDir}/${s}`:s);if(!a||a===".."||a.startsWith("../"))return null;let o=[i,...t].find(l=>l.vaultId===i.vaultId&&(!l.serverDir||a.startsWith(`${l.serverDir}/`))&&l.inScope(a,De(a)));return o?`${o.localRelDir}/${o.serverDir?a.slice(o.serverDir.length+1):a}`:null}function co(){let t=Le().readCreds(),e=Ve(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let f=Le().readCreds();if(n.signal.aborted||!e||Ve(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},i=()=>{let f=r();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},s=async(f,g,p)=>{let m=r();if(!m.cloudUrl||!m.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let y=await fetch(`${m.cloudUrl.replace(/\/+$/,"")}/api/amadeus${g}`,{method:f,headers:{Authorization:`Bearer ${m.token}`,...p!==void 0?{"Content-Type":"application/json"}:{}},body:p!==void 0?JSON.stringify(p):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!y.ok){let _=null;try{_=await y.json()}catch{}throw Object.assign(new Error(_?.detail||`http ${y.status}`),{status:y.status,code:_?.code})}let b=await y.json();return r(),b},a=null,o=async()=>(r(),a||(a=(await s("GET","/vaults")).vaults[0]?.id??"default",a)),l=()=>{try{let f=(r().token??"").split(".")[1],g=JSON.parse(Ct(ti(f)));return typeof g.userId=="string"?g.userId:null}catch{return null}},c=async()=>(await s("GET","/shared-with-me")).items.map(g=>{let p=Tc(g),m=g.path.split("/").pop()??g.path;return{...g,localPath:`${p.localRelDir}/${m}`}}),u=null;return{stop:()=>n.abort(),call:s,ensureOwnVault:o,myUserId:l,sharedWithMe:c,linkBase:async()=>{if(r(),u)return u;try{u=((await s("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||i()}catch{u=i()}return u},async heartbeat(f,g){let p=(f??"").replace(/\\/g,"/"),m,y=null,b=g.find(_=>p.startsWith(`${_.localRelDir}/`));b?(m=b.vaultId,y=b.serverDir?`${b.serverDir}/${p.slice(b.localRelDir.length+1)}`:p.slice(b.localRelDir.length+1)):(m=await o(),y=p||null),await s("POST",`/vaults/${encodeURIComponent(m)}/presence`,{page:y})}}}import{promises as Mc}from"node:fs";import ag from"node:path";var uo=".forsion-vault.md",Dc=t=>`${t}/${uo}`;function xi(t){let e=/^devices:\s*(\[.*\])\s*$/m.exec(t??"");if(!e)return null;try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(r=>!!r&&typeof r.id=="string"&&typeof r.name=="string").map(r=>({id:r.id,name:r.name,...typeof r.since=="string"?{since:r.since}:{}})):null}catch{return null}}var Oc=t=>`---
|
|
216
216
|
devices: ${JSON.stringify(t.map(e=>({id:e.id,name:e.name,...e.since?{since:e.since}:{}})))}
|
|
217
217
|
---
|
|
218
|
-
`;var tt=t=>t.replace(/\\/g,"/").normalize("NFC");function ji(t){let e=tt(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=tt(n);if(!r)return!1;if(t.some(o=>tt(o.path)===r))return!0;for(let o of e??[]){let i=tt(o);if(!i)continue;let s=`${i.replace(/\.md$/i,"")}.fd`;if(r===i||r.startsWith(`${i}/`)||r===s||r.startsWith(`${s}/`))return!1}return t.some(o=>{let i=ji(o);return!!i&&r.startsWith(i)})}function Fi(t,e,n){let r=tt(t),o=tt(e);return r===o?tt(n):r.startsWith(`${o}/`)?tt(n)+r.slice(o.length):null}function Qn(t,e,n){let r=!1,o=t.map(i=>{let s=Fi(i,e,n);return s===null?i:(r=!0,s)});return{changed:r,next:o}}async function Yc(t){let e=await Vc.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let o of e){if(!o.isDirectory()||o.name.startsWith("."))continue;let i=await Vc.readFile(rh.join(t,o.name,Ni),"utf8").catch(()=>null);if(i===null)continue;n.push(o.name);let s=oo(i);s?.length&&(r[o.name]=s)}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 io=t=>Ee().sha256Hex(t).slice(0,8);function Gc(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Ft(t,e=[]){let n=[],r=[];for(let o of t){let i=tt(o.path);if(!i)continue;r.push(i);let s=ji(o);s&&n.push(s)}return{entries:t,exclude:e,prefixes:n,paths:r}}function Jc(t,e){let n=Gc(tt(e));if(!n)return!1;if(fn(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 er(t,e,n){let r=!1,o=t.map(i=>{let s=Fi(i.path,e,n);return s===null?i:(r=!0,{...i,path:s})});return{changed:r,next:o}}function Kc(t,e,n,r){if(e==="delete"||e==="delete-folder"){let o=tt(n),i=t.filter(s=>{let a=tt(s.path);return!(a===o||e==="delete-folder"&&a.startsWith(`${o}/`))});return{changed:i.length!==t.length,next:i}}return r?er(t,n,r):{changed:!1,next:t}}function Li(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===ro?`\u300C${ro}\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 oh,promises as Xc}from"node:fs";async function Zc(t,e){try{await Xc.copyFile(Xt(t),Xt(e),oh.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await Xc.unlink(Xt(t)).catch(()=>{}),!0}var ih=/^\d{4}-\d{2}-\d{2}$/,Qc=["vault","content"],el=new Set(xc),sh=40,pn=t=>new Date(t).toISOString().slice(0,10),hn=t=>typeof t=="string"&&ih.test(t),tl=!1,it=Object.create(null),gn=!1,Ui=()=>Date.now(),tr=new Set,so="";function ut(t,e,n=1,r){try{if(!tl||!el.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let o=pn(Ui());if(r!==void 0){o!==so&&(tr.clear(),so=o);let a=`${t}\0${e}\0${r}`;if(tr.has(a))return;tr.add(a)}let i=it[o]??={},s=i[t]??={};s[e]=(s[e]??0)+Math.round(n),gn=!0}catch{}}function Hi(t){tl=t}function nl(t){if(it=Object.create(null),tr.clear(),so="",gn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!hn(e)||!n||typeof n!="object"))for(let r of Qc){let o=n[r];if(!o||typeof o!="object")continue;let i={};for(let[s,a]of Object.entries(o))el.has(s)&&typeof a=="number"&&Number.isFinite(a)&&a>0&&(i[s]=Math.round(a));Object.keys(i).length&&((it[e]??={})[r]=i)}}}function rl(){let t=pn(Ui()-sh*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 ol=()=>gn,il=()=>{gn=!1};function sl(t,e){let n=[];for(let r of Object.keys(it).sort())if(!(r<=t||r>e))for(let o of Qc){let i=it[r][o];i&&Object.keys(i).length&&n.push({day:r,system:o,counts:{...i}})}return n}function zi(t){for(let e of Object.keys(it))e<=t&&(delete it[e],gn=!0)}function al(){Object.keys(it).length&&(gn=!0),it=Object.create(null),tr.clear(),so=""}function cl(t){Ui=t}var ll=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],Bi=t=>ll.every(e=>typeof t[e]=="function"),lh=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function qi(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Re.get,()=>e?e.get():lh()),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,i)=>n().entryMark(o,i)),t.handle(Re.entryClosure,(r,o,i)=>n().entryClosure(o,i)),t.handle(Re.collabCall,(r,o,i)=>n().collabCall(o,i)),t.handle(Re.switchSide,(r,o)=>n().switchSide(r.sender.id,o)),t.setAmadeusSyncFactory(r=>{Sc(r),kc(uh(t));let o=ul(r);return e=o.handlers,o.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function uh(t){let e=t.contentSync?.merge;return e?(n,r,o,i)=>{if(!/\.db$/i.test(n)||/^(agents|human)(\/|$)/.test(n))return null;let s;try{s=e(n,r,o,i)}catch{return null}return s&&!s.conflict&&!dh(o,r,s.content)?null:s}:null}function dh(t,e,n){let r,o,i;try{[r,o,i]=[JSON.parse(t),JSON.parse(e),JSON.parse(n)]}catch{return!1}let s=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(o)){let u=s(o[l]),f=s(r?.[l]);if(!u||!f||c(a(f,u),a(u,f)))continue;let h=s(i?.[l]);if(!h||!c(a(u,h),a(h,u)))return!1}return!0}function ul(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,o=!1,i=$i(),s=new Map,a=()=>{let I=Date.now();for(let[F,v]of s)I-v.at>7e4&&s.delete(F);e(Re.presence,[...s.values()])},l={loadCreds:()=>t.readCreds(),onHealth:(I,F,v)=>ut("vault",I,F,v),onStatus:I=>e(Re.status,{...I,pendingDeletions:Se(),side:y()?"cloud":"local"}),onPresence:(I,F)=>{let v=F;v?.userId&&(s.set(v.userId,{userId:v.userId,username:String(v.username??"user"),page:v.page??null,at:Number(v.at)||Date.now()}),a())},onPresenceRoster:(I,F)=>{if(Array.isArray(F)){for(let v of F){let C=v;C?.userId&&s.set(C.userId,{userId:C.userId,username:String(C.username??"user"),page:C.page??null,at:Number(C.at)||Date.now()})}a()}}},u=()=>{let I=r;return{...l,onStatus:F=>{I===r&&l.onStatus(F)},onPresence:(F,v)=>{I===r&&l.onPresence(F,v)},onPresenceRoster:(F,v)=>{I===r&&l.onPresenceRoster(F,v)}}},f=Zn(u()),h=new Map,p=[],m=0,w=async()=>{if(!o||!Pe())return;let I=r,F=++m,v=i,C;try{C=await v.sharedWithMe()}catch{return}if(I!==r||!o||F!==m)return;let D=zc(C);p=D;let N=new Map(D.map(O=>[O.key,O.scopeKey]));for(let[O,L]of h)if(N.get(O)!==L.plan.scopeKey){if(await L.engine.stop(),I!==r)return;h.delete(O)}for(let O of D){if(h.has(O.key))continue;let L=Zn(u(),{localRoot:Zt.join(At(),...O.localRelDir.split("/")),shadowName:`amadeus-sync-${Yn()}-share-${O.key}`,vaultId:O.vaultId,serverDir:O.serverDir,inScope:O.inScope});h.set(O.key,{engine:L,plan:O}),L.start()}},y=()=>n()===At(),S=(I,F=I.base)=>{I.base=F;let v=[F,...I.pendingMoves];I.scope.current=Ft(v.flatMap(C=>C.entries),v.flatMap(C=>C.exclude))},g=new Map,j=new Set,x=new Set,M=null,E=()=>M??=new Promise(I=>{let F=()=>ch.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return I(F());ah("scutil",["--get","ComputerName"],{timeout:1500},(v,C)=>I(!v&&String(C).trim()||F()))}),T=async()=>{let I=(await et()).cloudSync?.deviceId;return I?{id:I,name:await E()}:null},_=new Map,P=(I,F,v)=>{let C=r,D=(_.get(I)??Promise.resolve()).catch(()=>{}).then(async()=>{C!==r||v&&!await v()||C!==r||await q(I,F,C)});return _.set(I,D),D.finally(()=>{_.get(I)===D&&_.delete(I)}).catch(()=>{}),D},q=async(I,F,v)=>{let C=i,D=encodeURIComponent(await C.ensureOwnVault()),N=qc(I);for(let O=0;O<3;O++){let L=null;try{L=await C.call("GET",`/vaults/${D}/file?path=${encodeURIComponent(N)}`)}catch(Z){if(Z?.status!==404)throw Z}let K=F(!!L,L?oo(L.content):null);if(K===void 0||v!==r)return;try{if(K===null){L&&await C.call("DELETE",`/vaults/${D}/file?path=${encodeURIComponent(N)}&baseSeq=${L.seq}`);return}await C.call("PUT",`/vaults/${D}/file`,{path:N,content:Wc(K),baseSeq:L?.seq??0});return}catch(Z){if(Z?.status!==409)throw Z}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},J=async I=>!!(await et()).entrySync?.some(F=>F.cloudName===I&&F.entries.length>0),R=(I,F)=>P(I,(v,C)=>{let D=C?.find(O=>O.id===F.id);if(D&&D.name===F.name)return;let N=D?.since??new Date().toISOString().slice(0,10);return[...(C??[]).filter(O=>O.id!==F.id),{...F,since:N}]},()=>J(I)),Y=(I,F)=>P(I,(v,C)=>{if(!v||!C?.some(N=>N.id===F))return;let D=C.filter(N=>N.id!==F);return D.length?D:null},async()=>!await J(I)),re=()=>{e(Re.entryChange)},X=async(I,F)=>{let v=g.get(I);if(!v)return;let C=O=>O&&O.startsWith(`${v.cloudName}/`)?O.slice(v.cloudName.length+1):null,D=C(F.path);if(!D)return;let N=!1;await dn(O=>{if(g.get(I)!==v)return!1;let L=(O.entrySync??[]).find(ie=>ie.vaultRoot===I);if(!L)return!1;let K=F.op,Z=C(F.newPath),Q=Kc(L.entries,K,D,Z),V=Z?Qn(L.exclude??[],D,Z):{changed:!1,next:L.exclude??[]};if(!Q.changed&&!V.changed)return!1;N=!0,L.entries=Q.next,V.changed&&(L.exclude=V.next),S(v,Ft(L.entries,L.exclude??[]))}),N&&g.get(I)===v&&re()},se=I=>{let F=r;return{...u(),onStatus:v=>{F===r&&e(Re.status,{...v,pendingDeletions:Se(),side:"local",binding:I})},onRemoteApplied:async v=>{F===r&&await X(I,v)}}},ee=async()=>{let I=Pe();if(!o||!I)return;let F=r,v=i,C=Yn(I);await t.adoptLegacyCloudState(I,Zc);let D=await et(I),N=D.entrySync??[];if(F!==r||!o||I!==Pe())return;let O=new Map(N.map(L=>[L.vaultRoot,L]));for(let[L,K]of g){let Z=O.get(L);if(!(Z&&Z.cloudName===K.cloudName)&&(await K.engine.stop(),F!==r||(g.delete(L),Z&&await Nc(`amadeus-sync-${C}-entry-${io(L)}`),F!==r)))return}for(let L of N){let K=g.get(L.vaultRoot);if(K){S(K,Ft(L.entries,L.exclude??[]));continue}let Z={current:Ft(L.entries,L.exclude??[])},Q=L.cloudName,V=Zn(se(L.vaultRoot),{accountId:I,localRoot:L.vaultRoot,shadowName:`amadeus-sync-${C}-entry-${io(L.vaultRoot)}`,vaultId:"first",serverDir:Q,clientIdSuffix:`entry-${io(L.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:ie=>ie===Q?!0:ie.startsWith(`${Q}/`)?Jc(Z.current,ie.slice(Q.length+1)):!1});g.set(L.vaultRoot,{engine:V,scope:Z,cloudName:Q,base:Z.current,pendingMoves:new Set}),V.start()}if(D.cloudSync?.enabled!==!1)for(let L of N){let K=L.entries.length>0,Z=K?j:x;Z.has(L.cloudName)||((K?x:j).delete(L.cloudName),(async()=>{try{let Q=await T();if(!Q||F!==r||(await(K?R(L.cloudName,Q):Y(L.cloudName,Q.id)),F!==r))return;Z.add(L.cloudName),(K?x:j).delete(L.cloudName)}catch{}})())}},oe=async(I,F,v,C,D)=>{let N=F.replace(/\\/g,"/").normalize("NFC"),O=v.replace(/\\/g,"/").normalize("NFC"),L=!1,K,Z,Q,V=D??"file";try{await dn(async ie=>{if(g.get(I)!==C)return!1;let pe=(ie.entrySync??[]).find(We=>We.vaultRoot===I);if(!pe)return!1;let fe=er(pe.entries,N,O),le=Qn(pe.exclude??[],N,O),Ae=fn(pe.entries,pe.exclude,N);!D&&await mn.stat(Zt.join(I,...O.split("/"))).then(We=>We.isDirectory(),()=>!1)&&(V="folder");let Yt=V==="folder"?"folder":/\.md$/i.test(O)?"page":"asset";Ae&&!fn(fe.next,le.next,O)&&(fe.next.push({path:O,kind:Yt}),fe.changed=!0),L=fe.changed||le.changed;let On=pe.entries.filter(We=>er([We],N,O).changed);return Ae&&!On.some(We=>We.path===N)&&On.push({path:N,kind:Yt}),K=Ft(On,(pe.exclude??[]).filter(We=>Qn([We],N,O).changed)),Z=C.base,C.pendingMoves.add(K),pe.entries=fe.next,pe.exclude=le.next,Q=Ft(pe.entries,pe.exclude),S(C,Q),L})}catch(ie){throw K&&C.pendingMoves.delete(K),S(C,C.base===Q&&Z?Z:C.base),ie}try{K&&await C.engine.notifyLocalMove(N,O,()=>{C.pendingMoves.delete(K),S(C)},V)}catch(ie){throw K&&C.pendingMoves.delete(K),await dn(pe=>{let fe=pe.entrySync?.find(le=>le.vaultRoot===I);if(!fe)return!1;fe.entries=er(fe.entries,O,N).next,fe.exclude=Qn(fe.exclude??[],O,N).next,S(C,Ft(fe.entries,fe.exclude))}),ie}L&&g.get(I)===C&&re()},te=I=>{let F=I.replace(/\\/g,"/");for(let{engine:v,plan:C}of h.values())if(F.startsWith(`${C.localRelDir}/`))return{engine:v,rel:F.slice(C.localRelDir.length+1)};return{engine:f,rel:F}};t.setMutationHooks((I,F)=>{if(y()){let v=te(I);v.engine.notifyLocal(v.rel,F);return}g.get(n()??"")?.engine.notifyLocal(I,F)},(I,F,v)=>{if(y()){let N=te(I),O=te(F);if(N.engine===O.engine)return N.engine.notifyLocalMove(N.rel,O.rel,void 0,v);N.engine.notifyLocal(N.rel,"remove"),O.engine.notifyLocal(O.rel,"write");return}let C=n()??"",D=g.get(C);if(D)return oe(C,I,F,D,v)},(I,F)=>{if(y()){let v=te(I),C=te(F),D=[v.engine.holdLocalMove(v.rel,C.rel)];return v.engine!==C.engine&&D.push(C.engine.holdLocalMove(v.rel,C.rel)),()=>{for(let N of D)N()}}return g.get(n()??"")?.engine.holdLocalMove(I,F)});let Se=()=>{let I=f.getStatus().pendingDeletions;for(let{engine:F}of h.values())I+=F.getStatus().pendingDeletions;for(let{engine:F}of g.values())I+=F.getStatus().pendingDeletions;return I},ve=I=>({...I,pendingDeletions:Se(),side:y()?"cloud":"local"}),Xe=()=>{if(!o)return Promise.resolve(f.getStatus());w();for(let{engine:I}of h.values())I.syncNow();for(let{engine:I}of g.values())I.syncNow();return f.syncNow()},je=async()=>{let I=++r;o=!1,i.stop();let F=[f.stop(),...[...h.values()].map(({engine:C})=>C.stop()),...[...g.values()].map(({engine:C})=>C.stop())];if(h.clear(),g.clear(),p=[],j.clear(),x.clear(),s.clear(),a(),await Promise.all(F),await t.awaitPendingVaultWrites(),I!==r)return;let v=n();if(v&&Xr(v)){let C=await et();if(I!==r)return;let D=C.localVault&&!Xr(C.localVault)?C.localVault:Zt.join(t.workspaceDir(),"Amadeus");if(await mn.mkdir(D,{recursive:!0}),I!==r||(await Ct({lastVault:D,localVault:D,lastPage:void 0}),I!==r))return;await t.activateRoot(D,!1)}I===r&&re()};return{handlers:{get:()=>ve(f.getStatus()),setEnabled:async I=>{if(!o)throw new Error("Cloud account is changing");let F=r;return await f.setEnabled(I),F!==r?f.getStatus():(await Promise.all([...h.values(),...g.values()].map(({engine:v})=>v.restart())),ve(f.getStatus()))},syncNow:()=>Xe(),confirmDeletions:()=>{for(let{engine:I}of h.values())I.confirmMassDeletions();for(let{engine:I}of g.values())I.confirmMassDeletions();return ve(f.confirmMassDeletions())},entryGet:async()=>{let I=await et(),F=At(),v=await Yc(F);return{vaults:I.entrySync??[],activeRoot:n(),cloudRoot:F,mirrorVaults:v.names,mirrorVaultDevices:v.devices,deviceId:I.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let I=n();if(!I)return null;let F=At(),v=await et(),C=I===F?v.localVault&&v.localVault!==F?v.localVault:null:F;if(!C)return null;let D=[],N=500,O=async(L,K)=>{if(D.length>=N)return;let Z;try{Z=await mn.readdir(L,{withFileTypes:!0})}catch{return}for(let Q of Z){if(D.length>=N)break;if(Q.name.startsWith(".")||Q.isSymbolicLink())continue;let V=K?`${K}/${Q.name}`:Q.name;if(Q.isDirectory())await O(Zt.join(L,Q.name),V);else if(Q.isFile()&&/\.db$/i.test(Q.name))try{D.push({rel:V,source:await mn.readFile(Zt.join(L,Q.name),"utf8")})}catch{}}};return await O(C,""),{root:C,vaultName:C===F?"\u4E91\u7AEF":Zt.basename(C),dbs:D}},entryEnable:async I=>{let F=r,v=i;if(!o||!Pe())return{error:"Sign in to enable cloud sync"};let C=n();if(!C||y())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let D=await et(),N=D.entrySync??[],O=N.find(L=>L.vaultRoot===C);if(!O){let L=(I.cloudName??Zt.basename(C)).normalize("NFC").trim(),K=Li(L,N.map(Z=>Z.cloudName));if(K)return{error:K};if(!I.merge)try{let Z=await v.ensureOwnVault(),Q=await v.call("GET",`/vaults/${encodeURIComponent(Z)}/tree`);if((Q.folders??[]).some(ie=>ie===L||ie.startsWith(`${L}/`))||(Q.entries??[]).some(ie=>ie.path===L||ie.path.startsWith(`${L}/`)))return{conflict:L}}catch(Z){return{error:Z?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}O={vaultRoot:C,cloudName:L,entries:[]},N.push(O)}return F!==r||!o?{error:"Cloud account changed; retry from the current account"}:(await dn(L=>{if(F!==r||!o)return!1;let K=L.entrySync??[],Z=K.find(le=>le.vaultRoot===C);if(!Z){let le=Li(O.cloudName,K.map(Ae=>Ae.cloudName));if(le)throw new Error(le);Z={vaultRoot:C,cloudName:O.cloudName,entries:[]},K.push(Z)}let Q=le=>String(le??"").replace(/\\/g,"/").normalize("NFC"),V=new Set;for(let le of I.entries??[]){let Ae=Q(le.path);Ae&&(V.add(Ae),!Z.entries.some(Yt=>Yt.path===Ae)&&Z.entries.push({path:Ae,kind:le.kind==="folder"||le.kind==="asset"?le.kind:"page"}))}let ie=(I.exclude??[]).map(Q).filter(Boolean),pe=new Set([...V,...(I.include??[]).map(Q).filter(Boolean)]);Z.exclude=[...new Set([...(Z.exclude??[]).filter(le=>!pe.has(le)),...ie])];let fe=new Set(ie);Z.entries=Z.entries.filter(le=>!fe.has(le.path)),L.entrySync=K,O=Z},D.cloudAccountId),F!==r?{error:"Cloud account changed; retry from the current account"}:(await ee(),g.get(C)?.engine.syncNow(),re(),{ok:!0,cloudName:O.cloudName}))},entryDisable:async I=>{let F=n(),v=!1,C=r;return await dn(D=>{if(C!==r||!o)return!1;let N=(D.entrySync??[]).find(K=>K.vaultRoot===F);if(!F||!N)return!1;let O=String(I??"").replace(/\\/g,"/").normalize("NFC"),L=N.entries.length;if(N.entries=N.entries.filter(K=>K.path!==O),fn(N.entries,N.exclude,O))N.exclude=[...new Set([...N.exclude??[],O])];else if(N.entries.length===L)return!1;v=!0}),!v||C!==r?{ok:!1}:(await ee(),re(),{ok:!0})},entryMark:async(I,F)=>{let v=String(I??"").normalize("NFC");if(!v||v.includes("/")||v.startsWith("."))return{error:"invalid name"};if(!o||!Pe())return{error:"Sign in first"};try{await P(v,C=>F?C?void 0:[]:C?null:void 0)}catch(C){return{error:C?.message||String(C)}}return f.syncNow(),{ok:!0}},entryClosure:(I,F)=>t.relatedClosure(String(I??""),F==="folder"?"folder":"page"),collabCall:async(I,F)=>{let v=i,C=async()=>v.ensureOwnVault(),D=O=>String((F??[])[O]??""),N=O=>(F??[])[O]??{};switch(I){case"listVaults":return(await v.call("GET","/vaults")).vaults;case"activeVaultId":return C();case"pageShare":return v.call("GET",`/vaults/${encodeURIComponent(await C())}/page-shares?path=${encodeURIComponent(D(0))}`);case"relatedItems":return v.call("GET",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(D(0))}/related`);case"setShareItem":return v.call("POST",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(D(0))}/items`,{path:D(1),included:(F??[])[2]===!0});case"createPageShare":return v.call("POST",`/vaults/${encodeURIComponent(await C())}/page-shares`,{path:D(0),...N(1)});case"updatePageShare":return v.call("PATCH",`/vaults/${encodeURIComponent(D(2)||await C())}/page-shares/${encodeURIComponent(D(0))}`,N(1));case"revokePageShare":return v.call("DELETE",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(D(0))}`);case"setParticipantRole":return v.call("PATCH",`/vaults/${encodeURIComponent(D(3)||await C())}/page-shares/${encodeURIComponent(D(0))}/members/${encodeURIComponent(D(1))}`,{role:D(2)});case"removeParticipant":return v.call("DELETE",`/vaults/${encodeURIComponent(D(2)||await C())}/page-shares/${encodeURIComponent(D(0))}/members/${encodeURIComponent(D(1))}`);case"sharedWithMe":{let O=await v.sharedWithMe();return w(),O}case"leaveShare":{let O=v.myUserId();if(!O)throw new Error("\u672A\u767B\u5F55");let L=await v.call("DELETE",`/vaults/${encodeURIComponent(D(1)||await C())}/page-shares/${encodeURIComponent(D(0))}/members/${encodeURIComponent(O)}`);return w(),L}case"publishes":return v.call("GET",`/vaults/${encodeURIComponent(await C())}/shares`);case"listAllShares":{let O=(await v.call("GET","/vaults")).vaults||[],L=v.myUserId(),K=[],Z=[];for(let Q of O){try{let V=await v.call("GET",`/vaults/${encodeURIComponent(Q.id)}/shares`);for(let ie of V.shares||[])K.push({...ie,vaultId:Q.id,vaultName:Q.name||""})}catch(V){t.log(`[connect] listAllShares publishes vault ${Q.id} failed: ${V?.message}`)}try{let V=await v.call("GET",`/vaults/${encodeURIComponent(Q.id)}/page-shares?expired=1`),ie=V?.shares||V?.pageShares||(Array.isArray(V)?V:[]);for(let pe of ie){let fe=pe.created_by??pe.createdBy;(!L||!fe||fe===L)&&Z.push({...pe,vaultId:Q.id,vaultName:Q.name||""})}}catch(V){t.log(`[connect] listAllShares pageShares vault ${Q.id} failed: ${V?.message}`)}}return{publishes:K,pageShares:Z,linkBase:await v.linkBase()}}case"createPublish":{let O=await v.call("POST",`/vaults/${encodeURIComponent(await C())}/shares`,{mode:D(0),path:D(1)});return{...O,url:`${await v.linkBase()}/share/${O.token}`}}case"revokePublish":return v.call("DELETE",`/vaults/${encodeURIComponent(await C())}/shares/${encodeURIComponent(D(0))}`);case"revokePublishIn":return v.call("DELETE",`/vaults/${encodeURIComponent(D(0))}/shares/${encodeURIComponent(D(1))}`);case"revokePageShareIn":return v.call("DELETE",`/vaults/${encodeURIComponent(D(0))}/page-shares/${encodeURIComponent(D(1))}`);case"myUserId":return v.myUserId();case"linkBase":return v.linkBase();case"heartbeat":return v.heartbeat((F??[])[0]??null,p);default:throw new Error(`unknown collab fn: ${I}`)}},switchSide:async(I,F)=>{let v=await et();if(F==="cloud"){if(!o||!Pe())throw new Error("Sign in to open cloud notes");let N=At();await mn.mkdir(N,{recursive:!0}),v.lastVault&&!Xr(v.lastVault)&&await Ct({localVault:v.lastVault}),await Ct({lastVault:N});let O=await t.activateRoot(N,!1);return t.bindRenderer(I,N),{...O,side:"cloud"}}let C=v.localVault&&await mn.stat(v.localVault).then(N=>N.isDirectory()).catch(()=>!1)?v.localVault:null;if(!C){let N=await t.ensureDefaultVault();return t.bindRenderer(I,N.root),{...N,side:"local"}}await Ct({lastVault:C});let D=await t.activateRoot(C,!1);return t.bindRenderer(I,C),{...D,side:"local"}}},instance:{start:()=>{o=!0,f.start(),w(),ee()},stopAllSync:je,restartAllSync:async()=>{let I=je(),F=r;await I,F===r&&(i=$i(),f=Zn(u()),o=!0,await Promise.all([f.restart(),w(),ee()]),F===r&&(re(),e(Re.status,ve(f.getStatus()))))},resolveSharedAsset:I=>Bc(p,I)}}}import{hostname as fh}from"node:os";var ph=256*1024;function dl(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>ph}var Wi=45e3,hh=3e3,gh=16*1024,mh=6e4,ao=t=>`${t.replace(/\/+$/,"")}/api`,nr=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??mh}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:i,token:s}=this.deps.getCreds();if(!s)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let a=this.deps.getPairing();if(!a){if(a=await this.register(i,s,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??Wi,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(`${ao(i)}/units/${a.unitId}/channel`,{headers:{Authorization:`Bearer ${s}`,"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"))>gh,p=setTimeout(()=>r.abort(),h?0:hh),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(i){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(i?.message||i),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??Wi,i=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 s=await this.hubFetch(`${ao(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:fh(),platform:process.platform}),signal:r.signal});if(!s.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${s.status}`);let a=await s.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{i&&clearTimeout(i)}}async consume(e,n){let r=e.getReader(),o=new TextDecoder,i="",s=this.deps.readIdleMs??Wi,a=null,c=()=>{s&&(a&&clearTimeout(a),a=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(s/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(()=>{})},s))};c();try{for(;;){let{done:l,value:u}=await r.read();if(l||n.signal.aborted)return;c(),i=this.parseFrames(i+o.decode(u,{stream:!0}),n)}}finally{a&&clearTimeout(a)}}parseFrames(e,n){let r=e,o;for(;(o=r.indexOf(`
|
|
218
|
+
`;var at=t=>t.replace(/\\/g,"/").normalize("NFC");function fo(t){let e=at(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function xn(t,e,n){let r=at(n);if(!r)return!1;if(t.some(i=>at(i.path)===r))return!0;for(let i of e??[]){let s=at(i);if(!s)continue;let a=`${s.replace(/\.md$/i,"")}.fd`;if(r===s||r.startsWith(`${s}/`)||r===a||r.startsWith(`${a}/`))return!1}return t.some(i=>{let s=fo(i);return!!s&&r.startsWith(s)})}function po(t,e,n){let r=at(t),i=at(e);return r===i?at(n):r.startsWith(`${i}/`)?at(n)+r.slice(i.length):null}function yr(t,e,n){let r=!1,i=t.map(s=>{let a=po(s,e,n);return a===null?s:(r=!0,a)});return{changed:r,next:i}}async function Nc(t){let e=await Mc.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let i of e){if(!i.isDirectory()||i.name.startsWith("."))continue;let s=await Mc.readFile(ag.join(t,i.name,uo),"utf8").catch(()=>null);if(s===null)continue;n.push(i.name);let a=xi(s);a?.length&&(r[i.name]=a)}return{names:n.sort(),devices:r}}var Ne={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",resolveHeld:"amadeus:sync:resolve-held",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryMark:"amadeus:entry-sync:mark",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};var Ti=t=>Ee().sha256Hex(t).slice(0,8);function Pc(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Kt(t,e=[]){let n=[],r=[];for(let i of t){let s=at(i.path);if(!s)continue;r.push(s);let a=fo(i);a&&n.push(a)}return{entries:t,exclude:e,prefixes:n,paths:r}}function $c(t,e){let n=Pc(at(e));if(!n)return!1;if(xn(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let i of t.paths)if(i.startsWith(r))return!0;for(let i of t.prefixes)if(i.startsWith(r))return!0;return!1}function wr(t,e,n){let r=!1,i=t.map(s=>{let a=po(s.path,e,n);return a===null?s:(r=!0,{...s,path:a})});return{changed:r,next:i}}function jc(t,e,n,r){if(e==="delete"||e==="delete-folder"){let i=at(n),s=t.filter(a=>{let o=at(a.path);return!(o===i||e==="delete-folder"&&o.startsWith(`${i}/`))});return{changed:s.length!==t.length,next:s}}return r?wr(t,n,r):{changed:!1,next:t}}function ho(t,e){let n=Yt(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Ai?`\u300C${Ai}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(n)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}import{constants as lg,promises as Lc}from"node:fs";async function Fc(t,e){try{await Lc.copyFile(un(t),un(e),lg.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await Lc.unlink(un(t)).catch(()=>{}),!0}var cg=/^\d{4}-\d{2}-\d{2}$/,Uc=["vault","content"],Hc=new Set(lc),ug=40,Tn=t=>new Date(t).toISOString().slice(0,10),In=t=>typeof t=="string"&&cg.test(t),zc=!1,ht=Object.create(null),Rn=!1,go=()=>Date.now(),br=new Set,Ii="";function lt(t,e,n=1,r){try{if(!zc||!Hc.has(e)||!(typeof n=="number"&&Number.isFinite(n)&&n>0))return;let i=Tn(go());if(r!==void 0){i!==Ii&&(br.clear(),Ii=i);let o=`${t}\0${e}\0${r}`;if(br.has(o))return;br.add(o)}let s=ht[i]??={},a=s[t]??={};a[e]=(a[e]??0)+Math.round(n),Rn=!0}catch{}}function mo(t){zc=t}function Bc(t){if(ht=Object.create(null),br.clear(),Ii="",Rn=!1,!(!t||typeof t!="object"||Array.isArray(t))){for(let[e,n]of Object.entries(t))if(!(!In(e)||!n||typeof n!="object"))for(let r of Uc){let i=n[r];if(!i||typeof i!="object")continue;let s={};for(let[a,o]of Object.entries(i))Hc.has(a)&&typeof o=="number"&&Number.isFinite(o)&&o>0&&(s[a]=Math.round(o));Object.keys(s).length&&((ht[e]??={})[r]=s)}}}function qc(){let t=Tn(go()-ug*864e5),e={};for(let n of Object.keys(ht).sort()){if(n<t){delete ht[n];continue}e[n]=JSON.parse(JSON.stringify(ht[n]))}return e}var Wc=()=>Rn,Gc=()=>{Rn=!1};function Vc(t,e){let n=[];for(let r of Object.keys(ht).sort())if(!(r<=t||r>e))for(let i of Uc){let s=ht[r][i];s&&Object.keys(s).length&&n.push({day:r,system:i,counts:{...s}})}return n}function yo(t){for(let e of Object.keys(ht))e<=t&&(delete ht[e],Rn=!0)}function Yc(){Object.keys(ht).length&&(Rn=!0),ht=Object.create(null),br.clear(),Ii=""}function Jc(t){go=t}var Kc=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],wo=t=>Kc.every(e=>typeof t[e]=="function"),pg=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,held:[],heldCount:0,rateLimitedUntil:null,side:"local"});function bo(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(Ne.get,()=>e?e.get():pg()),t.handle(Ne.setEnabled,(r,i)=>n().setEnabled(i)),t.handle(Ne.syncNow,()=>n().syncNow()),t.handle(Ne.confirmDeletions,()=>n().confirmDeletions()),t.handle(Ne.resolveHeld,(r,i)=>n().resolveHeld(i)),t.handle(Ne.entryGet,()=>n().entryGet()),t.handle(Ne.otherSideDbs,()=>n().otherSideDbs()),t.handle(Ne.entryEnable,(r,i)=>n().entryEnable(i)),t.handle(Ne.entryDisable,(r,i)=>n().entryDisable(i)),t.handle(Ne.entryMark,(r,i,s)=>n().entryMark(i,s)),t.handle(Ne.entryClosure,(r,i,s)=>n().entryClosure(i,s)),t.handle(Ne.collabCall,(r,i,s)=>n().collabCall(i,s)),t.handle(Ne.switchSide,(r,i)=>n().switchSide(r.sender.id,i)),t.setAmadeusSyncFactory(r=>{ec(r),nc(hg(t));let i=Xc(r);return e=i.handlers,i.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function hg(t){let e=t.contentSync?.merge;return e?(n,r,i,s)=>{if(!/\.db$/i.test(n)||/^(agents|human)(\/|$)/.test(n))return null;let a;try{a=e(n,r,i,s)}catch{return null}return a&&!a.conflict&&!So(i,r,a.content)?null:a}:null}function So(t,e,n){let r,i,s;try{[r,i,s]=[JSON.parse(t),JSON.parse(e),JSON.parse(n)]}catch{return!1}let a=c=>Array.isArray(c)&&c.every(u=>u&&typeof u=="object"&&typeof u.id=="string")?c.map(u=>u.id):null,o=(c,u)=>c.filter(f=>u.includes(f)),l=(c,u)=>c.length===u.length&&c.every((f,g)=>f===u[g]);for(let c of Object.keys(i)){let u=a(i[c]),f=a(r?.[c]);if(!u||!f||l(o(f,u),o(u,f)))continue;let g=a(s?.[c]);if(!g||!l(o(u,g),o(g,u)))return!1}return!0}function Xc(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,i=!1,s=co(),a=new Map,o=()=>{let M=Date.now();for(let[U,C]of a)M-C.at>7e4&&a.delete(U);e(Ne.presence,[...a.values()])},c={loadCreds:()=>t.readCreds(),onHealth:(M,U,C)=>lt("vault",M,U,C),onStatus:M=>e(Ne.status,{...M,pendingDeletions:me(),side:b()?"cloud":"local"}),onPresence:(M,U)=>{let C=U;C?.userId&&(a.set(C.userId,{userId:C.userId,username:String(C.username??"user"),page:C.page??null,at:Number(C.at)||Date.now()}),o())},onPresenceRoster:(M,U)=>{if(Array.isArray(U)){for(let C of U){let A=C;A?.userId&&a.set(A.userId,{userId:A.userId,username:String(A.username??"user"),page:A.page??null,at:Number(A.at)||Date.now()})}o()}}},u=()=>{let M=r;return{...c,onStatus:U=>{M===r&&c.onStatus(U)},onPresence:(U,C)=>{M===r&&c.onPresence(U,C)},onPresenceRoster:(U,C)=>{M===r&&c.onPresenceRoster(U,C)}}},f=mr(u()),g=new Map,p=[],m=0,y=async()=>{if(!i||!Be())return;let M=r,U=++m,C=s,A;try{A=await C.sharedWithMe()}catch{return}if(M!==r||!i||U!==m)return;let j=Ic(A);p=j;let F=new Map(j.map(z=>[z.key,z.scopeKey]));for(let[z,q]of g)if(F.get(z)!==q.plan.scopeKey){if(await q.engine.stop(),M!==r)return;g.delete(z)}for(let z of j){if(g.has(z.key))continue;let q=u(),ne=mr({...q,onStatus:re=>q.onStatus({...re,shareKey:z.key})},{localRoot:dn.join($t(),...z.localRelDir.split("/")),shadowName:`amadeus-sync-${_n()}-share-${z.key}`,vaultId:z.vaultId,serverDir:z.serverDir,inScope:z.inScope});g.set(z.key,{engine:ne,plan:z}),ne.start()}},b=()=>n()===$t(),_=(M,U=M.base)=>{M.base=U;let C=[U,...M.pendingMoves];M.scope.current=Kt(C.flatMap(A=>A.entries),C.flatMap(A=>A.exclude)),M.engine.rescope()},h=new Map,T=new Set,v=new Set,I=null,E=()=>I??=new Promise(M=>{let U=()=>fg.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return M(U());dg("scutil",["--get","ComputerName"],{timeout:1500},(C,A)=>M(!C&&String(A).trim()||U()))}),D=async()=>{let M=(await ot()).cloudSync?.deviceId;return M?{id:M,name:await E()}:null},x=new Map,L=(M,U,C)=>{let A=r,j=(x.get(M)??Promise.resolve()).catch(()=>{}).then(async()=>{A!==r||C&&!await C()||A!==r||await V(M,U,A)});return x.set(M,j),j.finally(()=>{x.get(M)===j&&x.delete(M)}).catch(()=>{}),j},V=async(M,U,C)=>{let A=s,j=encodeURIComponent(await A.ensureOwnVault()),F=Dc(M);for(let z=0;z<3;z++){let q=null;try{q=await A.call("GET",`/vaults/${j}/file?path=${encodeURIComponent(F)}`)}catch(re){if(re?.status!==404)throw re}let ne=U(!!q,q?xi(q.content):null);if(ne===void 0||C!==r)return;try{if(ne===null){q&&await A.call("DELETE",`/vaults/${j}/file?path=${encodeURIComponent(F)}&baseSeq=${q.seq}`);return}await A.call("PUT",`/vaults/${j}/file`,{path:F,content:Oc(ne),baseSeq:q?.seq??0});return}catch(re){if(re?.status!==409)throw re}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},H=async M=>!!(await ot()).entrySync?.some(U=>U.cloudName===M&&U.entries.length>0),N=(M,U)=>L(M,(C,A)=>{let j=A?.find(z=>z.id===U.id);if(j&&j.name===U.name)return;let F=j?.since??new Date().toISOString().slice(0,10);return[...(A??[]).filter(z=>z.id!==U.id),{...U,since:F}]},()=>H(M)),Y=(M,U)=>L(M,(C,A)=>{if(!C||!A?.some(F=>F.id===U))return;let j=A.filter(F=>F.id!==U);return j.length?j:null},async()=>!await H(M)),ee=()=>{e(Ne.entryChange)},J=async(M,U)=>{let C=h.get(M);if(!C)return;let A=z=>z&&z.startsWith(`${C.cloudName}/`)?z.slice(C.cloudName.length+1):null,j=A(U.path);if(!j)return;let F=!1;await Cn(z=>{if(h.get(M)!==C)return!1;let q=(z.entrySync??[]).find(oe=>oe.vaultRoot===M);if(!q)return!1;let ne=U.op,re=A(U.newPath),Z=jc(q.entries,ne,j,re),ie=re?yr(q.exclude??[],j,re):{changed:!1,next:q.exclude??[]};if(!Z.changed&&!ie.changed)return!1;F=!0,q.entries=Z.next,ie.changed&&(q.exclude=ie.next),_(C,Kt(q.entries,q.exclude??[]))}),F&&h.get(M)===C&&ee()},se=M=>{let U=r;return{...u(),onStatus:C=>{U===r&&e(Ne.status,{...C,pendingDeletions:me(),side:"local",binding:M})},onRemoteApplied:async C=>{U===r&&await J(M,C)}}},te=async()=>{let M=Be();if(!i||!M)return;let U=r,C=s,A=_n(M);await t.adoptLegacyCloudState(M,Fc);let j=await ot(M),F=j.entrySync??[];if(U!==r||!i||M!==Be())return;let z=new Map(F.map(q=>[q.vaultRoot,q]));for(let[q,ne]of h){let re=z.get(q);if(!(re&&re.cloudName===ne.cloudName)&&(await ne.engine.stop(),U!==r||(h.delete(q),re&&await vc(`amadeus-sync-${A}-entry-${Ti(q)}`),U!==r)))return}for(let q of F){let ne=h.get(q.vaultRoot);if(ne){_(ne,Kt(q.entries,q.exclude??[]));continue}let re={current:Kt(q.entries,q.exclude??[])},Z=q.cloudName,ie=mr(se(q.vaultRoot),{accountId:M,localRoot:q.vaultRoot,shadowName:`amadeus-sync-${A}-entry-${Ti(q.vaultRoot)}`,vaultId:"first",serverDir:Z,clientIdSuffix:`entry-${Ti(q.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:oe=>oe===Z?!0:oe.startsWith(`${Z}/`)?$c(re.current,oe.slice(Z.length+1)):!1});h.set(q.vaultRoot,{engine:ie,scope:re,cloudName:Z,base:re.current,pendingMoves:new Set}),ie.start()}if(j.cloudSync?.enabled!==!1)for(let q of F){let ne=q.entries.length>0,re=ne?T:v;re.has(q.cloudName)||((ne?v:T).delete(q.cloudName),(async()=>{try{let Z=await D();if(!Z||U!==r||(await(ne?N(q.cloudName,Z):Y(q.cloudName,Z.id)),U!==r))return;re.add(q.cloudName),(ne?v:T).delete(q.cloudName)}catch{}})())}},ae=async(M,U,C,A,j)=>{let F=U.replace(/\\/g,"/").normalize("NFC"),z=C.replace(/\\/g,"/").normalize("NFC"),q=!1,ne,re,Z,ie=j??"file";try{await Cn(async oe=>{if(h.get(M)!==A)return!1;let pe=(oe.entrySync??[]).find(yt=>yt.vaultRoot===M);if(!pe)return!1;let le=wr(pe.entries,F,z),X=yr(pe.exclude??[],F,z),ve=xn(pe.entries,pe.exclude,F);!j&&await Dn.stat(dn.join(M,...z.split("/"))).then(yt=>yt.isDirectory(),()=>!1)&&(ie="folder");let nn=ie==="folder"?"folder":/\.md$/i.test(z)?"page":"asset";ve&&!xn(le.next,X.next,z)&&(le.next.push({path:z,kind:nn}),le.changed=!0),q=le.changed||X.changed;let Jn=pe.entries.filter(yt=>wr([yt],F,z).changed);return ve&&!Jn.some(yt=>yt.path===F)&&Jn.push({path:F,kind:nn}),ne=Kt(Jn,(pe.exclude??[]).filter(yt=>yr([yt],F,z).changed)),re=A.base,A.pendingMoves.add(ne),pe.entries=le.next,pe.exclude=X.next,Z=Kt(pe.entries,pe.exclude),_(A,Z),q})}catch(oe){throw ne&&A.pendingMoves.delete(ne),_(A,A.base===Z&&re?re:A.base),oe}try{ne&&await A.engine.notifyLocalMove(F,z,()=>{A.pendingMoves.delete(ne),_(A)},ie)}catch(oe){throw ne&&A.pendingMoves.delete(ne),await Cn(pe=>{let le=pe.entrySync?.find(X=>X.vaultRoot===M);if(!le)return!1;le.entries=wr(le.entries,z,F).next,le.exclude=yr(le.exclude??[],z,F).next,_(A,Kt(le.entries,le.exclude))}),oe}q&&h.get(M)===A&&ee()},Q=M=>{let U=M.replace(/\\/g,"/");for(let{engine:C,plan:A}of g.values())if(U.startsWith(`${A.localRelDir}/`))return{engine:C,rel:U.slice(A.localRelDir.length+1)};return{engine:f,rel:U}};t.setMutationHooks((M,U)=>{if(b()){let C=Q(M);C.engine.notifyLocal(C.rel,U);return}h.get(n()??"")?.engine.notifyLocal(M,U)},(M,U,C)=>{if(b()){let F=Q(M),z=Q(U);if(F.engine===z.engine)return F.engine.notifyLocalMove(F.rel,z.rel,void 0,C);F.engine.notifyLocal(F.rel,"remove"),z.engine.notifyLocal(z.rel,"write");return}let A=n()??"",j=h.get(A);if(j)return ae(A,M,U,j,C)},(M,U)=>{if(b()){let C=Q(M),A=Q(U),j=[C.engine.holdLocalMove(C.rel,A.rel)];return C.engine!==A.engine&&j.push(A.engine.holdLocalMove(C.rel,A.rel)),()=>{for(let F of j)F()}}return h.get(n()??"")?.engine.holdLocalMove(M,U)});let me=()=>{let M=f.getStatus().pendingDeletions;for(let{engine:U}of g.values())M+=U.getStatus().pendingDeletions;for(let{engine:U}of h.values())M+=U.getStatus().pendingDeletions;return M},ge=M=>({...M,pendingDeletions:me(),side:b()?"cloud":"local"}),Pe=()=>{if(!i)return Promise.resolve(f.getStatus());y();for(let{engine:M}of g.values())M.syncNow();for(let{engine:M}of h.values())M.syncNow();return f.syncNow()},Ce=async()=>{let M=++r;i=!1,s.stop();let U=[f.stop(),...[...g.values()].map(({engine:A})=>A.stop()),...[...h.values()].map(({engine:A})=>A.stop())];if(g.clear(),h.clear(),p=[],T.clear(),v.clear(),a.clear(),o(),await Promise.all(U),await t.awaitPendingVaultWrites(),M!==r)return;let C=n();if(C&&bi(C)){let A=await ot();if(M!==r)return;let j=A.localVault&&!bi(A.localVault)?A.localVault:dn.join(t.workspaceDir(),"Amadeus");if(await Dn.mkdir(j,{recursive:!0}),M!==r||(await Pt({lastVault:j,localVault:j,lastPage:void 0}),M!==r))return;await t.activateRoot(j,!1)}M===r&&ee()};return{handlers:{get:()=>ge(f.getStatus()),setEnabled:async M=>{if(!i)throw new Error("Cloud account is changing");let U=r;return await f.setEnabled(M),U!==r?f.getStatus():(await Promise.all([...g.values(),...h.values()].map(({engine:C})=>C.restart())),ge(f.getStatus()))},syncNow:()=>Pe(),resolveHeld:M=>{let U=Array.isArray(M?.paths)?M.paths.filter(z=>typeof z=="string"):[],C=typeof M?.binding=="string"?M.binding:null,A=!C&&typeof M?.shareKey=="string"?M.shareKey:null,j=C?h.get(C)?.engine:A?g.get(A)?.engine:f;if(!j)return{error:"binding-not-found"};let F=j.resolveHeld(U,M.choice);return C?{...F,binding:C}:A?{...ge(F),shareKey:A}:ge(F)},confirmDeletions:()=>{for(let{engine:M}of g.values())M.confirmMassDeletions();for(let{engine:M}of h.values())M.confirmMassDeletions();return ge(f.confirmMassDeletions())},entryGet:async()=>{let M=await ot(),U=$t(),C=await Nc(U);return{vaults:M.entrySync??[],activeRoot:n(),cloudRoot:U,mirrorVaults:C.names,mirrorVaultDevices:C.devices,deviceId:M.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let M=n();if(!M)return null;let U=$t(),C=await ot(),A=M===U?C.localVault&&C.localVault!==U?C.localVault:null:U;if(!A)return null;let j=[],F=500,z=async(q,ne)=>{if(j.length>=F)return;let re;try{re=await Dn.readdir(q,{withFileTypes:!0})}catch{return}for(let Z of re){if(j.length>=F)break;if(Z.name.startsWith(".")||Z.isSymbolicLink())continue;let ie=ne?`${ne}/${Z.name}`:Z.name;if(Z.isDirectory())await z(dn.join(q,Z.name),ie);else if(Z.isFile()&&/\.db$/i.test(Z.name))try{j.push({rel:ie,source:await Dn.readFile(dn.join(q,Z.name),"utf8")})}catch{}}};return await z(A,""),{root:A,vaultName:A===U?"\u4E91\u7AEF":dn.basename(A),dbs:j}},entryEnable:async M=>{let U=r,C=s;if(!i||!Be())return{error:"Sign in to enable cloud sync"};let A=n();if(!A||b())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let j=await ot(),F=j.entrySync??[],z=F.find(q=>q.vaultRoot===A);if(!z){let q=(M.cloudName??dn.basename(A)).normalize("NFC").trim(),ne=ho(q,F.map(re=>re.cloudName));if(ne)return{error:ne};if(!M.merge)try{let re=await C.ensureOwnVault(),Z=await C.call("GET",`/vaults/${encodeURIComponent(re)}/tree`);if((Z.folders??[]).some(oe=>oe===q||oe.startsWith(`${q}/`))||(Z.entries??[]).some(oe=>oe.path===q||oe.path.startsWith(`${q}/`)))return{conflict:q}}catch(re){return{error:re?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}z={vaultRoot:A,cloudName:q,entries:[]},F.push(z)}return U!==r||!i?{error:"Cloud account changed; retry from the current account"}:(await Cn(q=>{if(U!==r||!i)return!1;let ne=q.entrySync??[],re=ne.find(X=>X.vaultRoot===A);if(!re){let X=ho(z.cloudName,ne.map(ve=>ve.cloudName));if(X)throw new Error(X);re={vaultRoot:A,cloudName:z.cloudName,entries:[]},ne.push(re)}let Z=X=>String(X??"").replace(/\\/g,"/").normalize("NFC"),ie=new Set;for(let X of M.entries??[]){let ve=Z(X.path);ve&&(ie.add(ve),!re.entries.some(nn=>nn.path===ve)&&re.entries.push({path:ve,kind:X.kind==="folder"||X.kind==="asset"?X.kind:"page"}))}let oe=(M.exclude??[]).map(Z).filter(Boolean),pe=new Set([...ie,...(M.include??[]).map(Z).filter(Boolean)]);re.exclude=[...new Set([...(re.exclude??[]).filter(X=>!pe.has(X)),...oe])];let le=new Set(oe);re.entries=re.entries.filter(X=>!le.has(X.path)),q.entrySync=ne,z=re},j.cloudAccountId),U!==r?{error:"Cloud account changed; retry from the current account"}:(await te(),h.get(A)?.engine.syncNow(),ee(),{ok:!0,cloudName:z.cloudName}))},entryDisable:async M=>{let U=n(),C=!1,A=r;return await Cn(j=>{if(A!==r||!i)return!1;let F=(j.entrySync??[]).find(ne=>ne.vaultRoot===U);if(!U||!F)return!1;let z=String(M??"").replace(/\\/g,"/").normalize("NFC"),q=F.entries.length;if(F.entries=F.entries.filter(ne=>ne.path!==z),xn(F.entries,F.exclude,z))F.exclude=[...new Set([...F.exclude??[],z])];else if(F.entries.length===q)return!1;C=!0}),!C||A!==r?{ok:!1}:(await te(),ee(),{ok:!0})},entryMark:async(M,U)=>{let C=String(M??"").normalize("NFC");if(!C||C.includes("/")||C.startsWith("."))return{error:"invalid name"};if(!i||!Be())return{error:"Sign in first"};try{await L(C,A=>U?A?void 0:[]:A?null:void 0)}catch(A){return{error:A?.message||String(A)}}return f.syncNow(),{ok:!0}},entryClosure:(M,U)=>t.relatedClosure(String(M??""),U==="folder"?"folder":"page"),collabCall:async(M,U)=>{let C=s,A=async()=>C.ensureOwnVault(),j=z=>String((U??[])[z]??""),F=z=>(U??[])[z]??{};switch(M){case"listVaults":return(await C.call("GET","/vaults")).vaults;case"activeVaultId":return A();case"pageShare":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/page-shares?path=${encodeURIComponent(j(0))}`);case"relatedItems":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}/related`);case"setShareItem":return C.call("POST",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}/items`,{path:j(1),included:(U??[])[2]===!0});case"createPageShare":return C.call("POST",`/vaults/${encodeURIComponent(await A())}/page-shares`,{path:j(0),...F(1)});case"updatePageShare":return C.call("PATCH",`/vaults/${encodeURIComponent(j(2)||await A())}/page-shares/${encodeURIComponent(j(0))}`,F(1));case"revokePageShare":return C.call("DELETE",`/vaults/${encodeURIComponent(await A())}/page-shares/${encodeURIComponent(j(0))}`);case"setParticipantRole":return C.call("PATCH",`/vaults/${encodeURIComponent(j(3)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(j(1))}`,{role:j(2)});case"removeParticipant":return C.call("DELETE",`/vaults/${encodeURIComponent(j(2)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(j(1))}`);case"sharedWithMe":{let z=await C.sharedWithMe();return y(),z}case"leaveShare":{let z=C.myUserId();if(!z)throw new Error("\u672A\u767B\u5F55");let q=await C.call("DELETE",`/vaults/${encodeURIComponent(j(1)||await A())}/page-shares/${encodeURIComponent(j(0))}/members/${encodeURIComponent(z)}`);return y(),q}case"publishes":return C.call("GET",`/vaults/${encodeURIComponent(await A())}/shares`);case"listAllShares":{let z=(await C.call("GET","/vaults")).vaults||[],q=C.myUserId(),ne=[],re=[];for(let Z of z){try{let ie=await C.call("GET",`/vaults/${encodeURIComponent(Z.id)}/shares`);for(let oe of ie.shares||[])ne.push({...oe,vaultId:Z.id,vaultName:Z.name||""})}catch(ie){t.log(`[connect] listAllShares publishes vault ${Z.id} failed: ${ie?.message}`)}try{let ie=await C.call("GET",`/vaults/${encodeURIComponent(Z.id)}/page-shares?expired=1`),oe=ie?.shares||ie?.pageShares||(Array.isArray(ie)?ie:[]);for(let pe of oe){let le=pe.created_by??pe.createdBy;(!q||!le||le===q)&&re.push({...pe,vaultId:Z.id,vaultName:Z.name||""})}}catch(ie){t.log(`[connect] listAllShares pageShares vault ${Z.id} failed: ${ie?.message}`)}}return{publishes:ne,pageShares:re,linkBase:await C.linkBase()}}case"createPublish":{let z=await C.call("POST",`/vaults/${encodeURIComponent(await A())}/shares`,{mode:j(0),path:j(1)});return{...z,url:`${await C.linkBase()}/share/${z.token}`}}case"revokePublish":return C.call("DELETE",`/vaults/${encodeURIComponent(await A())}/shares/${encodeURIComponent(j(0))}`);case"revokePublishIn":return C.call("DELETE",`/vaults/${encodeURIComponent(j(0))}/shares/${encodeURIComponent(j(1))}`);case"revokePageShareIn":return C.call("DELETE",`/vaults/${encodeURIComponent(j(0))}/page-shares/${encodeURIComponent(j(1))}`);case"myUserId":return C.myUserId();case"linkBase":return C.linkBase();case"heartbeat":return C.heartbeat((U??[])[0]??null,p);default:throw new Error(`unknown collab fn: ${M}`)}},switchSide:async(M,U)=>{let C=await ot();if(U==="cloud"){if(!i||!Be())throw new Error("Sign in to open cloud notes");let F=$t();await Dn.mkdir(F,{recursive:!0}),C.lastVault&&!bi(C.lastVault)&&await Pt({localVault:C.lastVault}),await Pt({lastVault:F});let z=await t.activateRoot(F,!1);return t.bindRenderer(M,F),{...z,side:"cloud"}}let A=C.localVault&&await Dn.stat(C.localVault).then(F=>F.isDirectory()).catch(()=>!1)?C.localVault:null;if(!A){let F=await t.ensureDefaultVault();return t.bindRenderer(M,F.root),{...F,side:"local"}}await Pt({lastVault:A});let j=await t.activateRoot(A,!1);return t.bindRenderer(M,A),{...j,side:"local"}}},instance:{start:()=>{i=!0,f.start(),y(),te()},stopAllSync:Ce,restartAllSync:async()=>{let M=Ce(),U=r;await M,U===r&&(s=co(),f=mr(u()),i=!0,await Promise.all([f.restart(),y(),te()]),U===r&&(ee(),e(Ne.status,ge(f.getStatus()))))},resolveSharedAsset:M=>Rc(p,M)}}}import{hostname as gg}from"node:os";var mg=256*1024;function Zc(t,e,n){if(n?.hasSecHeaders&&!n.gatewayStreamsSecHeaders)return!1;if(t.includes("text/event-stream"))return!0;let r=Number(e||NaN);return!Number.isFinite(r)||r>mg}var vo=45e3,yg=3e3,wg=16*1024,bg=6e4,Ri=t=>`${t.replace(/\/+$/,"")}/api`,Sr=class{deps;ctrl=null;conn=null;wake=null;redialNow=!1;inflight=new Map;connected=!1;lastError=null;hubCaps=new Set;constructor(e){this.deps=e}hubFetch(e,n){return(this.deps.hubFetch??fetch)(e,n)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??bg}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(n),r.ctrl.abort())}sleep(e){return new Promise(n=>{let r=setTimeout(i,e);function i(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,i()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,i=()=>r.abort();e.signal.addEventListener("abort",i,{once:!0}),this.conn=r;try{let{cloudUrl:s,token:a}=this.deps.getCreds();if(!a)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let o=this.deps.getPairing();if(!o){if(o=await this.register(s,a,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(o),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${o.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let c=this.deps.readIdleMs??vo,u=c?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(c/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},c):null,f;try{f=await this.hubFetch(`${Ri(s)}/units/${o.unitId}/channel`,{headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":o.secret,...l?{"X-Unit-Lan-Url":l}:{}},signal:r.signal})}finally{u&&clearTimeout(u)}if(f.status===403||f.status===404){let g=Number(f.headers.get("content-length"))>wg,p=setTimeout(()=>r.abort(),g?0:yg),m=await f.json().then(y=>y?.code,()=>null);throw clearTimeout(p),m==="UNIT_NOT_FOUND"||m==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${f.status} ${m}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${f.status} (not a hub verdict; keeping pairing and retrying)`)}if(!f.ok||!f.body)throw new Error(`channel HTTP ${f.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(f.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(s){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(s?.message||s),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",i),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,r){let i=this.deps.readIdleMs??vo,s=i?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(i/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},i):null;try{let a=await this.hubFetch(`${Ri(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:gg(),platform:process.platform}),signal:r.signal});if(!a.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${a.status}`);let o=await a.json();if(!o.unitId||!o.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:o.unitId,secret:o.secret}}finally{s&&clearTimeout(s)}}async consume(e,n){let r=e.getReader(),i=new TextDecoder,s="",a=this.deps.readIdleMs??vo,o=null,l=()=>{a&&(o&&clearTimeout(o),o=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(a/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),n.abort(),r.cancel().catch(()=>{})},a))};l();try{for(;;){let{done:c,value:u}=await r.read();if(c||n.signal.aborted)return;l(),s=this.parseFrames(s+i.decode(u,{stream:!0}),n)}}finally{o&&clearTimeout(o)}}parseFrames(e,n){let r=e,i;for(;(i=r.indexOf(`
|
|
219
219
|
|
|
220
|
-
`))>=0;){let
|
|
221
|
-
`).find(
|
|
222
|
-
`).find(a=>a.startsWith("data: "))?.slice(6);if(s)try{let a=JSON.parse(s);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 i;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})),i=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 s=i.headers.get("content-type")||"",a={};for(let u of["content-security-policy","x-content-type-options"]){let f=i.headers.get(u);f&&(a[u]=f)}let c=s||"application/octet-stream";i.body&&dl(s,i.headers.get("content-length"),{hasSecHeaders:Object.keys(a).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,i,n,c,a):await this.respond(e.id,i.status,c,Buffer.from(await i.arrayBuffer()),a,n.signal)}async respond(e,n,r,o,i,s){if(s?.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)]:[],...s?[s]:[]],h=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${ao(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,...i},bodyB64:o.toString("base64")}),...h?{signal:h}:{}}).then(p=>{p.body?.cancel().catch(()=>{})}).catch(p=>{s?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${p?.name==="TimeoutError"?`${Math.round(u/1e3)}s \u672A\u5B8C\u6210`:p?.message||p}`)})}async streamBack(e,n,r,o,i){let{cloudUrl:s,token:a}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let l=i?.["content-security-policy"],u=i?.["x-content-type-options"],f=`${ao(s)}/units/${c.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(o)}`+(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:j,value:x}=await p.read();j?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 yh(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 rr=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=yh(l)}let r=JSON.stringify(n);if(r===this.lastSent)return;let o=this.d.getPairing(),i;try{i=this.d.getCreds()}catch{return}if(!o||!i.token||!i.cloudUrl)return;let s=this.gen;this.inflight=!0;let a=new AbortController,c=setTimeout(()=>a.abort(),this.d.timeoutMs??1e4);try{let l=`${i.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(o.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(l,{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"X-Unit-Secret":o.secret,"Content-Type":"application/json"},body:r,signal:a.signal});try{await u.text()}catch{}if(s!==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){s===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 fl=["setUnitHubFactory"],Vi=t=>fl.every(e=>typeof t[e]=="function");function pl(t){let e=new rr({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),...typeof t.capsFeatures=="function"?{features:()=>t.capsFeatures()}:{},log:r=>t.log(r)}),n=new nr({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 Yi(t){let e=async(n,r,o)=>{let{base:i,token:s}=await t.getCloud();if(!s)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let a=await fetch(`${i}/api${r}`,{method:n,headers:{Authorization:`Bearer ${s}`,...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:i}=await t.getCloud();await t.openExternal(`${o}/api/units/${r}/open${i?`#token=${encodeURIComponent(i)}`:""}`)}),t.setUnitHubFactory(pl),t.log("[forsion-extend] unit hub registered")}import{createHash as jh}from"node:crypto";import{constants as jl,mkdirSync as Fh,readFileSync as Lh,renameSync as Uh,writeFileSync as Hh}from"node:fs";import{lstat as Rt,open as Xl,readFile as zh,readdir as Zl,statfs as Bh}from"node:fs/promises";import{cpus as qh,freemem as Wh,homedir as Fl,hostname as Ql,release as Vh,totalmem as Yh}from"node:os";import{basename as eu,join as ue}from"node:path";var wh=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,or=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,o="Z";if(typeof e=="string"){let i=e.match(wh);i?(i[1]||(n=!1,e=`0000-01-01T${e}`),r=!!i[2],r&&e[10]===" "&&(e=e.replace(" ","T")),i[2]&&+i[2]>23?e="":(o=i[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 bh(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Sh(t,e,n){let r=t.split(/\r\n|\n|\r/g),o="",i=(Math.log10(e+1)|0)+1;for(let s=e-1;s<=e+1;s++){let a=r[s-1];a&&(o+=s.toString().padEnd(i," "),o+=": ",o+=a,o+=`
|
|
223
|
-
`,
|
|
224
|
-
`))}return
|
|
220
|
+
`))>=0;){let s=r.slice(0,i);if(r=r.slice(i+2),s.includes("event: ready")){let o=s.split(`
|
|
221
|
+
`).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(o||"{}").caps;this.hubCaps=new Set(Array.isArray(l)?l.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!s.includes("event: dispatch"))continue;let a=s.split(`
|
|
222
|
+
`).find(o=>o.startsWith("data: "))?.slice(6);if(a)try{let o=JSON.parse(a);this.dispatch(o,n).catch(l=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${l?.message||l}`))}catch{}}return r}async dispatch(e,n){let r=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let i={ctrl:r,conn:n};this.inflight.set(e.id,i);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===i&&this.inflight.delete(e.id)}}async handle(e,n){let r=this.deps.getUnitWeb();if(!r.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,n.signal);return}let i={"x-unit-internal":r.internalSecret};e.ct&&(i["Content-Type"]=e.ct),e.accept&&(i.Accept=e.accept);let s;try{let u=new URL(`${r.url}${e.path}`);Object.assign(i,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:u,proxyCaller:e.proxyCaller,proxyOperator:e.proxyOperator})),s=await fetch(u,{method:e.method,headers:i,body:e.body??void 0,signal:n.signal})}catch(u){if(n.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${u?.message||u}`})),void 0,n.signal);return}let a=s.headers.get("content-type")||"",o={};for(let u of["content-security-policy","x-content-type-options"]){let f=s.headers.get(u);f&&(o[u]=f)}let l=a||"application/octet-stream";s.body&&Zc(a,s.headers.get("content-length"),{hasSecHeaders:Object.keys(o).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,s,n,l,o):await this.respond(e.id,s.status,l,Buffer.from(await s.arrayBuffer()),o,n.signal)}async respond(e,n,r,i,s,a){if(a?.aborted)return;let{cloudUrl:o,token:l}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let u=this.requestTimeoutMs*2,f=[...u?[AbortSignal.timeout(u)]:[],...a?[a]:[]],g=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${Ri(o)}/units/${c.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":c.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":r,...s},bodyB64:i.toString("base64")}),...g?{signal:g}:{}}).then(p=>{p.body?.cancel().catch(()=>{})}).catch(p=>{a?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${p?.name==="TimeoutError"?`${Math.round(u/1e3)}s \u672A\u5B8C\u6210`:p?.message||p}`)})}async streamBack(e,n,r,i,s){let{cloudUrl:a,token:o}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let c=s?.["content-security-policy"],u=s?.["x-content-type-options"],f=`${Ri(a)}/units/${l.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(i)}`+(c?`&csp=${encodeURIComponent(c)}`:"")+(u?`&xcto=${encodeURIComponent(u)}`:""),g=n.body;if(!g)return;let p=g.getReader(),m=0,y=this.requestTimeoutMs,b=y?setTimeout(()=>{m>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(y/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},y):null,_=new ReadableStream({async pull(h){++m===2&&b&&clearTimeout(b);let{done:T,value:v}=await p.read();T?h.close():h.enqueue(v)},cancel(h){return p.cancel(h)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${o}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:_,signal:r.signal,duplex:"half"})}catch(h){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${h?.message||h}`);try{await p.cancel()}catch{}}finally{b&&clearTimeout(b)}}};function Sg(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(typeof n!="string"||n.length===0||n.length>64)&&!e.includes(n)&&(e.push(n),e.length>=16))break;return e}var vr=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}capsChanged(){this.engineChanged()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(c){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${c?.message||c}`);return}let n={engine:e,tools:[]};if(typeof this.d.features=="function"){let c=[];try{c=this.d.features()}catch(u){this.d.log(`[unit-caps] \u8BFB\u80FD\u529B\u58F0\u660E\u5931\u8D25:${u?.message||u}`)}n.features=Sg(c)}let r=JSON.stringify(n);if(r===this.lastSent)return;let i=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!i||!s.token||!s.cloudUrl)return;let a=this.gen;this.inflight=!0;let o=new AbortController,l=setTimeout(()=>o.abort(),this.d.timeoutMs??1e4);try{let c=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(i.unitId)}/caps`,u=await(this.d.hubFetch??fetch)(c,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":i.secret,"Content-Type":"application/json"},body:r,signal:o.signal});try{await u.text()}catch{}if(a!==this.gen)return;u.ok?(this.lastSent=r,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}${n.features?`(\u80FD\u529B\u58F0\u660E ${n.features.length} \u9879)`:""}`)):u.status===404||u.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${u.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):u.status===400||u.status===401||u.status===403?this.warned.has(u.status)||(this.warned.add(u.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${u.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${u.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(c){a===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${o.signal.aborted?"\u8D85\u65F6":c?.message||c}`)}finally{clearTimeout(l),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var Qc=["setUnitHubFactory"],ko=t=>Qc.every(e=>typeof t[e]=="function");function eu(t){let e=new vr({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),...typeof t.capsFeatures=="function"?{features:()=>t.capsFeatures()}:{},log:r=>t.log(r)}),n=new Sr({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged(),capsChanged:()=>e.capsChanged()}}function Eo(t){let e=async(n,r,i)=>{let{base:s,token:a}=await t.getCloud();if(!a)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let o=await fetch(`${s}/api${r}`,{method:n,headers:{Authorization:`Bearer ${a}`,...i!==void 0?{"Content-Type":"application/json"}:{}},body:i!==void 0?JSON.stringify(i):void 0});return{status:o.status,json:await o.json().catch(()=>null)}}catch(o){return{status:0,json:{detail:String(o?.message||o)}}}};t.handle("units:list",(n,r)=>e("GET",r!=null&&typeof r=="object"&&r.shared===!0?"/units?shared=1":"/units")),t.handle("units:update",(n,r,i)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:i?.name,icon:i?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:i,token:s}=await t.getCloud();await t.openExternal(`${i}/api/units/${r}/open${s?`#token=${encodeURIComponent(s)}`:""}`)}),t.setUnitHubFactory(eu),t.log("[forsion-extend] unit hub registered")}import{createHash as Gg}from"node:crypto";import{constants as Au,mkdirSync as Vg,readFileSync as Yg,renameSync as Jg,writeFileSync as Kg}from"node:fs";import{lstat as Ft,open as Uu,readFile as Xg,readdir as Hu,statfs as Zg}from"node:fs/promises";import{cpus as Qg,freemem as em,homedir as xu,hostname as zu,release as tm,totalmem as nm}from"node:os";import{basename as Bu,join as de}from"node:path";var vg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,kr=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,i="Z";if(typeof e=="string"){let s=e.match(vg);s?(s[1]||(n=!1,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=!1,n.#e=null,n}};function kg(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Eg(t,e,n){let r=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let a=e-1;a<=e+1;a++){let o=r[a-1];o&&(i+=a.toString().padEnd(s," "),i+=": ",i+=o,i+=`
|
|
223
|
+
`,a===e&&(i+=" ".repeat(s+n+2),i+=`^
|
|
224
|
+
`))}return i}var ce=class extends Error{line;column;codeblock;constructor(e,n){let[r,i]=kg(n.toml,n.ptr),s=Eg(n.toml,r,i);super(`Invalid TOML document: ${e}
|
|
225
225
|
|
|
226
|
-
${
|
|
226
|
+
${s}`,n),this.line=r,this.column=i,this.codeblock=s}};var _g=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Cg=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Ag=/^[+-]?0[0-9_]/;function Di(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
|
|
229
|
-
`||n==="\r"&&t[
|
|
230
|
-
`))
|
|
231
|
-
`;else if(n==="f")
|
|
232
|
-
`,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function
|
|
228
|
+
`&&(e+=2));let a="",o=e,l=0;for(let c=e;c<t.length;c++)if(n=t[c],s&&(n===`
|
|
229
|
+
`||n==="\r"&&t[c+1]===`
|
|
230
|
+
`))l=l&&3;else{if(n<" "&&n!==" "||n==="\x7F")throw new ce("control characters are not allowed in strings",{toml:t,ptr:c});if((!l||l===3)&&n===r&&(!s||t[c+1]===r&&t[c+2]===r))return s&&(t[c+3]===r&&c++,t[c+3]===r&&c++),[l?a:a+t.slice(o,c),c+(s?3:1)];if(!l)!i&&n==="\\"&&(a+=t.slice(o,o=c),l=1);else if(l===1)if(n==="x"||n==="u"||n==="U"){let u=0,f=n==="x"?2:n==="u"?4:8;for(let g=0;g<f;g++,c++){let p=t.charCodeAt(c+1),m=p>=48&&p<=57?p-48:p>=65&&p<=70?p-65+10:p>=97&&p<=102?p-97+10:-1;if(m<0)throw new ce("invalid non-hex character in unicode escape",{toml:t,ptr:c+1});u=u<<4|m}if(u<0||u>1114111||u>=55296&&u<=57343)throw new ce("invalid unicode escape",{toml:t,ptr:c});a+=String.fromCodePoint(u),o=c+1,l=0}else if(n===" "||n===" ")l=2;else{if(n==="b")a+="\b";else if(n==="t")a+=" ";else if(n==="n")a+=`
|
|
231
|
+
`;else if(n==="f")a+="\f";else if(n==="r")a+="\r";else if(n==="e")a+="\x1B";else if(n==='"')a+='"';else if(n==="\\")a+="\\";else throw new ce("unrecognized escape sequence",{toml:t,ptr:c});o=c+1,l=0}else if(n!==" "&&n!==" "){if(l===2)throw new ce("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:o});l=!i&&n==="\\"?1:0,o=c}}throw new ce("unfinished string",{toml:t,ptr:e})}function tu(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=_g.test(t);if(i||Cg.test(t)){if(Ag.test(t))throw new ce("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let a=+t;if(isNaN(a))throw new ce("invalid number",{toml:e,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new ce("integer value cannot be represented losslessly",{toml:e,ptr:n});(i||r===!0)&&(a=BigInt(t))}return a}let s=new kr(t);if(!s.isValid())throw new ce("invalid value",{toml:e,ptr:n});return s}function Oi(t,e=0,n=t.length){let r=t.indexOf(`
|
|
232
|
+
`,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function On(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
|
|
235
|
-
`||
|
|
236
|
-
`);)e++;if(r||
|
|
237
|
-
`||
|
|
238
|
-
`))return
|
|
239
|
-
`&&t[
|
|
240
|
-
`&&
|
|
241
|
-
`&&
|
|
242
|
-
`&&t[a]!=="\r")throw new ae("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=gt(t,a)}return r}var ho=14,Ah=1440*6e4,xh=12e4,Th=15e3,Gi=1792*1024,Ih=7,Tt=t=>t.toISOString().slice(0,10),mt=t=>Date.parse(Tt(t))-(Ih-1)*Ah,bl=["sessions","activity"],po=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Ji(t,e,n){let r=t?.day===Tt(n)?t:void 0;return Object.fromEntries(bl.map(o=>[o,po(r?.[o])??Math.min(Math.max(po(e[o])??0,mt(n)),n.getTime())]))}function Ki(t,e,n,r,o,i){let s=e?.day===Tt(r)?e:void 0,a={sent:{...t},file:{day:Tt(r)}};for(let c of bl){let l=c in o&&!i.includes(c)&&!(`${c}Error`in o),u=po(s?.[c]);l?(a.file[c]=n[c],a.sent[c]=r.getTime()):u!==void 0&&(a.sent[c]=Math.min(po(t[c])??u,u))}return a}function Sl(t,e=[]){let n={...t},r=jn(JSON.stringify(n));for(let o of["activity","sessions","memory","runs","engine"]){if(r.length<=Gi)break;o in n&&(delete n[o],e.push(o),r=jn(JSON.stringify({...n,truncated:e})))}return r.length>Gi?null:r}async function Xi(t,e,n,r=new Date){let o=AbortSignal.timeout(xh);await t.writeFile(`${e}/${Tt(r)}.json`,n,r.getTime(),o);try{let i=Tt(new Date(r.getTime()-ho*24*60*6e4));for(let s of await t.walk(o)){let a=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(s.key);a&&a[1]===e&&a[2]<i&&await t.rm(s.key,o)}}catch{}}var Zi={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:Zi.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Qi(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Th)});return e.status===404?{...Zi}:e.ok?sr(await e.json()):null}catch{return null}}var kl=["merge","cloud","local"],El={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 Rh(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,o=new Set,i=n.rules.map(s=>{let a=Lt(s.source,!0),c=Rh(s.target);if(typeof s.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(s.id)||o.has(s.id)||r.has(a))throw Error("Duplicate or invalid sync rule");return o.add(s.id),r.add(a),{id:s.id,source:a,target:c,...s.sourceId&&/^[a-f0-9-]{36}$/i.test(s.sourceId)?{sourceId:s.sourceId}:{}}});return{version:1,revision:e,enabled:n.enabled,rules:i}}function wn(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 yt={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"},go=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,vl=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),es=(t,e,n)=>{let r=vl(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(o=>o.id!==n&&vl(o.name)===r)?"taken":null:null},_l=["Amadeus","agents","human","Plugins"];var It=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var ar=/^[a-z0-9][a-z0-9-]{0,63}$/,mo=new Set(["muse"]),cr=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&ar.test(e[1])?e[1]:null},Dh=t=>[...mo].some(e=>ts(t,`agents/${e}`));function Cl(t){let e=t.split(/^\s*\[/m)[0]??"",n=i=>{let s=new RegExp(`^[ \\t]*${i}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(s?.[1]!=null?s[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):s?.[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 bn=(t,e)=>wn(e,t)?.target??"off",ts=(t,e)=>t===e||t.startsWith(e+"/"),Oh=t=>It.some(e=>ts(t,e.path)),ns=t=>t.some(e=>e.id==="default")?yo():"default",Al=(t,e)=>t.enabled?bn(t.rules,e):"off";function xl(t,e,n){n==="off"&&(t=t.filter(i=>e?!i.source.startsWith(e+"/"):!i.source||Oh(i.source)));let r=t.find(i=>i.source===e),o=t.filter(i=>i!==r);return e&&bn(o,e)===n?o:r?t.map(i=>i===r?{...i,target:n}:i):[...t,{id:e?yo():ns(t),source:e,target:n}]}function Sn(t,e,n,r=!1){if(Dh(e))return t;let o=t.rules;if(!t.enabled){let i=o.find(a=>!a.source),s=e?o.filter(a=>a.source&&ts(a.source,e)):[];o=[{id:i?.id??ns(s),source:"",target:"off"},...s],e!=="agents"&&(o=rs(o,"agents","off"))}if(!e)for(let i of It)o.some(s=>s.source===i.path)||(o=[...o,{id:yo(),source:i.path,target:bn(o,i.path)}]);return Tl({...t,rules:xl(o,e,n)},r)}function Tl(t,e=!1){let n=r=>bn(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 Il(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:ns(t.rules),source:"",target:"default"},...t.rules];for(let n of It)n.id!=="agents"&&bn(e,n.path)==="off"&&(e=xl(e,n.path,"default"));return e=rs(e,"agents","off"),{...t,enabled:!0,rules:e}}function rs(t,e,n){let r=t.find(o=>o.source===e);return r?t.map(o=>o===r?{...o,target:n}:o):[...t,{id:yo(),source:e,target:n}]}function Rl(t,e){let n=t;for(let r of new Set(e))ar.test(r)&&!mo.has(r)&&(n=Sn(n,`agents/${r}`,"default"));return n}function Dl(t){let e=bn(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=rs(t.rules.filter(o=>!o.source.startsWith("agents/")),"agents","off");return t.enabled?Tl({...t,rules:r},!0):{...t,rules:r}}var Mh=0,yo=()=>`rule-${Date.now().toString(36)}-${(Mh++).toString(36)}`;var Ol=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var Ph=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function Ml(t,e=[]){let n=t;for(let r of[...e].filter(o=>o&&o.length>=2).sort((o,i)=>i.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 lr=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||Ph.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]}:{}}))}}},Pl=null;function $l(t){Pl=t}function Nl(){try{return Pl?.()??null}catch{return null}}var Gh=(t,e=[])=>{let n=Sl(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},tu=60*6e4,Jh=2*6e4,Kh=10*6e4,Ll=tu,Xh=4*1024*1024,Zh=256*1024,Ul=["user","teamwork","discussion","delegate"],Qh=/^(?:New remarks in the team chat:|You are activated now \()/,nu={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},is=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,ru=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,o)=>is.test(o)||e&&!/\s/.test(o)?n:`${r}[path]${r}`),ou=t=>ru(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>is.test(e)?e:"[path]"),fr=4e3,bo=(t,e)=>typeof t=="string"&&t?bt(ou(St(t.slice(0,fr))),e):void 0,eg={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},tg=64*1024,os=500,ng={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},rg=256*1024,Hl=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],og=["description","developer_instructions"],ig=["memory","harness","project_memory","human","dream","log_appended"],sg=["homeDir","readCreds","accountId","appVersion"],ss=t=>sg.every(e=>typeof t[e]=="function"),zl=Fl().length>3?Fl():null;function St(t){return typeof t=="string"?(zl?t.split(zl).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(St):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]":St(n)])):t}var ag=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ce=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,cg=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function vn(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,i]]of Object.entries(t).slice(0,100).entries())n[cg(o,r)]=ag.test(o)&&ce(i,80)!==void 0?i:vn(i,e+1);return n}var lg={"":/^(?: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)$/},Bl={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},ug=/^(?:apps|enabled_skill_ids)$/,ql=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function dg(t){try{let e=fo(t),n=[],r=[],o=8192,i=(c,l)=>o<=0?!1:(o-=l.length+1,c.push(l),!0),s=(c,l,u)=>{let f=lg[c].test(l)?l:`[key:${l.length}]`,h=Bl[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===""&&ug.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(i(r,l)){for(let[f,h]of Object.entries(u))if(!i(r,s(c,f,h)))return}};for(let[c,l]of Object.entries(e)){let u=c!==""&&Object.hasOwn(Bl,c);if(u&&ql(l))a(c,`[${c}]`,l);else if(u&&Array.isArray(l)&&l.length>0&&l.every(ql))for(let f of l)a(c,`[[${c}]]`,f);else i(n,s("",c,l));if(o<=0)break}return[...n,...r].join(`
|
|
243
|
-
`)}catch{return`[unparsed:${t.length}]`}}var
|
|
244
|
-
`)+1):
|
|
245
|
-
`).filter(
|
|
246
|
-
`)})}}catch(
|
|
234
|
+
`)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new ce("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function At(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=On(t,e)}return e}function nu(t,e,n,r,i=!1){if(!r)return e=Oi(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let a=t[s];if(a==="#")s=Oi(t,s);else{if(a===n)return s+1;if(a===r||i&&(a===`
|
|
237
|
+
`||a==="\r"&&t[s+1]===`
|
|
238
|
+
`))return s}}throw new ce("cannot find end of structure",{toml:t,ptr:e})}function xg(t,e,n){let r=t.slice(e,n),i=r.indexOf("#");return i>-1&&(On(t,i),r=r.slice(0,i)),[r.trimEnd(),i]}function Er(t,e,n,r,i){if(r===0)throw new ce("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let s=t[e];if(s==="["||s==="{"){let[l,c]=s==="["?iu(t,e,r,i):ru(t,e,r,i);if(n){if(c=At(t,c),t[c]===",")c++;else if(t[c]!==n)throw new ce("expected comma or end of structure",{toml:t,ptr:c})}return[l,c]}if(s==='"'||s==="'"){let[l,c]=Di(t,e);if(n){if(c=At(t,c),t[c]&&t[c]!==","&&t[c]!==n&&t[c]!==`
|
|
239
|
+
`&&t[c]!=="\r")throw new ce("unexpected character encountered",{toml:t,ptr:c});t[c]===","&&c++}return[l,c]}let a=nu(t,e,",",n),o=xg(t,e,a-(t[a-1]===","?1:0));if(!o[0])throw new ce("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&o[1]>-1&&(a=At(t,e+o[1]),t[a]===","&&a++),[tu(o[0],t,e,i),a]}var Tg=/^[a-zA-Z0-9-_]+[ \t]*$/;function Mi(t,e,n="="){let r=e-1,i=[],s=t.indexOf(n,e);if(s<0)throw new ce("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let a=t[e=++r];if(a!==" "&&a!==" ")if(a==='"'||a==="'"){if(a===t[e+1]&&a===t[e+2])throw new ce("multiline strings are not allowed in keys",{toml:t,ptr:e});let[o,l]=Di(t,e);r=t.indexOf(".",l);let c=t.slice(l,r<0||r>s?s:r),u=Oi(c);if(u>-1)throw new ce("newlines are not allowed in keys",{toml:t,ptr:e+r+u});if(c.trimStart())throw new ce("found extra tokens after the string part",{toml:t,ptr:l});if(s<l&&(s=t.indexOf(n,l),s<0))throw new ce("incomplete key-value: cannot find end of key",{toml:t,ptr:e});i.push(o)}else{r=t.indexOf(".",e);let o=t.slice(e,r<0||r>s?s:r);if(!Tg.test(o))throw new ce("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});i.push(o.trimEnd())}}while(r+1&&r<s);return[i,At(t,s+1,!0,!0)]}function ru(t,e,n,r){let i={},s=new Set,a;for(e++;(a=t[e++])!=="}"&&a;){if(a===",")throw new ce("expected value, found comma",{toml:t,ptr:e-1});if(a==="#")e=On(t,e);else if(a!==" "&&a!==" "&&a!==`
|
|
240
|
+
`&&a!=="\r"){let o,l=i,c=!1,[u,f]=Mi(t,e-1);for(let m=0;m<u.length;m++){if(m&&(l=c?l[o]:l[o]={}),o=u[m],(c=Object.hasOwn(l,o))&&(typeof l[o]!="object"||s.has(l[o])))throw new ce("trying to redefine an already defined value",{toml:t,ptr:e});!c&&o==="__proto__"&&Object.defineProperty(l,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new ce("trying to redefine an already defined value",{toml:t,ptr:e});let[g,p]=Er(t,f,"}",n-1,r);s.add(g),l[o]=g,e=p}}if(!a)throw new ce("unfinished table encountered",{toml:t,ptr:e});return[i,e]}function iu(t,e,n,r){let i=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new ce("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=On(t,e);else if(s!==" "&&s!==" "&&s!==`
|
|
241
|
+
`&&s!=="\r"){let a=Er(t,e-1,"]",n-1,r);i.push(a[0]),e=a[1]}}if(!s)throw new ce("unfinished array encountered",{toml:t,ptr:e});return[i,e]}function su(t,e,n,r){let i=e,s=n,a,o=!1,l;for(let c=0;c<t.length;c++){if(c){if(i=o?i[a]:i[a]={},s=(l=s[a]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=i.length-1;i=i[u],s=s[u].c}}if(a=t[c],(o=Object.hasOwn(i,a))&&s[a]?.t===0&&s[a]?.d)return null;o||(a==="__proto__"&&(Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0})),s[a]={t:c<t.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(l=s[a],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,i[a]=[]),i[a].push(i={}),l.c[l.i++]=l={t:1,d:!1,i:0,c:{}}),l.d))return null;if(l.d=!0,r===1)i=o?i[a]:i[a]={};else if(r===0&&o)return null;return[a,i,l.c]}function Ni(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,a=i;for(let o=At(t,0);o<t.length;){if(t[o]==="["){let l=t[++o]==="[",c=Mi(t,o+=+l,"]");if(l){if(t[c[1]-1]!=="]")throw new ce("expected end of table declaration",{toml:t,ptr:c[1]-1});c[1]++}let u=su(c[0],r,i,l?2:1);if(!u)throw new ce("trying to redefine an already defined table or value",{toml:t,ptr:o});a=u[2],s=u[1],o=c[1]}else{let l=Mi(t,o),c=su(l[0],s,a,0);if(!c)throw new ce("trying to redefine an already defined table or value",{toml:t,ptr:o});let u=Er(t,l[1],void 0,e,n);c[1][c[0]]=u[0],o=u[1]}if(o=At(t,o,!0),t[o]&&t[o]!==`
|
|
242
|
+
`&&t[o]!=="\r")throw new ce("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:o});o=At(t,o)}return r}var $i=14,Ig=1440*6e4,Rg=12e4,Dg=15e3,_o=1792*1024,Og=7,jt=t=>t.toISOString().slice(0,10),xt=t=>Date.parse(jt(t))-(Og-1)*Ig,ou=["sessions","activity"],Pi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Co(t,e,n){let r=t?.day===jt(n)?t:void 0;return Object.fromEntries(ou.map(i=>[i,Pi(r?.[i])??Math.min(Math.max(Pi(e[i])??0,xt(n)),n.getTime())]))}function Ao(t,e,n,r,i,s){let a=e?.day===jt(r)?e:void 0,o={sent:{...t},file:{day:jt(r)}};for(let l of ou){let c=l in i&&!s.includes(l)&&!(`${l}Error`in i),u=Pi(a?.[l]);c?(o.file[l]=n[l],o.sent[l]=r.getTime()):u!==void 0&&(o.sent[l]=Math.min(Pi(t[l])??u,u))}return o}function au(t,e=[]){let n={...t},r=nr(JSON.stringify(n));for(let i of["activity","sessions","memory","runs","engine"]){if(r.length<=_o)break;i in n&&(delete n[i],e.push(i),r=nr(JSON.stringify({...n,truncated:e})))}return r.length>_o?null:r}async function xo(t,e,n,r=new Date){let i=AbortSignal.timeout(Rg);await t.writeFile(`${e}/${jt(r)}.json`,n,r.getTime(),i);try{let s=jt(new Date(r.getTime()-$i*24*60*6e4));for(let a of await t.walk(i)){let o=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(a.key);o&&o[1]===e&&o[2]<s&&await t.rm(a.key,i)}}catch{}}var To={mode:"scheduled",intervalHours:24,requestedAt:0};function _r(t){let e=t&&typeof t=="object"?t:{},n=Number(e.intervalHours),r=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(n)&&n>=1&&n<=720?n:To.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Io(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Dg)});return e.status===404?{...To}:e.ok?_r(await e.json()):null}catch{return null}}var uu=["merge","cloud","local"],du={version:1,revision:0,enabled:!1,rules:[{id:"default",source:"",target:"default"}]};function Xt(t,e=!1){if(typeof t!="string"||!t&&!e||t.length>512||t.startsWith("/")||/[\\\u0000-\u001f\u007f]/.test(t)||t&&t.split("/").some(n=>!n||n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||n.startsWith(".forsion-sync")))throw Error("Invalid content path");return t}function Mg(t){if(t==="default"||t==="off"||typeof t=="string"&&/^device-[A-Za-z0-9_-]{1,64}$/.test(t))return t;throw Error("Invalid content target")}function Zt(t,e){let n=t;if(!n||n.version!==1||typeof n.enabled!="boolean"||!Array.isArray(n.rules)||n.rules.length>512)throw Error("Invalid content sync configuration");let r=new Set,i=new Set,s=n.rules.map(a=>{let o=Xt(a.source,!0),l=Mg(a.target);if(typeof a.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(a.id)||i.has(a.id)||r.has(o))throw Error("Duplicate or invalid sync rule");return i.add(a.id),r.add(o),{id:a.id,source:o,target:l,...a.sourceId&&/^[a-f0-9-]{36}$/i.test(a.sourceId)?{sourceId:a.sourceId}:{}}});return{version:1,revision:e,enabled:n.enabled,rules:s}}function Mn(t,e){let n=null;for(let r of e)(!r.source||t===r.source||t.startsWith(r.source+"/"))&&(!n||r.source.length>n.source.length)&&(n=r);return n}var gt={get:"penzor:sync:get",preview:"penzor:sync:preview",apply:"penzor:sync:apply",run:"penzor:sync:run",pause:"penzor:sync:pause",retry:"penzor:sync:retry",rename:"penzor:sync:rename",setup:"penzor:sync:setup",archiveSeen:"penzor:sync:archiveSeen",confirmDeletes:"penzor:sync:confirmDeletes",abandonDeletes:"penzor:sync:abandonDeletes"},lu=200,Ro=6e4,Ng=50;function Do(t,e,n,r){return t.deleted?"forget":t.busy||r?"skip":t.version?e&&e.version===t.version&&Li(e.file,t.file)?"delete":"download":n?"cancel":"skip"}var Li=(t,e)=>t===void 0||e===void 0||t===e,Pg=(t,e)=>{let n=e.indexOf("/");return t+":"+(n<0?"":e.slice(0,n))};function Oo(t,e,n){if(!t.length)return!1;if(n.latched||t.length>=lu||n.recent+t.length>Ng)return!0;let r=a=>{let o=new Map;for(let l of a){let c=Pg(l.ns,l.path);o.set(c,(o.get(c)??0)+1)}return o},i=r(t),s=r(e);for(let[a,o]of i)if(fr(o,s.get(a)??0,lu))return!0;return!1}var Fi=t=>t.replace(/\.local$/i,"").replace(/[-_]+/g," ").trim()||t,cu=t=>String(t??"").normalize("NFC").trim().replace(/\s+/g," ").toLowerCase(),Mo=(t,e,n)=>{let r=cu(t);return r?/[\[\]]/.test(t)||t.trim().length>64?"invalid":r==="macos"||r==="windows"||r==="linux"?"reserved":e.some(i=>i.id!==n&&cu(i.name)===r)?"taken":null:null},fu=["Amadeus","agents","human","Plugins"],fn=1024*1024,ji=50*fn,$g=[{prefix:"Amadeus/",ext:[".md",".db"],maxBytes:5*fn},{prefix:"Amadeus/",maxBytes:5*fn},{prefix:"agents/",maxBytes:5*fn},{prefix:"human/",maxBytes:5*fn},{prefix:"",maxBytes:50*fn}],jg=[{prefix:"",maxBytes:50*fn}];function Ui(t,e,n){let r=Array.isArray(n)&&n.length?n:e==="default"?$g:jg,i=t.toLowerCase();for(let s of r)if(!(!s||typeof s.prefix!="string"||!Number.isSafeInteger(s.maxBytes)||s.maxBytes<=0)&&t.startsWith(s.prefix)&&!(Array.isArray(s.ext)&&s.ext.length&&!s.ext.some(a=>typeof a=="string"&&i.endsWith(a.toLowerCase()))))return Math.min(s.maxBytes,ji);return ji}var Lg=6e4,Fg=10*6e4,pu=t=>t<=1?0:Math.min(Lg*2**(t-2),Fg),No="delete-guard";var Lt=[{id:"notes",path:"Amadeus"},{id:"agents",path:"agents"},{id:"profile",path:"human"},{id:"plugins",path:"Plugins"}];var Cr=/^[a-z0-9][a-z0-9-]{0,63}$/,Hi=new Set(["muse"]),Ar=t=>{let e=/^agents\/([^/]+)$/.exec(t);return e&&Cr.test(e[1])?e[1]:null},Ug=t=>[...Hi].some(e=>Po(t,`agents/${e}`));function hu(t){let e=t.split(/^\s*\[/m)[0]??"",n=s=>{let a=new RegExp(`^[ \\t]*${s}[ \\t]*=[ \\t]*(?:"((?:[^"\\\\\\n]|\\\\.)*)"|'([^'\\n]*)')`,"m").exec(e);return(a?.[1]!=null?a[1].replace(/\\(["\\])/g,"$1").replace(/\\n/g," "):a?.[2])?.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,80)||void 0},r=n("name"),i=n("name_en");return{...r?{name:r}:{},...i?{nameEn:i}:{}}}var Nn=(t,e)=>Mn(e,t)?.target??"off",Po=(t,e)=>t===e||t.startsWith(e+"/"),Hg=t=>Lt.some(e=>Po(t,e.path)),$o=t=>t.some(e=>e.id==="default")?zi():"default",gu=(t,e)=>t.enabled?Nn(t.rules,e):"off";function mu(t,e,n){n==="off"&&(t=t.filter(s=>e?!s.source.startsWith(e+"/"):!s.source||Hg(s.source)));let r=t.find(s=>s.source===e),i=t.filter(s=>s!==r);return e&&Nn(i,e)===n?i:r?t.map(s=>s===r?{...s,target:n}:s):[...t,{id:e?zi():$o(t),source:e,target:n}]}function Pn(t,e,n,r=!1){if(Ug(e))return t;let i=t.rules;if(!t.enabled){let s=i.find(o=>!o.source),a=e?i.filter(o=>o.source&&Po(o.source,e)):[];i=[{id:s?.id??$o(a),source:"",target:"off"},...a],e!=="agents"&&(i=jo(i,"agents","off"))}if(!e)for(let s of Lt)i.some(a=>a.source===s.path)||(i=[...i,{id:zi(),source:s.path,target:Nn(i,s.path)}]);return yu({...t,rules:mu(i,e,n)},r)}function yu(t,e=!1){let n=r=>Nn(t.rules,r)!=="off";return{...t,enabled:Lt.some(r=>n(r.path))||t.rules.some(r=>r.source&&r.target!=="off")||e&&n("")}}function wu(t){let e=t.rules.some(n=>n.source==="")?t.rules:[{id:$o(t.rules),source:"",target:"default"},...t.rules];for(let n of Lt)n.id!=="agents"&&Nn(e,n.path)==="off"&&(e=mu(e,n.path,"default"));return e=jo(e,"agents","off"),{...t,enabled:!0,rules:e}}function jo(t,e,n){let r=t.find(i=>i.source===e);return r?t.map(i=>i===r?{...i,target:n}:i):[...t,{id:zi(),source:e,target:n}]}function bu(t,e){let n=t;for(let r of new Set(e))Cr.test(r)&&!Hi.has(r)&&(n=Pn(n,`agents/${r}`,"default"));return n}function Su(t){let e=Nn(t.rules,"agents")!=="off"||t.rules.some(i=>i.source.startsWith("agents/")&&i.target!=="off"),n=t.rules.some(i=>i.source.startsWith("agents/"));if(!e&&!n)return null;let r=jo(t.rules.filter(i=>!i.source.startsWith("agents/")),"agents","off");return t.enabled?yu({...t,rules:r},!0):{...t,rules:r}}var zg=0,zi=()=>`rule-${Date.now().toString(36)}-${(zg++).toString(36)}`;var vu=["uploads","downloads","merges","renames","deletesSent","deletesLocal","conflictCopies","folderConflicts","tooLarge","errors"];var Bg=/^(?:account_changed|content_sync_closed|paused|not_signed_in)$/;function ku(t,e=[]){let n=t;for(let r of[...e].filter(i=>i&&i.length>=2).sort((i,s)=>s.length-i.length))n=n.split(r).join("[path]");return n.replace(/^(Duplicate folder sync identity|Concurrent (?:folder|file) rename): [\s\S]*$/,"$1: [path]")}var xr=class{since;cur=null;last=null;runs=[];totals={runs:0,completedRuns:0,idleRuns:0};errors=[];clock;constructor(e=Date.now){this.clock=e,this.since=e()}reset(){this.since=this.clock(),this.cur=null,this.last=null,this.runs=[],this.errors=[],this.totals={runs:0,completedRuns:0,idleRuns:0}}begin(e=this.clock()){this.cur={at:e,counts:{}}}count(e,n=1){n>0&&(this.cur&&(this.cur.counts[e]=(this.cur.counts[e]??0)+n),this.totals[e]=(this.totals[e]??0)+n)}fault(e,n=[],r=this.clock()){if(!e||Bg.test(e))return;this.count("errors"),/^File exceeds \d+ MB/.test(e)&&this.count("tooLarge");let i=this.errors[this.errors.length-1];if(i&&i.text===e){i.n++,i.at=r,this.addPaths(n);return}this.errors.push({first:r,at:r,n:1,text:e}),this.addPaths(n),this.errors.length>20&&this.errors.shift()}addPaths(e){let n=this.errors[this.errors.length-1],r=e.filter(i=>typeof i=="string"&&i);!n||!r.length||(n.paths=[...new Set([...n.paths??[],...r])].slice(0,8))}end(e,n=this.clock()){let r=this.cur;if(!r)return;this.cur=null;let i={at:r.at,ms:Math.max(0,n-r.at),completed:e,counts:r.counts};this.last=i,this.totals.runs++,e&&this.totals.completedRuns++,!e||Object.keys(r.counts).length?(this.runs.push(i),this.runs.length>20&&this.runs.shift()):this.totals.idleRuns++}snapshot(){let e=n=>({...n,counts:{...n.counts}});return{since:this.since,lastRun:this.last&&e(this.last),runs:this.runs.map(e),totals:{...this.totals},errors:this.errors.map(n=>({...n,...n.paths?{paths:[...n.paths]}:{}}))}}},Eu=null;function _u(t){Eu=t}function Cu(){try{return Eu?.()??null}catch{return null}}var rm=(t,e=[])=>{let n=au(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},qu=60*6e4,im=2*6e4,sm=10*6e4,Tu=qu,om=4*1024*1024,am=256*1024,Iu=["user","teamwork","discussion","delegate"],lm=/^(?:New remarks in the team chat:|You are activated now \()/,Wu={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Fo=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i,Gu=(t,e)=>t.replace(/(["'`])([^"'`\n]*[\\/][^"'`\n]*)\1/g,(n,r,i)=>Fo.test(i)||e&&!/\s/.test(i)?n:`${r}[path]${r}`),Vu=t=>Gu(t,!0).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>Fo.test(e)?e:"[path]"),Rr=4e3,qi=(t,e)=>typeof t=="string"&&t?It(Vu(Rt(t.slice(0,Rr))),e):void 0,cm={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},um=64*1024,Lo=500,dm={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},fm=256*1024,Ru=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],pm=["description","developer_instructions"],hm=["memory","harness","project_memory","human","dream","log_appended"],gm=["homeDir","readCreds","accountId","appVersion"],Uo=t=>gm.every(e=>typeof t[e]=="function"),Du=xu().length>3?xu():null;function Rt(t){return typeof t=="string"?(Du?t.split(Du).join("~"):t).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,(e,n,r)=>/^[a-f0-9]{48}$/.test(e)&&/(?:^|[^\w-])pr-$/.test(r.slice(Math.max(0,n-4),n))?e:`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(t)?t.map(Rt):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":Rt(n)])):t}var mm=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ue=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,ym=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function $n(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[r,[i,s]]of Object.entries(t).slice(0,100).entries())n[ym(i,r)]=mm.test(i)&&ue(s,80)!==void 0?s:$n(s,e+1);return n}var wm={"":/^(?:name|version|description|model|model_reasoning_effort|approval_mode|max_iterations|tools|enabled_skill_ids|enabled_mcp_servers|library_order|apps|avatar|share_default_memory|cloud_sync|activity_access|tools_strict|tools_mode|tools_list|created_by|created_at|developer_instructions|compaction|lead|slug|members|mode|max_rounds)$/,compaction:/^(?:enabled|reserveTokens|thresholdPercent|keepRecentTokens|summaryMaxTokens|thinking|model|instructions|prompt)$/,members:/^(?:slug|role)$/},Ou={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},bm=/^(?:apps|enabled_skill_ids)$/,Mu=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Sm(t){try{let e=Ni(t),n=[],r=[],i=8192,s=(l,c)=>i<=0?!1:(i-=c.length+1,l.push(c),!0),a=(l,c,u)=>{let f=wm[l].test(c)?c:`[key:${c.length}]`,g=Ou[l].test(c),p;return typeof u=="boolean"||typeof u=="number"?p=String(u):g&&typeof u=="string"&&!/[\r\n]/.test(u)&&JSON.stringify(u).length<=120?p=JSON.stringify(u):g&&u instanceof Date?p=u.toISOString():l===""&&bm.test(c)&&Array.isArray(u)&&u.every(m=>typeof m=="string"&&!/[\r\n]/.test(m))&&JSON.stringify(u).length<=2e3&&(p=`[${u.map(m=>JSON.stringify(m)).join(", ")}]`),`${f} = ${p??`"[text:${typeof u=="string"?u.length:JSON.stringify(u).length}]"`}`},o=(l,c,u)=>{if(s(r,c)){for(let[f,g]of Object.entries(u))if(!s(r,a(l,f,g)))return}};for(let[l,c]of Object.entries(e)){let u=l!==""&&Object.hasOwn(Ou,l);if(u&&Mu(c))o(l,`[${l}]`,c);else if(u&&Array.isArray(c)&&c.length>0&&c.every(Mu))for(let f of c)o(l,`[[${l}]]`,f);else s(n,a("",l,c));if(i<=0)break}return[...n,...r].join(`
|
|
243
|
+
`)}catch{return`[unparsed:${t.length}]`}}var Yu=async t=>{try{return(await Ft(t)).isFile()?await Xg(t,"utf8"):null}catch{return null}},Ir=t=>Ft(t).then(e=>e.isDirectory(),()=>!1),jn=async t=>{try{return JSON.parse(await Yu(t)??"null")}catch{return null}},Tt=async(t,e=200)=>{try{return(await Hu(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function vm(t,e){if(!(await Ft(t)).isFile())return"";let n=await Uu(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 a=s.toString("utf8");return i>0?a.slice(a.indexOf(`
|
|
244
|
+
`)+1):a}finally{await n.close()}}function km(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:ue(t.cloud?.defaultModel)??null,models:$n(t.models),tts:$n(t.tts),asr:$n(t.asr),specialAgents:$n(t.specialAgents),pluginSettings:$n(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:ue(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(r=>ue(r)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,r])=>({name:ue(n,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(t.channels).map(([n,r])=>({name:ue(n,64)??"[name]",enabled:r?.enabled===!0}))}}var Em=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function Nu(t){let e=[];for(let n of await Tt(t,100)){let r=de(t,n);if(!await Ir(r))continue;let i=await Yu(de(r,"config.toml"));e.push({id:n,config:i===null?null:Sm(i).slice(0,4096),files:(await Tt(r,400)).filter(s=>Em.has(s))})}return e}async function Pu(t){let e=[];for(let n of await Tt(t,300)){let r=await jn(de(t,n,"manifest.json"));r&&e.push({id:ue(r.id)??n,version:ue(r.version,40)??null,name:ue(r.nameEn)??ue(r.name)??null})}return e}var pn=t=>String(t?.code||t?.message||t).slice(0,120);async function _m(t,e,n,r=am){let i=g=>String(g).padStart(2,"0"),s=g=>{let p=new Date(g);return`${p.getFullYear()}${i(p.getMonth()+1)}${i(p.getDate())}${i(p.getHours())}${i(p.getMinutes())}`},a=g=>`${g.slice(0,4)}-${g.slice(4,6)}-${g.slice(6,8)}.log`,o=s(n),l=s(e.getTime()),c=[],u=r,f=!1;try{let g=(await Hu(t)).filter(p=>/^\d{4}-\d{2}-\d{2}\.log$/.test(p)&&p>=a(o)&&p<=a(l)).sort().reverse();for(let p of g){if(f)break;let y=(await vm(de(t,p),om).catch(_=>{if(_?.code==="ENOENT")return"";throw _})).split(`
|
|
245
|
+
`).filter(_=>/^\d{12} /.test(_)&&_.slice(0,12)>=o&&_.slice(0,12)<l),b=y.length;for(;b>0&&Buffer.byteLength(y[b-1])+1<=u;)u-=Buffer.byteLength(y[--b])+1;b>0&&(f=!0),b<y.length&&c.push({date:p.slice(0,10),log:y.slice(b).join(`
|
|
246
|
+
`)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:pn(g)}}return{activity:c.reverse(),...f?{activityTruncated:!0}:{}}}var It=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},$u=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},Ln=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function Cm(t,e,n=Wu,r=xt(e)){let i=de(t,"tangu","state.db"),s=await Ft(i).then(o=>o.isFile(),o=>o?.code==="ENOENT"?!1:pn(o));if(s!==!0)return s===!1?{sessions:[]}:{sessions:[],sessionsError:s};let a;try{let{DatabaseSync:o}=await import("node:sqlite");a=new o(i,{readOnly:!0}),a.exec("PRAGMA busy_timeout = 1500");let c="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",u=[Ln(r),Ln(e.getTime()),xt(e)],f=a.prepare(`SELECT s.id, s.kind, s.parent_session_id, s.app_id, s.title, s.model_id, s.project_name, s.archived, s.created_at, s.updated_at, MAX(m.updated_at) AS changed_at
|
|
247
247
|
FROM chat_messages m JOIN chat_sessions s ON s.id = m.session_id
|
|
248
|
-
WHERE s.kind IN (${
|
|
249
|
-
FROM chat_messages m WHERE m.session_id = ? AND ${
|
|
248
|
+
WHERE s.kind IN (${Iu.map(()=>"?").join(", ")}) AND ${c} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...Iu,...u,n.sessions+1),g=a.prepare(`SELECT m.role, m.content, m.reasoning, m.timestamp, m.model_id, m.is_error, m.tool_calls, length(m.tool_results) AS tool_result_chars, m.attachments, m.agent_slug
|
|
249
|
+
FROM chat_messages m WHERE m.session_id = ? AND ${c} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),p=[],m=0,y=f.length>n.sessions;for(let b of f.slice(0,n.sessions)){let _=g.all(b.id,...u,n.messages+1),h=_.length>n.messages,T=[],v=0;for(let D of _.slice(0,n.messages)){let x=$u(D.tool_calls),L=b.kind==="teamwork"&&D.role==="user"&&lm.test(String(D.content??"")),V={role:ue(D.role,16)??null,at:Number(D.timestamp)||null,agent:ue(D.agent_slug,64),model:ue(D.model_id,128),error:D.is_error?!0:void 0,text:L?void 0:It(D.content,n.textChars),relayChars:L?String(D.content??"").length:void 0,reasoning:It(D.reasoning,n.textChars),tools:x.length?x.map(N=>ue(N?.function?.name??N?.name,80)??"?"):void 0,toolArgChars:x.length?x.reduce((N,Y)=>N+String(Y?.function?.arguments??"").length,0):void 0,toolResultChars:Number(D.tool_result_chars)||void 0,attachments:$u(D.attachments).length||void 0},H=Buffer.byteLength(JSON.stringify(V));if(v+H>n.sessionBytes){h=!0;break}v+=H,T.push(V)}let I={id:ue(b.id,64)??null,kind:ue(b.kind,16)??null,parent:ue(b.parent_session_id,64),app:ue(b.app_id,50)??null,title:It(b.title,200)??null,model:ue(b.model_id,128)??null,project:It(b.project_name,120),archived:b.archived?!0:void 0,createdAt:ue(b.created_at,40)??null,updatedAt:ue(b.updated_at,40)??null,messages:T.reverse(),...h?{olderMessagesDropped:!0}:{}},E=Buffer.byteLength(JSON.stringify(I));if(m+E>n.totalBytes){y=!0;break}m+=E,p.push(I)}return{sessions:p,...y?{sessionsTruncated:!0}:{}}}catch(o){return{sessions:[],sessionsError:pn(o)}}finally{try{a?.close()}catch{}}}async function Am(t,e,n=cm){let r=de(t,"tangu","state.db"),i=await Ft(r).then(a=>a.isFile(),a=>a?.code==="ENOENT"?!1:pn(a));if(i!==!0)return i===!1?{runs:[]}:{runs:[],runsError:i};let s;try{let{DatabaseSync:a}=await import("node:sqlite");s=new a(r,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let l=s.prepare(`SELECT r.id, r.session_id, r.app_id, r.status, r.current_step, r.model_id, substr(r.error, 1, ${Rr}) 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(
|
|
251
|
+
WHERE r.updated_at >= ? AND r.updated_at < ? ORDER BY r.updated_at DESC, r.id LIMIT ?`).all(Ln(xt(e)),Ln(e.getTime()),n.runs+1),c=s.prepare(`SELECT e.type, json_extract(e.payload, '$.name') AS name, json_extract(e.payload, '$.isError') AS failed, json_extract(e.payload, '$.elapsedMs') AS ms,
|
|
252
252
|
json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
|
|
253
253
|
json_extract(e.payload, '$.reasoningTokens') AS reasoning, json_extract(e.payload, '$.llmMs') AS llm_ms, json_extract(e.payload, '$.ttftMs') AS ttft_ms,
|
|
254
|
-
json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${
|
|
255
|
-
FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),u=
|
|
256
|
-
`),...
|
|
257
|
-
WHERE created_at >= ? AND created_at < ? AND (${
|
|
258
|
-
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(En(mt(e)),En(e.getTime()),n.activity+1);y.length>n.activity&&(s.truncated=!0);for(let S of y.slice(0,n.activity))if(!c(s.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?bt(St(S.detail),n.detailChars):void 0,session:ce(S.session_ref,64)}))break}catch(m){s.activityError=Qt(m)}finally{try{p?.close()}catch{}}}for(let p of await wt(ue(r,"project-memory"),100)){let m=ue(r,"project-memory",p);if(!await dr(m))continue;let w=await ur(ue(m,"MEMORY.md"),n.fileChars),y=await Kl(m);if(!w&&!y)continue;let S=(await kn(ue(m,"PROJECT.json")))?.project;if(!c(s.projects,{id:ce(p,64)??null,name:typeof S=="string"?ce(eu(S.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:y,memory:w}))break}for(let p of await wt(ue(r,"teams"),100)){if(!await dr(ue(r,"teams",p)))continue;let m=await ur(ue(r,"teams",p,"TEAM.md"),n.fileChars);if(m&&!c(s.teams,{id:p,files:{"TEAM.md":m}}))break}let h=[];for(let p of await wt(ue(r,"agents"),100)){let m=ue(r,"agents",p);await dr(m)&&h.push({id:p,dir:m,at:Math.max(0,...await Promise.all([...Hl,".memory-state.json"].map(w=>o(ue(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 M of Hl){let E=await ur(ue(m,M),n.fileChars);E&&(y[M]=E)}let S=[];if(await dr(ue(m,"LOG")))for(let M of(await wt(ue(m,"LOG"),400)).filter(E=>/^\d{4}-\d{2}-\d{2}\.md$/.test(E)&&E.slice(0,10)>=i&&E.slice(0,10)<=Tt(e))){let E=await ur(ue(m,"LOG",M),n.logChars);E&&S.push({date:M.slice(0,10),text:E})}let g=(await kn(ue(m,".memory-dream.json")))?.last,j=await Kl(m),x=await Ig(m,n.fileChars);!Object.keys(y).length&&!S.length&&!j&&!x||c(s.agents,{id:p,updatedAt:w?new Date(w).toISOString():null,config:x,state:j,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"?bt(St(g.detail),n.detailChars):void 0}:void 0,files:Object.keys(y).length?y:void 0,log:S.length?S:void 0})}return s}async function cu(t){let e=(await kn(ue(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${jh("sha256").update(Ql()).digest("hex").slice(0,8)}`}async function Dg(t){let{home:e}=t,n=ue(e,"tangu"),r=t.now??new Date,o=s=>t.since?.[s]??mt(r),i=bg(t.engineLogs);return St({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:Vh(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:eu(e),cloudUrl:t.cloudUrl},device:{id:await cu(e),name:Ql()},system:await wg(e),config:pg(await kn(ue(e,"config.json"))),agents:await Wl(ue(n,"agents")),teams:await Wl(ue(n,"teams")),plugins:{desktop:await Vl(ue(e,"plugins")),engine:await Vl(ue(n,"plugins"))},inventory:{skills:await wt(ue(n,"skills")),spaces:await wt(ue(e,"spaces")),themes:await wt(ue(e,"themes"))},...t.activity?{...await gg(ue(e,"activity"),r,o("activity")),activitySince:new Date(o("activity")).toISOString()}:{},...t.sessions?{...await mg(e,r,nu,o("sessions")),sessionsSince:new Date(o("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await Rg(e,r)}:{},...await yg(e,r),runsSince:new Date(mt(r)).toISOString(),...i?{engine:i}:{},sync:{content:Ag(t.contentSync),legacy:xg(t.engineLogs)}})}function lu(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(x=>Yr({baseUrl:x.cloudUrl,vault:Gr,getToken:()=>x.token})),o=e.policyFor??Qi,i=()=>ue(t.homeDir(),"extend-diagnostics.json"),s=()=>{let x=M=>M&&typeof M=="object"?M:{};try{let M=JSON.parse(Lh(i(),"utf8"));return{accounts:x(M?.accounts),sent:x(M?.sent)}}catch{return{accounts:{},sent:{}}}},a=()=>s().accounts,c=(x,M,E)=>{let T=s();T.accounts[x]={...T.accounts[x],...M},Object.assign(T.sent,E),Fh(t.homeDir(),{recursive:!0});let _=`${i()}.${process.pid}.tmp`;Hh(_,JSON.stringify(T,null,2),{encoding:"utf8",mode:384}),Uh(_,i())},l=()=>{let x=t.readCreds();return x.token&&x.cloudUrl?t.accountId():null},u=()=>{let x=l(),M=x?a()[x]??{}:{},E=sr(M.policy);return{signedIn:!!x,enabled:M.enabled===!0,activity:M.activity!==!1,sessions:M.sessions??M.enabled!==!0,memory:M.memory??M.enabled!==!0,lastUploadAt:M.lastUploadAt??null,lastError:M.lastError??null,retainDays:ho,mode:E.mode,intervalHours:E.intervalHours}},f=()=>{try{return Gl(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 M={...t.readCreds()},E=n(),T=s(),_=T.accounts[x],P=M.cloudUrl.replace(/\/+$/,""),q=Ji(_?.file,T.sent[P]??{},E),J=(async()=>{try{let R=await Dg({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:M.cloudUrl,activity:_?.activity!==!1,sessions:_?.sessions===!0,now:E,since:q,engineLogs:f(),contentSync:Nl(),memory:()=>{let oe=l()===x?a()[x]:void 0;return oe?.enabled===!0&&oe.memory===!0}}),Y=await cu(t.homeDir()),re=a()[x];if(l()!==x||re?.enabled!==!0)return!1;if(re.activity===!1)for(let oe of["activity","activityTruncated","activityError","activitySince"])delete R[oe];if(re.sessions!==!0)for(let oe of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete R[oe];re.memory!==!0&&delete R.memory;let X=[],se=Gh(R,X);if(!se)throw new Error("snapshot too large");await Xi(r(M),Y,se,E),p.delete(x);let ee=Ki(s().sent[P]??{},_?.file,q,E,R,X);return c(x,{lastUploadAt:n().getTime(),lastError:void 0,file:ee.file},{[P]:ee.sent}),t.log(`[forsion-extend] diagnostics uploaded (${se.length} bytes)`),!0}catch(R){p.set(x,n().getTime());let Y=String(R?.message||R).slice(0,300);try{c(x,{lastError:Y})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${Y}`),!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 M=await o({...t.readCreds()}),E=l()===x?a()[x]:void 0;if(E?.enabled!==!0)return;M&&(M.mode!==E.policy?.mode||M.intervalHours!==E.policy?.intervalHours)&&c(x,{policy:{mode:M.mode,intervalHours:M.intervalHours}}),M&&E.requestSeen===void 0&&c(x,{requestSeen:M.requestedAt});let T=M??{...sr(E.policy),requestedAt:0},_=T.requestedAt>(E.requestSeen??T.requestedAt),P=E.lastUploadAt??0,q=!P||T.mode==="scheduled"&&n().getTime()-P>=T.intervalHours*tu;if(!_&&!q||n().getTime()-(p.get(x)??-Ll)<Ll)return;await m()&&_&&c(x,{requestSeen:T.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,M)=>{if(!t.isTrustedSender(x))return S;let E=l();if(!E)return u();let T={};typeof M?.enabled=="boolean"&&(T.enabled=M.enabled),T.enabled&&(T.requestSeen=void 0),typeof M?.activity=="boolean"&&(T.activity=M.activity),typeof M?.sessions=="boolean"&&(T.sessions=M.sessions),typeof M?.memory=="boolean"&&(T.memory=M.memory);let _=a()[E];for(let P of["sessions","memory"])T[P]!==void 0||_?.[P]!==void 0||(_?.enabled===!0?T[P]=!1:T.enabled&&(T[P]=!0));return c(E,T),T.enabled&&(p.delete(E),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),j=setInterval(()=>void w(),Kh);return g.unref?.(),j.unref?.(),t.log(`[forsion-extend] diagnostics registered${Gl(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(g),clearInterval(j)},{tick:w,settled:()=>y})}import{randomUUID as ku}from"node:crypto";import{appendFileSync as Bg,existsSync as qg,mkdirSync as ps,readFileSync as Eu,renameSync as _u,rmSync as hs,statSync as Wg,writeFileSync as Cu}from"node:fs";import{lstat as Ru}from"node:fs/promises";import{homedir as Vg,release as Yg}from"node:os";import{join as Cn}from"node:path";var pr={$comment:"\u5E2E\u52A9\u6539\u8FDB Forsion(\u533F\u540D\u9065\u6D4B)\u4E8B\u4EF6\u767D\u540D\u5355 v3(v1\u3001v2 \u539F\u6837\u4FDD\u7559,\u6BCF\u7248\u53EA\u52A0\u4E8B\u4EF6\u3001\u5B57\u6BB5\u4E0E\u679A\u4E3E\u503C;\u5951\u7EA6\u89C1\u540C\u76EE\u5F55 contract.md \xA76\u2013\xA715\u3001v3 \u89C1 \xA716\u2013\xA724)\u3002\u6B63\u5178\u5728\u4ED3\u6839 docs/ToBeImproved/\u9ED8\u8BA4\u6570\u636E\u91C7\u96C6\u65B9\u6848_2026-10-28/telemetry-schema.json;server(src/config/telemetry-schema.json)\u4E0E Forsion-Extend(src/core/telemetry-schema.json)\u5404\u5B58\u4E00\u4EFD\u539F\u6837\u526F\u672C,\u6539\u4E00\u5904\u4E09\u5904\u540C\u6539,\u5E76\u540C\u6B65\u9690\u79C1\u653F\u7B56\u300C\u6539\u8FDB\u6570\u636E\u300D\u4E00\u8282\u3002\u7C7B\u578B:int = 0..2147483647 \u7684\u6574\u6570;bool;enum = \u53EA\u80FD\u53D6\u5217\u51FA\u7684\u503C;id = \u5339\u914D ^[A-Za-z0-9._:/@+-]{1,max}$ \u7684\u77ED\u4E32;text = \u81EA\u7531\u6587\u672C,\u5FC5\u987B\u5148\u8FC7 sanitize \u518D\u622A\u5230 max\u3002\u4E0D\u5728\u8868\u91CC\u7684\u4E8B\u4EF6\u4E0E\u5B57\u6BB5\u4E00\u5F8B\u4E22\u3002",version:3,limits:{maxBatchBytes:65536,maxEvents:200},envelope:{installId:{type:"uuid"},app:{type:"enum",values:["desktop","web","mobile"]},appVersion:{type:"id",max:40},coreVersion:{type:"id",max:40},channel:{type:"enum",values:["stable","beta"]},os:{type:"enum",values:["darwin","win32","linux","android","ios","other"]},osVersion:{type:"id",max:40},arch:{type:"enum",values:["arm64","x64","ia32","other"]},locale:{type:"enum",values:["zh","en"]},region:{type:"enum",values:["CN","other"]}},eventFields:{event:{type:"enum",values:["crash","agent_run","tool_call","perf","feature","approval","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","sync_health","daily_muse","daily_muse_card","daily_memory","daily_judge","daily_human","quota_prompt","plugin_inventory","model_feedback","first_run"]},ts:{type:"iso-time"},sessionId:{type:"uuid"}},events:{crash:{process:{type:"enum",values:["main","renderer","engine","plugin-host","extend","other"]},errorName:{type:"id",max:60},stack:{type:"stack",max:4e3},uptimeS:{type:"int"},exitCode:{type:"int"},reason:{type:"enum",values:["exception","rejection","crashed","oom","killed","abnormal-exit","launch-failed","integrity-failure","other"]},pluginId:{type:"id",max:64}},agent_run:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},mode:{type:"enum",values:["chat","agent","muse","historian","team","task","other"]},steps:{type:"int"},llmCalls:{type:"int"},tokensIn:{type:"int"},tokensOut:{type:"int"},tokensCached:{type:"int"},retries:{type:"int"},durationMs:{type:"int"},outcome:{type:"enum",values:["done","error","aborted","other"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},recallEntries:{type:"int"},recallHistory:{type:"int"},recallTruncated:{type:"bool"},memoryTokens:{type:"int"},humanTokens:{type:"int"},profileTokens:{type:"int"},projectTokens:{type:"int"}},tool_call:{tool:{type:"id",max:80},calls:{type:"int"},failures:{type:"int"},totalMs:{type:"int"},maxMs:{type:"int"},runOutcome:{type:"enum",values:["done","error","aborted","other"]},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},pluginId:{type:"id",max:80}},perf:{kind:{type:"enum",values:["startup","hourly"]},startupMs:{type:"int"},engineReadyMs:{type:"int"},rssMb:{type:"int"},heapMb:{type:"int"},longTasks:{type:"int"}},feature:{name:{type:"enum",values:["space_open","view_open","plugin_open","setting_change"]},kind:{type:"id",max:60},id:{type:"id",max:80},key:{type:"id",max:80},value:{type:"id",max:40}},approval:{tool:{type:"id",max:80},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},reasonKind:{type:"enum",values:["custom-ask","escalate","mode","protected","control","always","other"]},mode:{type:"enum",values:["readonly","auto-edit","full-auto","custom","other"]},asked:{type:"int"},approved:{type:"int"},rejected:{type:"int"},expired:{type:"int"},decideSecTotal:{type:"int"},remoteAnswers:{type:"int"}},plugin_install:{id:{type:"id",max:80},entry:{type:"enum",values:["store","chat-card","muse-card","plugin-onboarding","deps","other"]},kind:{type:"enum",values:["plugin","skill","agent","space","theme","amadeus-plugin","other"]},source:{type:"enum",values:["github","npm","zip","other"]},stage:{type:"enum",values:["resolve","download","install","activate","done"]},outcome:{type:"enum",values:["done","error","canceled"]},errorClass:{type:"enum",values:["timeout","network","http","too-large","not-zip","integrity","identity","version","min-app","platform","deps","builtin","activate","disk","other"]},durationMs:{type:"int"},sizeKb:{type:"int"},restart:{type:"bool"}},plugin_deps:{total:{type:"int"},installed:{type:"int"},failedAt:{type:"int"},outcome:{type:"enum",values:["ready","not-ready","not-running","failed"]}},plugin_lifecycle:{id:{type:"id",max:80},action:{type:"enum",values:["uninstall","enable","disable","blocked"]},blockedReason:{type:"enum",values:["min-app","api","invalid","dev-fileext","deps","other"]},daysSinceInstall:{type:"int"},reason:{type:"enum",values:["unused","broken","slow","mistake"]}},plugin_load:{id:{type:"id",max:80},outcome:{type:"enum",values:["ok","error"]},activateMs:{type:"int"}},update:{target:{type:"enum",values:["app","engine","ui","builtin-plugin","store-plugin","first-boot-prefetch"]},id:{type:"id",max:80},outcome:{type:"enum",values:["available","not-available","staged","applied","current","error","incompatible","rolled-back","timeout","skipped"]},errorClass:{type:"enum",values:["network","http","integrity","signature","version","identity","incompatible","disk","other"]}},onboarding:{mode:{type:"enum",values:["full","returning","brief","update"]},outcome:{type:"enum",values:["finish","skip","error-skip"]},screens:{type:"int"},backJumps:{type:"int"},msStart:{type:"int"},msTheme:{type:"int"},msYou:{type:"int"},msTeam:{type:"int"},msWelcome:{type:"int"},signedIn:{type:"bool"},syncNotes:{type:"bool"},syncAgents:{type:"bool"},syncPlugins:{type:"bool"},addedAgent:{type:"bool"},museOn:{type:"bool"},computerHistoryOn:{type:"bool"},youWritten:{type:"bool"}},guide_tip:{pluginId:{type:"id",max:80},tipId:{type:"id",max:60},result:{type:"enum",values:["ok","learned","mute","gone","missing","replaced","closed"]}},command_use:{id:{type:"id",max:80},source:{type:"enum",values:["palette","hotkey","ribbon","agent","other"]},n:{type:"int"}},app_counts:{achChatSend:{type:"int"},achChatGroup:{type:"int"},achNoteCreate:{type:"int"},achNoteWikilink:{type:"int"},achNoteCanvas:{type:"int"},achBaseCreate:{type:"int"},achSpaceSave:{type:"int"},achSpaceSwitch:{type:"int"},achAgentCreate:{type:"int"},achAutomationCreate:{type:"int"},achMuseOpen:{type:"int"},achComputerUse:{type:"int"},achMarketInstall:{type:"int"},achThemeChange:{type:"int"},achTodoDone:{type:"int"},achCalendarEvent:{type:"int"},achAccountLogin:{type:"int"},achImageGenerate:{type:"int"},achDrawingCreate:{type:"int"},achMiniOpen:{type:"int"},achSpecialEnable:{type:"int"},chatStop:{type:"int"},chatRegenerate:{type:"int"},chatEditResend:{type:"int"},chatTruncateResend:{type:"int"},chatRetry:{type:"int"},chatRewind:{type:"int"},chatBranch:{type:"int"},chatSteer:{type:"int"},chatSteerWithdraw:{type:"int"},chatCompact:{type:"int"},chatRetryFailed:{type:"int"},searchOpen:{type:"int"},searchPick:{type:"int"},searchCloseEmpty:{type:"int"},providerLoginOk:{type:"int"},providerLoginFail:{type:"int"},byokSave:{type:"int"},byokImport:{type:"int"},byokImportStale:{type:"int"},byokDelete:{type:"int"},connTestOk:{type:"int"},connTestFail:{type:"int"},connTestAuthRejected:{type:"int"},modelSwitchUser:{type:"int"},modelSwitchRemember:{type:"int"},engineDefaultModelSet:{type:"int"},homeWidgetAdd:{type:"int"},homeWidgetRemove:{type:"int"},homeWidgetMove:{type:"int"},openNote:{type:"int"},openDatabase:{type:"int"},openDashboard:{type:"int"},openPdf:{type:"int"},openBoard:{type:"int"},openPluginFile:{type:"int"},openOther:{type:"int"}},sync_health:{system:{type:"enum",values:["vault","content","remote"]},day:{type:"id",max:10},cycles:{type:"int"},cycleMsTotal:{type:"int"},errAuth:{type:"int"},errOffline:{type:"int"},errVaultMissing:{type:"int"},errScan:{type:"int"},errMirrorMissing:{type:"int"},errHttp:{type:"int"},errTimeout:{type:"int"},errBlocked:{type:"int"},errOther:{type:"int"},conflicts:{type:"int"},skippedTooLarge:{type:"int"},skippedNotFound:{type:"int"},skippedExists:{type:"int"},skippedOther:{type:"int"},massDeleteGuard:{type:"int"},uploads:{type:"int"},downloads:{type:"int"}},daily_muse:{day:{type:"id",max:10},cyclesRule:{type:"int"},cyclesSchedule:{type:"int"},cyclesHeartbeat:{type:"int"},cyclesRunEnd:{type:"int"},cyclesModeAsk:{type:"int"},cyclesModeAgent:{type:"int"},cyclesModeAuto:{type:"int"},cyclesDone:{type:"int"},cyclesError:{type:"int"},cyclesAborted:{type:"int"},cyclesSilent:{type:"int"},cycleTokens:{type:"int"},cycleMs:{type:"int"},producedCards:{type:"int"},producedDms:{type:"int"},producedTodos:{type:"int"},producedStarters:{type:"int"},inboxMarked:{type:"int"},inboxUnmarked:{type:"int"},skipNoModel:{type:"int"},skipOutsideHours:{type:"int"},skipUserActive:{type:"int"},skipNothingDue:{type:"int"},skipAlreadyRunning:{type:"int"},skipBudgetBillable:{type:"int"},skipBudgetGross:{type:"int"},skipRestartCap:{type:"int"},skipRemoteLock:{type:"int"},skipSleepCleared:{type:"int"},dmProactive:{type:"int"},dmTodo:{type:"int"},dmApproval:{type:"int"},dmCard:{type:"int"},dmNotice:{type:"int"},dmRemind:{type:"int"},dmSuppressed:{type:"int"},dmAwaitingUser:{type:"int"},dmReadIn24h:{type:"int"},dmRepliedIn24h:{type:"int"},feedbackUp:{type:"int"},feedbackDown:{type:"int"},feedbackText:{type:"int"},todoCreated:{type:"int"},todoApproved:{type:"int"},todoInjected:{type:"int"},todoDone:{type:"int"},todoDismissed:{type:"int"},starterCreated:{type:"int"},starterUsed:{type:"int"},starterDismissed:{type:"int"},starterMuted:{type:"int"},ruleCreatedMuse:{type:"int"},ruleCreatedUser:{type:"int"},ruleObserveForced:{type:"int"},rulePromoted:{type:"int"},ruleExtended:{type:"int"},rulePaused:{type:"int"},ruleObservedHits:{type:"int"},approvalByAgent:{type:"int"},approvalUserApproved:{type:"int"},approvalUserRejected:{type:"int"},introAnswered:{type:"int"},introSkipped:{type:"int"},introWhenAnytime:{type:"int"},introWhenDaytime:{type:"int"},introWhenOpen:{type:"int"},introPaceAsNeeded:{type:"int"},introPaceDaily:{type:"int"},introPaceFree:{type:"int"},introFocusSchedule:{type:"int"},introFocusStudy:{type:"int"},introFocusProjects:{type:"int"},introFocusInbox:{type:"int"},introFocusCustom:{type:"int"},summarySent:{type:"int"},summaryProposed:{type:"int"},summaryAdopted:{type:"int"},summaryAskUpgrade:{type:"int"},sleepSet:{type:"int"},digestSent:{type:"int"},gEnabled:{type:"int"},gDaysEnabled:{type:"int"},gModeAsk:{type:"int"},gModeAgent:{type:"int"},gModeAuto:{type:"int"},gNotifyDigest:{type:"int"},gHeartbeatMin:{type:"int"},gMaxDmPerDay:{type:"int"},gOnboardingDay:{type:"int"},gRulesObserving:{type:"int"},gRulesEnabled:{type:"int"}},daily_muse_card:{day:{type:"id",max:10},cardKind:{type:"enum",values:["plugin","feature","inbox-ask","inbox-list","channel","settings","intro","summary","rule","rule-observed"]},created:{type:"int"},accept:{type:"int"},observe:{type:"int"},edit:{type:"int"},dismiss:{type:"int"},open:{type:"int"},apply:{type:"int"},yes:{type:"int"},later:{type:"int"},ignore:{type:"int"},ack:{type:"int"},item:{type:"int"},enable:{type:"int"},extend:{type:"int"},pause:{type:"int"},answer:{type:"int"},skip:{type:"int"},ok:{type:"int"},remove:{type:"int"},installed:{type:"int"},gone:{type:"int"},dismissIrrelevant:{type:"int"},dismissTiming:{type:"int"},dismissFrequent:{type:"int"},dismissKnown:{type:"int"},decideSecTotal:{type:"int"},decidedRemote:{type:"int"},gPendingOver3d:{type:"int"}},daily_memory:{day:{type:"id",max:10},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},addAgent:{type:"int"},addProject:{type:"int"},addPerson:{type:"int"},updateAgent:{type:"int"},updateProject:{type:"int"},updatePerson:{type:"int"},forgetAgent:{type:"int"},forgetProject:{type:"int"},forgetPerson:{type:"int"},moveScope:{type:"int"},srcExplicit:{type:"int"},srcHistorian:{type:"int"},srcDream:{type:"int"},srcManual:{type:"int"},srcRestore:{type:"int"},srcExternalEdit:{type:"int"},srcSync:{type:"int"},srcMigration:{type:"int"},errFull:{type:"int"},errVersionConflict:{type:"int"},errPortraitFull:{type:"int"},userEditAgentWritten7d:{type:"int"},userForgetAgentWritten7d:{type:"int"},userRestoreDreamRetired:{type:"int"},userEdit:{type:"int"},userForget:{type:"int"},userAdd:{type:"int"},userForgetWrong:{type:"int"},userForgetStale:{type:"int"},userForgetUnwanted:{type:"int"},userForgetDuplicate:{type:"int"},retellExisting:{type:"int"},retellForgotten:{type:"int"},candidatesAdded:{type:"int"},dreamAuto:{type:"int"},dreamManual:{type:"int"},dreamArchive:{type:"int"},dreamCompleted:{type:"int"},dreamSkipped:{type:"int"},dreamFailed:{type:"int"},dreamCancelled:{type:"int"},dreamCalls:{type:"int"},dreamSources:{type:"int"},dreamGroups:{type:"int"},dreamMerges:{type:"int"},dreamDiscarded:{type:"int"},dreamToPortrait:{type:"int"},dreamPending:{type:"int"},dreamDeferred:{type:"int"},dreamVerifyFail:{type:"int"},dreamRetried:{type:"int"},dreamMs:{type:"int"},harnessUpsertAgent:{type:"int"},harnessUpsertHistorian:{type:"int"},harnessUpsertMuse:{type:"int"},harnessUpsertUser:{type:"int"},harnessDelete:{type:"int"},harnessRollback:{type:"int"},gEntries:{type:"int"},gCharsPct:{type:"int"},gTombstones:{type:"int"},gCandidatesPending:{type:"int"},gCandidatesOldestDays:{type:"int"},gHarnessEntries:{type:"int"}},daily_judge:{day:{type:"id",max:10},rounds:{type:"int"},roundsIndependent:{type:"int"},roundsAssist:{type:"int"},roundsFork:{type:"int"},isolationSkips:{type:"int"},memCandidates:{type:"int"},projCandidatesAuto:{type:"int"},projCandidatesQueued:{type:"int"},projAdopted:{type:"int"},projDismissed:{type:"int"},projForgotten:{type:"int"},projRestored:{type:"int"},projCompacted:{type:"int"},harnessCandidatesAuto:{type:"int"},harnessCandidatesQueued:{type:"int"},signalStop:{type:"int"},signalToolLoop:{type:"int"},signalNudge:{type:"int"},signalCorrectionDecision:{type:"int"},signalCorrectionLexical:{type:"int"},titleUpdated:{type:"int"},summaryUpdated:{type:"int"},iconUpdated:{type:"int"}},daily_human:{day:{type:"id",max:10},wAgentShared:{type:"int"},wAgentAgent:{type:"int"},wAgentProject:{type:"int"},wAgentPortrait:{type:"int"},wAgentAgentMd:{type:"int"},wAgentMemory:{type:"int"},wUserShared:{type:"int"},wUserAgent:{type:"int"},wUserProject:{type:"int"},wUserPortrait:{type:"int"},wUserAgentMd:{type:"int"},wUserMemory:{type:"int"},srcRemember:{type:"int"},srcDream:{type:"int"},srcMove:{type:"int"},srcPromote:{type:"int"},srcUser:{type:"int"},userUndoAgentWrite7d:{type:"int"},moveScan:{type:"int"},moveMoved:{type:"int"},moveKept:{type:"int"},moveUndo:{type:"int"},promoteToAgentMd:{type:"int"},coldstartAgents:{type:"int"},coldstartPersonWrites:{type:"int"},coldstartRelearned:{type:"int"},mirrorConflicts:{type:"int"},syncConflictCopies:{type:"int"},gHumanMdEntries:{type:"int"},gAgentMdEntries:{type:"int"},gPortraitEntries:{type:"int"},gMemoryEntries:{type:"int"},gCalendarRows:{type:"int"},gAgentsWithHumanMd:{type:"int"},gAgentsTotal:{type:"int"}},quota_prompt:{entry:{type:"enum",values:["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","other"]},shown:{type:"int"},dismiss:{type:"int"},card:{type:"int"},points:{type:"int"},upgrade:{type:"int"},topup:{type:"int"},bgConvert:{type:"int"},bgSettings:{type:"int"},more:{type:"int"}},plugin_inventory:{day:{type:"id",max:10},id:{type:"id",max:80},source:{type:"enum",values:["store","builtin","local"]},installed:{type:"int"},enabled:{type:"int"},localCount:{type:"int"}},model_feedback:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},regenerate:{type:"int"},stop:{type:"int"},editResend:{type:"int"}},first_run:{outcome:{type:"enum",values:["done","error","aborted"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},sinceFirstLaunchS:{type:"int"},durationMs:{type:"int"}}}};var Mg=pr.events,Pg=pr.envelope,ls=pr.limits,fu=pr.version,$g=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ng=/^[A-Za-z0-9._:/@+-]+$/,pu=t=>typeof t=="string"&&$g.test(t),uu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,jg=[[/\/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]"]],hu=t=>jg.reduce((e,[n,r])=>e.replace(n,r),t);function du(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(uu,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=hu(r),(r.length>e?r.slice(0,e):r).replace(uu,"\uFFFD")}var gu=/^pr-[a-f0-9]{48}$/,Fg=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,mu=t=>gu.test(t)||Fg.test(t)||hu(t)===t;function Lg(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function cs(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 pu(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&&Ng.test(e)&&mu(e)?e:void 0;case"text":return typeof e=="string"&&e?du(e,t.max,n):void 0;case"stack":{let r=Lg(e);return r?du(r,t.max,n):void 0}}}function Ht(t,e){let n=typeof t?.event=="string"?Mg[t.event]:void 0;if(!n)return null;let r={},o=t.props&&typeof t.props=="object"?t.props:{};for(let[s,a]of Object.entries(n)){let c=cs(a,o[s],e);c!==void 0&&(r[s]=c)}let i=cs({type:"iso-time"},t.ts);return{event:t.event,ts:i??new Date().toISOString(),...pu(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function yu(t){let e={};for(let[n,r]of Object.entries(Pg)){if(n==="installId")continue;let o=cs(r,t[n]);e[n]=typeof o=="string"?o:null}return e}function wu(t,e){if(e==="aborted")return"aborted";if(!t)return;let n=t.toLowerCase();return/abort|cancel/.test(n)?"aborted":/timeout|timed out|etimedout/.test(n)?"timeout":/token_quota_exceeded/.test(n)?"quota":/\b429\b|rate.?limit|too many requests|quota/.test(n)?"rate_limit":/\b40[13]\b|unauthori[sz]ed|forbidden|invalid api key|authentication/.test(n)?"auth":/context.{0,20}(length|window|too long)|maximum context|too many tokens|prompt is too long/.test(n)?"context_length":/econn|enotfound|eai_again|socket|network|fetch failed|getaddrinfo/.test(n)?"network":/\b5\d\d\b|upstream|bad gateway|overloaded|service unavailable/.test(n)?"upstream":/tool/.test(n)?"tool":"other"}function bu(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 Ug=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function us(t,e){if(typeof t!="string"||!t)return;let n=So(t);if((n==="codex"||n==="forsion"&&gu.test(t))&&(e===void 0||e===n))return t;let o=t.slice(t.lastIndexOf("/")+1);return Ug.test(o)?o:void 0}function ds(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function fs(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}var Hg=/^market-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i,zg=/^[a-z0-9][a-z0-9-]{0,79}$/;function Su(t,e){if(typeof t!="string"||!t)return;let n=Hg.exec(t);if(n)return n[1].toLowerCase();if((e===!0||e===1)&&t.length<=80&&zg.test(t)&&mu(t))return t}function vu(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var Gg=10*6e4,Jg=6e4,Kg=50,Au=1024*1024,Xg=168*36e5,xu=15e3,Zg=200,Qg=2e3,gs=7,em=5e3,Tu=864e5,tm=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","quota_prompt","plugin_inventory","model_feedback","first_run"]),nm=new Set(["shown","dismiss","card","points","upgrade","topup","bgConvert","bgSettings","more"]),rm=1e3,Iu=36e5,ms=2,ys={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},om=new Set(["custom-ask","escalate","mode","protected","control","always"]);function im(t){let e=t.props&&typeof t.props=="object"?t.props:{};if(t.event==="model_feedback"){let n=typeof e.modelId=="string"?e.modelId:void 0,r=us(n,typeof e.providerKind=="string"?e.providerKind:"other");return r?{...t,props:{...e,modelId:r,providerKind:typeof e.providerKind=="string"?e.providerKind:So(n)}}:null}if(t.event==="plugin_inventory"){if(!hn(e.day))return null;if(e.source==="local"||e.id==="local")return{...t,props:{day:e.day,id:"local",source:"local",localCount:e.localCount}};let n=typeof e.id=="string"?e.id:"";return(e.source==="store"?!sm.test(n):e.source!=="builtin"||!(n.length<=80&&am.test(n)))?null:{...t,props:{day:e.day,id:n,source:e.source,installed:e.installed,enabled:e.enabled}}}return t}var sm=/^(?:market-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,am=/^[a-z0-9][a-z0-9-]{0,79}$/,cm={model_feedback:"modelId",plugin_inventory:"id",quota_prompt:"entry"},lm=new Set(["readonly","auto-edit","full-auto","custom"]),Du=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),ws=t=>({at:Du(t),id:"~"}),_n=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function um(t,e,n,r){let o=Cn(t,"tangu","state.db");if(!await Ru(o).then(s=>s.isFile(),()=>!1))return{events:[],cursor:e};let i;try{let{DatabaseSync:s}=await import("node:sqlite");i=new s(o,{readOnly:!0}),i.exec("PRAGMA busy_timeout = 1500");let a=i.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, ${Rr}) AS error
|
|
255
|
+
FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),u=y=>typeof y=="number"&&Number.isFinite(y)&&y>0?y:0,f=y=>y||void 0,g=[],p=0,m=l.length>n.runs;for(let y of l.slice(0,n.runs)){let b={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},_=new Map,h=[],T=0,v=c.all(y.id,n.events+1),I=v.length>n.events;for(let x of v.slice(0,n.events))if(x.type==="usage")b.llmCalls++,b.prompt+=u(x.prompt),b.completion+=u(x.completion),b.cached+=u(x.cached),b.reasoning+=u(x.reasoning),b.llmMs+=u(x.llm_ms),b.ttftMaxMs=Math.max(b.ttftMaxMs,u(x.ttft_ms)),b.requestMaxBytes=Math.max(b.requestMaxBytes,u(x.request_bytes));else if(x.type==="tool_result"){let L=ue(x.name,80)??"?",V=_.get(L)??(_.size<n.tools?{name:L,n:0,ms:0,maxMs:0}:void 0);if(!V){I=!0;continue}_.set(L,V),V.n++,x.failed&&(V.errors=(V.errors??0)+1),V.ms+=u(x.ms),V.maxMs=Math.max(V.maxMs,u(x.ms))}else if(x.type==="error"){let L=qi(x.error,n.errorChars);L&&!h.includes(L)&&h.length<3&&h.push(L)}else x.phase==="llm_retry"&&T++;let E={id:ue(y.id,64)??null,session:ue(y.session_id,64)??null,kind:ue(y.kind,16),app:ue(y.app_id,50),model:ue(y.model_id,128),status:ue(y.status,16)??null,error:qi(y.error,n.errorChars),createdAt:ue(y.created_at,40)??null,updatedAt:ue(y.updated_at,40)??null,steps:f(u(y.current_step)),tokens:f(u(y.tokens_total)),retries:f(T),...Object.fromEntries(Object.entries(b).map(([x,L])=>[x,f(L)])),errors:h.length?h:void 0,tools:_.size?[..._.values()]:void 0,partial:I||void 0},D=Buffer.byteLength(JSON.stringify(E));if(p+D>n.totalBytes){m=!0;break}p+=D,g.push(E)}return{runs:g,...m?{runsTruncated:!0}:{}}}catch(a){return{runs:[],runsError:pn(a)}}finally{try{s?.close()}catch{}}}async function xm(t){let e=i=>Math.round(i/1048576),n=i=>Ft(i).then(s=>s.isFile()?s.size:0,()=>0),r=de(t,"tangu","state.db");return{cpus:Qg().length,memTotalMB:e(nm()),memFreeMB:e(em()),diskFreeMB:await Zg(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 ju=t=>typeof t.diagnosticLogs=="function";function Tm(t,e=um){let n=t?.engine;if(!n||typeof n!="object")return null;let r=(Array.isArray(n.lines)?n.lines:[]).filter(l=>typeof l=="string"&&!!l),i=r.map(l=>qi(l,Lo)??""),s=i.some((l,c)=>l.length>Lo||r[c].length>Rr),a=i.length,o=e;for(;a>0&&Buffer.byteLength(i[a-1])+1<=o;)o-=Buffer.byteLength(i[--a])+1;return a>0&&(s=!0),{state:ue(n.state,32)??null,lastError:qi(n.lastError,Lo)??null,log:i.slice(a).join(`
|
|
256
|
+
`),...s?{logTruncated:!0}:{}}}var Ho={errors:20,errorChars:300,agents:100},Im=t=>Vu(Gu(t,!1).replace(/[^\s"'`<>()[\]{},;]*\/[^\s"'`<>()[\]{},;]*/g,e=>Fo.test(e)?e:"[path]")),Rm=(t,e=[],n=Ho.errorChars)=>It(Im(ku(Rt(t),e.map(r=>Rt(r)))),n)??"",Je=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?Math.round(t):0,Bi=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?new Date(t).toISOString():null,Ju=t=>{let e=t&&typeof t=="object"?t:{};return Object.fromEntries(vu.flatMap(n=>Je(e[n])?[[n,Je(e[n])]]:[]))},Lu=t=>{let e=t;return e&&typeof e=="object"?{at:Bi(e.at),ms:Je(e.ms),completed:e.completed===!0,...Ju(e.counts)}:null},Dm=Object.fromEntries(Lt.map(t=>[t.path,t.id])),Om=new Set(["idle","scanning","syncing","paused"]),Mm=new Set(["queued","active","done","failed","paused","conflict"]);function Nm(t,e){let n=(Array.isArray(t)?t:[]).filter(o=>!!o&&typeof o.source=="string"&&typeof o.target=="string"),r=o=>o===void 0?null:o==="default"?"shared":o==="off"?"off":e&&o===`device-${e}`?"device":/^device-/.test(o)?"other-device":"unknown",i={other:r(n.find(o=>o.source==="")?.target)};for(let o of Lt)i[o.id]=r(Mn(o.path,n)?.target);let s={},a={};for(let o of n){if(o.source===""||Dm[o.source])continue;let l=Ar(o.source);if(l&&Object.keys(s).length<Ho.agents)s[l]=r(o.target);else if(!l){let c=r(o.target)??"unknown";a[c]=(a[c]??0)+1}}return{...i,agentRules:s,folderRules:a,count:n.length}}function Pm(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(([a,o])=>Mm.has(a)&&Je(o)).map(([a,o])=>[a,Je(o)])):{},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"&&Om.has(e.phase)?e.phase:null,revision:Je(e.revision),rules:Nm(e.rules,n),backlog:r?{jobs:i,blocked:Je(r.blocked),pendingUploads:Je(r.pendingUploads),unconfirmed:Je(r.unconfirmed),trash:Je(r.trash),awaitingBytes:Je(r.awaitingBytes),dirty:Je(r.dirty)}:null,archive:e.archive==="running"||e.archive==="done"?e.archive:null,since:Bi(e.since),lastRun:Lu(e.lastRun),runs:(Array.isArray(e.runs)?e.runs:[]).slice(-20).map(Lu).filter(Boolean),totals:{runs:Je(s.runs),completedRuns:Je(s.completedRuns),idleRuns:Je(s.idleRuns),...Ju(s)},errors:(Array.isArray(e.errors)?e.errors:[]).slice(-Ho.errors).flatMap(a=>{if(!a||typeof a!="object"||typeof a.text!="string"||!a.text)return[];let o=Array.isArray(a.paths)?a.paths.filter(l=>typeof l=="string"):[];return[{first:Bi(a.first),at:Bi(a.at),n:Je(a.n)||1,kind:ki(a.text)??"other",text:Rm(a.text,o)}]})}}function $m(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 jm(t,e=pm){let n;try{n=Ni(t)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof n[r]=="string"&&n[r]?[[r,n[r]]]:[]))}async function Ku(t,e=fm){try{if(!(await Ft(t)).isFile())return null;let n=await Uu(t,Au.O_RDONLY|(Au.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 Tr=async(t,e)=>{let n=await Ku(t);return n?It(Rt(n),e):void 0};async function Lm(t,e){let n=await Ku(de(t,"config.toml")),r=Object.entries(n?jm(n):{}).map(([i,s])=>[i,It(Rt(s),e)??""]);return r.length?Object.fromEntries(r):void 0}async function Fu(t){let e=await jn(de(t,".memory-state.json"));if(!e||typeof e!="object")return;let n=r=>Array.isArray(r)?r.length:0;return{entries:n(e.entries),tombstones:n(e.tombstones),revisions:n(e.revisions),processedCandidates:n(e.processedCandidateIds),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:null,projectionPending:e.projectionPending===!0?!0:void 0}}async function Fm(t,e,n=dm){let r=de(t,"tangu"),i=p=>Ft(p).then(m=>m.isFile()?m.mtimeMs:0,()=>0),s=jt(new Date(xt(e))),a={agents:[],teams:[],projects:[],activity:[]},o=n.totalBytes,l=(p,m)=>{let y=Buffer.byteLength(JSON.stringify(m))+1;return y>o?(a.truncated=!0,!1):(o-=y,p.push(m),!0)},c=await Tr(de(r,"USER.md"),n.fileChars);c&&l([],c)&&(a.user=c);let u=de(r,"state.db"),f=await Ft(u).then(p=>p.isFile(),p=>p?.code==="ENOENT"?!1:pn(p));if(typeof f=="string")a.activityError=f;else if(f){let p;try{let{DatabaseSync:m}=await import("node:sqlite");p=new m(u,{readOnly:!0}),p.exec("PRAGMA busy_timeout = 1500");let b=p.prepare(`SELECT agent, action, substr(detail, 1, ${Rr}) AS detail, session_ref, created_at FROM special_agent_log
|
|
257
|
+
WHERE created_at >= ? AND created_at < ? AND (${hm.map(_=>`action GLOB '${_}*'`).join(" OR ")})
|
|
258
|
+
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(Ln(xt(e)),Ln(e.getTime()),n.activity+1);b.length>n.activity&&(a.truncated=!0);for(let _ of b.slice(0,n.activity))if(!l(a.activity,{at:ue(_.created_at,40)??null,agent:ue(_.agent,64)??null,action:ue(_.action,64)??null,detail:typeof _.detail=="string"&&_.detail?It(Rt(_.detail),n.detailChars):void 0,session:ue(_.session_ref,64)}))break}catch(m){a.activityError=pn(m)}finally{try{p?.close()}catch{}}}for(let p of await Tt(de(r,"project-memory"),100)){let m=de(r,"project-memory",p);if(!await Ir(m))continue;let y=await Tr(de(m,"MEMORY.md"),n.fileChars),b=await Fu(m);if(!y&&!b)continue;let _=(await jn(de(m,"PROJECT.json")))?.project;if(!l(a.projects,{id:ue(p,64)??null,name:typeof _=="string"?ue(Bu(_.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:b,memory:y}))break}for(let p of await Tt(de(r,"teams"),100)){if(!await Ir(de(r,"teams",p)))continue;let m=await Tr(de(r,"teams",p,"TEAM.md"),n.fileChars);if(m&&!l(a.teams,{id:p,files:{"TEAM.md":m}}))break}let g=[];for(let p of await Tt(de(r,"agents"),100)){let m=de(r,"agents",p);await Ir(m)&&g.push({id:p,dir:m,at:Math.max(0,...await Promise.all([...Ru,".memory-state.json"].map(y=>i(de(m,y)))))})}for(let{id:p,dir:m,at:y}of g.sort((b,_)=>_.at-b.at||b.id.localeCompare(_.id))){let b={};for(let I of Ru){let E=await Tr(de(m,I),n.fileChars);E&&(b[I]=E)}let _=[];if(await Ir(de(m,"LOG")))for(let I of(await Tt(de(m,"LOG"),400)).filter(E=>/^\d{4}-\d{2}-\d{2}\.md$/.test(E)&&E.slice(0,10)>=s&&E.slice(0,10)<=jt(e))){let E=await Tr(de(m,"LOG",I),n.logChars);E&&_.push({date:I.slice(0,10),text:E})}let h=(await jn(de(m,".memory-dream.json")))?.last,T=await Fu(m),v=await Lm(m,n.fileChars);!Object.keys(b).length&&!_.length&&!T&&!v||l(a.agents,{id:p,updatedAt:y?new Date(y).toISOString():null,config:v,state:T,dream:h&&typeof h=="object"?{state:ue(h.state,32),startedAt:ue(h.startedAt,40),finishedAt:ue(h.finishedAt,40),calls:typeof h.calls=="number"?h.calls:void 0,detail:typeof h.detail=="string"?It(Rt(h.detail),n.detailChars):void 0}:void 0,files:Object.keys(b).length?b:void 0,log:_.length?_:void 0})}return a}async function Xu(t){let e=(await jn(de(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Gg("sha256").update(zu()).digest("hex").slice(0,8)}`}async function Um(t){let{home:e}=t,n=de(e,"tangu"),r=t.now??new Date,i=a=>t.since?.[a]??xt(r),s=Tm(t.engineLogs);return Rt({schema:4,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:tm(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:Bu(e),cloudUrl:t.cloudUrl},device:{id:await Xu(e),name:zu()},system:await xm(e),config:km(await jn(de(e,"config.json"))),agents:await Nu(de(n,"agents")),teams:await Nu(de(n,"teams")),plugins:{desktop:await Pu(de(e,"plugins")),engine:await Pu(de(n,"plugins"))},inventory:{skills:await Tt(de(n,"skills")),spaces:await Tt(de(e,"spaces")),themes:await Tt(de(e,"themes"))},...t.activity?{...await _m(de(e,"activity"),r,i("activity")),activitySince:new Date(i("activity")).toISOString()}:{},...t.sessions?{...await Cm(e,r,Wu,i("sessions")),sessionsSince:new Date(i("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await Fm(e,r)}:{},...await Am(e,r),runsSince:new Date(xt(r)).toISOString(),...s?{engine:s}:{},sync:{content:Pm(t.contentSync),legacy:$m(t.engineLogs)}})}function Zu(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(v=>gi({baseUrl:v.cloudUrl,vault:mi,getToken:()=>v.token})),i=e.policyFor??Io,s=()=>de(t.homeDir(),"extend-diagnostics.json"),a=()=>{let v=I=>I&&typeof I=="object"?I:{};try{let I=JSON.parse(Yg(s(),"utf8"));return{accounts:v(I?.accounts),sent:v(I?.sent)}}catch{return{accounts:{},sent:{}}}},o=()=>a().accounts,l=(v,I,E)=>{let D=a();D.accounts[v]={...D.accounts[v],...I},Object.assign(D.sent,E),Vg(t.homeDir(),{recursive:!0});let x=`${s()}.${process.pid}.tmp`;Kg(x,JSON.stringify(D,null,2),{encoding:"utf8",mode:384}),Jg(x,s())},c=()=>{let v=t.readCreds();return v.token&&v.cloudUrl?t.accountId():null},u=()=>{let v=c(),I=v?o()[v]??{}:{},E=_r(I.policy);return{signedIn:!!v,enabled:I.enabled===!0,activity:I.activity!==!1,sessions:I.sessions??I.enabled!==!0,memory:I.memory??I.enabled!==!0,lastUploadAt:I.lastUploadAt??null,lastError:I.lastError??null,retainDays:$i,mode:E.mode,intervalHours:E.intervalHours}},f=()=>{try{return ju(t)?t.diagnosticLogs():null}catch{return null}},g=null,p=new Map,m=async()=>{let v=c();if(!v)return!1;if(g)return g.id===v?g.done:(await g.done,m());let I={...t.readCreds()},E=n(),D=a(),x=D.accounts[v],L=I.cloudUrl.replace(/\/+$/,""),V=Co(x?.file,D.sent[L]??{},E),H=(async()=>{try{let N=await Um({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:I.cloudUrl,activity:x?.activity!==!1,sessions:x?.sessions===!0,now:E,since:V,engineLogs:f(),contentSync:Cu(),memory:()=>{let ae=c()===v?o()[v]:void 0;return ae?.enabled===!0&&ae.memory===!0}}),Y=await Xu(t.homeDir()),ee=o()[v];if(c()!==v||ee?.enabled!==!0)return!1;if(ee.activity===!1)for(let ae of["activity","activityTruncated","activityError","activitySince"])delete N[ae];if(ee.sessions!==!0)for(let ae of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete N[ae];ee.memory!==!0&&delete N.memory;let J=[],se=rm(N,J);if(!se)throw new Error("snapshot too large");await xo(r(I),Y,se,E),p.delete(v);let te=Ao(a().sent[L]??{},x?.file,V,E,N,J);return l(v,{lastUploadAt:n().getTime(),lastError:void 0,file:te.file},{[L]:te.sent}),t.log(`[forsion-extend] diagnostics uploaded (${se.length} bytes)`),!0}catch(N){p.set(v,n().getTime());let Y=String(N?.message||N).slice(0,300);try{l(v,{lastError:Y})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${Y}`),!1}finally{g=null}})();return g={id:v,done:H},H},y=async()=>{try{let v=c();if(!v||o()[v]?.enabled!==!0)return;let I=await i({...t.readCreds()}),E=c()===v?o()[v]:void 0;if(E?.enabled!==!0)return;I&&(I.mode!==E.policy?.mode||I.intervalHours!==E.policy?.intervalHours)&&l(v,{policy:{mode:I.mode,intervalHours:I.intervalHours}}),I&&E.requestSeen===void 0&&l(v,{requestSeen:I.requestedAt});let D=I??{..._r(E.policy),requestedAt:0},x=D.requestedAt>(E.requestSeen??D.requestedAt),L=E.lastUploadAt??0,V=!L||D.mode==="scheduled"&&n().getTime()-L>=D.intervalHours*qu;if(!x&&!V||n().getTime()-(p.get(v)??-Tu)<Tu)return;await m()&&x&&l(v,{requestSeen:D.requestedAt})}catch(v){t.log(`[forsion-extend] diagnostics tick failed: ${String(v?.message||v)}`)}},b=Promise.resolve(),_={ok:!1,error:"untrusted"};t.handle("diagnostics:get",v=>t.isTrustedSender(v)?u():_),t.handle("diagnostics:set",(v,I)=>{if(!t.isTrustedSender(v))return _;let E=c();if(!E)return u();let D={};typeof I?.enabled=="boolean"&&(D.enabled=I.enabled),D.enabled&&(D.requestSeen=void 0),typeof I?.activity=="boolean"&&(D.activity=I.activity),typeof I?.sessions=="boolean"&&(D.sessions=I.sessions),typeof I?.memory=="boolean"&&(D.memory=I.memory);let x=o()[E];for(let L of["sessions","memory"])D[L]!==void 0||x?.[L]!==void 0||(x?.enabled===!0?D[L]=!1:D.enabled&&(D[L]=!0));return l(E,D),D.enabled&&(p.delete(E),b=Promise.all([b,y()]).then(()=>{})),u()}),t.handle("diagnostics:uploadNow",async v=>t.isTrustedSender(v)?(u().enabled&&await m(),u()):_);let h=setTimeout(()=>void y(),im),T=setInterval(()=>void y(),sm);return h.unref?.(),T.unref?.(),t.log(`[forsion-extend] diagnostics registered${ju(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(h),clearInterval(T)},{tick:y,settled:()=>b})}import{randomUUID as dd}from"node:crypto";import{appendFileSync as Zm,existsSync as Qm,mkdirSync as Vo,readFileSync as fd,renameSync as pd,rmSync as Yo,statSync as ey,writeFileSync as hd}from"node:fs";import{lstat as bd}from"node:fs/promises";import{homedir as ty,release as ny}from"node:os";import{join as Un}from"node:path";var Dr={$comment:"\u5E2E\u52A9\u6539\u8FDB Forsion(\u533F\u540D\u9065\u6D4B)\u4E8B\u4EF6\u767D\u540D\u5355 v3(v1\u3001v2 \u539F\u6837\u4FDD\u7559,\u6BCF\u7248\u53EA\u52A0\u4E8B\u4EF6\u3001\u5B57\u6BB5\u4E0E\u679A\u4E3E\u503C;\u5951\u7EA6\u89C1\u540C\u76EE\u5F55 contract.md \xA76\u2013\xA715\u3001v3 \u89C1 \xA716\u2013\xA724)\u3002\u6B63\u5178\u5728\u4ED3\u6839 docs/ToBeImproved/\u9ED8\u8BA4\u6570\u636E\u91C7\u96C6\u65B9\u6848_2026-10-28/telemetry-schema.json;server(src/config/telemetry-schema.json)\u4E0E Forsion-Extend(src/core/telemetry-schema.json)\u5404\u5B58\u4E00\u4EFD\u539F\u6837\u526F\u672C,\u6539\u4E00\u5904\u4E09\u5904\u540C\u6539,\u5E76\u540C\u6B65\u9690\u79C1\u653F\u7B56\u300C\u6539\u8FDB\u6570\u636E\u300D\u4E00\u8282\u3002\u7C7B\u578B:int = 0..2147483647 \u7684\u6574\u6570;bool;enum = \u53EA\u80FD\u53D6\u5217\u51FA\u7684\u503C;id = \u5339\u914D ^[A-Za-z0-9._:/@+-]{1,max}$ \u7684\u77ED\u4E32;text = \u81EA\u7531\u6587\u672C,\u5FC5\u987B\u5148\u8FC7 sanitize \u518D\u622A\u5230 max\u3002\u4E0D\u5728\u8868\u91CC\u7684\u4E8B\u4EF6\u4E0E\u5B57\u6BB5\u4E00\u5F8B\u4E22\u3002",version:3,limits:{maxBatchBytes:65536,maxEvents:200},envelope:{installId:{type:"uuid"},app:{type:"enum",values:["desktop","web","mobile"]},appVersion:{type:"id",max:40},coreVersion:{type:"id",max:40},channel:{type:"enum",values:["stable","beta"]},os:{type:"enum",values:["darwin","win32","linux","android","ios","other"]},osVersion:{type:"id",max:40},arch:{type:"enum",values:["arm64","x64","ia32","other"]},locale:{type:"enum",values:["zh","en"]},region:{type:"enum",values:["CN","other"]}},eventFields:{event:{type:"enum",values:["crash","agent_run","tool_call","perf","feature","approval","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","sync_health","daily_muse","daily_muse_card","daily_memory","daily_judge","daily_human","quota_prompt","plugin_inventory","model_feedback","first_run"]},ts:{type:"iso-time"},sessionId:{type:"uuid"}},events:{crash:{process:{type:"enum",values:["main","renderer","engine","plugin-host","extend","other"]},errorName:{type:"id",max:60},stack:{type:"stack",max:4e3},uptimeS:{type:"int"},exitCode:{type:"int"},reason:{type:"enum",values:["exception","rejection","crashed","oom","killed","abnormal-exit","launch-failed","integrity-failure","other"]},pluginId:{type:"id",max:64}},agent_run:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},mode:{type:"enum",values:["chat","agent","muse","historian","team","task","other"]},steps:{type:"int"},llmCalls:{type:"int"},tokensIn:{type:"int"},tokensOut:{type:"int"},tokensCached:{type:"int"},retries:{type:"int"},durationMs:{type:"int"},outcome:{type:"enum",values:["done","error","aborted","other"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},recallEntries:{type:"int"},recallHistory:{type:"int"},recallTruncated:{type:"bool"},memoryTokens:{type:"int"},humanTokens:{type:"int"},profileTokens:{type:"int"},projectTokens:{type:"int"}},tool_call:{tool:{type:"id",max:80},calls:{type:"int"},failures:{type:"int"},totalMs:{type:"int"},maxMs:{type:"int"},runOutcome:{type:"enum",values:["done","error","aborted","other"]},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},pluginId:{type:"id",max:80}},perf:{kind:{type:"enum",values:["startup","hourly"]},startupMs:{type:"int"},engineReadyMs:{type:"int"},rssMb:{type:"int"},heapMb:{type:"int"},longTasks:{type:"int"}},feature:{name:{type:"enum",values:["space_open","view_open","plugin_open","setting_change"]},kind:{type:"id",max:60},id:{type:"id",max:80},key:{type:"id",max:80},value:{type:"id",max:40}},approval:{tool:{type:"id",max:80},toolSource:{type:"enum",values:["builtin","mcp","plugin","other"]},reasonKind:{type:"enum",values:["custom-ask","escalate","mode","protected","control","always","other"]},mode:{type:"enum",values:["readonly","auto-edit","full-auto","custom","other"]},asked:{type:"int"},approved:{type:"int"},rejected:{type:"int"},expired:{type:"int"},decideSecTotal:{type:"int"},remoteAnswers:{type:"int"}},plugin_install:{id:{type:"id",max:80},entry:{type:"enum",values:["store","chat-card","muse-card","plugin-onboarding","deps","other"]},kind:{type:"enum",values:["plugin","skill","agent","space","theme","amadeus-plugin","other"]},source:{type:"enum",values:["github","npm","zip","other"]},stage:{type:"enum",values:["resolve","download","install","activate","done"]},outcome:{type:"enum",values:["done","error","canceled"]},errorClass:{type:"enum",values:["timeout","network","http","too-large","not-zip","integrity","identity","version","min-app","platform","deps","builtin","activate","disk","other"]},durationMs:{type:"int"},sizeKb:{type:"int"},restart:{type:"bool"}},plugin_deps:{total:{type:"int"},installed:{type:"int"},failedAt:{type:"int"},outcome:{type:"enum",values:["ready","not-ready","not-running","failed"]}},plugin_lifecycle:{id:{type:"id",max:80},action:{type:"enum",values:["uninstall","enable","disable","blocked"]},blockedReason:{type:"enum",values:["min-app","api","invalid","dev-fileext","deps","other"]},daysSinceInstall:{type:"int"},reason:{type:"enum",values:["unused","broken","slow","mistake"]}},plugin_load:{id:{type:"id",max:80},outcome:{type:"enum",values:["ok","error"]},activateMs:{type:"int"}},update:{target:{type:"enum",values:["app","engine","ui","builtin-plugin","store-plugin","first-boot-prefetch"]},id:{type:"id",max:80},outcome:{type:"enum",values:["available","not-available","staged","applied","current","error","incompatible","rolled-back","timeout","skipped"]},errorClass:{type:"enum",values:["network","http","integrity","signature","version","identity","incompatible","disk","other"]}},onboarding:{mode:{type:"enum",values:["full","returning","brief","update"]},outcome:{type:"enum",values:["finish","skip","error-skip"]},screens:{type:"int"},backJumps:{type:"int"},msStart:{type:"int"},msTheme:{type:"int"},msYou:{type:"int"},msTeam:{type:"int"},msWelcome:{type:"int"},signedIn:{type:"bool"},syncNotes:{type:"bool"},syncAgents:{type:"bool"},syncPlugins:{type:"bool"},addedAgent:{type:"bool"},museOn:{type:"bool"},computerHistoryOn:{type:"bool"},youWritten:{type:"bool"}},guide_tip:{pluginId:{type:"id",max:80},tipId:{type:"id",max:60},result:{type:"enum",values:["ok","learned","mute","gone","missing","replaced","closed"]}},command_use:{id:{type:"id",max:80},source:{type:"enum",values:["palette","hotkey","ribbon","agent","other"]},n:{type:"int"}},app_counts:{achChatSend:{type:"int"},achChatGroup:{type:"int"},achNoteCreate:{type:"int"},achNoteWikilink:{type:"int"},achNoteCanvas:{type:"int"},achBaseCreate:{type:"int"},achSpaceSave:{type:"int"},achSpaceSwitch:{type:"int"},achAgentCreate:{type:"int"},achAutomationCreate:{type:"int"},achMuseOpen:{type:"int"},achComputerUse:{type:"int"},achMarketInstall:{type:"int"},achThemeChange:{type:"int"},achTodoDone:{type:"int"},achCalendarEvent:{type:"int"},achAccountLogin:{type:"int"},achImageGenerate:{type:"int"},achDrawingCreate:{type:"int"},achMiniOpen:{type:"int"},achSpecialEnable:{type:"int"},chatStop:{type:"int"},chatRegenerate:{type:"int"},chatEditResend:{type:"int"},chatTruncateResend:{type:"int"},chatRetry:{type:"int"},chatRewind:{type:"int"},chatBranch:{type:"int"},chatSteer:{type:"int"},chatSteerWithdraw:{type:"int"},chatCompact:{type:"int"},chatRetryFailed:{type:"int"},searchOpen:{type:"int"},searchPick:{type:"int"},searchCloseEmpty:{type:"int"},providerLoginOk:{type:"int"},providerLoginFail:{type:"int"},byokSave:{type:"int"},byokImport:{type:"int"},byokImportStale:{type:"int"},byokDelete:{type:"int"},connTestOk:{type:"int"},connTestFail:{type:"int"},connTestAuthRejected:{type:"int"},modelSwitchUser:{type:"int"},modelSwitchRemember:{type:"int"},engineDefaultModelSet:{type:"int"},homeWidgetAdd:{type:"int"},homeWidgetRemove:{type:"int"},homeWidgetMove:{type:"int"},openNote:{type:"int"},openDatabase:{type:"int"},openDashboard:{type:"int"},openPdf:{type:"int"},openBoard:{type:"int"},openPluginFile:{type:"int"},openOther:{type:"int"}},sync_health:{system:{type:"enum",values:["vault","content","remote"]},day:{type:"id",max:10},cycles:{type:"int"},cycleMsTotal:{type:"int"},errAuth:{type:"int"},errOffline:{type:"int"},errVaultMissing:{type:"int"},errScan:{type:"int"},errMirrorMissing:{type:"int"},errHttp:{type:"int"},errTimeout:{type:"int"},errBlocked:{type:"int"},errOther:{type:"int"},conflicts:{type:"int"},skippedTooLarge:{type:"int"},skippedNotFound:{type:"int"},skippedExists:{type:"int"},skippedOther:{type:"int"},massDeleteGuard:{type:"int"},uploads:{type:"int"},downloads:{type:"int"}},daily_muse:{day:{type:"id",max:10},cyclesRule:{type:"int"},cyclesSchedule:{type:"int"},cyclesHeartbeat:{type:"int"},cyclesRunEnd:{type:"int"},cyclesModeAsk:{type:"int"},cyclesModeAgent:{type:"int"},cyclesModeAuto:{type:"int"},cyclesDone:{type:"int"},cyclesError:{type:"int"},cyclesAborted:{type:"int"},cyclesSilent:{type:"int"},cycleTokens:{type:"int"},cycleMs:{type:"int"},producedCards:{type:"int"},producedDms:{type:"int"},producedTodos:{type:"int"},producedStarters:{type:"int"},inboxMarked:{type:"int"},inboxUnmarked:{type:"int"},skipNoModel:{type:"int"},skipOutsideHours:{type:"int"},skipUserActive:{type:"int"},skipNothingDue:{type:"int"},skipAlreadyRunning:{type:"int"},skipBudgetBillable:{type:"int"},skipBudgetGross:{type:"int"},skipRestartCap:{type:"int"},skipRemoteLock:{type:"int"},skipSleepCleared:{type:"int"},dmProactive:{type:"int"},dmTodo:{type:"int"},dmApproval:{type:"int"},dmCard:{type:"int"},dmNotice:{type:"int"},dmRemind:{type:"int"},dmSuppressed:{type:"int"},dmAwaitingUser:{type:"int"},dmReadIn24h:{type:"int"},dmRepliedIn24h:{type:"int"},feedbackUp:{type:"int"},feedbackDown:{type:"int"},feedbackText:{type:"int"},todoCreated:{type:"int"},todoApproved:{type:"int"},todoInjected:{type:"int"},todoDone:{type:"int"},todoDismissed:{type:"int"},starterCreated:{type:"int"},starterUsed:{type:"int"},starterDismissed:{type:"int"},starterMuted:{type:"int"},ruleCreatedMuse:{type:"int"},ruleCreatedUser:{type:"int"},ruleObserveForced:{type:"int"},rulePromoted:{type:"int"},ruleExtended:{type:"int"},rulePaused:{type:"int"},ruleObservedHits:{type:"int"},approvalByAgent:{type:"int"},approvalUserApproved:{type:"int"},approvalUserRejected:{type:"int"},introAnswered:{type:"int"},introSkipped:{type:"int"},introWhenAnytime:{type:"int"},introWhenDaytime:{type:"int"},introWhenOpen:{type:"int"},introPaceAsNeeded:{type:"int"},introPaceDaily:{type:"int"},introPaceFree:{type:"int"},introFocusSchedule:{type:"int"},introFocusStudy:{type:"int"},introFocusProjects:{type:"int"},introFocusInbox:{type:"int"},introFocusCustom:{type:"int"},summarySent:{type:"int"},summaryProposed:{type:"int"},summaryAdopted:{type:"int"},summaryAskUpgrade:{type:"int"},sleepSet:{type:"int"},digestSent:{type:"int"},gEnabled:{type:"int"},gDaysEnabled:{type:"int"},gModeAsk:{type:"int"},gModeAgent:{type:"int"},gModeAuto:{type:"int"},gNotifyDigest:{type:"int"},gHeartbeatMin:{type:"int"},gMaxDmPerDay:{type:"int"},gOnboardingDay:{type:"int"},gRulesObserving:{type:"int"},gRulesEnabled:{type:"int"}},daily_muse_card:{day:{type:"id",max:10},cardKind:{type:"enum",values:["plugin","feature","inbox-ask","inbox-list","channel","settings","intro","summary","rule","rule-observed"]},created:{type:"int"},accept:{type:"int"},observe:{type:"int"},edit:{type:"int"},dismiss:{type:"int"},open:{type:"int"},apply:{type:"int"},yes:{type:"int"},later:{type:"int"},ignore:{type:"int"},ack:{type:"int"},item:{type:"int"},enable:{type:"int"},extend:{type:"int"},pause:{type:"int"},answer:{type:"int"},skip:{type:"int"},ok:{type:"int"},remove:{type:"int"},installed:{type:"int"},gone:{type:"int"},dismissIrrelevant:{type:"int"},dismissTiming:{type:"int"},dismissFrequent:{type:"int"},dismissKnown:{type:"int"},decideSecTotal:{type:"int"},decidedRemote:{type:"int"},gPendingOver3d:{type:"int"}},daily_memory:{day:{type:"id",max:10},agentRole:{type:"enum",values:["xyra","aria","recita","coding","muse","historian","custom"]},addAgent:{type:"int"},addProject:{type:"int"},addPerson:{type:"int"},updateAgent:{type:"int"},updateProject:{type:"int"},updatePerson:{type:"int"},forgetAgent:{type:"int"},forgetProject:{type:"int"},forgetPerson:{type:"int"},moveScope:{type:"int"},srcExplicit:{type:"int"},srcHistorian:{type:"int"},srcDream:{type:"int"},srcManual:{type:"int"},srcRestore:{type:"int"},srcExternalEdit:{type:"int"},srcSync:{type:"int"},srcMigration:{type:"int"},errFull:{type:"int"},errVersionConflict:{type:"int"},errPortraitFull:{type:"int"},userEditAgentWritten7d:{type:"int"},userForgetAgentWritten7d:{type:"int"},userRestoreDreamRetired:{type:"int"},userEdit:{type:"int"},userForget:{type:"int"},userAdd:{type:"int"},userForgetWrong:{type:"int"},userForgetStale:{type:"int"},userForgetUnwanted:{type:"int"},userForgetDuplicate:{type:"int"},retellExisting:{type:"int"},retellForgotten:{type:"int"},candidatesAdded:{type:"int"},dreamAuto:{type:"int"},dreamManual:{type:"int"},dreamArchive:{type:"int"},dreamCompleted:{type:"int"},dreamSkipped:{type:"int"},dreamFailed:{type:"int"},dreamCancelled:{type:"int"},dreamCalls:{type:"int"},dreamSources:{type:"int"},dreamGroups:{type:"int"},dreamMerges:{type:"int"},dreamDiscarded:{type:"int"},dreamToPortrait:{type:"int"},dreamPending:{type:"int"},dreamDeferred:{type:"int"},dreamVerifyFail:{type:"int"},dreamRetried:{type:"int"},dreamMs:{type:"int"},harnessUpsertAgent:{type:"int"},harnessUpsertHistorian:{type:"int"},harnessUpsertMuse:{type:"int"},harnessUpsertUser:{type:"int"},harnessDelete:{type:"int"},harnessRollback:{type:"int"},gEntries:{type:"int"},gCharsPct:{type:"int"},gTombstones:{type:"int"},gCandidatesPending:{type:"int"},gCandidatesOldestDays:{type:"int"},gHarnessEntries:{type:"int"}},daily_judge:{day:{type:"id",max:10},rounds:{type:"int"},roundsIndependent:{type:"int"},roundsAssist:{type:"int"},roundsFork:{type:"int"},isolationSkips:{type:"int"},memCandidates:{type:"int"},projCandidatesAuto:{type:"int"},projCandidatesQueued:{type:"int"},projAdopted:{type:"int"},projDismissed:{type:"int"},projForgotten:{type:"int"},projRestored:{type:"int"},projCompacted:{type:"int"},harnessCandidatesAuto:{type:"int"},harnessCandidatesQueued:{type:"int"},signalStop:{type:"int"},signalToolLoop:{type:"int"},signalNudge:{type:"int"},signalCorrectionDecision:{type:"int"},signalCorrectionLexical:{type:"int"},titleUpdated:{type:"int"},summaryUpdated:{type:"int"},iconUpdated:{type:"int"}},daily_human:{day:{type:"id",max:10},wAgentShared:{type:"int"},wAgentAgent:{type:"int"},wAgentProject:{type:"int"},wAgentPortrait:{type:"int"},wAgentAgentMd:{type:"int"},wAgentMemory:{type:"int"},wUserShared:{type:"int"},wUserAgent:{type:"int"},wUserProject:{type:"int"},wUserPortrait:{type:"int"},wUserAgentMd:{type:"int"},wUserMemory:{type:"int"},srcRemember:{type:"int"},srcDream:{type:"int"},srcMove:{type:"int"},srcPromote:{type:"int"},srcUser:{type:"int"},userUndoAgentWrite7d:{type:"int"},moveScan:{type:"int"},moveMoved:{type:"int"},moveKept:{type:"int"},moveUndo:{type:"int"},promoteToAgentMd:{type:"int"},coldstartAgents:{type:"int"},coldstartPersonWrites:{type:"int"},coldstartRelearned:{type:"int"},mirrorConflicts:{type:"int"},syncConflictCopies:{type:"int"},gHumanMdEntries:{type:"int"},gAgentMdEntries:{type:"int"},gPortraitEntries:{type:"int"},gMemoryEntries:{type:"int"},gCalendarRows:{type:"int"},gAgentsWithHumanMd:{type:"int"},gAgentsTotal:{type:"int"}},quota_prompt:{entry:{type:"enum",values:["chat-banner","run-error","run-toast","avatar-menu","muse-settings","quota-page","other"]},shown:{type:"int"},dismiss:{type:"int"},card:{type:"int"},points:{type:"int"},upgrade:{type:"int"},topup:{type:"int"},bgConvert:{type:"int"},bgSettings:{type:"int"},more:{type:"int"}},plugin_inventory:{day:{type:"id",max:10},id:{type:"id",max:80},source:{type:"enum",values:["store","builtin","local"]},installed:{type:"int"},enabled:{type:"int"},localCount:{type:"int"}},model_feedback:{modelId:{type:"id",max:80},providerKind:{type:"enum",values:["forsion","codex","byok","local","other"]},regenerate:{type:"int"},stop:{type:"int"},editResend:{type:"int"}},first_run:{outcome:{type:"enum",values:["done","error","aborted"]},errorClass:{type:"enum",values:["timeout","rate_limit","auth","network","context_length","upstream","tool","aborted","quota","other"]},sinceFirstLaunchS:{type:"int"},durationMs:{type:"int"}}}};var zm=Dr.events,Bm=Dr.envelope,Bo=Dr.limits,td=Dr.version,qm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Wm=/^[A-Za-z0-9._:/@+-]+$/,nd=t=>typeof t=="string"&&qm.test(t),Qu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Gm=[[/\/Users\/[^/\s]+\//gi,"~/"],[/\/home\/[^/\s]+\//gi,"~/"],[/[a-z]:\\Users\\[^\\\s]+\\/gi,"~\\"],[/~([/\\])[^\s"'`」:()]+/g,"~$1\u2026"],[/\/Volumes\/[^\s"'`」:()]+/g,"/Volumes/\u2026"],[/\b([d-z]):\\[^\s"'`」:()]+/gi,"$1:\\\u2026"],[/forsion-agent-space\/[^/\s]+\//g,"forsion-agent-space/\u2026/"],[/"[^"]{1,200}"/g,'"\u2026"'],[/'[^']{1,200}'/g,"'\u2026'"],[/`[^`]{1,200}`/g,"`\u2026`"],[/「[^「」]{1,200}」/g,"\u300C\u2026\u300D"],[/(https?:\/\/[^\s?#"'`」]+)[?#][^\s"'`」]*/gi,"$1"],[/sk-[A-Za-z0-9_-]{10,}/g,"[redacted]"],[/Bearer\s+\S+/gi,"[redacted]"],[/[0-9a-f]{32,}/gi,"[redacted]"],[/[A-Za-z0-9+/]{40,}={0,2}/g,"[redacted]"],[/[A-Za-z0-9_-]{40,}/g,"[redacted]"],[/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]"]],rd=t=>Gm.reduce((e,[n,r])=>e.replace(n,r),t);function ed(t,e,n){let r=t.slice(0,2e4).replace(/\u0000/g,"").replace(Qu,"\uFFFD");return n&&n.length>3&&(r=r.split(n).join("~")),r=rd(r),(r.length>e?r.slice(0,e):r).replace(Qu,"\uFFFD")}var id=/^pr-[a-f0-9]{48}$/,Vm=/^market-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,sd=t=>id.test(t)||Vm.test(t)||rd(t)===t;function Ym(t){if(typeof t!="string")return"";let e=t.search(/^\s+at /m);return e<0?"":t.slice(e)}function zo(t,e,n){switch(t.type){case"enum":return typeof e=="string"&&t.values.includes(e)?e:void 0;case"int":return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.min(Math.round(e),2147483647):void 0;case"bool":return typeof e=="boolean"?e:void 0;case"uuid":return nd(e)?e.toLowerCase():void 0;case"iso-time":return typeof e=="string"&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():void 0;case"id":return typeof e=="string"&&e.length<=t.max&&Wm.test(e)&&sd(e)?e:void 0;case"text":return typeof e=="string"&&e?ed(e,t.max,n):void 0;case"stack":{let r=Ym(e);return r?ed(r,t.max,n):void 0}}}function Qt(t,e){let n=typeof t?.event=="string"?zm[t.event]:void 0;if(!n)return null;let r={},i=t.props&&typeof t.props=="object"?t.props:{};for(let[a,o]of Object.entries(n)){let l=zo(o,i[a],e);l!==void 0&&(r[a]=l)}let s=zo({type:"iso-time"},t.ts);return{event:t.event,ts:s??new Date().toISOString(),...nd(t.sessionId)?{sessionId:t.sessionId.toLowerCase()}:{},props:r}}function od(t){let e={};for(let[n,r]of Object.entries(Bm)){if(n==="installId")continue;let i=zo(r,t[n]);e[n]=typeof i=="string"?i:null}return e}function ad(t,e){if(e==="aborted")return"aborted";if(!t)return;let n=t.toLowerCase();return/abort|cancel/.test(n)?"aborted":/timeout|timed out|etimedout/.test(n)?"timeout":/token_quota_exceeded/.test(n)?"quota":/\b429\b|rate.?limit|too many requests|quota/.test(n)?"rate_limit":/\b40[13]\b|unauthori[sz]ed|forbidden|invalid api key|authentication/.test(n)?"auth":/context.{0,20}(length|window|too long)|maximum context|too many tokens|prompt is too long/.test(n)?"context_length":/econn|enotfound|eai_again|socket|network|fetch failed|getaddrinfo/.test(n)?"network":/\b5\d\d\b|upstream|bad gateway|overloaded|service unavailable/.test(n)?"upstream":/tool/.test(n)?"tool":"other"}function ld(t){return t==="done"?"done":t==="failed"?"error":t==="aborted"?"aborted":"other"}function Wi(t){return t?/^pr-/.test(t)?"forsion":/^codex\//.test(t)?"codex":/^(?:ollama|lmstudio|local)[/:]/i.test(t)?"local":"byok":"other"}var Jm=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function qo(t,e){if(typeof t!="string"||!t)return;let n=Wi(t);if((n==="codex"||n==="forsion"&&id.test(t))&&(e===void 0||e===n))return t;let i=t.slice(t.lastIndexOf("/")+1);return Jm.test(i)?i:void 0}function Wo(t){return t==="builtin"||t==="mcp"||t==="plugin"?t:"other"}function Go(t,e){return e==="plugin"?"plugin":e==="mcp"||t.startsWith("mcp__")?"mcp":t}var Km=/^market-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i,Xm=/^[a-z0-9][a-z0-9-]{0,79}$/;function cd(t,e){if(typeof t!="string"||!t)return;let n=Km.exec(t);if(n)return n[1].toLowerCase();if((e===!0||e===1)&&t.length<=80&&Xm.test(t)&&sd(t))return t}function ud(t){return{user:"chat",agent:"agent",muse:"muse",historian:"historian",teamwork:"team",discussion:"team",subagent:"task"}[t||"user"]??"other"}var ry=10*6e4,iy=6e4,sy=50,gd=1024*1024,oy=168*36e5,md=15e3,ay=200,ly=2e3,Jo=7,cy=5e3,yd=864e5,uy=new Set(["crash","perf","feature","plugin_install","plugin_deps","plugin_lifecycle","plugin_load","update","onboarding","guide_tip","command_use","app_counts","quota_prompt","plugin_inventory","model_feedback","first_run"]),dy=new Set(["shown","dismiss","card","points","upgrade","topup","bgConvert","bgSettings","more"]),fy=1e3,wd=36e5,Ko=2,Xo={daily_muse:null,daily_muse_card:"cardKind",daily_memory:"agentRole",daily_judge:null,daily_human:null},py=new Set(["custom-ask","escalate","mode","protected","control","always"]);function hy(t){let e=t.props&&typeof t.props=="object"?t.props:{};if(t.event==="model_feedback"){let n=typeof e.modelId=="string"?e.modelId:void 0,r=qo(n,typeof e.providerKind=="string"?e.providerKind:"other");return r?{...t,props:{...e,modelId:r,providerKind:typeof e.providerKind=="string"?e.providerKind:Wi(n)}}:null}if(t.event==="plugin_inventory"){if(!In(e.day))return null;if(e.source==="local"||e.id==="local")return{...t,props:{day:e.day,id:"local",source:"local",localCount:e.localCount}};let n=typeof e.id=="string"?e.id:"";return(e.source==="store"?!gy.test(n):e.source!=="builtin"||!(n.length<=80&&my.test(n)))?null:{...t,props:{day:e.day,id:n,source:e.source,installed:e.installed,enabled:e.enabled}}}return t}var gy=/^(?:market-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,my=/^[a-z0-9][a-z0-9-]{0,79}$/,yy={model_feedback:"modelId",plugin_inventory:"id",quota_prompt:"entry"},wy=new Set(["readonly","auto-edit","full-auto","custom"]),Sd=t=>new Date(t).toISOString().slice(0,19).replace("T"," "),Zo=t=>({at:Sd(t),id:"~"}),Fn=t=>typeof t=="string"?Date.parse(`${t.replace(" ","T")}Z`):NaN;async function by(t,e,n,r){let i=Un(t,"tangu","state.db");if(!await bd(i).then(a=>a.isFile(),()=>!1))return{events:[],cursor:e};let s;try{let{DatabaseSync:a}=await import("node:sqlite");s=new a(i,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500");let o=s.prepare(`SELECT r.id, r.status, r.current_step, r.model_id, substr(r.error, 1, 2000) AS error, r.created_at, r.updated_at, s.kind
|
|
259
259
|
FROM agent_runs r LEFT JOIN chat_sessions s ON s.id = r.session_id
|
|
260
260
|
WHERE r.status IN ('done', 'failed', 'aborted') AND (r.updated_at > ? OR (r.updated_at = ? AND r.id > ?)) AND r.updated_at < ?
|
|
261
|
-
ORDER BY r.updated_at, r.id LIMIT ?`).all(e.at,e.at,e.id,r??"9999-12-31 23:59:59",
|
|
261
|
+
ORDER BY r.updated_at, r.id LIMIT ?`).all(e.at,e.at,e.id,r??"9999-12-31 23:59:59",ay),l=s.prepare(`SELECT e.type, json_extract(e.payload, '$.id') AS id, json_extract(e.payload, '$.name') AS name, json_extract(e.payload, '$.source') AS source,
|
|
262
262
|
json_extract(e.payload, '$.isError') AS failed, json_extract(e.payload, '$.elapsedMs') AS ms,
|
|
263
263
|
json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
|
|
264
264
|
json_extract(e.payload, '$.phase') AS phase,
|
|
@@ -268,22 +268,23 @@ ${i}`,n),this.line=r,this.column=o,this.codeblock=i}};var vh=/^((0x[0-9a-fA-F](_
|
|
|
268
268
|
json_extract(e.payload, '$.pluginId') AS pluginId, json_extract(e.payload, '$.pluginOfficial') AS pluginOfficial, e.created_at AS at
|
|
269
269
|
FROM agent_run_events e
|
|
270
270
|
WHERE e.run_id = ? AND e.type IN ('usage', 'tool_call', 'tool_result', 'status', 'approval_request', 'approval_result') AND json_valid(e.payload)
|
|
271
|
-
ORDER BY e.seq LIMIT ?`),
|
|
271
|
+
ORDER BY e.seq LIMIT ?`),c=y=>`(SELECT total(json_extract(s.value, '$.tokens')) FROM json_each(e.payload, '$.sections') s WHERE json_extract(s.value, '$.k') = '${y}')`,u=s.prepare(`SELECT json_extract(e.payload, '$.telemetry.agentRole') AS agentRole, json_extract(e.payload, '$.telemetry.recallEntries') AS recallEntries,
|
|
272
272
|
json_extract(e.payload, '$.telemetry.recallHistory') AS recallHistory, json_extract(e.payload, '$.telemetry.recallTruncated') AS recallTruncated,
|
|
273
273
|
json_type(e.payload, '$.sections') AS sectionsType,
|
|
274
|
-
${
|
|
275
|
-
${
|
|
274
|
+
${c("memory")} AS memoryTokens, ${c("human")} AS humanTokens,
|
|
275
|
+
${c("profile")} AS profileTokens, ${c("project")} AS projectTokens
|
|
276
276
|
FROM agent_run_events e
|
|
277
277
|
WHERE e.run_id = ? AND e.type = 'status' AND json_valid(e.payload) AND json_extract(e.payload, '$.phase') = 'context_info'
|
|
278
|
-
ORDER BY e.seq LIMIT 1`),f=
|
|
279
|
-
WHERE day > ? AND day < ? AND day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' AND event IN (${
|
|
280
|
-
ORDER BY day LIMIT ?`).all(e,n,...
|
|
281
|
-
`).filter(Boolean)}catch{return[]}},
|
|
278
|
+
ORDER BY e.seq LIMIT 1`),f=y=>typeof y=="number"&&Number.isFinite(y)&&y>0?y:0,g=y=>typeof y=="string"&&y?y:void 0,p=[],m=e;for(let y of o){m={at:String(y.updated_at),id:String(y.id)};let b={llmCalls:0,tokensIn:0,tokensOut:0,tokensCached:0,retries:0},_=new Map,h=new Map,T=new Map,v=[],I=new Map;for(let N of l.all(y.id,ly))if(N.type==="usage")b.llmCalls++,b.tokensIn+=f(N.prompt),b.tokensOut+=f(N.completion),b.tokensCached+=f(N.cached);else if(N.type==="tool_call"||N.type==="tool_result"){if(typeof N.id=="string"&&N.source!=null&&h.set(N.id,N.source),typeof N.id=="string"&&N.pluginId!=null&&T.set(N.id,{pluginId:N.pluginId,official:N.pluginOfficial}),N.type!=="tool_result"||typeof N.name!="string")continue;let Y=N.source??(typeof N.id=="string"?h.get(N.id):void 0),ee=Go(N.name,Y),J=Wo(Y),se=typeof N.id=="string"?T.get(N.id):void 0,te=Y==="plugin"?cd(N.pluginId??se?.pluginId,N.pluginOfficial??se?.official):void 0,ae=`${ee}\0${J}\0${te??""}`,Q=_.get(ae)??{tool:ee,toolSource:J,...te?{pluginId:te}:{},calls:0,failures:0,totalMs:0,maxMs:0};_.set(ae,Q),Q.calls++,N.failed&&Q.failures++,Q.totalMs+=f(N.ms),Q.maxMs=Math.max(Q.maxMs,f(N.ms))}else if(N.type==="approval_request")v.push({approvalId:g(N.approvalId),name:g(N.name),toolCallId:g(N.toolCallId),reasonKind:py.has(N.reasonKind)?N.reasonKind:"other",mode:wy.has(N.reasonMode)?N.reasonMode:"other",at:Fn(N.at)});else if(N.type==="approval_result"){let Y=g(N.approvalId);Y&&!I.has(Y)&&I.set(Y,{action:g(N.action),via:g(N.via),at:Fn(N.at)})}else N.phase==="llm_retry"&&b.retries++;let E=u.all(y.id)[0],D=ld(y.status),x=Fn(y.updated_at)-Fn(y.created_at),L=new Date(Number.isNaN(Fn(y.updated_at))?Date.now():Fn(y.updated_at)).toISOString(),V=Qt({event:"agent_run",ts:L,sessionId:n,props:{modelId:qo(y.model_id),providerKind:Wi(y.model_id),mode:ud(y.kind),steps:f(y.current_step),...b,durationMs:Number.isFinite(x)&&x>=0?x:void 0,outcome:D,errorClass:D==="done"?void 0:ad(y.error,y.status),...E?{agentRole:E.agentRole,recallEntries:E.recallEntries,recallHistory:E.recallHistory,recallTruncated:E.recallTruncated===1?!0:E.recallTruncated===0?!1:void 0,...E.sectionsType==="array"?{memoryTokens:E.memoryTokens,humanTokens:E.humanTokens,profileTokens:E.profileTokens,projectTokens:E.projectTokens}:{}}:{}}});V&&p.push(V);for(let N of _.values()){let Y=Qt({event:"tool_call",ts:L,sessionId:n,props:{...N,runOutcome:D}});Y&&Y.props.tool&&p.push(Y)}let H=new Map;for(let N of v){if(!N.name)continue;let Y=N.toolCallId?h.get(N.toolCallId):void 0,ee=Y==null?N.name.startsWith("mcp__")?"mcp":void 0:Go(N.name,Y),J=Wo(Y),se=`${ee??""}\0${J}\0${N.reasonKind}\0${N.mode}`,te=H.get(se)??{tool:ee,toolSource:J,reasonKind:N.reasonKind,mode:N.mode,asked:0,approved:0,rejected:0,expired:0,decideSecTotal:0,remoteAnswers:0};H.set(se,te),te.asked++;let ae=N.approvalId?I.get(N.approvalId):void 0;if(!ae){te.expired++;continue}ae.action==="approve"||ae.action==="approve_always"?te.approved++:ae.action==="reject"&&te.rejected++;let Q=Math.round((ae.at-N.at)/1e3);Number.isFinite(Q)&&Q>0&&(te.decideSecTotal+=Q),ae.via&&ae.via!=="local"&&te.remoteAnswers++}for(let N of H.values()){let Y=Qt({event:"approval",ts:L,sessionId:n,props:N});Y&&(Y.props.tool||N.tool===void 0)&&p.push(Y)}}return{events:p,cursor:m}}catch{return{events:[],cursor:e}}finally{try{s?.close()}catch{}}}async function Sy(t,e,n){let r=Un(t,"tangu","state.db"),i=await bd(r).then(a=>a.isFile(),a=>a?.code==="ENOENT"||a?.code==="ENOTDIR"?!1:null);if(i===null)return null;if(!i)return{days:[],complete:!0};let s;try{let{DatabaseSync:a}=await import("node:sqlite");if(s=new a(r,{readOnly:!0}),s.exec("PRAGMA busy_timeout = 1500"),!s.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'telemetry_ledger'").all().length)return{days:[],complete:!0};let o=Object.keys(Xo),l=s.prepare(`SELECT DISTINCT day FROM telemetry_ledger
|
|
279
|
+
WHERE day > ? AND day < ? AND day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' AND event IN (${o.map(()=>"?").join(", ")})
|
|
280
|
+
ORDER BY day LIMIT ?`).all(e,n,...o,Jo+1),c=s.prepare("SELECT event, dim, field, n FROM telemetry_ledger WHERE day = ? ORDER BY event, dim, field LIMIT ?"),u=[];for(let{day:f}of l.slice(0,Jo)){if(!In(f))continue;let g=new Map;for(let m of c.all(f,cy)){if(typeof m.event!="string"||!Object.hasOwn(Xo,m.event))continue;let y=Xo[m.event],b=typeof m.dim=="string"?m.dim:"";if((y?!b:b!=="")||typeof m.field!="string"||typeof m.n!="number")continue;let _=`${m.event}\0${b}`,h=g.get(_)??{event:m.event,dimKey:y,dim:b,fields:new Map};g.set(_,h),h.fields.set(m.field,(h.fields.get(m.field)??0)+m.n)}let p=[];for(let m of g.values()){let y=Qt({event:m.event,ts:`${f}T23:59:59.000Z`,props:{...Object.fromEntries(m.fields),day:f,...m.dimKey?{[m.dimKey]:m.dim}:{}}});!y||y.props.day!==f||m.dimKey&&y.props[m.dimKey]===void 0||Object.keys(y.props).some(b=>b!=="day"&&b!==m.dimKey)&&p.push(y)}u.push({day:f,events:p})}return{days:u,complete:l.length<=Jo}}catch{return null}finally{try{s?.close()}catch{}}}var vy=(t,e,n)=>Qt({event:"sync_health",ts:`${t}T23:59:59.000Z`,props:{...n,system:e,day:t}}),ky=t=>["darwin","win32","linux"].includes(t)?t:"other",Ey=t=>["arm64","x64","ia32"].includes(t)?t:"other",_y=()=>/^zh\b/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en";function vd(t,e={}){let n=e.now??(()=>new Date),r=e.fetch??fetch,i=()=>t.homeDir(),s=()=>Un(i(),"extend-telemetry.json"),a=()=>Un(i(),"telemetry"),o=()=>Un(a(),"queue.jsonl"),l=()=>Un(a(),"sent.jsonl"),c=t.telemetry,u=()=>Tn(n().getTime()-yd);Jc(()=>n().getTime());let f=()=>g()??{},g=()=>{let C;try{C=fd(s(),"utf8")}catch(A){return A?.code==="ENOENT"?{}:null}try{let A=JSON.parse(C);return A&&typeof A=="object"&&!Array.isArray(A)?A:null}catch{return null}},p=(C,A=f())=>{let j={...A,...C};Vo(i(),{recursive:!0});let F=`${s()}.${process.pid}.tmp`;return hd(F,JSON.stringify(j,null,2),{encoding:"utf8",mode:384}),pd(F,s()),j},m=()=>f().installId??p({installId:dd()}).installId,y=()=>{try{return!!t.readCreds().token}catch{return!1}},b=(C=f())=>C.enabled!==!1&&C.noticeSeen===!0&&c?.packaged===!0&&y(),_=C=>{try{return fd(C,"utf8").split(`
|
|
281
|
+
`).filter(Boolean)}catch{return[]}},h=()=>_(o()).flatMap(C=>{try{return[JSON.parse(C)]}catch{return[]}}),T=(C,A)=>{if(Vo(a(),{recursive:!0}),!A.length){Yo(C,{force:!0});return}let j=`${C}.${process.pid}.tmp`;hd(j,A.map(F=>JSON.stringify(F)).join(`
|
|
282
282
|
`)+`
|
|
283
|
-
`,{encoding:"utf8",mode:384}),
|
|
283
|
+
`,{encoding:"utf8",mode:384}),pd(j,C)},v=0,I=null,E=()=>{v++,Yo(o(),{force:!0}),Yo(l(),{force:!0}),Yc(),I=null},D=()=>{let C=n().getTime(),A=_(l()).flatMap(F=>{try{return[JSON.parse(F)]}catch{return[]}}),j=A.filter(F=>C-F.at<oy);return j.length!==A.length&&T(l(),j),j},x=0,L=!1,V=0,H=()=>{let C=g();if(!C)return mo(!1),!1;let A=b(C);return A&&C.closed?p({closed:void 0,cursor:Zo(n().getTime()),ledgerCursor:u()},C):A&&!In(C.ledgerCursor)?p({ledgerCursor:u()},C):!A&&!C.closed&&(x++,p({closed:!0},C)),mo(A),A},N=()=>{let C=g();if(!C){t.log("[forsion-extend] telemetry state unreadable; skipping the signed-in migration");return}if(C.signedInGate)return;let A={signedInGate:1};!y()&&C.enabled===void 0&&C.noticeSeen===!0&&(A.enabled=!1,A.syncHealth=void 0,x++,E(),t.log("[forsion-extend] telemetry turned off: not signed in (sending now needs a Forsion account)")),p(A,C)},Y=C=>{if(!(!C.length||!b())){Vo(a(),{recursive:!0}),Zm(o(),C.map(A=>JSON.stringify(A)).join(`
|
|
284
284
|
`)+`
|
|
285
|
-
`,{encoding:"utf8",mode:384});try{if(Wg(a()).size>Au){let C=g(),D=C.length,N=0;for(;D>0&&N+Buffer.byteLength(JSON.stringify(C[D-1]))+1<=Au/2;)N+=Buffer.byteLength(JSON.stringify(C[--D]))+1;j(a(),C.slice(D))}}catch{}g().length>=Kg&&te()}},re=()=>{let v=f();return{available:!!l,enabled:v.enabled!==!1,noticeSeen:v.noticeSeen===!0,signedIn:w(),active:y(v),packaged:l?.packaged===!0,installId:m(),queued:qg(a())?g().length:0,lastSentAt:v.lastSentAt??null,lastError:v.lastError??null}},X=()=>yu({app:"desktop",appVersion:t.appVersion(),coreVersion:l?.coreVersion()??void 0,channel:l?.channel(),os:pm(process.platform),osVersion:Yg(),arch:hm(process.arch),locale:gm()}),se=fu,ee=async v=>{try{let C=await v.json?.();return!!C&&typeof C=="object"&&C.detail==="unsupported v"}catch{return!1}},oe=null,te=()=>{if(oe)return oe;if(P||n().getTime()<q)return Promise.resolve();let v=_,C=x,D=(async()=>{try{for(let N=0;N<5;N++){let O=g();if(!O.length)return;let L=m(),K={v:se,installId:L,...X()},Z=[],Q=Buffer.byteLength(JSON.stringify({...K,events:[]}));for(let le of O){let Ae=Buffer.byteLength(JSON.stringify(le))+1;if(Z.length>=ls.maxEvents||Q+Ae>ls.maxBatchBytes)break;Z.push(le),Q+=Ae}if(!Z.length){j(a(),O.slice(1));continue}let{base:V}=await t.getCloud(),ie={...K,events:Z};if(!J()||v!==_)return;let pe=await r(`${V.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(ie),signal:AbortSignal.timeout(xu)}).catch(le=>({ok:!1,status:0,error:String(le?.message||le)})),fe=pe.status;if(fe===400&&K.v>ms&&await ee(pe)){se=ms,t.log(`[forsion-extend] telemetry server does not accept v${K.v}; resending as v${ms}`);continue}if(fe>=200&&fe<300||fe===400||fe===413){let le=new Set(Z.map(Ae=>JSON.stringify(Ae)));j(a(),g().filter(Ae=>!le.has(JSON.stringify(Ae))))}if(fe>=200&&fe<300){let le=n().getTime();C===x&&j(c(),[...T(),{at:le,body:ie}]),p({lastSentAt:le,lastError:void 0});continue}if(fe!==400&&fe!==413){let le=Number(pe.headers?.get?.("retry-after"));q=n().getTime()+(Number.isFinite(le)&&le>0?Math.min(le,3600)*1e3:5*6e4)}p({lastError:fe?`HTTP ${fe}`:String(pe.error??"network error").slice(0,200)});return}}catch(N){try{p({lastError:String(N?.message||N).slice(0,200)})}catch{}}})();return oe=D,D.finally(()=>{oe===D&&(oe=null)}),D},Se=v=>{if(!M||!v&&Math.floor(n().getTime()/Iu)===M.hour)return;let C=M;if(M=null,C.gen!==_||!J())return;let D=Ht({event:"quota_prompt",ts:n().toISOString(),sessionId:l?.sessionId,props:{...C.counts,entry:"quota-page"}});try{D&&Object.keys(D.props).some(N=>N!=="entry")&&Y([D])}catch(N){throw M=C,N}},ve=async()=>{try{if(T(),Se(!1),!J())return;let v=f(),C=_,D=v.cursor??ws(n().getTime()),N=await um(o(),D,l?.sessionId,Du(n().getTime()));if(!J()||C!==_)return;Y(N.events),N.cursor!==D&&p({cursor:N.cursor}),await Xe(C),await te()}catch(v){t.log(`[forsion-extend] telemetry tick failed: ${String(v?.message||v)}`)}},Xe=async v=>{let C=n().getTime(),D=pn(C),N=pn(C-Tu),O=f().ledgerCursor;if(hn(O)||(O=N,p({ledgerCursor:O})),zi(O),O>=N){je();return}let L=await dm(o(),O,D);if(!(!J()||v!==_)){if(L){let K=L.complete?N:L.days[L.days.length-1]?.day??O;if(K>O){let Z=sl(O,K),Q=[...new Set([...L.days.map(ie=>ie.day),...Z.map(ie=>ie.day)])].filter(ie=>ie>O&&ie<=K).sort(),V=[];for(let ie of Q){V.push(...L.days.find(pe=>pe.day===ie)?.events??[]);for(let pe of Z)if(pe.day===ie){let fe=fm(ie,pe.system,pe.counts);fe&&V.push(fe)}}Y(V),p({ledgerCursor:K}),zi(K)}}je()}},je=()=>{if(!ol())return;let v=h();if(!v)return;let C=rl();p({syncHealth:Object.keys(C).length?C:void 0},v),il()},Fe=l?.subscribe(v=>{try{if(!tm.has(v?.event)||!J())return;let C=im(v);if(!C)return;let D=Ht({...C,sessionId:l.sessionId},Vg()),N=cm[v.event];D&&(!N||D.props[N]!==void 0)&&Y([D])}catch(C){t.log(`[forsion-extend] telemetry event dropped: ${String(C?.message||C)}`)}}),we={ok:!1,error:"untrusted"};t.handle("telemetry:get",v=>t.isTrustedSender(v)?(J(),re()):we),t.handle("telemetry:set",(v,C)=>{if(!t.isTrustedSender(v))return we;let D=f(),N={};typeof C?.enabled=="boolean"&&(N.enabled=C.enabled),C?.noticeSeen===!0&&(N.noticeSeen=!0);let O={...D,...N};return!y(D)&&y(O)&&(N.cursor=ws(n().getTime()),N.ledgerCursor=u()),y(D)&&!y(O)&&_++,N.enabled===!1&&(N.syncHealth=void 0),p(N),N.enabled===!1&&E(),J(),re()}),t.handle("telemetry:quotaPrompt",(v,C)=>{if(!t.isTrustedSender(v))return we;let D=C?.action;return C?.entry!=="quota-page"||typeof D!="string"||!nm.has(D)?{ok:!1,error:"invalid"}:(Se(!1),J()?((!M||M.gen!==_)&&(M={hour:Math.floor(n().getTime()/Iu),gen:_,counts:{}}),M.counts[D]=Math.min((M.counts[D]??0)+1,rm),{ok:!0,counted:!0}):{ok:!0,counted:!1})}),t.handle("telemetry:sent",v=>t.isTrustedSender(v)?{batches:T()}:we),t.handle("telemetry:delete",async v=>{if(!t.isTrustedSender(v))return we;P=!0,_++;try{await oe?.catch(()=>{});let C=m(),{base:D}=await t.getCloud(),O=(await r(`${D.replace(/\/+$/,"")}/api/telemetry/install/${C}`,{method:"DELETE",signal:AbortSignal.timeout(xu)}).catch(L=>({ok:!1,status:0,error:String(L?.message||L)}))).status;return O>=200&&O<300?(E(),p({installId:ku(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),re()):{ok:!1,error:O?`HTTP ${O}`:"network error"}}finally{P=!1}});try{nl(f().syncHealth),R(),J()}catch(v){t.log(`[forsion-extend] telemetry startup check failed: ${String(v?.message||v)}`)}let Oe=t.addFlushHook?.(v=>{if(v!=="blur"){try{je()}catch{}try{Se(!0)}catch{}}}),I=setTimeout(()=>void ve(),Jg),F=setInterval(()=>void ve(),Gg);return I.unref?.(),F.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(I),clearInterval(F),Fe?.(),Oe?.()},{tick:ve,flush:te})}import{readFileSync as In,lstatSync as Bm,statSync as qm,renameSync as Wm,linkSync as Vm,unlinkSync as Is,readdirSync as Ym,rmdirSync as Gm,writeFileSync as Jm,mkdirSync as Km,copyFileSync as Xm,constants as Zm}from"node:fs";import{readFile as mr,writeFile as yr,mkdir as Rs,rename as Mo,readdir as wr,lstat as Dt,stat as Ds,unlink as br}from"node:fs/promises";import{join as De,dirname as nn,relative as Sr,sep as Rn}from"node:path";import{hostname as Os}from"node:os";import{randomUUID as at}from"node:crypto";import{isUtf8 as Ms}from"node:buffer";import{Readable as ed}from"node:stream";import{performance as Ps}from"node:perf_hooks";import{setImmediate as Qm}from"node:timers/promises";var mm=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],ym=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],hr=".memory-tombstones.json",Pu=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),wm=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,bm=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function Sm(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===hr)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:mm.includes(t)||Pu(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&wm(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var vm=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),km=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,Em=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function vo(t){let e=t.slice(t.lastIndexOf("/")+1);return km.test(e)||Em.test(e)}function $u(t,e,n=1){let r=t.lastIndexOf("/"),o=r<0?"":t.slice(0,r+1),i=r<0?t:t.slice(r+1),s=i.lastIndexOf("."),a=s>0?i.slice(0,s):i,c=s>0?i.slice(s):"",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`${o}${a} (conflict ${u})${c}`}function bs(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(vo(t))return!1;if(n){let l=t.slice(6);return e==="folder"?Mu(l):ym.includes(l)||Pu(l)}let o=t.slice(7),i=o.indexOf("/"),s=i<0?o:o.slice(0,i),a=i<0?"":o.slice(i+1);if(!bm(s)||vm(s))return!1;if(e==="file")return Sm(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 _m}from"node:path";var st=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),vt=t=>typeof t=="string",vs=t=>vt(t)&&t.length>0,zt=t=>typeof t=="boolean",en=t=>typeof t=="number"&&Number.isFinite(t),An=t=>en(t)&&Number.isSafeInteger(t)&&t>=0,Nu=t=>en(t)&&Number.isInteger(t)&&t>=0,ju=t=>An(t)&&t>0,xn=t=>vt(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),Co=t=>vt(t)&&/^[a-f0-9]{64}$/.test(t),Fu=t=>vt(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),Eo=(t,e)=>vt(t)&&e.includes(t),_e=(t,e)=>t===void 0||e(t),Lu=(t,e,n)=>e.every(r=>_e(t[r],n)),Uu=t=>vt(t)&&!t.includes("\0")&&_m(t);function Bt(t,e=!1){try{return Lt(t,e),!0}catch{return!1}}var Hu=t=>Bt(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,zu=t=>t===""||xn(t);function _o(t,e){let n=t.indexOf(":");return n>0&&xn(e)&&t.slice(n+1)===e&&Fu(t.slice(0,n))}function Cm(t,e){return st(e)&&_o(t,e.id)&&Bt(e.path)&&vs(e.version)&&Co(e.hash)&&Lu(e,["base","inode","stat"],vt)&&_e(e.statAt,en)&&_e(e.memoryDeleted,zt)}function Am(t,e){return st(e)&&_o(t,e.localId)&&xn(e.id)&&Bt(e.path)&&ju(e.revision)&&zu(e.parentId)&&Hu(e.name)}function xm(t){return st(t)&&xn(t.id)&&Bt(t.path)&&Fu(t.target)&&Eo(t.direction,["upload","download","merge","rename","delete"])&&Eo(t.state,["queued","active","done","failed","paused","conflict"])&&An(t.done)&&(t.size===null||An(t.size))&&en(t.at)&&_e(t.error,vt)&&_e(t.finishedAt,en)}function Tm(t){return st(t)&&Bt(t.path)&&Co(t.hash)&&vt(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&_e(t.parentId,xn)&&_e(t.stageRoot,Uu)&&_e(t.stageIdentity,Kt)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&Nu(t.stageDev)&&Nu(t.stageIno))}function Im(t){return st(t)&&Bt(t.prefix,!0)&&Uu(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Kt(t))}function Rm(t){return st(t)&&Eo(t.state,["running","done"])&&zt(t.seen)&&Lu(t,["name","folderId","shelfId","shelfName"],vt)&&_e(t.files,An)&&_e(t.at,en)&&_e(t.rewritten,zt)}var ko=(t,e)=>st(t)&&Object.entries(t).every(([n,r])=>e(n,r)),Ss=(t,e)=>Array.isArray(t)&&t.every(e);function Bu(t){if(!st(t)||!st(t.config)||!An(t.config.revision)||!zt(t.owned)||!zt(t.paused)||!ko(t.files,Cm)||!ko(t.folders,Am)||!Ss(t.jobs,xm)||!_e(t.accountReview,zt)||!_e(t.agentArchive,Rm)||!_e(t.roots,e=>Ss(e,Im))||!_e(t.trash,e=>Ss(e,Tm))||!_e(t.unconfirmed,e=>ko(e,(n,r)=>_o(n,n.slice(-36))&&Co(r)))||!_e(t.pendingUploads,e=>ko(e,(n,r)=>st(r)&&_o(n,r.id)&&Bt(r.path))))throw Error("Invalid content sync state; original data was retained");Ut(t.config,t.config.revision)}function qu(t){return st(t)&&xn(t.id)&&zu(t.parentId)&&Hu(t.name)&&Bt(t.path)&&Eo(t.kind,["file","folder"])&&ju(t.revision)&&zt(t.deleted)&&_e(t.busy,zt)&&_e(t.version,vs)&&_e(t.hash,Co)&&_e(t.size,An)&&_e(t.mtime,en)&&t.version===void 0==(t.hash===void 0)}function Wu(t){return qu(t)&&t.deleted===!0}function Ao(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!st(t)||t.schemaVersion!==1||t.namespace!==e||!vs(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,o=new Set;for(let i of t.nodes){if(!qu(i)||r.has(i.id)||!i.deleted&&o.has(i.path))throw n();r.set(i.id,i),i.deleted||o.add(i.path)}for(let i of r.values()){let s=i.parentId?r.get(i.parentId):void 0;if(i.parentId&&(!s||s.kind!=="folder"||s.deleted&&!i.deleted)||i.path!==(s?s.path+"/"+i.name:i.name))throw n()}}import{constants as Vu,lstatSync as tn,readdirSync as Dm,readFileSync as Om,renameSync as xo,unlinkSync as Mm,linkSync as Pm,mkdirSync as Io,realpathSync as ks,rmdirSync as $m}from"node:fs";import{open as Yu,lstat as Es,readdir as Nm,realpath as Gu,readFile as _s,writeFile as jm,mkdir as Ju,unlink as Fm}from"node:fs/promises";import{join as qt,dirname as To,relative as Cs,sep as Ro}from"node:path";import{randomUUID as Ku,createHash as Lm}from"node:crypto";var gr=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,Do=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),Xu=".forsion-sync-id.json",Um=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),Hm=t=>!Um.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),Ce=t=>Lm("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 nt(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 Gu(t),o=qt(r,...e.split("/").filter(Boolean)),i=Cs(r,o);if(i===".."||i.startsWith(".."+Ro))throw Error("Content path escapes root");let s=r;for(let a of i.split(Ro).filter(Boolean)){s=qt(s,a);try{if((await Es(s)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(c){if(c.code!=="ENOENT")throw c}}return o}function dt(t,e,n=!1){if(n||Lt(e,!0),Zu(e),e.split("/").some(i=>i===".."||i===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let o=ks(t);for(let i of e.split("/").filter(Boolean)){o=qt(o,i);try{if(tn(o).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(s){if(s.code!=="ENOENT")throw s}}return o}async function Oo(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 Gu(o.root)})}catch(i){if(i.code!=="ENOENT")throw i}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 i=o.root;if(!(await Es(i)).isDirectory())throw Error(`Sync root is not a directory: ${o.prefix||"Forsion"}`);let s=async(a,c)=>{let l=await Es(a);if(!l.isSymbolicLink()&&!(a!==i&&r.some(u=>u!==o&&u.root===a))&&!(c&&o.prefix===""&&n.some(u=>c===u||c.startsWith(u+"/")))){if(c){Lt(c);let u;if(l.isDirectory())try{let f=JSON.parse(await _s(qt(a,Xu),"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:i,kind:l.isDirectory()?"folder":"file",localId:u,...Do(l),size:l.isFile()?l.size:0})}if(l.isDirectory())for(let u of await Nm(a,{withFileTypes:!0}))!Hm(u.name)||!u.isDirectory()&&!u.isFile()||await s(qt(a,u.name),c?`${c}/${u.name}`:u.name)}};await s(i,o.prefix)}return[...e.values()].sort((o,i)=>o.path.split("/").length-i.path.split("/").length||o.path.localeCompare(i.path))}async function As(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await nt(t.root,Cs(t.root,qt(t.physical,Xu)).split(Ro).join("/"),!0),n=Ku();try{let r=await Yu(e,"wx",384);try{await r.writeFile(JSON.stringify({version:1,id:n})+`
|
|
286
|
-
`)}finally{await r.close()}return t.localId=n,n}catch(r){if(r.code!=="EEXIST")throw r;let o=JSON.parse(await _s(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 Tn(t){let e=await nt(t.root,Cs(t.root,t.physical).split(Ro).join("/")),n=await Yu(e,Vu.O_RDONLY|(Vu.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 qe(t,e){Lt(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 xs(t,e,n,r,o=async(i,s)=>s()){let i=qe(t,e);await Ju(i.root,{recursive:!0});let s=await nt(i.root,i.relative),a=await _s(s).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=qt(i.root,`.forsion-sync-${Ku()}.tmp`);try{await jm(c,n,{flag:"wx",mode:384}),await nt(i.root,i.relative),await o(s,()=>{dt(i.root,i.relative),Io(To(s),{recursive:!0}),dt(i.root,i.relative);let l=null;try{l=Om(s)}catch(u){if(u.code!=="ENOENT")throw u}if((l?Ce(l):null)!==r)throw Error("Local file changed during download");xo(c,s)})}finally{await Fm(c).catch(()=>{})}}async function Qu(t,e,n=async(r,o)=>o()){let r=qe(t,e);await Ju(r.root,{recursive:!0});let o=await nt(r.root,r.relative);await n([o],()=>{dt(r.root,r.relative),Io(o,{recursive:!0})})}async function Ts(t,e,n,r=async(o,i)=>i()){let o=qe(t,e),i=qe(t,n);if(o.root!==i.root)throw Error("Folder move crosses a managed source");let s=await nt(o.root,o.relative),a=await nt(i.root,i.relative);await r([s,a],()=>{if(dt(o.root,o.relative),dt(i.root,i.relative),zm(a)){let l=tn(s),u=tn(a),f=ks(To(s));if((l.dev===u.dev&&l.ino===u.ino&&f===ks(To(a))?Dm(f).filter(m=>{let w=tn(qt(f,m));return w.dev===l.dev&&w.ino===l.ino}):[]).length!==1)throw Error("Local rename destination exists");xo(s,a);return}Io(To(a),{recursive:!0});let c=tn(s);if(c.isDirectory()){if(process.platform==="win32"){xo(s,a);return}Io(a,{mode:448});try{xo(s,a)}catch(l){try{$m(a)}catch{}throw l}}else{Pm(s,a);let l=tn(s);if(l.ino!==c.ino||l.dev!==c.dev)throw Error("Source changed during rename");Mm(s)}})}function zm(t){try{return tn(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var td=(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)))),ey=()=>({config:structuredClone(El),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),Dn=50*1024*1024,ty=10*6e4,nd=1024*1024,$e=(t,e)=>`${t}:${e}`,Ot=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",rn=t=>t.slice(t.lastIndexOf("/")+1),vr=Ce(""),$s=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),Wt=t=>t.split("/").length,Ne=t=>t instanceof Error?t.message:String(t),ny={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},Ns=t=>t.file.replace(/\.json$/,".bases"),sd=5e3,ry=3e4,rd=3e4,oy=3e3,Po=10*6e4,iy=60*6e4,sy=10*6e4,ay=3*6e4,od=2e3,cy=1440*6e4,js=t=>/^(agents|human)\//.test(t)?ry:sd,ly=t=>Math.max(t.mtime,t.ctime);async function*Vt(t){let e=Ps.now()+8;for(let n of t)Ps.now()>=e&&(await Qm(),e=Ps.now()+8),yield n}function ad(t){if(!t.contentSync)return;let e=new Fs(t);for(let[n,r]of Object.entries({[yt.get]:(o,i)=>e.snapshot(o,i),[yt.preview]:o=>e.preview(o),[yt.apply]:(o,i)=>e.apply(typeof o=="string"?o:"",i),[yt.run]:()=>{e.touch(),e.kick()},[yt.pause]:o=>e.pause(o===!0),[yt.retry]:()=>{e.touch(),e.kick()},[yt.rename]:o=>e.rename(o),[yt.setup]:o=>e.setup(o),[yt.archiveSeen]:()=>e.archiveSeen()}))t.handle(n,async(o,...i)=>{if(!t.isTrustedSender(o))return{ok:!1,error:"untrusted"};try{return{ok:!0,value:await r(...i)}}catch(s){return{ok:!1,error:Ne(s)}}});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)),$l(()=>e.stats()),e.start()}var Fs=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 lr;logAccount=null;runAccount=null;blockedError=void 0;live(){let e=this.host.accountId();return!!e&&e===this.logAccount&&(!this.running||!this.runAccount||this.runAccount===e)}tally(e){this.live()&&this.runLog.count(e)}fault(e,n=[]){this.live()&&this.runLog.fault(e,n)}health=to((e,n,r)=>ut("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=mc(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{this.idleSkip()||this.run()},3e4)).unref?.(),(this.first=setTimeout(()=>{this.run()},5e3)).unref?.()}locale(){if(this.uiLocale)return this.uiLocale;try{return/^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en"}catch{return"zh"}}archiveStep(e){if(e.stored.accountReview||e.stored.agentArchive?.state==="done"||this.archiveRetry.account===e.account&&Date.now()<this.archiveRetry.at)return Promise.resolve();let n=()=>{this.archiveRetry={account:e.account,at:Date.now()+Po}};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 i=await o.json();if(this.guard(e),i.state!=="done"&&i.state!=="running"){n();return}let s=e.stored.agentArchive,a=i.archive;s?.rewritten||this.turnAgentsOff(e);let c={rewritten:!0,seen:s?.seen??!1,state:i.state};i.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=Dl(n);if(!r)return;e.stored.config=Ut(r,n.revision+1);let o=i=>i==="agents"||i.startsWith("agents/");for(let[i,s]of Object.entries(e.stored.files))o(s.path)&&(delete e.stored.files[i],delete e.stored.unconfirmed?.[i]);for(let[i,s]of Object.entries(e.stored.folders))o(s.path)&&delete e.stored.folders[i];for(let[i,s]of Object.entries(e.stored.pendingUploads??{}))o(s.path)&&delete e.stored.pendingUploads[i];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=Vn(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(Ei(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 Rs(nn(e.file),{recursive:!0,mode:448});let o=e.file+".tmp-"+at();try{await yr(o,r,{mode:384,flag:"wx"}),this.guard(e,!1),await Mo(o,e.file),e.persisted=r}finally{await br(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 Ei(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,Ce(e)+".json"),i=ey();try{let f=JSON.parse(await mr(o,"utf8"));Bu(f),i={...i,...f,config:Ut(f.config,f.config.revision)},i.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 s,a=De(this.host.homeDir(),"content-sync-device.json"),c=async()=>{let f=JSON.parse(await mr(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{s=await c()}catch(f){if(f.code!=="ENOENT")throw f;s={id:at()},await Rs(nn(a),{recursive:!0});try{await yr(a,JSON.stringify(s),{flag:"wx",mode:384})}catch(h){if(h.code!=="EEXIST")throw h;s=await c()}}if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=s.id,this.customName=typeof s.name=="string"?s.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:i,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),i.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=nn(e.file),r=vi(this.host.homeDir()),o=Ce(e.account),i=Vn(r),s=!i?.account&&(await wr(n).catch(c=>{if(c.code==="ENOENT")return[];throw c})).some(c=>/^[a-f0-9]{64}\.json$/.test(c)&&c!==o+".json"),a=i?.pending&&(e.stored.owned||e.stored.config.revision>0);if((i?.account&&i.account!==o||s||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)),i?.account!==o||i.pending){this.guard(e,!1);let c=Vn(r);if(c?.account!==i?.account||c?.epoch!==i?.epoch||c?.pending!==i?.pending)throw Error("account_changed");ki(r,{version:1,account:o,...i?.epoch?{epoch:i.epoch}:{}})}e.binding={file:r,account:o,epoch:i?.epoch},this.guard(e,!1)}async rootIdentity(e,n){let r=e.rootIdentities.get(n);if(r){let i=await Ds(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!i.isDirectory()||!lt(r,i))throw Error("Sync root changed; preview before rebinding");return r}let o=await zn(n).catch(i=>{throw i.code==="ENOENT"?Error("Sync root unavailable: "+n):i});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 i=n.find(a=>a.prefix===o.prefix);if(!i||i.root!==o.root)throw Error("content_roots_changed_preview_required");let s=await this.rootIdentity(e,o.root);if(o.dev!==void 0&&!ln(o,s))throw Error("Sync root changed; preview before rebinding");if(o.dev!==void 0&&o.dev!==s.dev){let a=String(o.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(a)&&qe(n,c.path).root===o.root&&(c.inode=String(s.dev)+":"+c.inode.slice(a.length),delete c.stat,delete c.statAt)}JSON.stringify(o)!==JSON.stringify({...o,...s})&&(Object.assign(o,s),r=!0)}return r&&await this.persist(e),Oo(n)}async write(e,n,r,o){this.guard(e),await xs(e.roots,n,r,o,(i,s)=>this.lock(e,i,s)),await this.recordRoots(e)}async recordRoots(e){this.guard(e);let n=!1;for(let r of e.roots){if(e.stored.roots?.some(i=>i.prefix===r.prefix&&i.root===r.root))continue;await Ds(r.root).catch(i=>{if(i.code==="ENOENT")return null;throw i})&&((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 i=()=>{if(this.guard(e),e.stored.paused&&!o)throw Error("paused");for(let[s,a]of e.rootIdentities){let c;try{c=qm(s)}catch{throw Error("Sync root unavailable: "+s)}if(!c.isDirectory()||!lt(a,c))throw Error("Sync root changed; restart before retrying")}r(),this.wroteLocal=!0};return this.host.contentSync.withWriteLock?.(n,i)??Promise.resolve().then(i)}async previewScan(e,n){for(let r of e.stored.roots??[])n.some(o=>o.prefix===r.prefix&&o.root===r.root)&&await Dt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return Oo(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=ti(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),i=Date.now();if(this.activeAt=i,o){let s=this.dirty.get(o);s?s.last=i:this.dirty.set(o,{first:i,last:i})}this.schedule(o?void 0:i+sd)}))}logical(e,n){let r=null;for(let s of e.roots)(n===s.root||n.startsWith(s.root+Rn))&&(!r||s.root.length>r.root.length)&&(r=s);if(!r)return null;let o=Sr(r.root,n).split(Rn).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+js(e),n.first+rd)}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>=sy&&e-this.lastRunAt<ay-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",i,s,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(i instanceof Buffer){u["Content-Type"]="application/octet-stream",u["Content-Length"]=String(i.length);let m=async function*(){for(let w=0;w<i.length;w+=64*1024)e.abort.signal.throwIfAborted(),yield i.subarray(w,w+64*1024),s?.(Math.min(i.length,w+64*1024))};f=ed.from(m())}else i!==void 0&&(u["Content-Type"]="application/json",f=JSON.stringify(i));let h={method:o,headers:u,body:f,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...i 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 o==="DELETE"&&this.tally("deletesSent"),p}async json(e,n,r="",o="GET",i){let s=await(await this.request(e,n,r,o,i)).json();return this.guard(e),s}async manifests(e,n){let r=new Map;for(let i of new Set(n.rules.filter(s=>s.target!=="off").map(s=>s.target))){let s=JSON.parse(await this.manifestText(e,i));Ao(s,i),await this.knownTombstones(e,i,s),r.set(i,s)}let o=[r.get("default"),r.get(`device-${this.deviceId}`)].filter(Boolean);return o.length&&(this.cloudAgents=[...new Set(o.flatMap(i=>i.nodes.filter(s=>!s.deleted&&s.kind==="file").map(s=>/^agents\/([^/]+)\/config\.toml$/.exec(s.path)?.[1]).filter(s=>!!s&&ar.test(s))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),o=r&&Date.now()-r.at<iy?r:void 0,i=await this.request(e,n,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...o?{"If-None-Match":o.etag}:{}});if(i.status===304)return await i.body?.cancel(),o?o.text:(e.manifests.delete(n),this.manifestText(e,n));let s=await i.text();this.guard(e),Ao(JSON.parse(s),n);let a=i.headers.get("etag");return r?.text!==s&&this.touch(),a?e.manifests.set(n,{etag:a,text:s,at:Date.now()}):e.manifests.delete(n),s}async knownTombstones(e,n,r){if(typeof r.tombstonesSince!="string")return;let o=new Set(r.nodes.map(l=>l.id)),i=new Set;for(let[l,u]of Object.entries(e.stored.files))l.startsWith(n+":")&&i.add(u.id);for(let[l,u]of Object.entries(e.stored.folders))l.startsWith(n+":")&&i.add(u.id);for(let[l,u]of Object.entries(e.stored.pendingUploads??{}))l.startsWith(n+":")&&i.add(u.id);let s=e.tombstones.get(n);s||e.tombstones.set(n,s=new Map);for(let l of[...s.keys()])o.has(l)&&s.delete(l);let a=Date.now(),c=[...i].filter(l=>{if(o.has(l))return!1;let u=s.get(l);return!u||!u.node&&a-u.at>=cy});for(let l=0;l<c.length;l+=od){let u=c.slice(l,l+od),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=>Wu(m)&&f.has(m.id)).map(m=>[m.id,m]));for(let m of u)s.set(m,{node:p.get(m)??null,at:a})}for(let l of i)if(!o.has(l)){let u=s.get(l)?.node;u&&r.nodes.push(structuredClone(u))}}route(e,n,r="file"){if(vo(e)||bs(e,r)===!1)return null;let o=wn(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||go(Os())}setSources(e){let n=new Map,r={files:0,size:0};for(let i of e)i.kind==="folder"&&n.set(i.path,{size:0,files:0});for(let i of e)if(i.kind==="file"){_l.some(s=>i.path.startsWith(s+"/"))||(r.files++,r.size+=i.size);for(let s=Ot(i.path);s;s=Ot(s)){let a=n.get(s);a&&(a.size+=i.size,a.files++)}}let o=new Map(e.filter(i=>i.kind==="file"&&/^agents\/[^/]+\/config\.toml$/.test(i.path)).map(i=>[i.path.slice(0,-12),i]));this.others=r,this.sources=[...n].sort(([i],[s])=>Wt(i)-Wt(s)||(i<s?-1:1)).slice(0,2e3).map(([i,s])=>({path:i,kind:"folder",size:s.size,files:s.files,...cr(i)&&o.has(i)?{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,...Cl((await Tn(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||go(Os()),i=es(o,this.devices,this.deviceId);if(i)throw Error(i==="taken"?"device_name_taken":i==="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-"+at();try{await yr(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await Mo(r,n)}finally{await br(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<Po){r-this.devicesAt>=Po&&await this.refreshDevices(e);return}let o=(a,c)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:a,...c?{unique:!0}:{}}),i=async()=>(await this.json(e,"devices")).devices,s=a=>/device_name_(taken|reserved|invalid)/.test(Ne(a));try{await o(this.deviceName(),!0)}catch(a){if(!s(a))throw a;let c=!1;if(!this.customName){let l=go(Os());for(let u=0;u<5&&!c;u++){let f=await i(),h=null;for(let p=2;p<100&&!h;p++){let m=`${l} ${p}`;es(m,f,this.deviceId)||(h=m)}if(!h)break;try{await o(h,!0),await this.saveName(h),c=!0}catch(p){if(!s(p))throw p}}}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 mr(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((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}:{}}}),i=JSON.stringify({devices:o});if(i===this.cachedDevices)return;let s=e+".tmp-"+at();try{await yr(s,i,{mode:384,flag:"wx"}),await Mo(s,e),this.cachedDevices=i}catch(a){this.error=Ne(a)}finally{await br(s).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=Sn(Il(n.stored.config),"","off");for(let a of It)a.id!=="agents"&&r[a.id]===!1&&(o=Sn(o,a.path,"off"));let i=new Set(this.sources.filter(a=>a.agent).map(a=>a.path.slice(7))),s=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(a=>typeof a=="string"&&i.has(a)):[];return this.preview(Rl(o,s))}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 i=!this.focused;this.focused=!0,this.touch(),i&&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(i=>{this.session===r&&this.setSources(i)},()=>{})),o.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(i=>{let s=i.agent&&this.agentNames.get(i.path);return s?{...i,...s.name?{name:s.name}:{},...s.nameEn?{nameEn:s.nameEn}:{}}:i}),...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:i,...s})=>s)(r.stored.agentArchive)}:{}}}stats(){let e=this.host.accountId(),n=e&&this.session?.account===e?this.session:null,r=n?.stored,o={},i=e&&e===this.logAccount?this.runLog.snapshot():new lr().snapshot();for(let s of r?.jobs??[])o[s.state]=(o[s.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(s=>({source:s.source,target:s.target})),backlog:r?{jobs:o,blocked:[...this.blocked.values()].reduce((s,a)=>s+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,...i}}async preview(e){let n=await this.getSession();if(e?.revision!==n.stored.config.revision)throw Error("config_changed");let o=Ut(e,n.stored.config.revision+1),i=await this.host.contentSync.roots();this.guard(n);let s=await this.previewScan(n,i),a=this.effective(o,s);if(n.stored.agentArchive?.state==="running"&&s.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(s);let l=0,u=0,f=0,h=0,p=new Map;for await(let S of Vt(s.filter(g=>g.kind==="file"))){let g=this.route(S.path,a);if(!g)continue;let j=c.get(g)?.nodes.find(M=>!M.deleted&&M.kind==="file"&&M.path===S.path);if(S.size>Dn){l++,h+=S.size;continue}let x=Ce(await Tn(S));this.guard(n),p.set(S.path,x),x!==j?.hash&&(l++,h+=S.size,j?.version&&f++)}let m=o.enabled?this.agentAsks(n,s,a,c,p):[];for(let[S,g]of c)for await(let j of Vt(g.nodes))!j.deleted&&j.kind==="file"&&j.version&&this.route(j.path,a)===S&&!s.some(x=>x.path===j.path)&&u++;let w=this.signature(s,c,i),y={token:at(),config:a,upload:o.enabled?l:0,download:o.enabled?u:0,conflicts:o.enabled?f:0,bytes:o.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(o=>[o.path,o.size,o.mtime,o.inode]),[...n].map(([o,i])=>[o,i.nodes.map(s=>[s.id,s.revision,s.version,s.deleted])])]))}async apply(e,n){let r=this.serial,o;this.serial=new Promise(i=>{o=i}),await r;try{let i=await this.getSession(),s=this.previewValue;if(!s||s.value.token!==e||s.account!==i.account||s.value.expiresAt<Date.now()||s.value.config.revision!==i.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let a=s.value.agentAsks??[],c=uy(n);this.resolving=!0;try{let l=await this.host.contentSync.roots(),u=await this.previewScan(i,l),f=await this.manifests(i,s.value.config);if(this.signature(u,f,l)!==s.signature)throw Error("preview_changed");let h=[];for(let y of l)await Ds(y.root).catch(g=>{if(g.code==="ENOENT")return null;throw g})&&h.push({...y,...await zn(y.root)});let p=structuredClone(s.value.config);for(let y of p.rules){let S=u.find(g=>g.kind==="folder"&&g.path===y.source);S&&(y.sourceId=await As(S))}let m=a.length?Ut(a.reduce((y,S)=>Sn(y,`agents/${S.slug}`,"off"),p),p.revision):p;if(this.guard(i),this.previewValue!==s||s.value.config.revision!==i.stored.config.revision+1)throw Error("preview_expired");let w=structuredClone(i.stored);i.stored.config=m,i.stored.owned=!0,i.stored.paused=!1,delete i.stored.unconfirmed;for(let[y,S]of Object.entries(i.stored.files))(w.config.enabled!==i.stored.config.enabled||!td(w.roots??h,h)||this.route(S.path,w.config)!==this.route(S.path,i.stored.config))&&delete i.stored.files[y];for(let[y,S]of Object.entries(i.stored.folders))(w.config.enabled!==i.stored.config.enabled||!td(w.roots??h,h)||this.route(S.path,w.config,"folder")!==this.route(S.path,i.stored.config,"folder"))&&delete i.stored.folders[y];i.stored.roots=h,i.rootIdentities=new Map(h.map(y=>[y.root,y])),await this.persist(i);try{await this.accountWrite(i,y=>this.host.contentSync.claim(!0,y))}catch(y){throw i.stored=w,await this.persist(i),await this.accountWrite(i,S=>this.host.contentSync.claim(w.owned,S)).catch(()=>{}),y}if(this.previewValue=null,i.roots=l,await this.watchRoots(i),a.length)try{await this.resolveAsks(i,a,c,p)}catch(y){throw this.fault(Ne(y)),y}i.stored.accountReview&&(delete i.stored.accountReview,await this.persist(i))}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,i){let s=e.stored.jobs.findLast(c=>c.path===n&&c.target===r&&c.direction===o&&["failed","paused","queued"].includes(c.state));if(s)return Object.assign(s,{state:"active",done:0,size:i,at:Date.now(),error:void 0,finishedAt:void 0}),s;let a={id:at(),path:n,target:r,direction:o,state:"active",done:0,size:i,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,i,s){if(this.guard(e),e.stored.paused)throw Error("paused");this.activeAt=Date.now();let a=this.job(e,n,r,o,i);try{let c=await s(a);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(a),o==="upload"?ut("content","uploads"):o==="download"&&ut("content","downloads");let l=ny[o];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,o,i=!1,s=!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,i=!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(y=>{this.error=Ne(y)}),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(y=>["failed","paused","active"].includes(y.state)&&["upload","download","merge"].includes(y.direction)).map(y=>y.target+"\0"+y.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 f=y=>y.endsWith("/"+hr),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 Vt(S.nodes.filter(j=>j.kind==="file"&&!j.busy&&f(j.path)))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.route(g.path,l)!==y||c.some(j=>j.path===g.path))){if(this.isBlocked(y,g.path)){p.add(m(g.path)??"");continue}h.add(g.id);try{await this.missing(o,g,y,c,l)}catch(j){this.error=Ne(j),p.add(m(g.path)??"")}}}for await(let y of Vt(c.filter(S=>S.kind==="file").sort((S,g)=>+!f(S.path)-+!f(g.path)))){if(this.guard(o),o.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(o,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 Vt(S.nodes.filter(j=>j.kind==="file"&&!j.busy&&!h.has(j.id)))){if(this.guard(o),o.stored.paused)throw Error("paused");if(!(this.isBlocked(y,g.path)||this.route(g.path,l)!==y||c.some(j=>j.path===g.path)||w(g.path))){if(this.holdGone(g.path)){r.add(g.path);continue}try{await this.missing(o,g,y,c,l)}catch(j){this.error=Ne(j)}}}await this.cleanupFolders(o,l,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(o).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=Po)&&(await this.accountWrite(o,y=>this.host.contentSync.changed(y)),this.changedAt=Date.now()),this.guard(o),await this.persist(o),await this.pruneBases(o),s=!0}catch(a){this.error=Ne(a)}finally{this.phase=o?.stored.paused?"paused":"idle",i&&(this.noteHealth(n,s),this.live()&&this.runLog.end(s));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&&(ut("content","cycles"),ut("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?eo(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<js(e)&&r-n.first<rd}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,o){let i=r.filter(a=>a.kind==="folder"),s=new Map;for(let a of i)if(a.localId){if(s.has(a.localId))throw Error(`Duplicate folder sync identity: ${a.path}`);s.set(a.localId,a.path)}for(let[a,c]of o){for await(let l of Vt(c.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,f)=>Wt(u.path)-Wt(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?i.find(h=>h.localId===u.localId):null)??i.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,()=>Ts(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=qe(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 Qu(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),i.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 Vt(i.sort((u,f)=>Wt(u.path)-Wt(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||bs(l.path,"folder")===!1)continue;let h=await As(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(j=>j.kind==="file"&&j.path.startsWith(l.path+"/")&&this.route(j.path,n)===a)){let j=Object.entries(e.stored.files).find(([x,M])=>x.startsWith(a+":")&&M.path===g.path)?.[1];if(!j){S=!0;break}if(!this.sameAsShadow(j,g)){let x=Ce(await Tn(g));if(x!==j.hash&&!(j.memoryDeleted&&$s(g.path)&&x===vr)){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?at():h,parentId:y,name:rn(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:rn(l.path),revision:m.revision}));for(let j of c.nodes)j.path.startsWith(S+"/")&&(j.path=l.path+j.path.slice(S.length));Object.assign(m,g);for(let[j,x]of Object.entries(e.stored.files))j.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),ut("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 o=await this.scan(e);for(let[i,s]of r)for await(let a of Vt(s.nodes.filter(c=>c.kind==="folder"&&!c.busy).sort((c,l)=>Wt(l.path)-Wt(c.path)))){if(this.isBlocked(i,a.path)||this.route(a.path,n,"folder")!==i)continue;let c=Object.entries(e.stored.folders).find(([u,f])=>u.startsWith(i+":")&&f.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(f=>f.path.startsWith(a.path+"/"))||(await wr(l.physical)).some(f=>f!==".forsion-sync-id.json"))continue;await this.operation(e,a.path,i,"delete",null,()=>this.lock(e,l.physical,()=>{dt(l.root,Sr(l.root,l.physical).split(Rn).join("/"));let f=Ym(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?In(h):null;p&&Is(h);try{Gm(l.physical)}catch(m){if(p)try{Jm(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)||s.nodes.some(u=>u.parentId===a.id&&!u.deleted))continue;await this.operation(e,a.path,i,"delete",null,()=>this.json(e,i,`/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>Dn)throw Error("File exceeds 50 MB content limit");let i=await this.request(e,r,`/nodes/${n.id}/content`),s=[],a=0;if(i.body){let l=i.body.getReader();for(;;){let u=await l.read();if(u.done)break;if(this.guard(e),a+=u.value.length,a>Dn)throw await l.cancel(),Error("Content too large");s.push(u.value),o.done=a}}let c=Buffer.concat(s);if(n.hash&&Ce(c)!==n.hash)throw Error("Cloud file changed during download");return c}async fileRenames(e,n,r,o){for(let[i,s]of o)for(let a of s.nodes.filter(c=>c.kind==="file"&&!c.deleted&&!c.busy)){let c=e.stored.files[$e(i,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)!==i))try{if(this.route(a.path,n)!==i)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,l.path,i,"rename",null,()=>Ts(e.roots,l.path,a.path,(u,f)=>this.lock(e,u,f))),c.path=a.path}catch(u){this.block(i,l.path,u),this.block(i,a.path,u)}}}async upload(e,n,r,o,i){if(o.length>Dn)throw Error("File exceeds 50 MB content limit");this.guard(e);let s=this.host.readCreds(),a=ed.from((async function*(){for(let l=0;l<o.length;l+=64*1024)e.abort.signal.throwIfAborted(),yield o.subarray(l,l+64*1024),i.done=Math.min(o.length,l+64*1024)})()),c=await fetch(s.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(r)}/nodes/${n.id}/content`,{method:"PUT",headers:{Authorization:`Bearer ${s.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,i,s){let a=$e(n,r.id),c=Ce(o),l=Ms(o);l&&o.length>=nd&&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<nd?{base:o.toString("utf8")}:{},...s?{inode:s.inode,stat:s.key,statAt:s.at}:i?{inode:i.inode}:{}}}async seen(e,n,r){let o=qe(e.roots,n),i=await Dt(De(o.root,...o.relative.split("/"))).catch(()=>null);if(!i?.isFile())return;let s=Do(i);return{key:gr(s),at:r,inode:s.inode}}sameAsShadow(e,n){return!this.dirty.has(n.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===gr(n)&&ly(n)<=e.statAt-oy}unchanged(e,n,r,o,i){let s=$e(n,r.id);return this.sameAsShadow(o,i)&&o.id===r.id&&o.path===i.path&&!r.busy&&!r.deleted&&r.version===o.version&&r.hash===o.hash&&!e.stored.unconfirmed?.[s]&&!e.stored.pendingUploads?.[s]&&!this.openJobs.has(n+"\0"+i.path)}hold(e,n){if(e.path.endsWith("/"+hr)||n?.stat===gr(e))return!1;let r=e.mtime,o=Date.now(),i=this.dirty.get(e.path);if(Math.floor(r)<=this.flushAt)return!1;if(i)i.last=Math.max(i.last,r);else{if(o-r>=js(e.path))return!1;i={first:Math.min(o,r),last:r},this.dirty.set(e.path,i)}return this.dueAt(e.path,i)>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=Ns(e),i=De(o,n);if(await Dt(i).then(()=>!0,()=>!1))return;await Rs(o,{recursive:!0,mode:448});let s=i+".tmp-"+at();try{await yr(s,r,{mode:384,flag:"wx"}),await Mo(s,i)}finally{await br(s).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await mr(De(Ns(e),n.hash)).catch(o=>{if(o.code==="ENOENT")return null;throw o});return r&&Ce(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(o=>o.hash)),r=Ns(e);for(let o of await wr(r).catch(()=>[]))n.has(o)||await br(De(r,o)).catch(()=>{})}async file(e,n,r,o,i){if(r.size>Dn){ut("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 s=i.nodes.find(S=>S.kind==="file"&&!S.deleted&&S.path===r.path);if(!s){let S=Object.entries(e.stored.files).find(([g,j])=>g.startsWith(o+":")&&j.inode===r.inode&&j.path!==r.path)?.[1];if(S){let g=qe(e.roots,S.path),j=await Dt(De(g.root,g.relative)).then(async M=>Do(M).inode!==r.inode||Ot(S.path)!==Ot(r.path)?!0:(await wr(nn(r.physical))).includes(rn(S.path)),M=>M.code==="ENOENT"?!1:Promise.reject(M)),x=i.nodes.find(M=>M.id===S.id&&!M.deleted);if(!j&&x)try{if(x.path!==S.path)throw Error(`Concurrent file rename: ${r.path}`);let M=Ot(r.path),E=M?i.nodes.find(_=>_.path===M&&_.kind==="folder"&&!_.deleted)?.id:"";if(M&&!E)throw Error("Rename parent unavailable");let T=await this.operation(e,r.path,o,"rename",null,()=>this.json(e,o,`/nodes/${x.id}`,"PATCH",{name:rn(r.path),parentId:E,revision:x.revision}));Object.assign(x,T),S.path=r.path,s=x}catch(M){for(let E of new Set([S.path,x.path,r.path]))this.block(o,E,M);throw M}}}let a=s?e.stored.files[$e(o,s.id)]:Object.entries(e.stored.files).find(([S,g])=>S.startsWith(o+":")&&g.path===r.path)?.[1];if(!a&&s?.version&&o==="default"&&(a=await this.legacyBaseline(r.path,s)),s&&a&&this.unchanged(e,o,s,a,r))return;if(this.hold(r,a))return"held";let c=Date.now(),l=await Tn(r),u=Ce(l),f={key:gr(r),at:c,inode:r.inode};if(this.guard(e),this.settled(r.path,c),!s){if((a?i.nodes.find(T=>T.id===a.id&&T.deleted):null)&&a&&(a.hash===u||a.memoryDeleted&&$s(r.path)&&u===vr)){$s(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[$e(o,a.id)]);return}let g=Ot(r.path),j=g?i.nodes.find(T=>T.path===g&&!T.deleted&&T.kind==="folder")?.id:"";if(g&&!j)throw Error("Parent folder is unavailable");let x=Object.entries(e.stored.pendingUploads??{}).find(([T,_])=>T.startsWith(o+":")&&_.path===r.path&&!i.nodes.some(P=>P.id===_.id))?.[1];for(let[T,_]of Object.entries(e.stored.pendingUploads??{}))T.startsWith(o+":")&&_.path===r.path&&i.nodes.some(P=>P.id===_.id&&P.deleted)&&delete e.stored.pendingUploads[T];let M=x?.id??at(),E=$e(o,M);(e.stored.pendingUploads??={})[E]={id:M,path:r.path},await this.persist(e),s=await this.json(e,o,"/nodes","POST",{id:M,parentId:j,name:rn(r.path),kind:"file"}),e.tombstones.get(o)?.delete(s.id),s.id!==M&&delete e.stored.pendingUploads[E],i.nodes.push(s),a=void 0}if(s.busy)return;let h=$e(o,s.id);if(s.version&&this.awaitingBytes.delete(h),s.hash===u){await this.shadow(e,o,s,l,r,f);return}if(s.hash&&e.stored.unconfirmed?.[h]===s.hash&&(await this.shadow(e,o,s,await this.operation(e,r.path,o,"download",s.size??null,S=>this.download(e,s,o,S)),r),a=e.stored.files[h]),!s.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<ty)return}if(this.awaitingBytes.delete(h),!s.version||a&&s.version===a.version){(e.stored.unconfirmed??={})[h]=u,await this.persist(e);let S=await this.operation(e,r.path,o,"upload",l.length,g=>this.upload(e,s,o,l,g));Object.assign(s,S),await this.shadow(e,o,s,l,r,f);return}let p=await this.operation(e,r.path,o,"download",s.size??null,S=>this.download(e,s,o,S)),m=p,w=!1;if(!a||a.hash!==u){let S=l.toString("utf8"),g=p.toString("utf8"),j=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,j,g):null;if(x?(m=Buffer.from(x.content),w=x.conflict):w=!0,w){await this.preserveConflict(e,r.path,l)&&(ut("content","conflicts"),this.tally("conflictCopies"));let M=this.job(e,r.path,o,"merge",l.length);M.state="conflict",M.error="Both versions preserved",M.finishedAt=Date.now()}if(!m.equals(p)){let M=await this.operation(e,r.path,o,"merge",m.length,E=>this.upload(e,s,o,m,E));Object.assign(s,M)}}let y=Date.now();await this.write(e,r.path,m,u),await this.shadow(e,o,s,m,r,await this.seen(e,r.path,y))}async preserveConflict(e,n,r){let o=qe(e.roots,n),i=await nt(o.root,o.relative),s=rn(n),a=Ce(r);for(let c of await wr(nn(i))){if(c.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==s||!vo(c))continue;let l=Ot(n)?Ot(n)+"/"+c:c,u=qe(e.roots,l),f=await nt(u.root,u.relative),h=await Dt(f);if(h.isFile()&&h.size===r.length&&Ce(await mr(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 o=1;;o++){let i=$u(n,r,o),s=qe(e.roots,i);if(!await Dt(De(s.root,...s.relative.split("/"))).then(()=>!0,a=>a.code==="ENOENT"?!1:Promise.reject(a)))return i}}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,i){let s=[],a=c=>c.length?Math.max(...c):null;for(let c of n){let l=c.kind==="folder"?cr(c.path):null;if(!l||mo.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=(o.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&&i.get(y.path)!==S.hash}).length;!w&&p.length===h.length&&p.every(y=>m.has(y.path))||s.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 s}async resolveAsks(e,n,r,o){for(let i of n){try{await this.resolveAsk(e,i,r[i.slug]??"merge",o)}catch(l){throw this.dropShadows(e,i.namespace,`agents/${i.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Ne(l)}`)}let s=`agents/${i.slug}`,a=o.rules.find(l=>l.source===s),c=Sn(e.stored.config,s,Al(o,s));a&&(c={...c,rules:c.rules.map(l=>l.source===s?{...a,target:l.target}:l)}),e.stored.config=Ut(c,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,o){let i=n.namespace,s=`agents/${n.slug}/`;if(this.dropShadows(e,i,s),r==="local"){await this.archiveAgent(e,i,n.slug),await this.persist(e);return}let a=await this.json(e,i);this.guard(e),Ao(a,i);let c=new Map(a.nodes.filter(p=>!p.deleted&&!p.busy&&p.kind==="file"&&p.version&&p.path.startsWith(s)&&this.route(p.path,o)===i).map(p=>[p.path,p])),l=p=>p.endsWith("/"+hr),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=qe(e.roots,p);if(id(De(w.root,w.relative)))continue;let y=await this.operation(e,p,i,"download",m.size??null,S=>this.download(e,m,i,S));await this.shadow(e,i,m,y,void 0,await u(p,y,null))}let f=(await this.scan(e)).filter(p=>p.kind==="file"&&p.path.startsWith(s)&&this.route(p.path,o)===i&&p.size<=Dn).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 Tn(p),w=Ce(m),y=c.get(p.path),S=p.path.slice(s.length);if(y&&y.hash===w){await this.shadow(e,i,y,m,p);continue}if(r==="cloud"){if(await this.keep(e,`${h}/${S}`,m),y){let E=await this.operation(e,p.path,i,"download",y.size??null,T=>this.download(e,y,i,T));await this.shadow(e,i,y,E,p,await u(p.path,E,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,i,"download",y.size??null,E=>this.download(e,y,i,E)),j=i==="default"?await this.legacyBaseline(p.path,y):void 0;if(j?.hash===w){await this.shadow(e,i,y,g,p,await u(p.path,g,w));continue}let x=j?await this.readBase(e,j):null,M=Ms(m)&&Ms(g)?this.host.contentSync.merge(p.path,m.toString("utf8"),x,g.toString("utf8")):null;if(M&&!M.conflict){let E=Buffer.from(M.content);E.equals(m)||await this.write(e,p.path,E,w),await this.shadow(e,i,y,g)}else(y.mtime??0)>p.mtime?(await this.keep(e,`${h}/${S}`,m),await this.shadow(e,i,y,g,p,await u(p.path,g,w))):(await this.keep(e,`${h}/${S}`,g),await this.shadow(e,i,y,g))}await this.persist(e)}dropShadows(e,n,r){for(let[o,i]of Object.entries(e.stored.files))o.startsWith(n+":")&&i.path.startsWith(r)&&(delete e.stored.files[o],delete e.stored.unconfirmed?.[o])}async removedDir(e,n,r="agents"){let o=new Date,i=a=>String(a).padStart(2,"0"),s=`${o.getFullYear()}-${i(o.getMonth()+1)}-${i(o.getDate())} ${i(o.getHours())}${i(o.getMinutes())}`;for(let a=1;;a++){let c=`${r}/.removed/${n} ${s}${a>1?` ${a}`:""}`,l=qe(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 xs(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(dt(n.root,Sr(n.root,n.physical).split(Rn).join("/")),Ce(In(n.physical))!==r)throw Error("Local file changed before replacing");Is(n.physical)})}async archiveAgent(e,n,r){let o=this.host.readCreds();if(!o.token)throw Error("not_signed_in");let i=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:at(),locale:this.locale()}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)])});this.guard(e);let s=await i.json().catch(()=>({}));if(this.guard(e),!i.ok||s?.state!=="done")throw Error(typeof s?.detail=="string"?s.detail:`agent_archive_http_${i.status}`)}async absent(e,n){this.guard(e);let r=qe(e.roots,n),o=await nt(r.root,r.relative);try{return await Dt(o),!1}catch(i){if(i.code==="ENOENT")return!0;throw i}}async missing(e,n,r,o,i){let s=e.stored.files[$e(r,n.id)],a=e.stored.pendingUploads?.[$e(r,n.id)];if(n.deleted){s&&delete e.stored.files[$e(r,n.id)],a&&delete e.stored.pendingUploads[$e(r,n.id)];return}if(n.busy||s?.inode&&this.blocked.has(r)&&o.some(u=>u.kind==="file"&&u.inode===s.inode&&this.isBlocked(r,u.path)&&this.route(u.path,i)===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(s&&s.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 Oo(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);l&&(n.path=l.path+"/"+rn(n.path))}let r=qe(e.roots,n.path),o=await nt(r.root,r.relative);if(!/^\.forsion-sync-trash-[a-f0-9-]+$/.test(n.stage))throw Error("Invalid sync recovery journal");let i=n.stageRoot??r.root,s=await this.rootIdentity(e,i),a=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(a&&!ln(a,s))throw Error("Sync recovery root changed; journal retained");let c=De(i,n.stage);await Dt(c).then(()=>!0,l=>l.code==="ENOENT"?!1:Promise.reject(l))&&await this.lock(e,o,()=>{if(dt(i,n.stage,!0),Ce(In(c))!==n.hash)throw Error("Sync recovery content changed");dt(r.root,r.relative),Km(nn(o),{recursive:!0});let l=id(o)?o+` (sync recovery ${at().slice(0,8)})`:o;try{Vm(c,l)}catch(u){if(u.code!=="EXDEV")throw u;if(Xm(c,l,Zm.COPYFILE_EXCL),Ce(In(l))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}Is(c)},!0),e.stored.trash=e.stored.trash.filter(l=>l!==n)}}async clearDeletedMemory(e,n,r,o,i,s){o.memoryDeleted&&o.hash===vr&&s===vr||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!o.memoryDeleted&&i.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`,i)}o.memoryDeleted=!0,await this.persist(e);let a=Date.now();i.length&&await this.write(e,r.path,Buffer.alloc(0),s);let c=await this.seen(e,r.path,a);e.stored.files[$e(n,o.id)]={...o,hash:vr,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 nt(n.root,Sr(n.root,n.physical).split(Rn).join("/")),i={path:n.path,stage:".forsion-sync-trash-"+at(),hash:r},s=De(n.root,i.stage),a=await this.rootIdentity(e,n.root);i.stageRoot=n.root,i.stageDev=a.dev,i.stageIno=a.ino,i.stageIdentity=a;try{let c=JSON.parse(In(De(nn(o),".forsion-sync-id.json"),"utf8")).id;/^[a-f0-9-]{36}$/i.test(c)&&(i.parentId=c)}catch{}(e.stored.trash??=[]).push(i),await this.persist(e);try{await this.lock(e,o,()=>{if(dt(n.root,Sr(n.root,o).split(Rn).join("/")),Ce(In(o))!==r)throw Error("Local file changed before deletion");Wm(o,s)}),await this.host.contentSync.trash(s),e.stored.trash=e.stored.trash.filter(c=>c!==i)}catch(c){throw this.host.accountId()===e.account&&!e.abort.signal.aborted&&await this.recoverTrash(e),c}}};function uy(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))ar.test(n)&&kl.includes(r)&&(e[n]=r);return e}function id(t){try{return Bm(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}aa(Ba);function r0(t){za(t.contentSync?.withWriteLock?.bind(t.contentSync)),ya(t),yi(t),ad(t),t.log("[forsion-extend] cloud account handlers registered"),ci(t)?li(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),di(t)?fi(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),_i(t)?Ci(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),Bi(t)?qi(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),Vi(t)?Yi(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),ss(t)?lu(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),ss(t)&&Ou(t)}export{bc as ACCOUNT_SEAM,ll as AMADEUS_SEAM,ai as CONNECT_MAX_FILES,Va as CONNECT_MAX_FILE_BYTES,Ya as CONNECT_MAX_TOTAL_BYTES,Gr as DIAGNOSTICS_VAULT,nc as FORSION_CONNECT_LOCAL_SDK,ga as PAY_PERIODS,ha as PAY_TABS,ic as PENZOR_MAX_FILE,Re as SYNC_IPC,fl as UNIT_SEAM,qn as UPLOAD_MAX_FILE,rr as UnitCapsReporter,nr as UnitHost,Ve as cloudJson,Ja as collectProjectFiles,Zr as conflictCopyPath,Pp as conflictCopyVariant,ec as connectMetaOf,wc as createAccountCloud,ul as createAmadeusCloud,Yr as createPenzorRemote,pl as createUnitHub,Vr as deviceHeader,ui as expectedPartsOf,Ue as forsionAccountId,$r as forsionRefreshToken,Bn as forsionWhoami,_i as hasAccountHost,Bi as hasAmadeusHost,ci as hasConnectHost,di as hasRemoteSyncHost,Vi as hasUnitHost,tc as makePreviewProxy,hc as multipartFrame,Xa as readConnectMeta,Ci as registerAccount,qi as registerAmadeus,r0 as registerCloud,li as registerConnect,fi as registerPenzor,yi as registerPenzorTransfers,Yi as registerUnit,Jr as safeDownloadName,Qa as scanSdkUsage,Pr as shouldRefreshToken,pi as speedOf,dl as streamWorthy,Gc as stripConflictSuffix,$p as textFingerprint,Bo as tokenAgeMs,da as tokenRemainingMs,hi as uploadError,Za as writeConnectMeta};
|
|
285
|
+
`,{encoding:"utf8",mode:384});try{if(ey(o()).size>gd){let A=h(),j=A.length,F=0;for(;j>0&&F+Buffer.byteLength(JSON.stringify(A[j-1]))+1<=gd/2;)F+=Buffer.byteLength(JSON.stringify(A[--j]))+1;T(o(),A.slice(j))}}catch{}h().length>=sy&&Q()}},ee=()=>{let C=f();return{available:!!c,enabled:C.enabled!==!1,noticeSeen:C.noticeSeen===!0,signedIn:y(),active:b(C),packaged:c?.packaged===!0,installId:m(),queued:Qm(o())?h().length:0,lastSentAt:C.lastSentAt??null,lastError:C.lastError??null}},J=()=>od({app:"desktop",appVersion:t.appVersion(),coreVersion:c?.coreVersion()??void 0,channel:c?.channel(),os:ky(process.platform),osVersion:ny(),arch:Ey(process.arch),locale:_y()}),se=td,te=async C=>{try{let A=await C.json?.();return!!A&&typeof A=="object"&&A.detail==="unsupported v"}catch{return!1}},ae=null,Q=()=>{if(ae)return ae;if(L||n().getTime()<V)return Promise.resolve();let C=x,A=v,j=(async()=>{try{for(let F=0;F<5;F++){let z=h();if(!z.length)return;let q=m(),ne={v:se,installId:q,...J()},re=[],Z=Buffer.byteLength(JSON.stringify({...ne,events:[]}));for(let X of z){let ve=Buffer.byteLength(JSON.stringify(X))+1;if(re.length>=Bo.maxEvents||Z+ve>Bo.maxBatchBytes)break;re.push(X),Z+=ve}if(!re.length){T(o(),z.slice(1));continue}let{base:ie}=await t.getCloud(),oe={...ne,events:re};if(!H()||C!==x)return;let pe=await r(`${ie.replace(/\/+$/,"")}/api/telemetry/batch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(oe),signal:AbortSignal.timeout(md)}).catch(X=>({ok:!1,status:0,error:String(X?.message||X)})),le=pe.status;if(le===400&&ne.v>Ko&&await te(pe)){se=Ko,t.log(`[forsion-extend] telemetry server does not accept v${ne.v}; resending as v${Ko}`);continue}if(le>=200&&le<300||le===400||le===413){let X=new Set(re.map(ve=>JSON.stringify(ve)));T(o(),h().filter(ve=>!X.has(JSON.stringify(ve))))}if(le>=200&&le<300){let X=n().getTime();A===v&&T(l(),[...D(),{at:X,body:oe}]),p({lastSentAt:X,lastError:void 0});continue}if(le!==400&&le!==413){let X=Number(pe.headers?.get?.("retry-after"));V=n().getTime()+(Number.isFinite(X)&&X>0?Math.min(X,3600)*1e3:5*6e4)}p({lastError:le?`HTTP ${le}`:String(pe.error??"network error").slice(0,200)});return}}catch(F){try{p({lastError:String(F?.message||F).slice(0,200)})}catch{}}})();return ae=j,j.finally(()=>{ae===j&&(ae=null)}),j},me=C=>{if(!I||!C&&Math.floor(n().getTime()/wd)===I.hour)return;let A=I;if(I=null,A.gen!==x||!H())return;let j=Qt({event:"quota_prompt",ts:n().toISOString(),sessionId:c?.sessionId,props:{...A.counts,entry:"quota-page"}});try{j&&Object.keys(j.props).some(F=>F!=="entry")&&Y([j])}catch(F){throw I=A,F}},ge=async()=>{try{if(D(),me(!1),!H())return;let C=f(),A=x,j=C.cursor??Zo(n().getTime()),F=await by(i(),j,c?.sessionId,Sd(n().getTime()));if(!H()||A!==x)return;Y(F.events),F.cursor!==j&&p({cursor:F.cursor}),await Pe(A),await Q()}catch(C){t.log(`[forsion-extend] telemetry tick failed: ${String(C?.message||C)}`)}},Pe=async C=>{let A=n().getTime(),j=Tn(A),F=Tn(A-yd),z=f().ledgerCursor;if(In(z)||(z=F,p({ledgerCursor:z})),yo(z),z>=F){Ce();return}let q=await Sy(i(),z,j);if(!(!H()||C!==x)){if(q){let ne=q.complete?F:q.days[q.days.length-1]?.day??z;if(ne>z){let re=Vc(z,ne),Z=[...new Set([...q.days.map(oe=>oe.day),...re.map(oe=>oe.day)])].filter(oe=>oe>z&&oe<=ne).sort(),ie=[];for(let oe of Z){ie.push(...q.days.find(pe=>pe.day===oe)?.events??[]);for(let pe of re)if(pe.day===oe){let le=vy(oe,pe.system,pe.counts);le&&ie.push(le)}}Y(ie),p({ledgerCursor:ne}),yo(ne)}}Ce()}},Ce=()=>{if(!Wc())return;let C=g();if(!C)return;let A=qc();p({syncHealth:Object.keys(A).length?A:void 0},C),Gc()},He=c?.subscribe(C=>{try{if(!uy.has(C?.event)||!H())return;let A=hy(C);if(!A)return;let j=Qt({...A,sessionId:c.sessionId},ty()),F=yy[C.event];j&&(!F||j.props[F]!==void 0)&&Y([j])}catch(A){t.log(`[forsion-extend] telemetry event dropped: ${String(A?.message||A)}`)}}),Ae={ok:!1,error:"untrusted"};t.handle("telemetry:get",C=>t.isTrustedSender(C)?(H(),ee()):Ae),t.handle("telemetry:set",(C,A)=>{if(!t.isTrustedSender(C))return Ae;let j=f(),F={};typeof A?.enabled=="boolean"&&(F.enabled=A.enabled),A?.noticeSeen===!0&&(F.noticeSeen=!0);let z={...j,...F};return!b(j)&&b(z)&&(F.cursor=Zo(n().getTime()),F.ledgerCursor=u()),b(j)&&!b(z)&&x++,F.enabled===!1&&(F.syncHealth=void 0),p(F),F.enabled===!1&&E(),H(),ee()}),t.handle("telemetry:quotaPrompt",(C,A)=>{if(!t.isTrustedSender(C))return Ae;let j=A?.action;return A?.entry!=="quota-page"||typeof j!="string"||!dy.has(j)?{ok:!1,error:"invalid"}:(me(!1),H()?((!I||I.gen!==x)&&(I={hour:Math.floor(n().getTime()/wd),gen:x,counts:{}}),I.counts[j]=Math.min((I.counts[j]??0)+1,fy),{ok:!0,counted:!0}):{ok:!0,counted:!1})}),t.handle("telemetry:sent",C=>t.isTrustedSender(C)?{batches:D()}:Ae),t.handle("telemetry:delete",async C=>{if(!t.isTrustedSender(C))return Ae;L=!0,x++;try{await ae?.catch(()=>{});let A=m(),{base:j}=await t.getCloud(),z=(await r(`${j.replace(/\/+$/,"")}/api/telemetry/install/${A}`,{method:"DELETE",signal:AbortSignal.timeout(md)}).catch(q=>({ok:!1,status:0,error:String(q?.message||q)}))).status;return z>=200&&z<300?(E(),p({installId:dd(),lastSentAt:void 0,lastError:void 0,ledgerCursor:u(),syncHealth:void 0}),ee()):{ok:!1,error:z?`HTTP ${z}`:"network error"}}finally{L=!1}});try{Bc(f().syncHealth),N(),H()}catch(C){t.log(`[forsion-extend] telemetry startup check failed: ${String(C?.message||C)}`)}let ut=t.addFlushHook?.(C=>{if(C!=="blur"){try{Ce()}catch{}try{me(!0)}catch{}}}),M=setTimeout(()=>void ge(),iy),U=setInterval(()=>void ge(),ry);return M.unref?.(),U.unref?.(),t.log(`[forsion-extend] telemetry registered (${c?c.packaged?"packaged":"dev build: never sends":"host has no telemetry seam: never sends"})`),Object.assign(()=>{clearTimeout(M),clearInterval(U),He?.(),ut?.()},{tick:ge,flush:Q})}import{readFileSync as Gn,lstatSync as Zy,statSync as Qy,renameSync as ew,linkSync as tw,unlinkSync as aa,readdirSync as nw,rmdirSync as rw,writeFileSync as iw,mkdirSync as sw,copyFileSync as ow,constants as aw}from"node:fs";import{readFile as Pr,writeFile as $r,mkdir as la,rename as rs,readdir as jr,lstat as Bt,stat as ca,unlink as Lr}from"node:fs/promises";import{join as Fe,dirname as wn,relative as Fr,sep as Vn}from"node:path";import{hostname as ua}from"node:os";import{createHash as lw,randomUUID as mt}from"node:crypto";import{isUtf8 as da}from"node:buffer";import{Readable as cw}from"node:stream";import{performance as fa}from"node:perf_hooks";import{setImmediate as uw}from"node:timers/promises";var Cy=["config.toml","SOUL.md","HARNESS.md","HUMAN.md","MEMORY.md","CALENDAR.db"],Ay=["HUMAN.md","AGENT.md","SOUL.md","MEMORY.md","CALENDAR.db"],Or=".memory-tombstones.json",Ed=t=>/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}\/data\.db$/.test(t),kd=t=>t==="WidgetData"||/^WidgetData\/[a-z0-9][a-z0-9_-]{0,63}$/.test(t),xy=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)&&Number.isFinite(Date.parse(`${t}T00:00:00Z`))&&new Date(`${t}T00:00:00Z`).toISOString().slice(0,10)===t,Ty=t=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(t)&&!t.startsWith("__");function Iy(t){if(!t||t.length>1024||/[\\\x00-\x1f:]/.test(t))return!1;if(t===Or)return!0;let e=t.split("/");return e.some(n=>!n||n.startsWith(".")||n.endsWith(".")||n.endsWith(" "))?!1:Cy.includes(t)||Ed(t)?!0:t.startsWith("LOG/")?e.length===2&&t.endsWith(".md")&&xy(e[1].slice(0,-3)):e.length>1&&e[0]==="Library"}var Ry=t=>t==="muse"||/^historian-[a-z0-9]{1,12}$/.test(t),Dy=/\(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,Oy=/\(conflict [A-Za-z0-9_-]{1,64} \d{10,}\)/;function Gi(t){let e=t.slice(t.lastIndexOf("/")+1);return Dy.test(e)||Oy.test(e)}function _d(t,e,n=1){let r=t.lastIndexOf("/"),i=r<0?"":t.slice(0,r+1),s=r<0?t:t.slice(r+1),a=s.lastIndexOf("."),o=a>0?s.slice(0,a):s,l=a>0?s.slice(a):"",c=f=>String(f).padStart(2,"0"),u=`${e.getFullYear()}-${c(e.getMonth()+1)}-${c(e.getDate())} ${c(e.getHours())}${c(e.getMinutes())}${n>1?` ${n}`:""}`;return`${i}${o} (conflict ${u})${l}`}function Qo(t,e="file"){if(t==="agents"||t==="human")return e==="folder";let n=t.startsWith("human/"),r=t.startsWith("agents/");if(!n&&!r)return null;if(Gi(t))return!1;if(n){let c=t.slice(6);return e==="folder"?kd(c):Ay.includes(c)||Ed(c)}let i=t.slice(7),s=i.indexOf("/"),a=s<0?i:i.slice(0,s),o=s<0?"":i.slice(s+1);if(!Ty(a)||Ry(a))return!1;if(e==="file")return Iy(o);if(o===""||o==="LOG"||kd(o))return!0;let l=o.split("/");return l[0]==="Library"&&l.every(c=>c&&!c.startsWith(".")&&!c.endsWith(".")&&!c.endsWith(" "))}import{isAbsolute as My}from"node:path";var it=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Dt=t=>typeof t=="string",hn=t=>Dt(t)&&t.length>0,Ut=t=>typeof t=="boolean",gn=t=>typeof t=="number"&&Number.isFinite(t),zn=t=>gn(t)&&Number.isSafeInteger(t)&&t>=0,Cd=t=>gn(t)&&Number.isInteger(t)&&t>=0,xd=t=>zn(t)&&t>0,mn=t=>Dt(t)&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t),Ji=t=>Dt(t)&&/^[a-f0-9]{64}$/.test(t),ea=t=>Dt(t)&&/^(default|device-[A-Za-z0-9_-]{1,64})$/.test(t),Mr=(t,e)=>Dt(t)&&e.includes(t),be=(t,e)=>t===void 0||e(t),Td=(t,e,n)=>e.every(r=>be(t[r],n)),Id=t=>Dt(t)&&!t.includes("\0")&&My(t);function Ht(t,e=!1){try{return Xt(t,e),!0}catch{return!1}}var Rd=t=>Ht(t)&&!t.includes("/")&&Buffer.byteLength(t)<=255,Dd=t=>t===""||mn(t);function Yi(t,e){let n=t.indexOf(":");return n>0&&mn(e)&&t.slice(n+1)===e&&ea(t.slice(0,n))}function Ny(t,e){return it(e)&&Yi(t,e.id)&&Ht(e.path)&&hn(e.version)&&Ji(e.hash)&&Td(e,["base","inode","stat"],Dt)&&be(e.statAt,gn)&&be(e.memoryDeleted,Ut)&&be(e.file,hn)}function Py(t,e){return it(e)&&Yi(t,e.localId)&&mn(e.id)&&Ht(e.path)&&xd(e.revision)&&Dd(e.parentId)&&Rd(e.name)}function $y(t){return it(t)&&mn(t.id)&&Ht(t.path)&&ea(t.target)&&Mr(t.direction,["upload","download","merge","rename","delete"])&&Mr(t.state,["queued","active","done","failed","paused","conflict"])&&zn(t.done)&&(t.size===null||zn(t.size))&&gn(t.at)&&be(t.error,Dt)&&be(t.finishedAt,gn)}function jy(t){return it(t)&&Ht(t.path)&&Ji(t.hash)&&Dt(t.stage)&&/^\.forsion-sync-trash-[a-f0-9-]+$/.test(t.stage)&&be(t.parentId,mn)&&be(t.stageRoot,Id)&&be(t.stageIdentity,Vt)&&(t.stageDev===void 0&&t.stageIno===void 0||t.stageRoot!==void 0&&Cd(t.stageDev)&&Cd(t.stageIno))}function Ly(t){return it(t)&&Ht(t.prefix,!0)&&Id(t.root)&&(t.dev===void 0&&t.ino===void 0&&t.volumeId===void 0&&t.birthtimeMs===void 0||Vt(t))}function Fy(t){return it(t)&&Mr(t.state,["running","done"])&&Ut(t.seen)&&Td(t,["name","folderId","shelfId","shelfName"],Dt)&&be(t.files,zn)&&be(t.at,gn)&&be(t.rewritten,Ut)}function Ad(t){return it(t)&&hn(t.key)&&ea(t.ns)&&mn(t.id)&&Ht(t.path)&&Mr(t.side,["cloud","local"])}function Uy(t){return it(t)&&Ut(t.latched)&&Hn(t.pending,Ad)&&be(t.confirmed,e=>Hn(e,hn))&&be(t.restore,e=>Hn(e,Ad))}var Vi=(t,e)=>it(t)&&Object.entries(t).every(([n,r])=>e(n,r)),Hn=(t,e)=>Array.isArray(t)&&t.every(e);function Od(t){if(!it(t)||!it(t.config)||!zn(t.config.revision)||!Ut(t.owned)||!Ut(t.paused)||!Vi(t.files,Ny)||!Vi(t.folders,Py)||!Hn(t.jobs,$y)||!be(t.accountReview,Ut)||!be(t.deleteGuard,Uy)||!be(t.agentArchive,Fy)||!be(t.roots,e=>Hn(e,Ly))||!be(t.trash,e=>Hn(e,jy))||!be(t.unconfirmed,e=>Vi(e,(n,r)=>Yi(n,n.slice(-36))&&Ji(r)))||!be(t.pendingUploads,e=>Vi(e,(n,r)=>it(r)&&Yi(n,r.id)&&Ht(r.path))))throw Error("Invalid content sync state; original data was retained");Zt(t.config,t.config.revision)}function Md(t){return it(t)&&mn(t.id)&&Dd(t.parentId)&&Rd(t.name)&&Ht(t.path)&&Mr(t.kind,["file","folder"])&&xd(t.revision)&&Ut(t.deleted)&&be(t.busy,Ut)&&be(t.version,hn)&&be(t.hash,Ji)&&be(t.size,zn)&&be(t.mtime,gn)&&be(t.file,hn)&&t.version===void 0==(t.hash===void 0)}function Nd(t){return Md(t)&&t.deleted===!0}function Ki(t,e){let n=()=>Error("Incomplete or invalid cloud content manifest");if(!it(t)||t.schemaVersion!==1||t.namespace!==e||!hn(t.folder)||!Array.isArray(t.nodes))throw n();let r=new Map,i=new Set;for(let s of t.nodes){if(!Md(s)||r.has(s.id)||!s.deleted&&i.has(s.path))throw n();r.set(s.id,s),s.deleted||i.add(s.path)}for(let s of r.values()){let a=s.parentId?r.get(s.parentId):void 0;if(s.parentId&&(!a||a.kind!=="folder"||a.deleted&&!s.deleted)||s.path!==(a?a.path+"/"+s.name:s.name))throw n()}}import{constants as Pd,lstatSync as yn,readdirSync as Hy,readFileSync as zy,renameSync as Xi,unlinkSync as By,linkSync as qy,mkdirSync as es,realpathSync as ta,rmdirSync as Wy}from"node:fs";import{open as Fd,lstat as Zi,readdir as $d,realpath as Ud,readFile as na,writeFile as Gy,mkdir as Hd,unlink as Vy}from"node:fs/promises";import{join as zt,dirname as Qi,relative as ra,sep as ts}from"node:path";import{randomUUID as zd,createHash as Yy}from"node:crypto";var Nr=t=>`${t.size}:${t.mtime}:${t.ctime}:${t.inode}`,Bn=t=>({size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,inode:`${t.dev}:${t.ino}:${t.birthtimeMs}`}),Bd=".forsion-sync-id.json",Jy=new Set([".git","node_modules",".DS_Store",".Trash",".trash","__pycache__",".cache"]),jd=t=>!Jy.has(t)&&!t.startsWith(".forsion-sync")&&!/\.tmp-[0-9]|\.lock$|-(wal|shm)$/.test(t)&&(!t.startsWith(".")||t===".memory-tombstones.json"),Oe=t=>Yy("sha256").update(t).digest("hex");function qd(t){if(process.platform==="win32"&&t.split("/").some(e=>/[:*?"<>|]/.test(e)||/^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\..*)?$/i.test(e)))throw Error("This name is not a safe Windows file destination")}async function ct(t,e,n=!1){if(n){if(e.split("/").some(o=>o===".."||o==="."||!o)||e.startsWith("/")||e.includes("\\"))throw Error("Invalid internal content path")}else Xt(e,!0);qd(e);let r=await Ud(t),i=zt(r,...e.split("/").filter(Boolean)),s=ra(r,i);if(s===".."||s.startsWith(".."+ts))throw Error("Content path escapes root");let a=r;for(let o of s.split(ts).filter(Boolean)){a=zt(a,o);try{if((await Zi(a)).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(l){if(l.code!=="ENOENT")throw l}}return i}function vt(t,e,n=!1){if(n||Xt(e,!0),qd(e),e.split("/").some(s=>s===".."||s===".")||e.startsWith("/")||e.includes("\\"))throw Error("Unsafe sync path");let i=ta(t);for(let s of e.split("/").filter(Boolean)){i=zt(i,s);try{if(yn(i).isSymbolicLink())throw Error("Content symlinks are not synchronized")}catch(a){if(a.code!=="ENOENT")throw a}}return i}var Ld=t=>t?.code!=="ENOENT";async function ns(t){let e=new Map,n=[],r=[],i=new Set,s=t.filter(u=>u.prefix).map(u=>u.prefix),a=[];for(let u of t)try{a.push({...u,root:await Ud(u.root)})}catch(f){if(f.code!=="ENOENT")throw f}if(new Set(a.map(u=>u.root)).size!==a.length)throw Error("Managed roots refer to the same directory; choose a separate vault folder");let o=u=>{try{return Xt(u),!0}catch{return!1}},l=async u=>{let f;try{f=await $d(u,{withFileTypes:!0})}catch{return}for(let g of f){if(!jd(g.name)||!g.isDirectory()&&!g.isFile())continue;let p=zt(u,g.name);try{let m=await Zi(p);if(m.isSymbolicLink())continue;i.add(Bn(m).inode),m.isDirectory()&&await l(p)}catch{}}};for(let u of a){let f=u.root;if(!(await Zi(f)).isDirectory())throw Error(`Sync root is not a directory: ${u.prefix||"Forsion"}`);let g=async(p,m)=>{let y;try{y=await Zi(p)}catch(h){if(!m||p===f)throw h;Ld(h)&&(n.push({path:m,reason:"unreadable"}),r.push(m));return}if(y.isSymbolicLink()||p!==f&&a.some(h=>h!==u&&h.root===p)||m&&u.prefix===""&&s.some(h=>m===h||m.startsWith(h+"/")))return;if(m&&!o(m)){n.push({path:m,reason:"invalid-name"}),i.add(Bn(y).inode),y.isDirectory()&&await l(p);return}let b,_=null;if(y.isDirectory())try{try{let h=JSON.parse(await na(zt(p,Bd),"utf8"));/^[a-f0-9-]{36}$/i.test(h.id)&&(b=h.id)}catch(h){if(h.code!=="ENOENT"&&!(h instanceof SyntaxError))throw h}_=await $d(p,{withFileTypes:!0})}catch(h){if(!m||p===f)throw h;if(!Ld(h))return;n.push({path:m,reason:"unreadable"}),r.push(m);return}if(m&&e.set(m,{path:m,physical:p,root:f,kind:y.isDirectory()?"folder":"file",localId:b,...Bn(y),size:y.isFile()?y.size:0}),!!_)for(let h of _)!jd(h.name)||!h.isDirectory()&&!h.isFile()||await g(zt(p,h.name),m?`${m}/${h.name}`:h.name)};await g(f,u.prefix)}let c=[...e.values()].sort((u,f)=>u.path.split("/").length-f.path.split("/").length||u.path.localeCompare(f.path));return Ky(c,{skipped:n,unscanned:r,skippedInodes:i})}function Ky(t,e){for(let[n,r]of Object.entries(e))Object.defineProperty(t,n,{value:r,enumerable:!1,configurable:!0});return t}var qn=(t,e)=>t.some(n=>e===n||e.startsWith(n+"/"));async function ia(t){if(t.kind!=="folder")throw Error("Folder identity required");if(t.localId)return t.localId;let e=await ct(t.root,ra(t.root,zt(t.physical,Bd)).split(ts).join("/"),!0),n=zd();try{let r=await Fd(e,"wx",384);try{await r.writeFile(JSON.stringify({version:1,id:n})+`
|
|
286
|
+
`)}finally{await r.close()}return t.localId=n,n}catch(r){if(r.code!=="EEXIST")throw r;let i=JSON.parse(await na(e,"utf8"));if(!/^[a-f0-9-]{36}$/i.test(i.id))throw Error("Invalid folder sync identity");return t.localId=i.id,i.id}}async function Wn(t){let e=await ct(t.root,ra(t.root,t.physical).split(ts).join("/")),n=await Fd(e,Pd.O_RDONLY|(Pd.O_NOFOLLOW||0));try{if((await n.stat()).size>50*1024*1024)throw Error("File exceeds 50 MB content limit");return await n.readFile()}finally{await n.close()}}function Ke(t,e){Xt(e);let n=[...t].sort((r,i)=>i.prefix.length-r.prefix.length).find(r=>!r.prefix||e===r.prefix||e.startsWith(r.prefix+"/"));if(!n)throw Error("Content root unavailable");return{root:n.root,relative:n.prefix?e.slice(n.prefix.length).replace(/^\//,""):e}}async function sa(t,e,n,r,i=async(s,a)=>a()){let s=Ke(t,e);await Hd(s.root,{recursive:!0});let a=await ct(s.root,s.relative),o=await na(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});if((o?Oe(o):null)!==r)throw Error("Local file changed during download");let l=zt(s.root,`.forsion-sync-${zd()}.tmp`);try{await Gy(l,n,{flag:"wx",mode:384}),await ct(s.root,s.relative),await i(a,()=>{vt(s.root,s.relative),es(Qi(a),{recursive:!0}),vt(s.root,s.relative);let c=null;try{c=zy(a)}catch(u){if(u.code!=="ENOENT")throw u}if((c?Oe(c):null)!==r)throw Error("Local file changed during download");Xi(l,a)})}finally{await Vy(l).catch(()=>{})}}async function Wd(t,e,n=async(r,i)=>i()){let r=Ke(t,e);await Hd(r.root,{recursive:!0});let i=await ct(r.root,r.relative);await n([i],()=>{vt(r.root,r.relative),es(i,{recursive:!0})})}async function oa(t,e,n,r=async(i,s)=>s()){let i=Ke(t,e),s=Ke(t,n);if(i.root!==s.root)throw Error("Folder move crosses a managed source");let a=await ct(i.root,i.relative),o=await ct(s.root,s.relative);await r([a,o],()=>{if(vt(i.root,i.relative),vt(s.root,s.relative),Xy(o)){let c=yn(a),u=yn(o),f=ta(Qi(a));if((c.dev===u.dev&&c.ino===u.ino&&f===ta(Qi(o))?Hy(f).filter(m=>{let y=yn(zt(f,m));return y.dev===c.dev&&y.ino===c.ino}):[]).length!==1)throw Error("Local rename destination exists");Xi(a,o);return}es(Qi(o),{recursive:!0});let l=yn(a);if(l.isDirectory()){if(process.platform==="win32"){Xi(a,o);return}es(o,{mode:448});try{Xi(a,o)}catch(c){try{Wy(o)}catch{}throw c}}else{qy(a,o);let c=yn(a);if(c.ino!==l.ino||c.dev!==l.dev)throw Error("Source changed during rename");By(a)}})}function Xy(t){try{return yn(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Gd=(t,e,n,r,i)=>JSON.stringify([t,e,n,r,i]),Ot=(t,e,n)=>`${t}:${e}:${n}`,Vd=t=>({key:t.key,ns:t.ns,id:t.id,path:t.path,side:t.side}),Yd=t=>lw("sha256").update(t.map(e=>e.key).sort().join(`
|
|
287
|
+
`)).digest("hex").slice(0,24),dw=(t,e)=>t.length===e.length&&t.every(n=>e.some(r=>n.prefix===r.prefix&&n.root===r.root&&(n.dev===void 0||an(n,r)))),fw=()=>({config:structuredClone(du),owned:!1,paused:!1,folders:{},files:{},jobs:[]}),qt=ji,pw=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CLOSED"]),hw=t=>{let e=t;return!!e&&(e.name==="TypeError"&&/fetch failed/i.test(e.message??"")||pw.has(String(e.cause?.code??e.code??"")))},gw=t=>{let e=t;return e&&e.code==="TOO_LARGE"&&Number.isSafeInteger(e.maxBytes)&&e.maxBytes>0?e.maxBytes:null},mw=t=>`l:${t.size}:${t.mtime}`,yw=10*6e4,Jd=1024*1024,Re=(t,e)=>`${t}:${e}`,Wt=t=>t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",bn=t=>t.slice(t.lastIndexOf("/")+1),Yn=Oe(""),ww=t=>/\.db$/i.test(t)&&!/^(agents|human)(\/|$)/.test(t),is=t=>t==="human/MEMORY.md"||/^agents\/[a-z0-9][a-z0-9-]{0,63}\/MEMORY\.md$/.test(t),en=t=>t.split("/").length,Ue=t=>t instanceof Error?t.message:String(t),bw={upload:"uploads",download:"downloads",merge:"merges",rename:"renames",delete:void 0},pa=t=>t.file.replace(/\.json$/,".bases"),Qd=5e3,Sw=3e4,Kd=3e4,vw=3e3,ss=10*6e4,kw=60*6e4,Ew=10*6e4,_w=3*6e4,Xd=2e3,Cw=1440*6e4,ha=t=>/^(agents|human)\//.test(t)?Sw:Qd,Aw=t=>Math.max(t.mtime,t.ctime);async function*tn(t){let e=fa.now()+8;for(let n of t)fa.now()>=e&&(await uw(),e=fa.now()+8),yield n}function ef(t){if(!t.contentSync)return;let e=new ga(t);for(let[n,r]of Object.entries({[gt.get]:(i,s)=>e.snapshot(i,s),[gt.preview]:i=>e.preview(i),[gt.apply]:(i,s)=>e.apply(typeof i=="string"?i:"",s),[gt.run]:()=>{e.retrySoon(),e.touch(),e.kick()},[gt.pause]:i=>e.pause(i===!0),[gt.retry]:()=>{e.retryFailed(),e.touch(),e.kick()},[gt.rename]:i=>e.rename(i),[gt.setup]:i=>e.setup(i),[gt.archiveSeen]:()=>e.archiveSeen(),[gt.confirmDeletes]:i=>e.confirmDeletes(typeof i=="string"?i:""),[gt.abandonDeletes]:i=>e.abandonDeletes(typeof i=="string"?i:"")}))t.handle(n,async(i,...s)=>{if(!t.isTrustedSender(i))return{ok:!1,error:"untrusted"};try{return{ok:!0,value:await r(...s)}}catch(a){return{ok:!1,error:Ue(a)}}});t.addQuitGuard?.(n=>e.running&&!e.quitting?{message:n==="zh"?"\u8FD8\u6709\u5185\u5BB9\u6B63\u5728\u540C\u6B65":"Content is still syncing"}:null),t.addFlushHook?.(n=>e.flush(n)),_u(()=>e.stats()),e.start()}var ga=class{session=null;initializing=null;previewValue=null;watcher=null;sources=[];agentNames=new Map;cloudAgents;sourcesAt=0;activeAt=Date.now();lastRunAt=0;focused=!1;devices=[];others;deviceId="";customName="";serial=Promise.resolve();scheduled=null;tick=null;first=null;blocked=new Map;phase="idle";lastError;get error(){return this.lastError}set error(e){this.lastError=e,e&&this.fault(e)}runLog=new xr;logAccount=null;runAccount=null;blockedError=void 0;live(){let e=this.host.accountId();return!!e&&e===this.logAccount&&(!this.running||!this.runAccount||this.runAccount===e)}tally(e){this.live()&&this.runLog.count(e)}fault(e,n=[]){this.live()&&this.runLog.fault(e,n)}health=Ei((e,n,r)=>lt("content",e,n,r));httpStatus=0;closed=!1;runFinished=Promise.resolve();archiving=null;archiveRetry={account:"",at:0};resolving=!1;awaitingBytes=new Map;scanned={skipped:[],unscanned:[],skippedInodes:new Set};deleteStamps=[];failures=new Map;tooLarge=new Map;tooLargeSeen=null;recordsAccount=null;roundVisited=null;bypassBackoff=!1;bypassThisRound=!1;limitsByNs=new Map;round=null;uiLocale=null;running=!1;quitting=!1;again=!1;flushing=null;flushRequest=0;flushThrough=0;dirty=new Map;flushAt=0;due=null;registered=null;devicesAt=0;changedAt=0;wroteLocal=!1;openJobs=new Set;host;options;accountGeneration=0;stopAccountWatch;constructor(e,n={}){this.host=e,this.options=n,this.stopAccountWatch=Kl(e,()=>{this.accountGeneration++,this.previewValue=null,this.session?.abort.abort(new Error("account_changed"))})}start(){(this.tick=setInterval(()=>{this.idleSkip()||this.run()},3e4)).unref?.(),(this.first=setTimeout(()=>{this.run()},5e3)).unref?.()}locale(){if(this.uiLocale)return this.uiLocale;try{return/^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale)?"zh":"en"}catch{return"zh"}}archiveStep(e){if(e.stored.accountReview||e.stored.agentArchive?.state==="done"||this.archiveRetry.account===e.account&&Date.now()<this.archiveRetry.at)return Promise.resolve();let n=()=>{this.archiveRetry={account:e.account,at:Date.now()+ss}};return this.archiving??=(async()=>{try{let r=this.host.readCreds();if(!r.token)return;let i=await this.gatedFetch(e,r.cloudUrl,"/api/remotesync/agent-archive",{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({locale:this.locale()})},6e4);if(this.guard(e),!i.ok){n();return}let s=await i.json();if(this.guard(e),s.state!=="done"&&s.state!=="running"){n();return}let a=e.stored.agentArchive,o=s.archive;a?.rewritten||this.turnAgentsOff(e);let l={rewritten:!0,seen:a?.seen??!1,state:s.state};s.state==="done"&&(o?.folderId?Object.assign(l,{folderId:o.folderId,name:o.name??void 0,shelfId:o.shelfId??void 0,shelfName:o.shelfName??void 0,files:o.files??0,at:o.at??Date.now()}):l.seen=!0),e.stored.agentArchive=l,await this.persist(e)}catch(r){if(Ue(r)==="account_changed"||e.abort.signal.aborted)return;n(),this.host.log?.(`[content-sync] agent archive: ${Ue(r)}`)}finally{this.archiving=null}})()}turnAgentsOff(e){let n=e.stored.config;if(!n.enabled&&n.revision===0)return;let r=Su(n);if(!r)return;e.stored.config=Zt(r,n.revision+1);let i=s=>s==="agents"||s.startsWith("agents/");for(let[s,a]of Object.entries(e.stored.files))i(a.path)&&(delete e.stored.files[s],delete e.stored.unconfirmed?.[s]);for(let[s,a]of Object.entries(e.stored.folders))i(a.path)&&delete e.stored.folders[s];for(let[s,a]of Object.entries(e.stored.pendingUploads??{}))i(a.path)&&delete e.stored.pendingUploads[s];this.previewValue=null}async archiveSeen(){let e=await this.getSession();e.stored.agentArchive&&(e.stored.agentArchive.seen=!0,await this.persist(e))}async close(){this.closed=!0,this.stopAccountWatch(),this.tick&&clearInterval(this.tick),this.first&&clearTimeout(this.first),this.scheduled&&clearTimeout(this.scheduled),this.due&&clearTimeout(this.due),this.session?.abort.abort(),await this.watcher?.close(),await this.runFinished}currentBinding(e){if(!e.binding)return!0;let n=dr(e.binding.file);return n!==null&&!n.pending&&n.account===e.binding.account&&n.epoch===e.binding.epoch}guard(e,n=!0){if(this.closed)throw Error("content_sync_closed");if(Zs(this.host),this.host.accountId()!==e.account||this.session!==e||e.generation!==this.accountGeneration)throw Error("account_changed");if(!this.currentBinding(e))throw Error("content_account_changed_preview_required");n&&e.abort.signal.throwIfAborted()}async accountWrite(e,n){let r=async()=>{this.guard(e),await n(e.account),this.guard(e)};this.host.accountTransition?await this.host.accountTransition(r):await r()}async persist(e){let n=e.writes.catch(()=>{}).then(async()=>{this.guard(e,!1);let r=JSON.stringify(e.stored);if(r===e.persisted)return;await la(wn(e.file),{recursive:!0,mode:448});let i=e.file+".tmp-"+mt();try{await $r(i,r,{mode:384,flag:"wx"}),this.guard(e,!1),await rs(i,e.file),e.persisted=r}finally{await Lr(i).catch(()=>{})}});return e.writes=n,n}async getSession(){let e=this.host.accountId();if(!e)throw this.logAccount&&(this.runLog.reset(),this.logAccount=null),this.session?.abort.abort(),this.session=null,Error("not_signed_in");let n=this.accountGeneration;return Zs(this.host),this.initializing?this.initializing.then(r=>(this.guard(r),r)):this.session?.account===e&&this.session.generation===n&&this.currentBinding(this.session)?(this.guard(this.session,!1),this.session):(this.session?.abort.abort(new Error("account_changed")),this.logAccount!==e&&(this.runLog.reset(),this.logAccount=e),this.initializing=(async()=>{await this.watcher?.close(),this.watcher=null,this.previewValue=null,this.sources=[],this.agentNames.clear(),this.cloudAgents=void 0,this.devices=[],this.dirty.clear(),this.registered=null,this.devicesAt=0,this.changedAt=0;let r=Fe(this.host.homeDir(),"content-sync"),i=Fe(r,Oe(e)+".json"),s=fw();try{let f=JSON.parse(await Pr(i,"utf8"));Od(f),s={...s,...f,config:Zt(f.config,f.config.revision)},s.jobs=Array.isArray(f.jobs)?f.jobs.slice(-200):[]}catch(f){if(f.code!=="ENOENT")throw Error("Invalid content sync state; original data was retained")}let a,o=Fe(this.host.homeDir(),"content-sync-device.json"),l=async()=>{let f=JSON.parse(await Pr(o,"utf8"));if(typeof f?.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(f.id))throw Error("Invalid device sync ID");return f};try{a=await l()}catch(f){if(f.code!=="ENOENT")throw f;a={id:mt()},await la(wn(o),{recursive:!0});try{await $r(o,JSON.stringify(a),{flag:"wx",mode:384})}catch(g){if(g.code!=="EEXIST")throw g;a=await l()}}if(this.host.accountId()!==e)throw Error("account_changed");this.deviceId=a.id,this.customName=typeof a.name=="string"?a.name:"";let c=await this.host.contentSync.roots();if(this.host.accountId()!==e)throw Error("account_changed");let u={account:e,generation:n,file:i,stored:s,roots:c,abort:new AbortController,writes:Promise.resolve(),manifests:new Map,rootIdentities:new Map,tombstones:new Map};return this.session=u,await this.bindAccount(u),await this.recoverTrash(u),this.guard(u),s.owned&&await this.accountWrite(u,f=>this.host.contentSync.claim(!0,f)),this.setSources(await this.scan(u,c).catch(f=>(this.error=Ue(f),[]))),await this.register(u,!0),await this.watchRoots(u),u})().catch(r=>{throw this.session?.account===e&&(this.session.abort.abort(),this.session=null),r}).finally(()=>{this.initializing=null}),this.initializing)}async bindAccount(e){let n=wn(e.file),r=Ks(this.host.homeDir()),i=Oe(e.account),s=dr(r),a=!s?.account&&(await jr(n).catch(l=>{if(l.code==="ENOENT")return[];throw l})).some(l=>/^[a-f0-9]{64}\.json$/.test(l)&&l!==i+".json"),o=s?.pending&&(e.stored.owned||e.stored.config.revision>0);if((s?.account&&s.account!==i||a||o)&&(e.stored.accountReview=!0,e.stored.owned=!0,e.stored.config.enabled&&(e.stored.config={...e.stored.config,enabled:!1,revision:e.stored.config.revision+1}),await this.persist(e)),s?.account!==i||s.pending){this.guard(e,!1);let l=dr(r);if(l?.account!==s?.account||l?.epoch!==s?.epoch||l?.pending!==s?.pending)throw Error("account_changed");Xs(r,{version:1,account:i,...s?.epoch?{epoch:s.epoch}:{}})}e.binding={file:r,account:i,epoch:s?.epoch},this.guard(e,!1)}async rootIdentity(e,n){let r=e.rootIdentities.get(n);if(r){let s=await ca(n).catch(()=>{throw Error("Sync root unavailable: "+n)});if(!s.isDirectory()||!bt(r,s))throw Error("Sync root changed; preview before rebinding");return r}let i=await ar(n).catch(s=>{throw s.code==="ENOENT"?Error("Sync root unavailable: "+n):s});return this.guard(e),e.rootIdentities.set(n,i),i}async scan(e,n=e.roots){let r=!1;for(let s of e.stored.roots??[]){let a=n.find(l=>l.prefix===s.prefix);if(!a||a.root!==s.root)throw Error("content_roots_changed_preview_required");let o=await this.rootIdentity(e,s.root);if(s.dev!==void 0&&!an(s,o))throw Error("Sync root changed; preview before rebinding");if(s.dev!==void 0&&s.dev!==o.dev){let l=String(s.dev)+":";for(let c of Object.values(e.stored.files))c.inode?.startsWith(l)&&Ke(n,c.path).root===s.root&&(c.inode=String(o.dev)+":"+c.inode.slice(l.length),delete c.stat,delete c.statAt)}JSON.stringify(s)!==JSON.stringify({...s,...o})&&(Object.assign(s,o),r=!0)}r&&await this.persist(e);let i=await ns(n);return this.scanned={skipped:i.skipped,unscanned:i.unscanned,skippedInodes:i.skippedInodes},i}async write(e,n,r,i){this.guard(e),await sa(e.roots,n,r,i,(s,a)=>this.lock(e,s,a)),await this.recordRoots(e)}async recordRoots(e){this.guard(e);let n=!1;for(let r of e.roots){if(e.stored.roots?.some(s=>s.prefix===r.prefix&&s.root===r.root))continue;await ca(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&((e.stored.roots??=[]).push({...r,...await this.rootIdentity(e,r.root)}),n=!0)}n&&await this.persist(e)}lock(e,n,r,i=!1){let s=()=>{if(this.guard(e),e.stored.paused&&!i)throw Error("paused");for(let[a,o]of e.rootIdentities){let l;try{l=Qy(a)}catch{throw Error("Sync root unavailable: "+a)}if(!l.isDirectory()||!bt(o,l))throw Error("Sync root changed; restart before retrying")}r(),this.wroteLocal=!0};return this.host.contentSync.withWriteLock?.(n,s)??Promise.resolve().then(s)}async previewScan(e,n){for(let r of e.stored.roots??[])n.some(i=>i.prefix===r.prefix&&i.root===r.root)&&await Bt(r.root).catch(()=>{throw Error(`Sync root unavailable: ${r.prefix||"Forsion"}`)});return ns(n)}async watchRoots(e){this.options.watch!==!1&&(this.guard(e),await this.watcher?.close(),this.watcher=Rs(e.roots.map(n=>n.root),{ignoreInitial:!0,ignored:n=>{let r=n.split(/[\\/]/).at(-1)??"";return r.startsWith(".")&&r!==".memory-tombstones.json"||r==="node_modules"||r==="__pycache__"}}),this.watcher.on("all",(n,r)=>{let i=this.logical(e,r),s=Date.now();if(this.activeAt=s,i){let a=this.dirty.get(i);a?a.last=s:this.dirty.set(i,{first:s,last:s})}this.schedule(i?void 0:s+Qd)}))}logical(e,n){let r=null;for(let a of e.roots)(n===a.root||n.startsWith(a.root+Vn))&&(!r||a.root.length>r.root.length)&&(r=a);if(!r)return null;let i=Fr(r.root,n).split(Vn).join("/");return(r.prefix?i?`${r.prefix}/${i}`:r.prefix:i)||null}dueAt(e,n){return n.last<=this.flushAt?0:Math.min(n.last+ha(e),n.first+Kd)}schedule(e){let n=e??1/0;for(let[r,i]of this.dirty)n=Math.min(n,this.dueAt(r,i));this.due&&clearTimeout(this.due),this.due=null,!(n===1/0||this.closed)&&(this.due=setTimeout(()=>{this.due=null;let r=this.session;r?.stored.config.enabled&&!r.stored.paused&&this.kick()},Math.max(0,n-Date.now())+50),this.due.unref?.())}kick(){if(this.running){this.again=!0;return}this.run()}touch(){this.activeAt=Date.now()}idleSkip(e=Date.now()){return e-this.activeAt>=Ew&&e-this.lastRunAt<_w-5e3}flush(e){let n=this.session;if(!(this.closed||!this.host.accountId()||n&&(!n.stored.config.enabled||n.stored.paused)))return this.flushRequest++,this.flushThrough=Math.max(this.flushThrough,Date.now()),this.bypassBackoff=!0,e==="quit"&&(this.quitting=!0),this.flushAt=this.quitting?1/0:this.flushThrough,this.flushing?this.flushing:this.flushing=(async()=>{try{for(;!this.closed;){let r=this.serial;if(await r,r!==this.serial)continue;if(this.running){await this.runFinished;continue}let i=this.flushRequest;if(await this.run(),i===this.flushRequest)return}}finally{this.flushing=null,this.quitting=!1,this.flushAt=this.flushThrough}})()}async request(e,n,r="",i="GET",s,a,o){for(;;){this.guard(e);let l=this.host.readCreds();if(!l.token)throw Error("not_signed_in");let c=Jt(l.cloudUrl);await c.ready(e.abort.signal),this.guard(e);let u=l.cloudUrl.replace(/\/+$/,"")+`/api/remotesync/content/${encodeURIComponent(n)}${r}`,f={Authorization:`Bearer ${l.token}`,"X-Content-Device":this.deviceId,"X-Content-Caps":No,...o},g;if(s instanceof Buffer){f["Content-Type"]="application/octet-stream",f["Content-Length"]=String(s.length);let y=async function*(){for(let b=0;b<s.length;b+=64*1024)e.abort.signal.throwIfAborted(),yield s.subarray(b,b+64*1024),a?.(Math.min(s.length,b+64*1024))};g=cw.from(y())}else s!==void 0&&(f["Content-Type"]="application/json",g=JSON.stringify(s));let p={method:i,headers:f,body:g,signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(12e4)]),...s instanceof Buffer?{duplex:"half"}:{}},m=await fetch(u,p);if(this.guard(e),!m.ok&&!(m.status===304&&o?.["If-None-Match"])){let y=await m.json().catch(()=>({}));if(c.observe(m.status,m.headers,y?.code,y?.retryAfterMs))continue;throw this.httpStatus=m.status,Object.assign(new Error(typeof y?.detail=="string"?y.detail:`content_http_${m.status}`),{status:m.status,...typeof y?.code=="string"?{code:y.code}:{},...Number.isSafeInteger(y?.maxBytes)&&y.maxBytes>0?{maxBytes:y.maxBytes}:{}})}return c.observe(m.status,m.headers),i==="DELETE"&&this.tally("deletesSent"),m}}async gatedFetch(e,n,r,i,s){let a=Jt(n);for(;;){await a.ready(e.abort.signal),this.guard(e);let o=await fetch(n.replace(/\/+$/,"")+r,{...i,headers:{...i.headers,"X-Content-Caps":No},signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(s)])});if(o.status===429){let l=await o.clone().json().catch(()=>({}));if(a.observe(o.status,o.headers,l?.code,l?.retryAfterMs))continue}return a.observe(o.status,o.headers),o}}async json(e,n,r="",i="GET",s,a){let o=await(await this.request(e,n,r,i,s,void 0,a)).json();return this.guard(e),o}async manifests(e,n){let r=new Map;for(let s of new Set(n.rules.filter(a=>a.target!=="off").map(a=>a.target))){let a=JSON.parse(await this.manifestText(e,s));Ki(a,s),await this.knownTombstones(e,s,a),r.set(s,a)}let i=[r.get("default"),r.get(`device-${this.deviceId}`)].filter(Boolean);return i.length&&(this.cloudAgents=[...new Set(i.flatMap(s=>s.nodes.filter(a=>!a.deleted&&a.kind==="file").map(a=>/^agents\/([^/]+)\/config\.toml$/.exec(a.path)?.[1]).filter(a=>!!a&&Cr.test(a))))].sort()),r}async manifestText(e,n){let r=e.manifests.get(n),i=r&&Date.now()-r.at<kw?r:void 0,s=await this.request(e,n,"","GET",void 0,void 0,{"X-Content-Tombstones":"recent",...i?{"If-None-Match":i.etag}:{}});if(s.status===304)return await s.body?.cancel(),i?i.text:(e.manifests.delete(n),this.manifestText(e,n));let a=await s.text();this.guard(e),Ki(JSON.parse(a),n);let o=s.headers.get("etag");return r?.text!==a&&this.touch(),o?e.manifests.set(n,{etag:o,text:a,at:Date.now()}):e.manifests.delete(n),a}async knownTombstones(e,n,r){if(typeof r.tombstonesSince!="string")return;let i=new Set(r.nodes.map(c=>c.id)),s=new Set;for(let[c,u]of Object.entries(e.stored.files))c.startsWith(n+":")&&s.add(u.id);for(let[c,u]of Object.entries(e.stored.folders))c.startsWith(n+":")&&s.add(u.id);for(let[c,u]of Object.entries(e.stored.pendingUploads??{}))c.startsWith(n+":")&&s.add(u.id);let a=e.tombstones.get(n);a||e.tombstones.set(n,a=new Map);for(let c of[...a.keys()])i.has(c)&&a.delete(c);let o=Date.now(),l=[...s].filter(c=>{if(i.has(c))return!1;let u=a.get(c);return!u||!u.node&&o-u.at>=Cw});for(let c=0;c<l.length;c+=Xd){let u=l.slice(c,c+Xd),f=new Set(u),g=await this.json(e,n,"/tombstones","POST",{ids:u}),p=new Map((Array.isArray(g?.nodes)?g.nodes:[]).filter(m=>Nd(m)&&f.has(m.id)).map(m=>[m.id,m]));for(let m of u)a.set(m,{node:p.get(m)??null,at:o})}for(let c of s)if(!i.has(c)){let u=a.get(c)?.node;u&&r.nodes.push(structuredClone(u))}}route(e,n,r="file"){if(Gi(e)||Qo(e,r)===!1)return null;let i=Mn(e,n.rules);return i&&i.target!=="off"?i.target:null}effective(e,n){let r=new Map(n.filter(i=>i.localId).map(i=>[i.localId,i.path]));return{...e,rules:e.rules.map(i=>i.sourceId&&r.has(i.sourceId)?{...i,source:r.get(i.sourceId)}:i)}}deviceName(){return this.customName||Fi(ua())}setSources(e){let n=new Map,r={files:0,size:0};for(let s of e)s.kind==="folder"&&n.set(s.path,{size:0,files:0});for(let s of e)if(s.kind==="file"){fu.some(a=>s.path.startsWith(a+"/"))||(r.files++,r.size+=s.size);for(let a=Wt(s.path);a;a=Wt(a)){let o=n.get(a);o&&(o.size+=s.size,o.files++)}}let i=new Map(e.filter(s=>s.kind==="file"&&/^agents\/[^/]+\/config\.toml$/.test(s.path)).map(s=>[s.path.slice(0,-12),s]));this.others=r,this.sources=[...n].sort(([s],[a])=>en(s)-en(a)||(s<a?-1:1)).slice(0,2e3).map(([s,a])=>({path:s,kind:"folder",size:a.size,files:a.files,...Ar(s)&&i.has(s)?{agent:!0}:{}})),this.sourcesAt=Date.now(),this.readAgentNames(i)}async readAgentNames(e){for(let n of this.agentNames.keys())e.has(n)||this.agentNames.delete(n);for(let[n,r]of e){let i=`${r.mtime}:${r.size}`;if(!(this.agentNames.get(n)?.key===i||r.size>256*1024))try{this.agentNames.set(n,{key:i,...hu((await Wn(r)).toString("utf8"))})}catch{this.agentNames.set(n,{key:i})}}}async rename(e){let n=typeof e=="string"?e.trim():"";if(n.length>64||/[\u0000-\u001f\u007f]/.test(n))throw Error("Invalid device name");let r=await this.getSession(),i=n||Fi(ua()),s=Mo(i,this.devices,this.deviceId);if(s)throw Error(s==="taken"?"device_name_taken":s==="reserved"?"device_name_reserved":"device_name_invalid");return await this.json(r,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:i,unique:!0}),await this.saveName(n),await this.register(r,!0),this.deviceName()}async saveName(e){let n=Fe(this.host.homeDir(),"content-sync-device.json"),r=n+".tmp-"+mt();try{await $r(r,JSON.stringify({id:this.deviceId,...e?{name:e}:{}}),{mode:384,flag:"wx"}),await rs(r,n)}finally{await Lr(r).catch(()=>{})}this.customName=e}async register(e,n=!1){let r=Date.now();if(!n&&this.registered?.name===this.deviceName()&&r-this.registered.at<ss){r-this.devicesAt>=ss&&await this.refreshDevices(e);return}let i=(o,l)=>this.json(e,"devices",`/${encodeURIComponent(this.deviceId)}`,"PUT",{name:o,...l?{unique:!0}:{}}),s=async()=>(await this.json(e,"devices")).devices,a=o=>/device_name_(taken|reserved|invalid)/.test(Ue(o));try{await i(this.deviceName(),!0)}catch(o){if(!a(o))throw o;let l=!1;if(!this.customName){let c=Fi(ua());for(let u=0;u<5&&!l;u++){let f=await s(),g=null;for(let p=2;p<100&&!g;p++){let m=`${c} ${p}`;Mo(m,f,this.deviceId)||(g=m)}if(!g)break;try{await i(g,!0),await this.saveName(g),l=!0}catch(p){if(!a(p))throw p}}}l||await i(this.deviceName(),!1)}this.registered={name:this.deviceName(),at:r},await this.refreshDevices(e)}async refreshDevices(e){this.devicesAt=Date.now(),this.devices=(await this.json(e,"devices")).devices,await this.cacheDevices()}cachedDevices="";async cacheDevices(){let e=Fe(this.host.homeDir(),"content-sync-devices.json"),n=[];try{let o=JSON.parse(await Pr(e,"utf8"));Array.isArray(o?.devices)&&(n=o.devices)}catch{}let r=new Map(n.filter(o=>o&&typeof o.id=="string").map(o=>[o.id,o])),i=this.devices.map(o=>{let l=r.get(o.id),c=[...Array.isArray(l?.aliases)?l.aliases:[],...l&&typeof l.name=="string"&&l.name!==o.name?[l.name]:[]],u=c.filter((f,g)=>typeof f=="string"&&f!==o.name&&c.lastIndexOf(f)===g).slice(-5);return{id:o.id,name:o.name,...u.length?{aliases:u}:{}}}),s=JSON.stringify({devices:i});if(s===this.cachedDevices)return;let a=e+".tmp-"+mt();try{await $r(a,s,{mode:384,flag:"wx"}),await rs(a,e),this.cachedDevices=s}catch(o){this.error=Ue(o)}finally{await Lr(a).catch(()=>{})}}async setup(e){let n=await this.getSession(),r=e&&typeof e=="object"?e:{};if(n.stored.config.enabled||n.stored.config.revision>0)return null;let i=Pn(wu(n.stored.config),"","off");for(let o of Lt)o.id!=="agents"&&r[o.id]===!1&&(i=Pn(i,o.path,"off"));let s=new Set(this.sources.filter(o=>o.agent).map(o=>o.path.slice(7))),a=Array.isArray(r.agentSlugs)?r.agentSlugs.slice(0,512).filter(o=>typeof o=="string"&&s.has(o)):[];return this.preview(bu(i,a))}retryFailed(){this.failures.clear(),this.tooLarge.clear(),this.bypassBackoff=!0}retrySoon(){this.bypassBackoff=!0}rateLimitedUntil(){let e=this.host.readCreds();return e.cloudUrl?Jt(e.cloudUrl).until():null}capFor(e,n,r){let i=Ui(n,e,r?.limits),s=this.tooLarge.get(e+"\0"+n)?.learned;return s&&s.published===i?Math.min(i,s.maxBytes):i}noteTooLarge(e,n,r,i,s,a){let o=n+"\0"+r,l=this.tooLarge.get(o);this.tooLargeSeen?.add(o),this.failures.delete(o),lt("content","skippedTooLarge",1,r),e.stored.jobs=e.stored.jobs.filter(c=>!(c.path===r&&c.target===n&&(c.state==="failed"||c.state==="paused")&&(c.direction==="upload"||c.direction==="download"))),this.tooLarge.set(o,{ns:n,path:r,size:i,maxBytes:s,...a??l?.learned?{learned:a??l.learned}:{}})}tooLargeList(){return[...this.tooLarge.values()].map(e=>({path:e.path,reason:"too-large",size:e.size,maxBytes:e.maxBytes}))}backingOff(e,n,r){let i=e+"\0"+n,s=this.failures.get(i);return this.roundVisited?.add(i),s?s.fp!==r?(this.failures.delete(i),!1):!this.bypassThisRound&&Date.now()<s.retryAt:!1}succeeded(e,n){this.failures.delete(e+"\0"+n)}fileFailed(e,n,r,i,s,a){if(e.abort.signal.aborted||hw(i))throw i;let o=n+"\0"+r,l=gw(i);if(l!==null){let m=i.size,y=Number.isSafeInteger(m)?m:a??0;this.noteTooLarge(e,n,r,y,l,{maxBytes:l,published:Ui(r,n,this.limitsByNs.get(n))});return}this.error=Ue(i);let c=this.failures.get(o),u=(c&&c.fp===s?c.count:0)+1,f=Date.now()+pu(u),g=i?.code;this.failures.set(o,{ns:n,path:r,reason:Ue(i),...typeof g=="string"?{code:g}:{},count:u,retryAt:f,fp:s});let p=e.stored.jobs.findLast(m=>m.path===r&&m.target===n&&m.state==="failed");p&&(p.retryAt=f)}failureList(){return[...this.failures.values()].sort((e,n)=>e.retryAt-n.retryAt).slice(0,200).map(e=>({path:e.path,target:e.ns,reason:e.reason,...e.code?{code:e.code}:{},count:e.count,retryAt:e.retryAt}))}async snapshot(e,n){(e==="zh"||e==="en")&&(this.uiLocale=e);let r=await this.getSession(),i=n&&typeof n=="object"?n:{};if(i.focused===!0){let s=!this.focused;this.focused=!0,this.touch(),s&&r.stored.config.enabled&&!r.stored.paused&&Date.now()-this.lastRunAt>3e4&&this.kick()}else i.focused===!1&&(this.focused=!1);return!r.stored.config.enabled&&!this.running&&Date.now()-this.sourcesAt>1e4&&(this.sourcesAt=Date.now(),this.scan(r).then(s=>{this.session===r&&this.setSources(s)},()=>{})),i.devices===!0&&Date.now()-this.devicesAt>6e4&&(this.devicesAt=Date.now(),this.refreshDevices(r).catch(()=>{})),{available:!0,account:Oe(r.account),deviceId:this.deviceId,deviceName:this.deviceName(),config:structuredClone(r.stored.config),running:this.running,paused:r.stored.paused,phase:this.phase,jobs:structuredClone(r.stored.jobs),devices:this.devices,sources:this.sources.map(s=>{let a=s.agent&&this.agentNames.get(s.path);return a?{...s,...a.name?{name:a.name}:{},...a.nameEn?{nameEn:a.nameEn}:{}}:s}),...this.cloudAgents?{cloudAgents:this.cloudAgents}:{},...this.others?{others:this.others}:{},...r.stored.accountReview?{error:"content_account_changed_preview_required"}:this.error?{error:this.error}:{},...r.stored.agentArchive?{agentArchive:(({rewritten:s,...a})=>a)(r.stored.agentArchive)}:{},...(s=>s&&(s.latched||s.pending.length)?{deletes:{latched:s.latched,pending:s.pending.length,token:Yd(s.pending),items:s.pending.slice(0,200).map(a=>({path:a.path,side:a.side}))}}:{})(r.stored.deleteGuard),...(s=>s.length?{skipped:s.slice(0,200),skippedCount:s.length}:{})([...this.scanned.skipped,...this.recordsAccount===r.account?this.tooLargeList():[]]),...(s=>s?{rateLimitedUntil:s}:{})(this.rateLimitedUntil()),...this.failures.size&&this.recordsAccount===r.account?{failures:this.failureList()}:{}}}async confirmDeletes(e){await this.decideDeletes("confirm",e)}async abandonDeletes(e){await this.decideDeletes("restore",e)}deferredDecision=[];async decideDeletes(e,n){let r=await this.getSession(),i=r.stored.deleteGuard?.pending??[],s=i.map(a=>a.key);if(n!==void 0&&n!==Yd(i))throw Error("deletes_changed");if(!(!s.length&&!r.stored.deleteGuard?.latched)){if(this.running){this.deferredDecision.push({kind:e,keys:s}),this.again=!0;return}this.applyDecision(r,e,s),await this.persist(r),this.touch(),this.kick()}}applyDecision(e,n,r){let i=e.stored.deleteGuard;if(!i)return;let s=new Set(r),a=i.pending.filter(f=>!s.has(f.key)),o=i.pending.filter(f=>s.has(f.key)),l=[...new Set([...i.confirmed??[],...o.map(f=>f.key)])],c=[...new Map([...i.restore??[],...o].map(f=>[Ot(f.side,f.ns,f.id),f])).values()],u={latched:a.length>0,pending:a,...n==="confirm"?{confirmed:l}:i.confirmed?.length?{confirmed:i.confirmed}:{},...n==="restore"?{restore:c}:i.restore?.length?{restore:i.restore}:{}};u.latched||u.pending.length||u.confirmed?.length||u.restore?.length?e.stored.deleteGuard=u:delete e.stored.deleteGuard,n==="confirm"&&(this.deleteStamps=[])}stats(){let e=this.host.accountId(),n=e&&this.session?.account===e?this.session:null,r=n?.stored,i={},s=e&&e===this.logAccount?this.runLog.snapshot():new xr().snapshot();for(let a of r?.jobs??[])i[a.state]=(i[a.state]??0)+1;return{deviceId:this.deviceId||null,session:!!n,enabled:!!r?.config.enabled,paused:!!r?.paused,running:!!n&&this.running,phase:n?this.phase:"idle",revision:r?.config.revision??0,rules:(r?.config.rules??[]).map(a=>({source:a.source,target:a.target})),backlog:r?{jobs:i,blocked:[...this.blocked.values()].reduce((a,o)=>a+o.length,0),pendingUploads:Object.keys(r.pendingUploads??{}).length,unconfirmed:Object.keys(r.unconfirmed??{}).length,trash:r.trash?.length??0,awaitingBytes:this.awaitingBytes.size,dirty:this.dirty.size}:null,archive:r?.agentArchive?.state??null,...s}}async preview(e){let n=await this.getSession();if(e?.revision!==n.stored.config.revision)throw Error("config_changed");let i=Zt(e,n.stored.config.revision+1),s=await this.host.contentSync.roots();this.guard(n);let a=await this.previewScan(n,s),o=this.effective(i,a);if(n.stored.agentArchive?.state==="running"&&a.some(N=>N.kind==="file"&&N.path.startsWith("agents/")&&this.route(N.path,o)))throw Error("agent_archive_running");let l=await this.manifests(n,o);this.guard(n),this.setSources(a);let c=0,u=0,f=0,g=0,p=await this.bindingsOf(s),m=new Map,y=new Map;for(let[N,Y]of Object.entries(n.stored.files))this.survives(n.stored,o,p,Y.path)&&(m.set(N,Y),y.set(N.slice(0,N.indexOf(":"))+"\0"+Y.path,Y));let b=n.stored.deleteGuard,_=new Set((b?.restore??[]).map(N=>Ot(N.side,N.ns,N.id))),h=[],T=new Map,v=new Set(a.map(N=>N.path));for await(let N of tn(a.filter(Y=>Y.kind==="file"))){let Y=this.route(N.path,o);if(!Y)continue;let ee=l.get(Y),J=ee?.nodes.find(te=>!te.deleted&&te.kind==="file"&&te.path===N.path);if(N.size>Ui(N.path,Y,ee?.limits))continue;let se=Oe(await Wn(N));if(this.guard(n),T.set(N.path,se),!J){let te=y.get(Y+"\0"+N.path),ae=te&&ee?.nodes.find(Q=>Q.id===te.id&&Q.deleted);if(ae&&te&&is(N.path)&&(te.hash===se||te.memoryDeleted&&se===Yn))continue;if(ae&&te&&te.hash===se&&!_.has(Ot("local",Y,te.id))){h.push({ns:Y,path:N.path});continue}}se!==J?.hash&&(c++,g+=N.size,J?.version&&f++)}let I=i.enabled?this.agentAsks(n,a,o,l,T):[],E=h.length;for(let[N,Y]of l)for await(let ee of tn(Y.nodes)){if(ee.deleted||ee.kind!=="file"||this.route(ee.path,o)!==N||v.has(ee.path))continue;let J=m.get(Re(N,ee.id)),se=qn(a.unscanned,ee.path)||!!J?.inode&&a.skippedInodes.has(J.inode);if(J&&J.path!==ee.path&&v.has(J.path))continue;let te=Do(ee,J,!!n.stored.pendingUploads?.[Re(N,ee.id)],se);te==="download"?u++:te==="delete"&&await this.absent(n,ee.path,s)&&(_.has(Ot("cloud",N,ee.id))?u++:h.push({ns:N,path:ee.path}))}let D=h.length-E,x=[...m].map(([N,Y])=>({ns:N.slice(0,N.indexOf(":")),path:Y.path})),L=Oo(h,x,{latched:!!b?.latched,recent:this.deleteStamps.filter(N=>Date.now()-N<Ro).length}),V=this.signature(a,l,s),H={token:mt(),config:o,upload:i.enabled?c:0,download:i.enabled?u:0,conflicts:i.enabled?f:0,bytes:i.enabled?g:0,oldTargetsRetained:!0,expiresAt:Date.now()+5*6e4,deleteCloud:i.enabled?D:0,deleteLocal:i.enabled?E:0,...i.enabled&&L?{deletesHeld:!0}:{},...I.length?{agentAsks:I}:{}};return this.previewValue={value:H,account:n.account,signature:V},H}async bindingsOf(e){let n=[];for(let r of e)await ca(r.root).catch(s=>{if(s.code==="ENOENT")return null;throw s})&&n.push({...r,...await ar(r.root)});return n}survives(e,n,r,i,s="file"){return e.config.enabled===n.enabled&&dw(e.roots??r,r)&&this.route(i,e.config,s)===this.route(i,n,s)}signature(e,n,r){return Oe(JSON.stringify([r,e.map(i=>[i.path,i.size,i.mtime,i.inode]),[...n].map(([i,s])=>[i,s.nodes.map(a=>[a.id,a.revision,a.version,a.deleted])])]))}async apply(e,n){let r=this.serial,i;this.serial=new Promise(s=>{i=s}),await r;try{let s=await this.getSession(),a=this.previewValue;if(!a||a.value.token!==e||a.account!==s.account||a.value.expiresAt<Date.now()||a.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");if(this.running)throw Error("sync_in_progress");let o=a.value.agentAsks??[],l=xw(n);this.resolving=!0;try{let c=await this.host.contentSync.roots(),u=await this.previewScan(s,c),f=await this.manifests(s,a.value.config);if(this.signature(u,f,c)!==a.signature)throw Error("preview_changed");let g=await this.bindingsOf(c),p=structuredClone(a.value.config);for(let b of p.rules){let _=u.find(h=>h.kind==="folder"&&h.path===b.source);_&&(b.sourceId=await ia(_))}let m=o.length?Zt(o.reduce((b,_)=>Pn(b,`agents/${_.slug}`,"off"),p),p.revision):p;if(this.guard(s),this.previewValue!==a||a.value.config.revision!==s.stored.config.revision+1)throw Error("preview_expired");let y=structuredClone(s.stored);s.stored.config=m,s.stored.owned=!0,s.stored.paused=!1,delete s.stored.unconfirmed;for(let[b,_]of Object.entries(s.stored.files))this.survives(y,s.stored.config,g,_.path)||delete s.stored.files[b];for(let[b,_]of Object.entries(s.stored.folders))this.survives(y,s.stored.config,g,_.path,"folder")||delete s.stored.folders[b];s.stored.roots=g,s.rootIdentities=new Map(g.map(b=>[b.root,b])),await this.persist(s);try{await this.accountWrite(s,b=>this.host.contentSync.claim(!0,b))}catch(b){throw s.stored=y,await this.persist(s),await this.accountWrite(s,_=>this.host.contentSync.claim(y.owned,_)).catch(()=>{}),b}if(this.previewValue=null,s.roots=c,await this.watchRoots(s),o.length)try{await this.resolveAsks(s,o,l,p)}catch(b){throw this.fault(Ue(b)),b}s.stored.accountReview&&(delete s.stored.accountReview,await this.persist(s))}finally{this.resolving=!1}}finally{i()}this.run()}async pause(e){let n=await this.getSession();if(!e&&n.stored.accountReview)throw Error("content_account_changed_preview_required");n.stored.paused=e,e?(n.abort.abort(new Error("paused")),this.phase="paused"):this.running||(n.abort=new AbortController),await this.persist(n),e||this.run()}job(e,n,r,i,s){let a=e.stored.jobs.findLast(l=>l.path===n&&l.target===r&&l.direction===i&&["failed","paused","queued"].includes(l.state));if(a)return Object.assign(a,{state:"active",done:0,size:s,at:Date.now(),error:void 0,finishedAt:void 0}),a;let o={id:mt(),path:n,target:r,direction:i,state:"active",done:0,size:s,at:Date.now()};return e.stored.jobs.push(o),e.stored.jobs=e.stored.jobs.slice(-200),o}done(e){e.state="done",e.done=e.size??e.done,e.finishedAt=Date.now()}async operation(e,n,r,i,s,a){if(this.guard(e),e.stored.paused)throw Error("paused");this.activeAt=Date.now();let o=this.job(e,n,r,i,s);try{let l=await a(o);if(this.guard(e),e.stored.paused)throw Error("paused");this.done(o),i==="upload"?lt("content","uploads"):i==="download"&<("content","downloads");let c=bw[i];return c&&this.tally(c),l}catch(l){throw o.state=e.stored.paused?"paused":"failed",o.error=Ue(l),o.finishedAt=Date.now(),l}}async run(){if(this.running||this.closed||this.resolving)return;this.running=!0;let e;this.runFinished=new Promise(o=>{e=o});let n=Date.now();this.lastRunAt=n,this.wroteLocal=!1;let r=new Set,i,s=!1,a=!1;try{if(i=await this.getSession(),this.runAccount=i.account,i.stored.accountReview){this.error="content_account_changed_preview_required";return}if(await this.archiveStep(i),!i.stored.config.enabled||i.stored.paused)return;i.abort.signal.aborted&&(i.abort=new AbortController),this.blocked.clear(),this.phase="scanning",this.error=void 0,s=!0,this.httpStatus=0,this.live()&&this.runLog.begin(n);let o=await this.host.contentSync.roots();this.guard(i),i.roots=o,this.tooLargeSeen=new Set,this.roundVisited=new Set,this.recordsAccount!==i.account&&(this.failures.clear(),this.tooLarge.clear(),this.recordsAccount=i.account),this.bypassThisRound=this.bypassBackoff,this.bypassBackoff=!1,await this.host.contentSync.agentFiles?.prepare().catch(T=>{this.error=Ue(T)}),this.guard(i);let l=await this.scan(i,o);await this.recordRoots(i);let c=this.effective(i.stored.config,l),u=await this.manifests(i,c);this.guard(i),this.limitsByNs=new Map([...u].map(([T,v])=>[T,v.limits]));let f=new Map;for(let[T,v]of u)for(let I of v.nodes)I.kind==="file"&&!I.deleted&&f.set(T+"\0"+I.path,I.version??"");let g=(T,v)=>`${mw(v)}|c:${f.get(T+"\0"+v.path)??""}`;await this.register(i),this.openJobs=new Set(i.stored.jobs.filter(T=>["failed","paused","active"].includes(T.state)&&["upload","download","merge"].includes(T.direction)).map(T=>T.target+"\0"+T.path)),await this.folders(i,c,l,u),await this.recordRoots(i),await this.fileRenames(i,c,l,u),l=await this.scan(i,o),c=this.effective(c,l),i.stored.config=c,this.setSources(l),this.phase="syncing",this.round={plan:[],restore:new Map((i.stored.deleteGuard?.restore??[]).map(T=>[Ot(T.side,T.ns,T.id),T])),restoreHit:new Set,restoreDone:new Set,tracked:Object.entries(i.stored.files).map(([T,v])=>({ns:T.slice(0,T.indexOf(":")),path:v.path})),undecided:new Set};let p=(T,v)=>this.round.undecided.add(T+"\0"+v),m=T=>T.endsWith("/"+Or),y=new Set,b=new Set,_=T=>T.startsWith("agents/")?T.slice(0,T.lastIndexOf("/")+1):null,h=T=>T.endsWith("/MEMORY.md")&&b.has(_(T)??"");for(let[T,v]of u)for await(let I of tn(v.nodes.filter(E=>E.kind==="file"&&!E.busy&&m(E.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(I.path,c)!==T||l.some(E=>E.path===I.path))){if(this.isBlocked(T,I.path)){b.add(_(I.path)??""),p(T,I.path);continue}if(this.backingOff(T,I.path,`c:${I.version??""}`)){b.add(_(I.path)??""),p(T,I.path);continue}y.add(I.id);try{await this.missing(i,I,T,l,c)==="unknown"?b.add(_(I.path)??""):this.succeeded(T,I.path)}catch(E){this.fileFailed(i,T,I.path,E,`c:${I.version??""}`,I.size),b.add(_(I.path)??""),p(T,I.path)}}}for await(let T of tn(l.filter(v=>v.kind==="file").sort((v,I)=>+!m(v.path)-+!m(I.path)))){if(this.guard(i),i.stored.paused)throw Error("paused");let v=this.route(T.path,c);if(v){if(h(T.path)){p(v,T.path);continue}if(this.isBlocked(v,T.path)){m(T.path)&&b.add(_(T.path)??""),p(v,T.path);continue}if(this.backingOff(v,T.path,g(v,T))){p(v,T.path),m(T.path)&&b.add(_(T.path)??"");continue}try{let I=await this.file(i,c,T,v,u.get(v));I==="held"?(r.add(T.path),p(v,T.path)):I==="too-large"?(p(v,T.path),m(T.path)&&b.add(_(T.path)??"")):this.succeeded(v,T.path)}catch(I){this.fileFailed(i,v,T.path,I,g(v,T),T.size),p(v,T.path),m(T.path)&&b.add(_(T.path)??"")}}}for(let[T,v]of u)for await(let I of tn(v.nodes.filter(E=>E.kind==="file"&&!E.busy&&!y.has(E.id)))){if(this.guard(i),i.stored.paused)throw Error("paused");if(!(this.route(I.path,c)!==T||l.some(E=>E.path===I.path))){if(this.isBlocked(T,I.path)||h(I.path)){p(T,I.path);continue}if(this.holdGone(I.path)){r.add(I.path),p(T,I.path);continue}if(this.backingOff(T,I.path,`c:${I.version??""}`)){p(T,I.path);continue}try{await this.missing(i,I,T,l,c),this.succeeded(T,I.path)}catch(E){this.fileFailed(i,T,I.path,E,`c:${I.version??""}`,I.size),p(T,I.path)}}}await this.executeDeletes(i,this.round),await this.cleanupFolders(i,c,u),this.wroteLocal&&Date.now()-this.devicesAt>=6e4&&await this.refreshDevices(i).catch(()=>{}),(this.wroteLocal||Date.now()-this.changedAt>=ss)&&(await this.accountWrite(i,T=>this.host.contentSync.changed(T)),this.changedAt=Date.now()),this.guard(i),await this.persist(i),await this.pruneBases(i),a=!0;for(let T of[...this.tooLarge.keys()])this.tooLargeSeen?.has(T)||this.tooLarge.delete(T);for(let T of[...this.failures.keys()])this.roundVisited?.has(T)||this.failures.delete(T);!this.error&&this.failures.size&&(this.error=[...this.failures.values()].reduce((T,v)=>T.retryAt>v.retryAt?T:v).reason)}catch(o){this.error=Ue(o)}finally{if(this.round=null,this.phase=i?.stored.paused?"paused":"idle",i&&this.host.accountId()===i.account)for(let o of this.deferredDecision.splice(0))this.applyDecision(i,o.kind,o.keys);s&&(this.noteHealth(n,a),this.live()&&this.runLog.end(a));for(let[o,l]of this.dirty)!r.has(o)&&l.last<n&&this.dirty.delete(o);i&&this.host.accountId()===i.account&&(await this.persist(i).catch(()=>{}),!this.closed&&i.abort.signal.aborted&&!i.stored.paused&&i.stored.config.enabled&&(i.abort=new AbortController,this.again=!0)),this.running=!1,this.runAccount=null,this.again&&!this.closed?(this.again=!1,queueMicrotask(()=>void this.run())):this.schedule(),e()}}noteHealth(e,n){n&&(lt("content","cycles"),lt("content","cycleMsTotal",Math.max(0,Date.now()-e)));let r=this.blocked.size?"errBlocked":this.error?ki(this.error,this.httpStatus):null;r?this.health.error(r):this.error||this.health.ok()}holdGone(e){let n=this.dirty.get(e);if(!n)return!1;let r=Date.now();return n.last>this.flushAt&&r-n.last<ha(e)&&r-n.first<Kd}isBlocked(e,n){return(this.blocked.get(e)??[]).some(r=>n===r||n.startsWith(r+"/"))}block(e,n,r){if(this.blocked.set(e,[...this.blocked.get(e)??[],n]),this.lastError=Ue(r),r!==void 0&&r===this.blockedError){this.live()&&this.runLog.addPaths([n]);return}this.blockedError=r,this.fault(Ue(r),[n])}async folders(e,n,r,i){let s=r.filter(o=>o.kind==="folder"),a=new Map;for(let o of s)if(o.localId){if(a.has(o.localId))throw Error(`Duplicate folder sync identity: ${o.path}`);a.set(o.localId,o.path)}for(let[o,l]of i){for await(let c of tn(l.nodes.filter(u=>u.kind==="folder"&&!u.deleted&&!u.busy).sort((u,f)=>en(u.path)-en(f.path))))if(!(this.isBlocked(o,c.path)||qn(this.scanned.unscanned,c.path)))try{let u=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(o+":")&&p.id===c.id)?.[1],f=(u?s.find(g=>g.localId===u.localId):null)??s.find(g=>g.path===c.path);if(u&&f&&c.path!==u.path&&f.path!==u.path&&c.path!==f.path)throw Error(`Concurrent folder rename: ${f.path}`);if(u&&f&&c.path!==u.path&&f.path===u.path){if(this.route(f.path,n,"folder")!==o)continue;if(this.route(c.path,n,"folder")!==o)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,f.path,o,"rename",null,()=>oa(e.roots,f.path,c.path,(p,m)=>this.lock(e,p,m)));let g=f.path;for(let p of r)if(p.path===g||p.path.startsWith(g+"/")){let m=p.path;p.path=c.path+m.slice(g.length);let y=Ke(e.roots,p.path);p.physical=Fe(y.root,y.relative)}for(let[p,m]of Object.entries(e.stored.files))p.startsWith(o+":")&&m.path.startsWith(u.path+"/")&&(m.path=c.path+m.path.slice(u.path.length));for(let p of n.rules)(p.source===u.path||p.source.startsWith(u.path+"/"))&&(p.source=c.path+p.source.slice(u.path.length))}if(!f&&this.route(c.path,n,"folder")===o&&!u){await Wd(e.roots,c.path,(p,m)=>this.lock(e,p,m));let g=(await this.scan(e)).find(p=>p.path===c.path);g&&(r.push(g),s.push(g))}}catch(u){this.block(o,c.path,u),this.tally("folderConflicts");let f=Object.entries(e.stored.folders).find(([g,p])=>g.startsWith(o+":")&&p.id===c.id)?.[1];f&&this.block(o,f.path,u)}for await(let c of tn(s.sort((u,f)=>en(u.path)-en(f.path))))if(!this.isBlocked(o,c.path))try{let u=this.route(c.path,n,"folder"),f=n.rules.some(_=>_.target===o&&_.source.startsWith(c.path+"/"));if(u!==o&&!f||Qo(c.path,"folder")===!1)continue;let g=await ia(c),p=e.stored.folders[Re(o,g)],m=p?l.nodes.find(_=>_.id===p.id):l.nodes.find(_=>_.path===c.path&&!_.deleted);if(m?.deleted){let _=(e.stored.deleteGuard?.restore??[]).some(h=>h.side==="local"&&h.ns===o&&h.path.startsWith(c.path+"/"));if(p&&!_){let h=!1;for(let T of r.filter(v=>v.kind==="file"&&v.path.startsWith(c.path+"/")&&this.route(v.path,n)===o)){let v=Object.entries(e.stored.files).find(([I,E])=>I.startsWith(o+":")&&E.path===T.path)?.[1];if(!v){h=!0;break}if(!this.sameAsShadow(v,T)){let I=Oe(await Wn(T));if(I!==v.hash&&!(v.memoryDeleted&&is(T.path)&&I===Yn)){h=!0;break}}}if(!h)continue}m=void 0}let y=Wt(c.path),b=y?l.nodes.find(_=>_.path===y&&_.kind==="folder"&&!_.deleted)?.id:"";if(y&&!b)throw Error("Cloud parent is unavailable");if(!m)m=await this.json(e,o,"/nodes","POST",{id:p?mt():g,parentId:b,name:bn(c.path),kind:"folder"}),e.tombstones.get(o)?.delete(m.id),l.nodes.push(m);else if(p&&m.path!==c.path){if(m.revision!==p.revision)throw Error(`Concurrent folder rename: ${c.path}`);let _=m.path,h=await this.operation(e,c.path,o,"rename",null,()=>this.json(e,o,`/nodes/${m.id}`,"PATCH",{parentId:b,name:bn(c.path),revision:m.revision}));for(let T of l.nodes)T.path.startsWith(_+"/")&&(T.path=c.path+T.path.slice(_.length));Object.assign(m,h);for(let[T,v]of Object.entries(e.stored.files))T.startsWith(o+":")&&v.path.startsWith(_+"/")&&(v.path=c.path+v.path.slice(_.length))}e.stored.folders[Re(o,g)]={id:m.id,localId:g,path:c.path,revision:m.revision,parentId:m.parentId,name:m.name}}catch(u){this.block(o,c.path,u);let f=c.localId?e.stored.folders[Re(o,c.localId)]:void 0;f&&this.block(o,f.path,u),lt("content","conflicts"),this.tally("folderConflicts");let g=this.job(e,c.path,o,"rename",null);g.state="conflict",g.error=Ue(u),g.finishedAt=Date.now()}}}async cleanupFolders(e,n,r){let i=await this.scan(e);for(let[s,a]of r)for await(let o of tn(a.nodes.filter(l=>l.kind==="folder"&&!l.busy).sort((l,c)=>en(c.path)-en(l.path)))){if(this.isBlocked(s,o.path)||this.route(o.path,n,"folder")!==s||qn(this.scanned.unscanned,o.path))continue;let l=Object.entries(e.stored.folders).find(([u,f])=>u.startsWith(s+":")&&f.id===o.id);if(!l)continue;let c=i.find(u=>u.path===o.path&&u.kind==="folder");if(o.deleted&&c){if(i.some(f=>f.path.startsWith(o.path+"/"))||(await jr(c.physical)).some(f=>f!==".forsion-sync-id.json"))continue;await this.operation(e,o.path,s,"delete",null,()=>this.lock(e,c.physical,()=>{vt(c.root,Fr(c.root,c.physical).split(Vn).join("/"));let f=nw(c.physical);if(f.some(m=>m!==".forsion-sync-id.json"))throw Error("Folder changed before deletion");let g=Fe(c.physical,".forsion-sync-id.json"),p=f.length?Gn(g):null;p&&aa(g);try{rw(c.physical)}catch(m){if(p)try{iw(g,p,{flag:"wx",mode:384})}catch{}throw m}})),this.tally("deletesLocal"),delete e.stored.folders[l[0]]}else if(!o.deleted&&!c){if(e.stored.deleteGuard?.latched||e.stored.deleteGuard?.pending.length||e.stored.deleteGuard?.restore?.length||!await this.absent(e,o.path)||a.nodes.some(u=>u.parentId===o.id&&!u.deleted))continue;await this.operation(e,o.path,s,"delete",null,()=>this.json(e,s,`/nodes/${o.id}`,"DELETE",{revision:o.revision,version:null})),o.deleted=!0,delete e.stored.folders[l[0]]}}}async download(e,n,r,i){if(n.size!==void 0&&n.size>qt)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:qt});let s=await this.request(e,r,`/nodes/${n.id}/content`),a=[],o=0;if(s.body){let c=s.body.getReader();for(;;){let u=await c.read();if(u.done)break;if(this.guard(e),o+=u.value.length,o>qt)throw await c.cancel(),Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:qt});a.push(u.value),i.done=o}}let l=Buffer.concat(a);if(n.hash&&Oe(l)!==n.hash)throw Error("Cloud file changed during download");return l}async fileRenames(e,n,r,i){for(let[s,a]of i)for(let o of a.nodes.filter(l=>l.kind==="file"&&!l.deleted&&!l.busy)){let l=e.stored.files[Re(s,o.id)];if(!l||l.path===o.path)continue;let c=r.find(u=>u.kind==="file"&&u.path===l.path);if(!(!c||this.route(c.path,n)!==s))try{if(this.route(o.path,n)!==s)throw Error("Remote rename crosses a sync rule; review the destination");await this.operation(e,c.path,s,"rename",null,()=>oa(e.roots,c.path,o.path,(u,f)=>this.lock(e,u,f))),l.path=o.path}catch(u){this.block(s,c.path,u),this.block(s,o.path,u)}}}async upload(e,n,r,i,s){let a=this.capFor(r,n.path,{limits:this.limitsByNs.get(r)});if(i.length>a)throw Object.assign(Error("content_too_large"),{code:"TOO_LARGE",maxBytes:a,size:i.length});let o=await this.request(e,r,`/nodes/${n.id}/content`,"PUT",i,u=>{s.done=u},{"X-Content-Version":n.version??"create",...n.version&&n.file?{"X-Content-File":n.file}:{}}),l=await o.json(),c=o.headers.get("x-content-file");return c&&/^[A-Za-z0-9_-]{1,64}$/.test(c)&&(l.file=c),l}async shadow(e,n,r,i,s,a){let o=Re(n,r.id),l=Oe(i),c=da(i);c&&i.length>=Jd&&await this.keepBase(e,l,i);for(let u of e.stored.jobs)u.path===r.path&&u.target===n&&["failed","paused","active"].includes(u.state)&&["upload","download","merge"].includes(u.direction)&&this.done(u);e.stored.pendingUploads&&delete e.stored.pendingUploads[o],delete e.stored.unconfirmed?.[o],e.stored.files[o]={id:r.id,path:r.path,version:r.version,hash:l,...r.file?{file:r.file}:{},...c&&i.length<Jd?{base:i.toString("utf8")}:{},...a?{inode:a.inode,stat:a.key,statAt:a.at}:s?{inode:s.inode}:{}}}async seen(e,n,r){let i=Ke(e.roots,n),s=await Bt(Fe(i.root,...i.relative.split("/"))).catch(()=>null);if(!s?.isFile())return;let a=Bn(s);return{key:Nr(a),at:r,inode:a.inode}}sameAsShadow(e,n){return!this.dirty.has(n.path)&&e.stat!==void 0&&e.statAt!==void 0&&e.stat===Nr(n)&&Aw(n)<=e.statAt-vw}unchanged(e,n,r,i,s){let a=Re(n,r.id),o=this.sameAsShadow(i,s)&&i.id===r.id&&i.path===s.path&&!r.busy&&!r.deleted&&r.version===i.version&&r.hash===i.hash&&Li(i.file,r.file)&&!e.stored.unconfirmed?.[a]&&!e.stored.pendingUploads?.[a]&&!this.openJobs.has(n+"\0"+s.path);return o&&i.file===void 0&&r.file&&(i.file=r.file),o}hold(e,n){if(e.path.endsWith("/"+Or)||n?.stat===Nr(e))return!1;let r=e.mtime,i=Date.now(),s=this.dirty.get(e.path);if(Math.floor(r)<=this.flushAt)return!1;if(s)s.last=Math.max(s.last,r);else{if(i-r>=ha(e.path))return!1;s={first:Math.min(i,r),last:r},this.dirty.set(e.path,s)}return this.dueAt(e.path,s)>i}settled(e,n){let r=this.dirty.get(e);r&&(r.last<n?this.dirty.delete(e):r.first=n)}async keepBase(e,n,r){let i=pa(e),s=Fe(i,n);if(await Bt(s).then(()=>!0,()=>!1))return;await la(i,{recursive:!0,mode:448});let a=s+".tmp-"+mt();try{await $r(a,r,{mode:384,flag:"wx"}),await rs(a,s)}finally{await Lr(a).catch(()=>{})}}async readBase(e,n){if(n.base!==void 0)return n.base;let r=await Pr(Fe(pa(e),n.hash)).catch(i=>{if(i.code==="ENOENT")return null;throw i});return r&&Oe(r)===n.hash?r.toString("utf8"):null}async pruneBases(e){let n=new Set(Object.values(e.stored.files).map(i=>i.hash)),r=pa(e);for(let i of await jr(r).catch(()=>[]))n.has(i)||await Lr(Fe(r,i)).catch(()=>{})}async file(e,n,r,i,s){if(r.size>qt)return this.noteTooLarge(e,i,r.path,r.size,qt),"too-large";let a=v=>{let I=this.capFor(i,r.path,s);return v.length<=I?!1:(this.noteTooLarge(e,i,r.path,v.length,I),!0)},o=s.nodes.find(v=>v.kind==="file"&&!v.deleted&&v.path===r.path);if(!o){let v=Object.entries(e.stored.files).find(([I,E])=>I.startsWith(i+":")&&E.inode===r.inode&&E.path!==r.path)?.[1];if(v){let I=Ke(e.roots,v.path),E=await Bt(Fe(I.root,I.relative)).then(async x=>Bn(x).inode!==r.inode||Wt(v.path)!==Wt(r.path)?!0:(await jr(wn(r.physical))).includes(bn(v.path)),x=>x.code==="ENOENT"?!1:Promise.reject(x)),D=s.nodes.find(x=>x.id===v.id&&!x.deleted);if(!E&&D)try{if(D.path!==v.path)throw Error(`Concurrent file rename: ${r.path}`);let x=Wt(r.path),L=x?s.nodes.find(H=>H.path===x&&H.kind==="folder"&&!H.deleted)?.id:"";if(x&&!L)throw Error("Rename parent unavailable");let V=await this.operation(e,r.path,i,"rename",null,()=>this.json(e,i,`/nodes/${D.id}`,"PATCH",{name:bn(r.path),parentId:L,revision:D.revision}));Object.assign(D,V),v.path=r.path,o=D}catch(x){for(let L of new Set([v.path,D.path,r.path]))this.block(i,L,x);throw x}}}let l=o?e.stored.files[Re(i,o.id)]:Object.entries(e.stored.files).find(([v,I])=>v.startsWith(i+":")&&I.path===r.path)?.[1];if(!l&&o?.version&&i==="default"&&(l=await this.legacyBaseline(r.path,o)),o&&l&&this.unchanged(e,i,o,l,r))return;if(!o&&!l&&r.size>this.capFor(i,r.path,s))return this.noteTooLarge(e,i,r.path,r.size,this.capFor(i,r.path,s)),"too-large";if(this.hold(r,l))return"held";let c=Date.now(),u=await Wn(r),f=Oe(u),g={key:Nr(r),at:c,inode:r.inode};this.guard(e),this.settled(r.path,c);let p,m;if(!o){if((l?s.nodes.find(V=>V.id===l.id&&V.deleted):null)&&l&&(l.hash===f||l.memoryDeleted&&is(r.path)&&f===Yn)){if(is(r.path)){await this.clearDeletedMemory(e,i,r,l,u,f);return}let V=Ot("local",i,l.id),H=this.round;if(!H.restore.has(V)){H.plan.push({key:Gd("local",i,l.id,f,r.path),ns:i,id:l.id,path:r.path,side:"local",e:r,hash:f});return}H.restoreHit.add(V),p=V,m=Re(i,l.id)}if(a(u))return"too-large";let I=Wt(r.path),E=I?s.nodes.find(V=>V.path===I&&!V.deleted&&V.kind==="folder")?.id:"";if(I&&!E)throw Error("Parent folder is unavailable");let D=Object.entries(e.stored.pendingUploads??{}).find(([V,H])=>V.startsWith(i+":")&&H.path===r.path&&!s.nodes.some(N=>N.id===H.id))?.[1];for(let[V,H]of Object.entries(e.stored.pendingUploads??{}))V.startsWith(i+":")&&H.path===r.path&&s.nodes.some(N=>N.id===H.id&&N.deleted)&&delete e.stored.pendingUploads[V];let x=D?.id??mt(),L=Re(i,x);(e.stored.pendingUploads??={})[L]={id:x,path:r.path},await this.persist(e),o=await this.json(e,i,"/nodes","POST",{id:x,parentId:E,name:bn(r.path),kind:"file"}),e.tombstones.get(i)?.delete(o.id),o.id!==x&&delete e.stored.pendingUploads[L],s.nodes.push(o),l=void 0}if(o.busy)return;let y=Re(i,o.id);if(o.version&&this.awaitingBytes.delete(y),o.hash===f){await this.shadow(e,i,o,u,r,g);return}if(o.hash&&e.stored.unconfirmed?.[y]===o.hash&&(await this.shadow(e,i,o,await this.operation(e,r.path,i,"download",o.size??null,v=>this.download(e,o,i,v)),r),l=e.stored.files[y]),!o.version&&l&&l.hash===f&&!e.stored.pendingUploads?.[y]){let v=this.awaitingBytes.get(y)??Date.now();if(this.awaitingBytes.set(y,v),Date.now()-v<yw)return}if(this.awaitingBytes.delete(y),!o.version||l&&o.version===l.version&&Li(l.file,o.file)){if(a(u))return"too-large";(e.stored.unconfirmed??={})[y]=f,await this.persist(e);let v=await this.operation(e,r.path,i,"upload",u.length,I=>this.upload(e,o,i,u,I));Object.assign(o,v),await this.shadow(e,i,o,u,r,g),p&&(this.round.restoreDone.add(p),m&&m!==y&&delete e.stored.files[m]);return}let b=await this.operation(e,r.path,i,"download",o.size??null,v=>this.download(e,o,i,v)),_=b,h=!1;if(!l||l.hash!==f){let v=u.toString("utf8"),I=b.toString("utf8"),E=l?await this.readBase(e,l):null,D=Buffer.from(v).equals(u)&&Buffer.from(I).equals(b)?this.host.contentSync.merge(r.path,v,E,I):null;if(D&&!D.conflict&&E!==null&&ww(r.path)&&!So(E,v,D.content)&&(D=null),D?(_=Buffer.from(D.content),h=D.conflict):h=!0,h){await this.preserveConflict(e,r.path,u)&&(lt("content","conflicts"),this.tally("conflictCopies"));let x=this.job(e,r.path,i,"merge",u.length);x.state="conflict",x.error="Both versions preserved",x.finishedAt=Date.now()}if(!_.equals(b)){let x=await this.operation(e,r.path,i,"merge",_.length,L=>this.upload(e,o,i,_,L));Object.assign(o,x)}}let T=Date.now();await this.write(e,r.path,_,f),await this.shadow(e,i,o,_,r,await this.seen(e,r.path,T))}async preserveConflict(e,n,r){let i=Ke(e.roots,n),s=await ct(i.root,i.relative),a=bn(n),o=Oe(r);for(let l of await jr(wn(s))){if(l.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}(?: \d+)?\)/,"")!==a||!Gi(l))continue;let c=Wt(n)?Wt(n)+"/"+l:l,u=Ke(e.roots,c),f=await ct(u.root,u.relative),g=await Bt(f);if(g.isFile()&&g.size===r.length&&Oe(await Pr(f))===o)return!1}return await this.write(e,await this.copyName(e,n),r,null),!0}async copyName(e,n){let r=new Date;for(let i=1;;i++){let s=_d(n,r,i),a=Ke(e.roots,s);if(!await Bt(Fe(a.root,...a.relative.split("/"))).then(()=>!0,o=>o.code==="ENOENT"?!1:Promise.reject(o)))return s}}async legacyBaseline(e,n){let r=await this.host.contentSync.agentFiles?.baseline(e).catch(()=>null);if(!(!r||!n.version)&&!(r.pending&&Number(n.version.split(":")[0])!==r.seq))return{id:n.id,path:e,version:`${r.seq}:${r.hash}`,hash:r.hash,...r.base!==void 0?{base:r.base}:{}}}agentAsks(e,n,r,i,s){let a=[],o=l=>l.length?Math.max(...l):null;for(let l of n){let c=l.kind==="folder"?Ar(l.path):null;if(!c||Hi.has(c))continue;let u=`agents/${c}/`,f=this.route(u+"config.toml",r);if(!f||Object.entries(e.stored.files).some(([b,_])=>b.startsWith(f+":")&&_.path.startsWith(u)))continue;let g=(i.get(f)?.nodes??[]).filter(b=>!b.deleted&&b.kind==="file"&&b.version&&b.path.startsWith(u)&&this.route(b.path,r)===f),p=n.filter(b=>b.kind==="file"&&b.path.startsWith(u)&&this.route(b.path,r)===f);if(!g.length||!p.length)continue;let m=new Map(g.map(b=>[b.path,b])),y=p.filter(b=>{let _=m.get(b.path);return!!_&&s.get(b.path)!==_.hash}).length;!y&&p.length===g.length&&p.every(b=>m.has(b.path))||a.push({slug:c,namespace:f,cloudFiles:g.length,localFiles:p.length,differ:y,cloudMtime:o(g.map(b=>b.mtime??0)),localMtime:o(p.map(b=>b.mtime))})}return a}async resolveAsks(e,n,r,i){for(let s of n){try{await this.resolveAsk(e,s,r[s.slug]??"merge",i)}catch(c){throw this.dropShadows(e,s.namespace,`agents/${s.slug}/`),await this.persist(e),Error(`agent_open_failed: ${Ue(c)}`)}let a=`agents/${s.slug}`,o=i.rules.find(c=>c.source===a),l=Pn(e.stored.config,a,gu(i,a));o&&(l={...l,rules:l.rules.map(c=>c.source===a?{...o,target:c.target}:c)}),e.stored.config=Zt(l,e.stored.config.revision+1),await this.persist(e)}}async resolveAsk(e,n,r,i){let s=n.namespace,a=`agents/${n.slug}/`;if(this.dropShadows(e,s,a),r==="local"){await this.archiveAgent(e,s,n.slug),await this.persist(e);return}let o=await this.json(e,s);this.guard(e),Ki(o,s);let l=new Map(o.nodes.filter(p=>!p.deleted&&!p.busy&&p.kind==="file"&&p.version&&p.path.startsWith(a)&&this.route(p.path,i)===s).map(p=>[p.path,p])),c=p=>p.endsWith("/"+Or),u=async(p,m,y)=>{let b=Date.now();return await this.write(e,p,m,y),this.seen(e,p,b)};for(let[p,m]of l){if(!c(p))continue;let y=Ke(e.roots,p);if(Zd(Fe(y.root,y.relative)))continue;let b=await this.operation(e,p,s,"download",m.size??null,_=>this.download(e,m,s,_));await this.shadow(e,s,m,b,void 0,await u(p,b,null))}let f=(await this.scan(e)).filter(p=>p.kind==="file"&&p.path.startsWith(a)&&this.route(p.path,i)===s&&p.size<=qt).sort((p,m)=>+!c(p.path)-+!c(m.path)),g=await this.removedDir(e,n.slug);for(let p of f){this.guard(e);let m=await Wn(p),y=Oe(m),b=l.get(p.path),_=p.path.slice(a.length);if(b&&b.hash===y){await this.shadow(e,s,b,m,p);continue}if(r==="cloud"){if(await this.keep(e,`${g}/${_}`,m),b){let E=await this.operation(e,p.path,s,"download",b.size??null,D=>this.download(e,b,s,D));await this.shadow(e,s,b,E,p,await u(p.path,E,y))}else _==="MEMORY.md"?await this.write(e,p.path,Buffer.alloc(0),y):await this.removeLocal(e,p,y);continue}if(!b)continue;let h=await this.operation(e,p.path,s,"download",b.size??null,E=>this.download(e,b,s,E)),T=s==="default"?await this.legacyBaseline(p.path,b):void 0;if(T?.hash===y){await this.shadow(e,s,b,h,p,await u(p.path,h,y));continue}let v=T?await this.readBase(e,T):null,I=da(m)&&da(h)?this.host.contentSync.merge(p.path,m.toString("utf8"),v,h.toString("utf8")):null;if(I&&!I.conflict){let E=Buffer.from(I.content);E.equals(m)||await this.write(e,p.path,E,y),await this.shadow(e,s,b,h)}else(b.mtime??0)>p.mtime?(await this.keep(e,`${g}/${_}`,m),await this.shadow(e,s,b,h,p,await u(p.path,h,y))):(await this.keep(e,`${g}/${_}`,h),await this.shadow(e,s,b,h))}await this.persist(e)}dropShadows(e,n,r){for(let[i,s]of Object.entries(e.stored.files))i.startsWith(n+":")&&s.path.startsWith(r)&&(delete e.stored.files[i],delete e.stored.unconfirmed?.[i])}async removedDir(e,n,r="agents"){let i=new Date,s=o=>String(o).padStart(2,"0"),a=`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())} ${s(i.getHours())}${s(i.getMinutes())}`;for(let o=1;;o++){let l=`${r}/.removed/${n} ${a}${o>1?` ${o}`:""}`,c=Ke(e.roots,l);if(!await Bt(Fe(c.root,...c.relative.split("/"))).then(()=>!0,u=>u.code==="ENOENT"?!1:Promise.reject(u)))return l}}async keep(e,n,r){this.guard(e),await sa(e.roots,n,r,null)}async removeLocal(e,n,r){await this.lock(e,n.physical,()=>{if(vt(n.root,Fr(n.root,n.physical).split(Vn).join("/")),Oe(Gn(n.physical))!==r)throw Error("Local file changed before replacing");aa(n.physical)})}async archiveAgent(e,n,r){let i=this.host.readCreds();if(!i.token)throw Error("not_signed_in");let s=await this.gatedFetch(e,i.cloudUrl,"/api/remotesync/agent-archive/agent",{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json","X-Content-Device":this.deviceId},body:JSON.stringify({namespace:n,slug:r,opId:mt(),locale:this.locale()})},12e4);this.guard(e);let a=await s.json().catch(()=>({}));if(this.guard(e),!s.ok||a?.state!=="done")throw Error(typeof a?.detail=="string"?a.detail:`agent_archive_http_${s.status}`)}async absent(e,n,r=e.roots){this.guard(e);let i=Ke(r,n),s=await ct(i.root,i.relative);try{return await Bt(s),!1}catch(a){if(a.code==="ENOENT")return!0;throw a}}async missing(e,n,r,i,s){let a=e.stored.files[Re(r,n.id)],o=e.stored.pendingUploads?.[Re(r,n.id)];if(!n.deleted&&a?.inode&&this.blocked.has(r)&&i.some(y=>y.kind==="file"&&y.inode===a.inode&&this.isBlocked(r,y.path)&&this.route(y.path,s)===r)){this.round?.undecided.add(r+"\0"+n.path);return}let l=qn(this.scanned.unscanned,n.path)||!!a?.inode&&this.scanned.skippedInodes.has(a.inode),c=Do(n,a,!!o,l),u=this.round,f=()=>u.plan.some(y=>y.side==="local"&&y.ns===r&&y.id===n.id)||u.restore.has(Ot("local",r,n.id))||!!e.stored.deleteGuard?.pending.some(y=>y.side==="local"&&y.ns===r&&y.id===n.id);if(c==="forget"){a&&!f()&&delete e.stored.files[Re(r,n.id)],o&&delete e.stored.pendingUploads[Re(r,n.id)];return}if(c==="skip")return u.undecided.add(r+"\0"+n.path),a&&u.undecided.add(r+"\0"+a.path),l?"unknown":void 0;if(c==="cancel"){await this.absent(e,n.path)&&(await this.operation(e,n.path,r,"delete",null,()=>this.json(e,r,`/nodes/${n.id}`,"DELETE",{revision:n.revision,version:null})),delete e.stored.pendingUploads[Re(r,n.id)],n.deleted=!0);return}let g;if(c==="delete"){if(!await this.absent(e,n.path))return;let y=Ot("cloud",r,n.id);if(!u.restore.has(y)){u.plan.push({key:Gd("cloud",r,n.id,n.version,n.path),ns:r,id:n.id,path:n.path,side:"cloud",node:n});return}u.restoreHit.add(y),g=y}if(n.size!==void 0&&n.size>qt){this.noteTooLarge(e,r,n.path,n.size,qt),u.undecided.add(r+"\0"+n.path);return}let p=await this.operation(e,n.path,r,"download",n.size??null,y=>this.download(e,n,r,y)),m=Date.now();await this.write(e,n.path,p,null),await this.shadow(e,r,n,p,void 0,await this.seen(e,n.path,m)),g&&u.restoreDone.add(g)}async executeDeletes(e,n){let r=e.stored.deleteGuard,i=n.plan,s=new Set(i.map(_=>_.key)),a=new Set(i.map(_=>Ot(_.side,_.ns,_.id))),o=new Set((r?.confirmed??[]).filter(_=>s.has(_))),l=Date.now();this.deleteStamps=this.deleteStamps.filter(_=>l-_<Ro);let c=i.filter(_=>!o.has(_.key)),u=Oo(c,n.tracked,{latched:!!r?.latched,recent:this.deleteStamps.length});u&&!r?.latched&<("content","massDeleteGuard");let f=_=>{let h=e.stored.files[Re(_.ns,_.id)];return[_.path,...h?[h.path]:[]].some(v=>n.undecided.has(_.ns+"\0"+v)||qn(this.scanned.unscanned,v))||!!h?.inode&&this.scanned.skippedInodes.has(h.inode)},g=(r?.pending??[]).filter(_=>!a.has(Ot(_.side,_.ns,_.id))&&f(_)),p=[...n.restore].filter(([_,h])=>!n.restoreDone.has(_)&&(n.restoreHit.has(_)||f(h))).map(([,_])=>_),m={latched:u||g.length>0,pending:[...u?c.map(Vd):[],...g],...o.size?{confirmed:[...o]}:{},...p.length?{restore:p}:{}},y=()=>{m.latched||m.pending.length||m.confirmed?.length||m.restore?.length?e.stored.deleteGuard=m:delete e.stored.deleteGuard};y(),await this.persist(e);let b=[...i.filter(_=>o.has(_.key)),...u?[]:c];for(let _=0;_<b.length;_++){let h=b[_],T=o.has(h.key);try{if(h.side==="cloud"){if(!await this.absent(e,h.path))continue;let v=h.node;await this.operation(e,h.path,h.ns,"delete",v.size??null,()=>this.json(e,h.ns,`/nodes/${v.id}`,"DELETE",{revision:v.revision,version:v.version,...v.file?{file:v.file}:{}},T?{"X-Content-Delete-Confirmed":"1"}:void 0)),delete e.stored.files[Re(h.ns,v.id)],v.deleted=!0}else await this.operation(e,h.path,h.ns,"delete",h.e.size,()=>this.trashFile(e,h.e,h.hash)),this.tally("deletesLocal"),delete e.stored.files[Re(h.ns,h.id)];T?m.confirmed=m.confirmed?.filter(v=>v!==h.key):this.deleteStamps.push(Date.now())}catch(v){if(v?.code!=="MASS_DELETE_BLOCKED"){this.error=Ue(v);continue}m.latched||lt("content","massDeleteGuard"),m.latched=!0,m.pending=[...m.pending,...b.slice(_).filter(I=>I.side==="cloud").map(Vd)];for(let I of b.slice(_+1))if(I.side==="local")try{await this.operation(e,I.path,I.ns,"delete",I.e.size,()=>this.trashFile(e,I.e,I.hash)),this.tally("deletesLocal"),delete e.stored.files[Re(I.ns,I.id)]}catch(E){this.error=Ue(E)}break}}y(),await this.persist(e)}async recoverTrash(e){for(let n of[...e.stored.trash??[]]){if(n.parentId){let c=(await ns(e.roots)).find(u=>u.kind==="folder"&&u.localId===n.parentId);c&&(n.path=c.path+"/"+bn(n.path))}let r=Ke(e.roots,n.path),i=await ct(r.root,r.relative);if(!/^\.forsion-sync-trash-[a-f0-9-]+$/.test(n.stage))throw Error("Invalid sync recovery journal");let s=n.stageRoot??r.root,a=await this.rootIdentity(e,s),o=n.stageIdentity??(n.stageDev===void 0?void 0:{dev:n.stageDev,ino:n.stageIno});if(o&&!an(o,a))throw Error("Sync recovery root changed; journal retained");let l=Fe(s,n.stage);await Bt(l).then(()=>!0,c=>c.code==="ENOENT"?!1:Promise.reject(c))&&await this.lock(e,i,()=>{if(vt(s,n.stage,!0),Oe(Gn(l))!==n.hash)throw Error("Sync recovery content changed");vt(r.root,r.relative),sw(wn(i),{recursive:!0});let c=Zd(i)?i+` (sync recovery ${mt().slice(0,8)})`:i;try{tw(l,c)}catch(u){if(u.code!=="EXDEV")throw u;if(ow(l,c,aw.COPYFILE_EXCL),Oe(Gn(c))!==n.hash)throw Error("Sync recovery copy incomplete; original retained")}aa(l)},!0),e.stored.trash=e.stored.trash.filter(c=>c!==n)}}async clearDeletedMemory(e,n,r,i,s,a){i.memoryDeleted&&i.hash===Yn&&a===Yn||(await this.operation(e,r.path,n,"delete",r.size,async()=>{if(!i.memoryDeleted&&s.length){let c=r.path==="human/MEMORY.md",u=await this.removedDir(e,c?"memory":r.path.split("/")[1],c?"human":"agents");await this.keep(e,`${u}/MEMORY.md`,s)}i.memoryDeleted=!0,await this.persist(e);let o=Date.now();s.length&&await this.write(e,r.path,Buffer.alloc(0),a);let l=await this.seen(e,r.path,o);e.stored.files[Re(n,i.id)]={...i,hash:Yn,base:"",stat:void 0,statAt:void 0,...l?{inode:l.inode,stat:l.key,statAt:l.at}:{}}}),this.tally("deletesLocal"))}async trashFile(e,n,r){this.guard(e);let i=await ct(n.root,Fr(n.root,n.physical).split(Vn).join("/")),s={path:n.path,stage:".forsion-sync-trash-"+mt(),hash:r},a=Fe(n.root,s.stage),o=await this.rootIdentity(e,n.root);s.stageRoot=n.root,s.stageDev=o.dev,s.stageIno=o.ino,s.stageIdentity=o;try{let l=JSON.parse(Gn(Fe(wn(i),".forsion-sync-id.json"),"utf8")).id;/^[a-f0-9-]{36}$/i.test(l)&&(s.parentId=l)}catch{}(e.stored.trash??=[]).push(s),await this.persist(e);try{await this.lock(e,i,()=>{if(vt(n.root,Fr(n.root,i).split(Vn).join("/")),Oe(Gn(i))!==r)throw Error("Local file changed before deletion");ew(i,a)}),await this.host.contentSync.trash(a),e.stored.trash=e.stored.trash.filter(l=>l!==s)}catch(l){throw this.host.accountId()===e.account&&!e.abort.signal.aborted&&await this.recoverTrash(e),l}}};function xw(t){let e={};if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))Cr.test(n)&&uu.includes(r)&&(e[n]=r);return e}function Zd(t){try{return Zy(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}Ha(El);function Rk(t){kl(t.contentSync?.withWriteLock?.bind(t.contentSync)),Xa(t),Gs(t),ef(t),t.log("[forsion-extend] cloud account handlers registered"),js(t)?Ls(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Us(t)?Hs(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),Qs(t)?eo(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),wo(t)?bo(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),ko(t)?Eo(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Uo(t)?Zu(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off"),Uo(t)&&vd(t)}export{Ql as ACCOUNT_SEAM,Kc as AMADEUS_SEAM,$s as CONNECT_MAX_FILES,Al as CONNECT_MAX_FILE_BYTES,xl as CONNECT_MAX_TOTAL_BYTES,mi as DIAGNOSTICS_VAULT,$l as FORSION_CONNECT_LOCAL_SDK,Ja as PAY_PERIODS,Ya as PAY_TABS,Fl as PENZOR_MAX_FILE,Ne as SYNC_IPC,Qc as UNIT_SEAM,cr as UPLOAD_MAX_FILE,vr as UnitCapsReporter,Sr as UnitHost,Ze as cloudJson,Il as collectProjectFiles,Si as conflictCopyPath,Dh as conflictCopyVariant,Nl as connectMetaOf,Zl as createAccountCloud,Xc as createAmadeusCloud,gi as createPenzorRemote,eu as createUnitHub,hi as deviceHeader,Fs as expectedPartsOf,Ve as forsionAccountId,ri as forsionRefreshToken,lr as forsionWhoami,Qs as hasAccountHost,wo as hasAmadeusHost,js as hasConnectHost,Us as hasRemoteSyncHost,ko as hasUnitHost,Pl as makePreviewProxy,Yl as multipartFrame,Dl as readConnectMeta,eo as registerAccount,bo as registerAmadeus,Rk as registerCloud,Ls as registerConnect,Hs as registerPenzor,Gs as registerPenzorTransfers,Eo as registerUnit,yi as safeDownloadName,Ml as scanSdkUsage,ni as shouldRefreshToken,zs as speedOf,Zc as streamWorthy,Pc as stripConflictSuffix,Oh as textFingerprint,ws as tokenAgeMs,Wa as tokenRemainingMs,Bs as uploadError,Ol as writeConnectMeta};
|
|
287
288
|
/*! Bundled license information:
|
|
288
289
|
|
|
289
290
|
chokidar/index.js:
|