grix-connector 4.7.0 → 4.7.2

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.
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.7.0",
4
- "tarball": "grix-dsh-bridge-4.7.0.tgz",
5
- "size": 23124,
3
+ "bridgeVersion": "4.7.2",
4
+ "tarball": "grix-dsh-bridge-4.7.2.tgz",
5
+ "size": 23125,
6
6
  "unpackedSize": 92668,
7
- "shasum": "1c8f073063d25f1277a5954406517cbd37d91af3",
8
- "integrity": "sha512-deYX3BWFwmN3GIcJqIx9m8dh4reLrewehNkaaVFfmeqoGjerCL1VsLUcCiR7tQq4WGQNj7VDQ0N2Zuqm8mcT6A=="
7
+ "shasum": "97458fce62fe3ab12a7f5607675dfc257109a06d",
8
+ "integrity": "sha512-8DMvPMXMOjccDRSeOPKi/qYXb9COt87PgECppPKdt4AnzaXVDEzihsiZGCtqD0HpELqqn6oNYm1f+lU8OheP0w=="
9
9
  }
@@ -1,4 +1,4 @@
1
- import{execFile as w,execFileSync as $}from"node:child_process";import{existsSync as O}from"node:fs";import{dirname as T,join as y}from"node:path";import{promisify as k}from"node:util";import{log as I}from"../log/logger.js";import{probeUrls as v}from"./speed-test.js";const C=k(w),A=1e4,x=2,M=3e3;function R(t,e={}){if((e.platform??process.platform)!=="win32")return{command:"npm",args:t};const i=e.env??process.env,o=e.nodePath??process.execPath,u=[typeof i.npm_execpath=="string"?i.npm_execpath:"",y(T(o),"node_modules","npm","bin","npm-cli.js")];try{const n=$("where.exe",["npm.cmd"],{encoding:"utf-8",timeout:3e3,windowsHide:!0}).split(/\r?\n/).map(l=>l.trim()).filter(Boolean);for(const l of n)u.push(y(T(l),"node_modules","npm","bin","npm-cli.js"))}catch{}const s=u.find(n=>n&&O(n));if(!s)throw new Error("Unable to locate npm-cli.js for safe Windows execution");return{command:o,args:[s,...t]}}class b extends Error{output;constructor(e,r){super(e),this.name="NpmInstallError",this.output=r}}const f=[{id:"official",label:"npm \u5B98\u65B9",url:"https://registry.npmjs.org"},{id:"npmmirror",label:"npmmirror (\u6DD8\u5B9D\u955C\u50CF)",url:"https://registry.npmmirror.com"}];async function P(){const t=await v(f.map(r=>({url:r.url,label:r.label})),5e3),e=[];for(const r of t)if(r.reachable){const i=f.find(o=>o.url===r.url);i&&e.push(i)}for(const r of t)if(!r.reachable){const i=f.find(o=>o.url===r.url);i&&!e.includes(i)&&e.push(i)}for(const r of f)e.includes(r)||e.push(r);return e}async function B(){try{const t=R(["config","get","registry"]),{stdout:e}=await C(t.command,t.args,{timeout:A,encoding:"utf-8"});return e.trim()}catch{return"https://registry.npmjs.org"}}async function J(t,e,r,i){const o=await P();if(o.length===0)throw new Error("All npm registries are unreachable. Check your network connection.");let u="",s="";for(const n of o)for(let l=0;l<=x;l++)try{return I.info("installer",`npm install ${t} using ${n.label} (${n.url})`),{output:await D(t,n.url,e,r,i),registry:n.label,registryUrl:n.url}}catch(a){const c=a instanceof Error?a.message:String(a),d=L(a);if(u=c,s=F(`${s}
2
- [${n.label}] ${c}
3
- ${d}`.trim(),r),I.info("installer",`${n.label} failed: ${c.slice(0,200)}`),j(c)&&l<x){await new Promise(m=>setTimeout(m,M));continue}if(!U(c))throw new b(c,s);break}throw new b(`npm install failed on all registries. Last error: ${u}`,s)}function U(t){return/ECONNRESET|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ERR_SOCKET_TIMEOUT|getaddrinfo|socket hang up|network|fetch failed|timed out|tunneling socket|self.signed|404|ETARGET|No matching version|notarget/i.test(t)}function j(t){return/\bEBUSY\b|resource busy or locked|EPERM[^\n]*\brename\b|\bELOCKED\b/i.test(t)}function D(t,e,r,i,o){return new Promise((u,s)=>{const n=["install","-g",t,"--registry",e,"--prefer-online","--no-audit","--no-fund"];o?.prefix&&n.push("--prefix",o.prefix),o?.ignoreScripts&&n.push("--ignore-scripts");const l=process.platform==="win32",a=R(n,{env:o?.env});let c=!1,d=Promise.resolve(),m;const g=w(a.command,a.args,{maxBuffer:i,windowsHide:!0,env:o?.env},async(p,_,N)=>{clearTimeout(m),await d;const E=`${_??""}
4
- ${N??""}`.trim();if(p){const h=E||p.message,S=c||p.killed===!0?`ETIMEDOUT: npm install exceeded ${r}ms (registry likely unreachable): ${h}`:h;s(new b(S,E||h));return}u(E)});m=setTimeout(()=>{c=!0,l&&g.pid?d=new Promise(p=>{w("taskkill",["/PID",String(g.pid),"/T","/F"],{windowsHide:!0,timeout:1e4},()=>{g.kill("SIGTERM"),p()})}):g.kill("SIGTERM")},r),m.unref?.()})}function L(t){if(t&&typeof t=="object"&&"output"in t){const e=t.output;return typeof e=="string"?e:""}return""}function F(t,e){return t.length<=e?t:t.slice(-e)}function Q(t){return f.map(e=>({label:e.label,command:`npm install -g ${t} --registry ${e.url}`}))}export{f as NPM_REGISTRIES,b as NpmInstallError,B as getCurrentRegistry,Q as getMirrorInstallCommands,U as isRetriableRegistryError,j as isTransientInstallError,J as npmInstallWithMirror,P as probeRegistries,R as resolveNpmInvocation};
1
+ import{execFile as b,execFileSync as C}from"node:child_process";import{existsSync as $,mkdirSync as k}from"node:fs";import{basename as O,dirname as x,join as y}from"node:path";import{promisify as A}from"node:util";import{resolveRuntimePaths as P}from"../config/paths.js";import{log as I}from"../log/logger.js";import{probeUrls as D}from"./speed-test.js";const M=A(b),U=1e4,N=2,j=3e3;function L(e){if(!e)return!1;const t=e.replace(/\\/g,"/").toLowerCase();return O(t)==="npm-cli.js"||t.includes("/node_modules/npm/")}function F(){try{const e=y(P().rootDir,"npm-cache");return k(e,{recursive:!0}),e}catch{return}}function R(e,t={}){if((t.platform??process.platform)!=="win32")return{command:"npm",args:e};const i=t.env??process.env,n=t.nodePath??process.execPath,u=typeof i.npm_execpath=="string"?i.npm_execpath:"",c=[L(u)?u:"",y(x(n),"node_modules","npm","bin","npm-cli.js")];try{const s=C("where.exe",["npm.cmd"],{encoding:"utf-8",timeout:3e3,windowsHide:!0}).split(/\r?\n/).map(l=>l.trim()).filter(Boolean);for(const l of s)c.push(y(x(l),"node_modules","npm","bin","npm-cli.js"))}catch{}const o=c.find(s=>s&&$(s));if(!o)throw new Error("Unable to locate npm-cli.js for safe Windows execution");return{command:n,args:[o,...e]}}class T extends Error{output;constructor(t,r){super(t),this.name="NpmInstallError",this.output=r}}const p=[{id:"official",label:"npm \u5B98\u65B9",url:"https://registry.npmjs.org"},{id:"npmmirror",label:"npmmirror (\u6DD8\u5B9D\u955C\u50CF)",url:"https://registry.npmmirror.com"}];async function G(){const e=await D(p.map(r=>({url:r.url,label:r.label})),5e3),t=[];for(const r of e)if(r.reachable){const i=p.find(n=>n.url===r.url);i&&t.push(i)}for(const r of e)if(!r.reachable){const i=p.find(n=>n.url===r.url);i&&!t.includes(i)&&t.push(i)}for(const r of p)t.includes(r)||t.push(r);return t}async function te(){try{const e=R(["config","get","registry"]),{stdout:t}=await M(e.command,e.args,{timeout:U,encoding:"utf-8"});return t.trim()}catch{return"https://registry.npmjs.org"}}async function re(e,t,r,i){const n=await G();if(n.length===0)throw new Error("All npm registries are unreachable. Check your network connection.");let u="",c="";for(const o of n)for(let s=0;s<=N;s++)try{return I.info("installer",`npm install ${e} using ${o.label} (${o.url})`),{output:await W(e,o.url,t,r,i),registry:o.label,registryUrl:o.url}}catch(l){const a=l instanceof Error?l.message:String(l),f=Y(l);if(u=a,c=z(`${c}
2
+ [${o.label}] ${a}
3
+ ${f}`.trim(),r),I.info("installer",`${o.label} failed: ${a.slice(0,200)}`),K(a)&&s<N){await new Promise(d=>setTimeout(d,j));continue}if(!H(a))throw new T(a,c);break}throw new T(`npm install failed on all registries. Last error: ${u}`,c)}function H(e){return/ECONNRESET|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ERR_SOCKET_TIMEOUT|getaddrinfo|socket hang up|network|fetch failed|timed out|tunneling socket|self.signed|404|ETARGET|No matching version|notarget/i.test(e)}function K(e){return/\bEBUSY\b|resource busy or locked|EPERM[^\n]*\brename\b|\bELOCKED\b/i.test(e)}function W(e,t,r,i,n){return new Promise((u,c)=>{const o=["install","-g",e,"--registry",t,"--prefer-online","--no-audit","--no-fund"],s=F();s&&o.push("--cache",s),n?.prefix&&o.push("--prefix",n.prefix),n?.ignoreScripts&&o.push("--ignore-scripts");const l=process.platform==="win32",a=R(o,{env:n?.env});let f=!1,d=Promise.resolve(),E;const g=b(a.command,a.args,{maxBuffer:i,windowsHide:!0,env:n?.env},async(m,_,S)=>{clearTimeout(E),await d;const h=`${_??""}
4
+ ${S??""}`.trim();if(m){const w=h||m.message,v=f||m.killed===!0?`ETIMEDOUT: npm install exceeded ${r}ms (registry likely unreachable): ${w}`:w;c(new T(v,h||w));return}u(h)});E=setTimeout(()=>{f=!0,l&&g.pid?d=new Promise(m=>{b("taskkill",["/PID",String(g.pid),"/T","/F"],{windowsHide:!0,timeout:1e4},()=>{g.kill("SIGTERM"),m()})}):g.kill("SIGTERM")},r),E.unref?.()})}function Y(e){if(e&&typeof e=="object"&&"output"in e){const t=e.output;return typeof t=="string"?t:""}return""}function z(e,t){return e.length<=t?e:e.slice(-t)}function ne(e){return p.map(t=>({label:t.label,command:`npm install -g ${e} --registry ${t.url}`}))}export{p as NPM_REGISTRIES,T as NpmInstallError,te as getCurrentRegistry,ne as getMirrorInstallCommands,L as isNpmCliEntry,H as isRetriableRegistryError,K as isTransientInstallError,re as npmInstallWithMirror,G as probeRegistries,F as resolveNpmCacheDir,R as resolveNpmInvocation};
@@ -1,2 +1,2 @@
1
- import{execFile as wt,execFileSync as R}from"node:child_process";import{randomUUID as Q}from"node:crypto";import{promisify as yt}from"node:util";import{uptime as St}from"node:os";import{closeSync as Et,copyFileSync as kt,cpSync as It,existsSync as d,linkSync as Pt,mkdirSync as E,mkdtempSync as tt,openSync as vt,readFileSync as P,renameSync as h,rmSync as p,statfsSync as xt,symlinkSync as $t,unlinkSync as H,writeFileSync as x}from"node:fs";import{basename as v,dirname as w,join as l,relative as rt,resolve as u,sep as b}from"node:path";import{GRIX_PATHS as $}from"../log/index.js";import{appendRotatingFileSync as Dt}from"../log/rotation.js";import{getMachineName as Nt}from"../util/host-info.js";import{resolveInstallId as At}from"../util/install-id.js";import{NPM_REGISTRIES as Rt,npmInstallWithMirror as et,probeRegistries as bt,resolveNpmInvocation as M}from"../installer/npm-registry.js";import{resolveWindowsServiceRuntimeDir as nt}from"../../service/service-paths.js";const it=yt(wt);class f extends Error{code;constructor(r,e){super(e),this.name="UpgradeError",this.code=r}}const Ut=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function O(t){const r=String(t??"").trim().replace(/^v(?=\d)/,"");if(!Ut.test(r))throw new f("INVALID_VERSION",`Invalid connector upgrade version: ${String(t)}`);return r}const Y=".grix-upgrade-backup",Ft=".grix-upgrade-failed",ot=".grix-upgrade-backup",at=".grix-upgrade-next",Lt="upgrade-wrapper.pause.json",Tt="upgrade-rollback.intent.json",Mt=".grix-connector-upgrade.lock",ct=[250,750],C=[100,250,750,1500];function st(){return l($.log,"upgrade.log")}function I(){return l($.data,"upgrade-pending.json")}function lr(){let t=null;try{t=_()}catch{return{in_progress:!1}}if(!t)return{in_progress:!1};const r=t.phase??"staged";return{in_progress:!(r==="failed"||r==="rolled_back"),phase:r,from:t.from_version,target:t.target_version}}function dr(){return d(I())}function gr(t,r="failed"){const e=new Date().toISOString().replace(/[:.]/g,""),n=l($.data,`upgrade-pending.${r}-${e}.json`);try{return x(n,JSON.stringify(t,null,2),"utf-8"),n}catch{return null}}function _(){const t=I();if(!d(t))return null;try{return JSON.parse(P(t,"utf-8"))}catch{return null}}function pr(t,r,e){const n={from_version:t,target_version:r,upgraded_at:new Date().toISOString(),crash_count:0,transaction_id:Q(),...e?{phase:e}:{}},i=I();E(w(i),{recursive:!0});let a;try{a=vt(i,"wx",384)}catch(o){throw o?.code==="EEXIST"?new f("UPGRADE_IN_PROGRESS","Another connector upgrade transaction is already active"):o}try{x(a,JSON.stringify(n),"utf-8")}catch(o){try{H(i)}catch{}throw o}finally{Et(a)}return n}function _r(t){const r=t.package_dir;if(!r)return null;const e=u(r);if(!e.includes(`${b}node_modules${b}`))return null;try{const n=JSON.parse(P(l(e,"package.json"),"utf-8"));return n.name!=="grix-connector"||typeof n.version!="string"?null:n.version.trim().replace(/^v/,"")||null}catch{return null}}function Ot(t,r){E(w(t),{recursive:!0});const e=`${t}.tmp-${process.pid}`;x(e,JSON.stringify(r),"utf-8"),h(e,t)}function D(t,r){const e=_();if(!e)throw new f("PENDING_MISSING","Upgrade transaction is missing");if(r&&e.transaction_id!==r)throw new f("UPGRADE_TRANSACTION_CHANGED","Upgrade transaction ownership changed");const n={...e,...t};return Ot(I(),n),n}function j(){return l($.data,Lt)}function Ct(){return l($.data,Tt)}function mr(t,r){const e=_();if(!e?.transaction_id||e.phase!=="staged"||r&&e.transaction_id!==r)throw new f("INVALID_UPGRADE_STATE","Windows upgrade is not staged for activation");const n=j();E(w(n),{recursive:!0});const i=`${n}.tmp-${process.pid}`;return x(i,JSON.stringify({transaction_id:e.transaction_id}),"utf-8"),h(i,n),D({phase:"handoff_ready",old_pid:t,old_command_line:Gt(t)??void 0,old_boot_time:Date.now()-St()*1e3,activation_started_at:new Date().toISOString(),wrapper_pause_file:n},e.transaction_id)}function Gt(t){if(process.platform!=="win32"||!Number.isInteger(t)||t<=0)return null;try{const r=`${process.env.SystemRoot||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;return R(r,["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`(Get-CimInstance Win32_Process -Filter 'ProcessId=${t}').CommandLine`],{encoding:"utf-8",timeout:3e3,windowsHide:!0}).trim()||null}catch{return null}}function hr(t,r){const e=_();if(!e?.transaction_id||e.transaction_id!==t||e.phase!=="verifying")throw new f("INVALID_UPGRADE_STATE","Windows upgrade is not awaiting verification");const n=Ct();E(w(n),{recursive:!0});const i=`${n}.tmp-${process.pid}`;x(i,JSON.stringify({transaction_id:t,message:r}),"utf-8"),h(i,n);const a=j();E(w(a),{recursive:!0});const o=`${a}.tmp-${process.pid}`;return x(o,JSON.stringify({transaction_id:t}),"utf-8"),h(o,a),D({phase:"rolling_back",guardian_pid:void 0,error_code:"STARTUP_CRASH",error_msg:r,wrapper_pause_file:a},t)}function wr(){try{p(j(),{force:!0})}catch{}}function Vt(t=_()){if(z(t)){try{p(u(t.staging_prefix),{recursive:!0,force:!0})}catch{}if(ut(t))try{p(u(t.runtime_next_dir),{recursive:!0,force:!0})}catch{}}}function ut(t){if(!t?.runtime_dir||!t.runtime_backup_dir||!t.runtime_next_dir)return!1;const r=u(t.runtime_dir),e=nt($.base),n=l(w(w(e)),"runtime"),i=r===u(n),a=r===u(e)&&/^GrixConnectorDaemon-[0-9a-f]{12}$/.test(v(r))&&v(w(r))==="runtimes"&&v(w(w(r)))==="grix-connector";return(i||a)&&u(t.runtime_backup_dir)===`${r}${ot}`&&u(t.runtime_next_dir)===`${r}${at}`}function J(t){return l(u(t),Mt)}function K(t){try{const r=d(t)&&!d(l(t,"owner.json"))?t:l(t,"owner.json"),e=JSON.parse(P(r,"utf-8"));return typeof e.transaction_id=="string"&&typeof e.pending_file=="string"?e:null}catch{return null}}function ft(t){if(!t||!d(t.pending_file))return!1;try{return JSON.parse(P(t.pending_file,"utf-8")).transaction_id===t.transaction_id}catch{return!0}}function Wt(t){const r=_();if(!r?.transaction_id)throw new f("PENDING_MISSING","Upgrade transaction disappeared before npm staging");const e=J(t),n={transaction_id:r.transaction_id,pending_file:I()};D({npm_prefix:u(t),npm_lock_file:e},r.transaction_id);const i=`${e}.candidate-${r.transaction_id}-${Q()}`;try{x(i,JSON.stringify(n),{encoding:"utf-8",flag:"wx"}),Pt(i,e),p(i,{force:!0})}catch(a){try{p(i,{force:!0})}catch{}if(!d(e))throw a;const o=K(e);if(o?.transaction_id===r.transaction_id&&u(o.pending_file)===u(I()))return;throw new f(ft(o)?"UPGRADE_IN_PROGRESS":"UPGRADE_LOCK_RECOVERY_REQUIRED",ft(o)?`Another Windows service root is upgrading the shared npm prefix ${u(t)}`:`A stale or incomplete Windows upgrade lock requires recovery at ${e}`)}}function Bt(t=_(),r={}){if(!t?.transaction_id||!t.npm_prefix||!t.npm_lock_file)return!0;const e=J(t.npm_prefix);if(u(t.npm_lock_file)!==e)return!1;if(!d(e))return!0;const n=K(e);if(!n)return!1;if(n.transaction_id!==t.transaction_id||u(n.pending_file)!==u(I()))return!0;const i=r.remove??p,a=r.sleep??(o=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,o)});for(let o=0;;o+=1)try{return i(e,{recursive:!0,force:!0}),!d(e)}catch(c){const s=c?.code;if((s==="EBUSY"||s==="EPERM"||s==="EACCES")&&o<C.length){a(C[o]);continue}return m(`shared npm-prefix lock release failed at ${e}: ${c instanceof Error?c.message:String(c)}`),!1}}function G(t,r){const e=u(t);return u(r)===`${e}${Y}`&&e.includes(`${b}node_modules${b}`)&&v(e)==="grix-connector"}function Ht(t,r){const e=rt(u(t),u(r));return e!==""&&e!==".."&&!e.startsWith(`..${b}`)}function z(t){if(!t?.npm_prefix||!t.staging_prefix||!t.staged_package_dir)return!1;const r=u(t.npm_prefix),e=u(t.staging_prefix),n=u(t.staged_package_dir);return w(e)===r&&v(e).startsWith(".grix-upgrade-stage-")&&Ht(e,n)&&v(w(n))==="node_modules"&&v(n)==="grix-connector"}function Yt(t,r){const e=_();!e||!G(t,r)||D({package_dir:u(t),backup_dir:u(r)},e.transaction_id)}function jt(t){if(!G(t.packageDir,t.backupDir))throw new f("UNSAFE_UPGRADE_PATH","Refusing to record an unsafe global package path");if(!z({npm_prefix:t.npmPrefix,staging_prefix:t.stagingPrefix,staged_package_dir:t.stagedPackageDir}))throw new f("UNSAFE_UPGRADE_PATH","Refusing to record an unsafe npm staging path");const r=_();if(!r)throw new f("PENDING_MISSING","Upgrade transaction disappeared during staging");let e;try{const n=JSON.parse(P(l(t.packageDir,"package.json"),"utf-8"));if(n.name!=="grix-connector"||typeof n.version!="string")throw new Error("invalid metadata");e=O(n.version)}catch(n){throw new f("VERSION_VERIFY_FAILED",`Unable to identify the active global package before staging: ${n instanceof Error?n.message:String(n)}`)}D({phase:"staged",activation_strategy:t.activationStrategy,package_from_version:e,npm_prefix:u(t.npmPrefix),package_dir:u(t.packageDir),backup_dir:u(t.backupDir),staged_package_dir:u(t.stagedPackageDir),staging_prefix:u(t.stagingPrefix)},r.transaction_id)}function Jt(t,r,e={}){const n=_();if(!n?.transaction_id)throw new f("PENDING_MISSING","Upgrade transaction disappeared before runtime staging");const i=nt($.base),a=`${i}${ot}`,o=`${i}${at}`;D({runtime_dir:i,runtime_backup_dir:a,runtime_next_dir:o},n.transaction_id);const c=e.copyTree??It,s=e.copyFile??kt,g=e.sleep??(k=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,k)});for(let k=0;;k+=1)try{E(w(i),{recursive:!0}),p(o,{recursive:!0,force:!0}),E(o,{recursive:!0}),c(l(t.stagedPackageDir,"dist"),l(o,"dist"),{recursive:!0,force:!0}),s(l(t.stagedPackageDir,"package.json"),l(o,"package.json"));const y=l(t.stagedPackageDir,"node_modules");d(y)&&c(y,l(o,"node_modules"),{recursive:!0,force:!0});const S=F(o,"grix-connector",r);L(o,S);return}catch(y){try{p(o,{recursive:!0,force:!0})}catch{}const S=y?.code;if(S==="ENOSPC")throw new f("DISK_FULL",`Insufficient space for the isolated Windows runtime: ${y.message}`);if((S==="EBUSY"||S==="EPERM"||S==="EACCES"||S==="ENOTEMPTY")&&k<ct.length){g(ct[k]);continue}throw new f("RUNTIME_STAGE_FAILED",`Could not prepare the isolated Windows runtime before shutdown: ${y instanceof Error?y.message:String(y)}`)}}function V(t,r){if(!d(t))return!0;const e=r.remove??p,n=r.sleep??(i=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,i)});for(let i=0;;i+=1)try{if(e(t,{recursive:!0,force:!0}),!d(t))return!0;throw Object.assign(new Error(`path still exists after removal: ${t}`),{code:"EBUSY"})}catch(a){const o=a?.code;if((o==="EBUSY"||o==="EPERM"||o==="EACCES"||o==="ENOTEMPTY")&&i<C.length){n(C[i]);continue}return m(`upgrade artifact cleanup failed at ${t}: ${a instanceof Error?a.message:String(a)}`),!1}}function yr(t=_(),r={}){if(t?.transaction_id&&_()?.transaction_id!==t.transaction_id)return!1;let e=!0,n=process.platform!=="win32";if(t?.npm_lock_file||t?.npm_prefix){if(!t.transaction_id||!t.npm_lock_file||!t.npm_prefix)return!1;const o=J(t.npm_prefix);if(u(t.npm_lock_file)!==o)return!1;if(d(o)){const c=K(o);if(c?.transaction_id!==t.transaction_id||u(c.pending_file)!==u(I()))return!1;n=!0}else{if(t.backup_dir&&d(t.backup_dir))return!1;n=!1}}const i=t?.package_dir,a=t?.backup_dir;return n&&i&&a&&G(i,a)&&(e=V(a,r)&&e),z(t)&&(e=V(u(t.staging_prefix),r)&&e),ut(t)&&(e=V(u(t.runtime_backup_dir),r)&&e,e=V(u(t.runtime_next_dir),r)&&e),e}function Sr(t=_()){const r=t?.package_dir,e=t?.backup_dir;if(!r||!e||!G(r,e)||!d(e))return!1;const n=`${r}${Ft}`;try{return p(n,{recursive:!0,force:!0}),d(r)&&h(r,n),h(e,r),p(n,{recursive:!0,force:!0}),m(`atomic rollback restored ${r}`),!0}catch(i){try{!d(r)&&d(n)&&h(n,r)}catch{}return m(`atomic rollback failed: ${i instanceof Error?i.message:String(i)}`),!1}}function lt(t,r={}){const e=I();if(t){const n=_();if(!n)return!0;if(n.transaction_id!==t)return!1}if(d(e))try{(r.unlink??H)(e)}catch{return!1}return!d(e)}function Er(t=_(),r={}){if(!t?.transaction_id)return lt(void 0,{unlink:r.unlinkPending});const e=_();if(e?.transaction_id!==t.transaction_id)return!1;const n=e.phase==="finalizing"?e:D({phase:"finalizing"},t.transaction_id);return Bt(n,{remove:r.removeLock,sleep:r.sleep})?lt(t.transaction_id,{unlink:r.unlinkPending}):!1}function m(t){const r=`[${new Date().toISOString()}] ${t}
2
- `;try{Dt(st(),r)}catch{}}function kr(t=4096){const r=st();if(!d(r))return"";try{const e=P(r,"utf-8");return e.length<=t?e:e.slice(-t)}catch{return""}}function dt(){try{const t=M(["--version"]);return R(t.command,t.args,{encoding:"utf-8",timeout:1e4,windowsHide:!0}).trim()}catch{throw new f("NPM_NOT_FOUND","npm is not available or timed out")}}const U=1e6;function gt(){let t;try{t=X(["prefix","-g"])}catch{return U}try{const r=xt(t),e=Math.floor(Number(r.bavail)*Number(r.bsize)/(1024*1024));return!Number.isFinite(e)||e<0?U:Math.min(e,U)}catch{return U}}function Ir(){let t;try{t=dt()}catch(e){return{ok:!1,errorCode:"NPM_NOT_FOUND",errorMsg:e instanceof Error?e.message:"npm not available"}}const r=gt();return r<100?{ok:!1,errorCode:"DISK_FULL",errorMsg:`Only ${r}MB free disk space (need >= 100MB)`,npmVersion:t,diskFreeMb:r}:{ok:!0,npmVersion:t,diskFreeMb:r}}function Pr(){let t="";try{t=dt()}catch{}let r=U;try{r=gt()}catch{}return{npm_version:t,node_version:process.version,disk_free_mb:r,platform:process.platform,arch:process.arch,host_name:Nt(),install_id:At()}}function F(t,r,e){const n=l(t,"package.json");let i;try{i=JSON.parse(P(n,"utf-8"))}catch{throw new f("VERSION_VERIFY_FAILED",`Unable to read staged package metadata: ${n}`)}if(i.name!==r||i.version?.replace(/^v(?=\d)/,"")!==e)throw new f("VERSION_MISMATCH",`Staged package ${String(i.name)}@${String(i.version)} does not match ${r}@${e}`);return i}function Kt(t){return typeof t.bin=="string"?[[v(t.name),t.bin]]:!t.bin||typeof t.bin!="object"?[]:Object.entries(t.bin).filter(r=>typeof r[1]=="string")}function L(t,r){const e=Kt(r);if(e.length===0)throw new f("VERSION_VERIFY_FAILED",`Staged package ${r.name} has no executable bin`);for(const[,n]of e){const i=l(t,n);if(!d(i))throw new f("VERSION_VERIFY_FAILED",`Staged package entrypoint is missing: ${i}`)}return e}function zt(t,r,e){if(process.platform==="win32")return;const n=l(t,"bin");E(n,{recursive:!0});for(const[i,a]of e){const o=l(n,i);if(d(o))continue;const c=`${o}.grix-upgrade-${process.pid}`;try{H(c)}catch{}$t(rt(n,l(r,a)),c),h(c,o)}}function Xt(t){const r=u(t.activePackageDir),e=u(t.stagedPackageDir),n=`${r}${Y}`,i=F(e,t.packageName,t.version),a=L(e,i);d(n)&&(d(r)?p(n,{recursive:!0,force:!0}):h(n,r)),Yt(r,n);let o=!1;try{d(r)&&(h(r,n),o=!0),h(e,r);const c=F(r,t.packageName,t.version),s=L(r,c);return zt(t.npmPrefix,r,s),{packageDir:r,backupDir:n}}catch(c){try{d(r)&&p(r,{recursive:!0,force:!0}),o&&d(n)&&h(n,r)}catch{}throw c}}function X(t,r=1e4){try{const e=M(t);return R(e.command,e.args,{encoding:"utf-8",timeout:r,windowsHide:!0}).trim()}catch{throw new f("NPM_NOT_FOUND",`Unable to resolve npm ${t.join(" ")}`)}}function W(t){return X(t)}const pt=Rt.find(t=>t.id==="official")?.url??"https://registry.npmjs.org";async function qt(t,r,e){const n=["view",`${t}@${r}`,"dist.integrity","--registry",e,"--no-audit","--no-fund"],i=M(n),{stdout:a}=await it(i.command,i.args,{timeout:1e4,windowsHide:!0});return a.trim()}async function _t(t,r,e,n={}){if(!e)return;let i;try{i=new URL(e).origin}catch{return}if(i===new URL(pt).origin)return;const a=n.fetchIntegrity??qt;let o;try{o=await a(t,r,pt)}catch(s){m(`integrity cross-check skipped: official registry unreachable (${s instanceof Error?s.message:String(s)})`);return}if(!o){m("integrity cross-check skipped: official registry returned no dist.integrity");return}let c;try{c=await a(t,r,e)}catch(s){m(`integrity cross-check skipped: mirror metadata unreadable (${s instanceof Error?s.message:String(s)})`);return}if(!c){m("integrity cross-check skipped: mirror returned no dist.integrity");return}if(c!==o)throw new f("INTEGRITY_MISMATCH",`Mirror ${e} reports dist.integrity ${c} but official npm reports ${o} for ${t}@${r}`);m(`integrity cross-check passed for ${t}@${r} via ${e}`)}async function mt(t,r,e,n={},i=process.platform==="win32"?"staged":"atomic"){const a=`${t}@${r}`,o=W(["prefix","-g"]),c=W(["root","-g"]);E(o,{recursive:!0}),i==="staged"&&Wt(o);const s=tt(l(o,".grix-upgrade-stage-"));try{m(`staging npm install ${a} under ${s}`);const g=n.installWithMirror??et,{registry:k,registryUrl:y}=await g(a,e,10*1024*1024,{prefix:s,...i==="staged"?{env:{...process.env,GRIX_UPGRADE_STAGING:"1"}}:{}});await(n.verifyIntegrityConsensus??_t)(t,r,y);const N=W(["root","-g","--prefix",s]),A=l(N,t),B=F(A,t,r),T=L(A,B),ht=l(A,T[0][1]),q=R(process.execPath,[ht,"--version"],{encoding:"utf-8",timeout:15e3,maxBuffer:2*1024*1024,windowsHide:!0}).trim().replace(/^v(?=\d)/,"");if(q!==r)throw new f("VERSION_MISMATCH",`Staged CLI reported ${q||"<empty>"}, expected ${r}`);const Z=l(c,t);return{npmPrefix:o,packageDir:Z,backupDir:`${u(Z)}${Y}`,stagedPackageDir:A,stagingPrefix:s,registry:k}}catch(g){try{p(s,{recursive:!0,force:!0})}catch{}throw g}}async function Zt(t,r,e,n){const i=await mt(t,r,e,n,"atomic");try{const a=Xt({packageName:t,version:r,npmPrefix:i.npmPrefix,activePackageDir:i.packageDir,stagedPackageDir:i.stagedPackageDir});m(`atomic package switch succeeded via ${i.registry}; backup=${a.backupDir}`)}finally{try{p(i.stagingPrefix,{recursive:!0,force:!0})}catch{}}}async function vr(t,r,e=12e4,n={}){r=O(r);const i=_()?.transaction_id,a=`${t}@${r}`,o=n.activationMode??(process.platform==="win32"?"staged":"atomic");m(`npm install -g ${a} starting (${o} staging with mirror fallback)`);try{if(o==="staged"){const c=await mt(t,r,e,n,o);try{jt({...c,activationStrategy:process.platform==="win32"?"wrapper-runtime":"service-start"}),process.platform==="win32"&&Jt(c,r)}catch(s){try{p(c.stagingPrefix,{recursive:!0,force:!0})}catch{}throw s}return m(`staged package verified via ${c.registry}; waiting for guardian activation`),{activationRequired:!0,packageDir:c.packageDir,backupDir:c.backupDir,stagedPackageDir:c.stagedPackageDir,stagingPrefix:c.stagingPrefix}}else return await Zt(t,r,e,n),{activationRequired:!1}}catch(c){if(o==="staged"){const g=_();i&&g?.transaction_id===i&&Vt(g)}if(c instanceof f)throw c;const s=c instanceof Error?c.message:String(c);throw m(`npm install failed: ${s}`),/timed out|ETIMEDOUT/i.test(s)?new f("NPM_TIMEOUT",`npm install timed out after ${e/1e3}s (tried all mirrors): ${s}`):s.includes("EACCES")||s.includes("permission denied")?new f("NPM_INSTALL_FAILED",`Permission denied: ${s}`):s.includes("ENOSPC")||s.includes("no space left")?new f("DISK_FULL",`Disk full: ${s}`):s.includes("404")||s.includes("not found")?new f("NPM_INSTALL_FAILED",`Package not found: ${s}`):new f("NPM_INSTALL_FAILED",s)}}function xr(t){let r;try{r=X(["root","-g"])}catch{throw new f("VERSION_VERIFY_FAILED","Unable to resolve the global npm package directory")}let e;try{const n=l(r,"grix-connector","package.json"),i=JSON.parse(P(n,"utf-8"));if(i.name!=="grix-connector"||typeof i.version!="string"||!i.version.trim())throw new Error("invalid package metadata");e=i.version.trim().replace(/^v(?=\d)/,"")}catch{throw new f("VERSION_VERIFY_FAILED","Unable to read the installed grix-connector version")}if(e!==t)throw new f("VERSION_MISMATCH",`Installed version ${e} does not match expected ${t}`);return e}async function $r(t,r){r=O(r);let e=!1;for(const n of await bt())try{const i=["view",`${t}@${r}`,"version","--registry",n.url,"--no-audit","--no-fund"],a=M(i),{stdout:o}=await it(a.command,a.args,{timeout:8e3,windowsHide:!0});if(o.trim())return!0}catch(i){const a=i,o=a.stderr||a.message||String(i);/ETARGET|No matching version|notarget|E404/i.test(o)&&(e=!0)}return!e}async function Dr(t,r,e,n=12e4,i={}){e=O(e);const a=`${r}@${e}`,o=l(t,"versions",e);E(l(t,"versions"),{recursive:!0});const c=tt(l(t,"versions",`.stage-${e}-`));m(`installing ${a} into version store under ${c}`);try{const s=i.installWithMirror??et,{registry:g,registryUrl:k}=await s(a,n,10*1024*1024,{prefix:c,env:{...process.env,GRIX_UPGRADE_STAGING:"1"},ignoreScripts:!0});await(i.verifyIntegrityConsensus??_t)(r,e,k);const S=W(["root","-g","--prefix",c]),N=l(S,r),A=F(N,r,e),B=L(N,A),T=R(process.execPath,[l(N,B[0][1]),"--version"],{encoding:"utf-8",timeout:15e3,maxBuffer:2*1024*1024,windowsHide:!0}).trim().replace(/^v(?=\d)/,"");if(T!==e)throw new f("VERSION_MISMATCH",`Installed CLI reported ${T||"<empty>"}, expected ${e}`);return p(o,{recursive:!0,force:!0}),h(N,o),m(`${a} verified via ${g}; placed at ${o}`),{registry:g,versionDir:o}}catch(s){if(s instanceof f)throw s;const g=s instanceof Error?s.message:String(s);throw m(`version store install failed: ${g}`),/timed out|ETIMEDOUT/i.test(g)?new f("NPM_TIMEOUT",`npm install timed out after ${n/1e3}s (tried all mirrors): ${g}`):g.includes("ENOSPC")||g.includes("no space left")?new f("DISK_FULL",`Disk full: ${g}`):new f("NPM_INSTALL_FAILED",g)}finally{try{p(c,{recursive:!0,force:!0})}catch{}}}export{f as UpgradeError,Wt as acquireNpmPrefixUpgradeLock,gr as archivePendingJournal,mr as armWindowsUpgradeHandoff,hr as armWindowsUpgradeRollback,gt as checkDiskSpace,dt as checkNpmAvailable,yr as cleanupPendingBackup,Pr as collectEnvInfo,Xt as commitStagedGlobalPackage,Vt as discardPendingStaging,Er as finalizePendingTransaction,kr as getUpgradeLogTail,Dr as installVersionIntoStore,$r as isVersionAvailable,O as normalizeUpgradeVersion,vr as npmInstall,dr as pendingExists,Ir as preflightCheck,Jt as prepareStagedWindowsRuntime,_ as readPending,_r as readPendingPackageVersion,Bt as releasePendingUpgradeLock,lt as removePending,wr as removeWindowsHandoffFiles,Sr as rollbackPendingInstall,D as updatePending,m as upgradeLog,lr as upgradeStatusSnapshot,xr as verifyInstalledVersion,_t as verifyMirrorIntegrityConsensus,Ct as windowsRollbackIntentPath,j as windowsWrapperPausePath,pr as writePending,Ot as writePendingData};
1
+ import{execFile as yt,execFileSync as R}from"node:child_process";import{randomUUID as Q}from"node:crypto";import{promisify as Et}from"node:util";import{uptime as kt}from"node:os";import{closeSync as It,copyFileSync as Pt,cpSync as vt,existsSync as d,linkSync as xt,mkdirSync as E,mkdtempSync as tt,openSync as $t,readFileSync as P,renameSync as h,rmSync as g,statfsSync as Dt,symlinkSync as Nt,unlinkSync as H,writeFileSync as x}from"node:fs";import{basename as v,dirname as w,join as l,relative as et,resolve as u,sep as b}from"node:path";import{GRIX_PATHS as $}from"../log/index.js";import{appendRotatingFileSync as At}from"../log/rotation.js";import{getMachineName as Rt}from"../util/host-info.js";import{resolveInstallId as bt}from"../util/install-id.js";import{NPM_REGISTRIES as Tt,npmInstallWithMirror as rt,probeRegistries as Ut,resolveNpmCacheDir as nt,resolveNpmInvocation as M}from"../installer/npm-registry.js";import{resolveWindowsServiceRuntimeDir as it}from"../../service/service-paths.js";const ot=Et(yt);class f extends Error{code;constructor(e,r){super(r),this.name="UpgradeError",this.code=e}}const Lt=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function O(t){const e=String(t??"").trim().replace(/^v(?=\d)/,"");if(!Lt.test(e))throw new f("INVALID_VERSION",`Invalid connector upgrade version: ${String(t)}`);return e}const Y=".grix-upgrade-backup",Ft=".grix-upgrade-failed",at=".grix-upgrade-backup",ct=".grix-upgrade-next",Mt="upgrade-wrapper.pause.json",Ot="upgrade-rollback.intent.json",Ct=".grix-connector-upgrade.lock",st=[250,750],C=[100,250,750,1500];function ut(){return l($.log,"upgrade.log")}function I(){return l($.data,"upgrade-pending.json")}function pe(){let t=null;try{t=_()}catch{return{in_progress:!1}}if(!t)return{in_progress:!1};const e=t.phase??"staged";return{in_progress:!(e==="failed"||e==="rolled_back"),phase:e,from:t.from_version,target:t.target_version}}function ge(){return d(I())}function _e(t,e="failed"){const r=new Date().toISOString().replace(/[:.]/g,""),n=l($.data,`upgrade-pending.${e}-${r}.json`);try{return x(n,JSON.stringify(t,null,2),"utf-8"),n}catch{return null}}function _(){const t=I();if(!d(t))return null;try{return JSON.parse(P(t,"utf-8"))}catch{return null}}function me(t,e,r){const n={from_version:t,target_version:e,upgraded_at:new Date().toISOString(),crash_count:0,transaction_id:Q(),...r?{phase:r}:{}},i=I();E(w(i),{recursive:!0});let a;try{a=$t(i,"wx",384)}catch(o){throw o?.code==="EEXIST"?new f("UPGRADE_IN_PROGRESS","Another connector upgrade transaction is already active"):o}try{x(a,JSON.stringify(n),"utf-8")}catch(o){try{H(i)}catch{}throw o}finally{It(a)}return n}function he(t){const e=t.package_dir;if(!e)return null;const r=u(e);if(!r.includes(`${b}node_modules${b}`))return null;try{const n=JSON.parse(P(l(r,"package.json"),"utf-8"));return n.name!=="grix-connector"||typeof n.version!="string"?null:n.version.trim().replace(/^v/,"")||null}catch{return null}}function Gt(t,e){E(w(t),{recursive:!0});const r=`${t}.tmp-${process.pid}`;x(r,JSON.stringify(e),"utf-8"),h(r,t)}function D(t,e){const r=_();if(!r)throw new f("PENDING_MISSING","Upgrade transaction is missing");if(e&&r.transaction_id!==e)throw new f("UPGRADE_TRANSACTION_CHANGED","Upgrade transaction ownership changed");const n={...r,...t};return Gt(I(),n),n}function j(){return l($.data,Mt)}function Vt(){return l($.data,Ot)}function we(t,e){const r=_();if(!r?.transaction_id||r.phase!=="staged"||e&&r.transaction_id!==e)throw new f("INVALID_UPGRADE_STATE","Windows upgrade is not staged for activation");const n=j();E(w(n),{recursive:!0});const i=`${n}.tmp-${process.pid}`;return x(i,JSON.stringify({transaction_id:r.transaction_id}),"utf-8"),h(i,n),D({phase:"handoff_ready",old_pid:t,old_command_line:Wt(t)??void 0,old_boot_time:Date.now()-kt()*1e3,activation_started_at:new Date().toISOString(),wrapper_pause_file:n},r.transaction_id)}function Wt(t){if(process.platform!=="win32"||!Number.isInteger(t)||t<=0)return null;try{const e=`${process.env.SystemRoot||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;return R(e,["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`(Get-CimInstance Win32_Process -Filter 'ProcessId=${t}').CommandLine`],{encoding:"utf-8",timeout:3e3,windowsHide:!0}).trim()||null}catch{return null}}function Se(t,e){const r=_();if(!r?.transaction_id||r.transaction_id!==t||r.phase!=="verifying")throw new f("INVALID_UPGRADE_STATE","Windows upgrade is not awaiting verification");const n=Vt();E(w(n),{recursive:!0});const i=`${n}.tmp-${process.pid}`;x(i,JSON.stringify({transaction_id:t,message:e}),"utf-8"),h(i,n);const a=j();E(w(a),{recursive:!0});const o=`${a}.tmp-${process.pid}`;return x(o,JSON.stringify({transaction_id:t}),"utf-8"),h(o,a),D({phase:"rolling_back",guardian_pid:void 0,error_code:"STARTUP_CRASH",error_msg:e,wrapper_pause_file:a},t)}function ye(){try{g(j(),{force:!0})}catch{}}function Bt(t=_()){if(z(t)){try{g(u(t.staging_prefix),{recursive:!0,force:!0})}catch{}if(ft(t))try{g(u(t.runtime_next_dir),{recursive:!0,force:!0})}catch{}}}function ft(t){if(!t?.runtime_dir||!t.runtime_backup_dir||!t.runtime_next_dir)return!1;const e=u(t.runtime_dir),r=it($.base),n=l(w(w(r)),"runtime"),i=e===u(n),a=e===u(r)&&/^GrixConnectorDaemon-[0-9a-f]{12}$/.test(v(e))&&v(w(e))==="runtimes"&&v(w(w(e)))==="grix-connector";return(i||a)&&u(t.runtime_backup_dir)===`${e}${at}`&&u(t.runtime_next_dir)===`${e}${ct}`}function J(t){return l(u(t),Ct)}function K(t){try{const e=d(t)&&!d(l(t,"owner.json"))?t:l(t,"owner.json"),r=JSON.parse(P(e,"utf-8"));return typeof r.transaction_id=="string"&&typeof r.pending_file=="string"?r:null}catch{return null}}function lt(t){if(!t||!d(t.pending_file))return!1;try{return JSON.parse(P(t.pending_file,"utf-8")).transaction_id===t.transaction_id}catch{return!0}}function Ht(t){const e=_();if(!e?.transaction_id)throw new f("PENDING_MISSING","Upgrade transaction disappeared before npm staging");const r=J(t),n={transaction_id:e.transaction_id,pending_file:I()};D({npm_prefix:u(t),npm_lock_file:r},e.transaction_id);const i=`${r}.candidate-${e.transaction_id}-${Q()}`;try{x(i,JSON.stringify(n),{encoding:"utf-8",flag:"wx"}),xt(i,r),g(i,{force:!0})}catch(a){try{g(i,{force:!0})}catch{}if(!d(r))throw a;const o=K(r);if(o?.transaction_id===e.transaction_id&&u(o.pending_file)===u(I()))return;throw new f(lt(o)?"UPGRADE_IN_PROGRESS":"UPGRADE_LOCK_RECOVERY_REQUIRED",lt(o)?`Another Windows service root is upgrading the shared npm prefix ${u(t)}`:`A stale or incomplete Windows upgrade lock requires recovery at ${r}`)}}function Yt(t=_(),e={}){if(!t?.transaction_id||!t.npm_prefix||!t.npm_lock_file)return!0;const r=J(t.npm_prefix);if(u(t.npm_lock_file)!==r)return!1;if(!d(r))return!0;const n=K(r);if(!n)return!1;if(n.transaction_id!==t.transaction_id||u(n.pending_file)!==u(I()))return!0;const i=e.remove??g,a=e.sleep??(o=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,o)});for(let o=0;;o+=1)try{return i(r,{recursive:!0,force:!0}),!d(r)}catch(c){const s=c?.code;if((s==="EBUSY"||s==="EPERM"||s==="EACCES")&&o<C.length){a(C[o]);continue}return m(`shared npm-prefix lock release failed at ${r}: ${c instanceof Error?c.message:String(c)}`),!1}}function G(t,e){const r=u(t);return u(e)===`${r}${Y}`&&r.includes(`${b}node_modules${b}`)&&v(r)==="grix-connector"}function jt(t,e){const r=et(u(t),u(e));return r!==""&&r!==".."&&!r.startsWith(`..${b}`)}function z(t){if(!t?.npm_prefix||!t.staging_prefix||!t.staged_package_dir)return!1;const e=u(t.npm_prefix),r=u(t.staging_prefix),n=u(t.staged_package_dir);return w(r)===e&&v(r).startsWith(".grix-upgrade-stage-")&&jt(r,n)&&v(w(n))==="node_modules"&&v(n)==="grix-connector"}function Jt(t,e){const r=_();!r||!G(t,e)||D({package_dir:u(t),backup_dir:u(e)},r.transaction_id)}function Kt(t){if(!G(t.packageDir,t.backupDir))throw new f("UNSAFE_UPGRADE_PATH","Refusing to record an unsafe global package path");if(!z({npm_prefix:t.npmPrefix,staging_prefix:t.stagingPrefix,staged_package_dir:t.stagedPackageDir}))throw new f("UNSAFE_UPGRADE_PATH","Refusing to record an unsafe npm staging path");const e=_();if(!e)throw new f("PENDING_MISSING","Upgrade transaction disappeared during staging");let r;try{const n=JSON.parse(P(l(t.packageDir,"package.json"),"utf-8"));if(n.name!=="grix-connector"||typeof n.version!="string")throw new Error("invalid metadata");r=O(n.version)}catch(n){throw new f("VERSION_VERIFY_FAILED",`Unable to identify the active global package before staging: ${n instanceof Error?n.message:String(n)}`)}D({phase:"staged",activation_strategy:t.activationStrategy,package_from_version:r,npm_prefix:u(t.npmPrefix),package_dir:u(t.packageDir),backup_dir:u(t.backupDir),staged_package_dir:u(t.stagedPackageDir),staging_prefix:u(t.stagingPrefix)},e.transaction_id)}function zt(t,e,r={}){const n=_();if(!n?.transaction_id)throw new f("PENDING_MISSING","Upgrade transaction disappeared before runtime staging");const i=it($.base),a=`${i}${at}`,o=`${i}${ct}`;D({runtime_dir:i,runtime_backup_dir:a,runtime_next_dir:o},n.transaction_id);const c=r.copyTree??vt,s=r.copyFile??Pt,p=r.sleep??(k=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,k)});for(let k=0;;k+=1)try{E(w(i),{recursive:!0}),g(o,{recursive:!0,force:!0}),E(o,{recursive:!0}),c(l(t.stagedPackageDir,"dist"),l(o,"dist"),{recursive:!0,force:!0}),s(l(t.stagedPackageDir,"package.json"),l(o,"package.json"));const S=l(t.stagedPackageDir,"node_modules");d(S)&&c(S,l(o,"node_modules"),{recursive:!0,force:!0});const y=U(o,"grix-connector",e);L(o,y);return}catch(S){try{g(o,{recursive:!0,force:!0})}catch{}const y=S?.code;if(y==="ENOSPC")throw new f("DISK_FULL",`Insufficient space for the isolated Windows runtime: ${S.message}`);if((y==="EBUSY"||y==="EPERM"||y==="EACCES"||y==="ENOTEMPTY")&&k<st.length){p(st[k]);continue}throw new f("RUNTIME_STAGE_FAILED",`Could not prepare the isolated Windows runtime before shutdown: ${S instanceof Error?S.message:String(S)}`)}}function V(t,e){if(!d(t))return!0;const r=e.remove??g,n=e.sleep??(i=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,i)});for(let i=0;;i+=1)try{if(r(t,{recursive:!0,force:!0}),!d(t))return!0;throw Object.assign(new Error(`path still exists after removal: ${t}`),{code:"EBUSY"})}catch(a){const o=a?.code;if((o==="EBUSY"||o==="EPERM"||o==="EACCES"||o==="ENOTEMPTY")&&i<C.length){n(C[i]);continue}return m(`upgrade artifact cleanup failed at ${t}: ${a instanceof Error?a.message:String(a)}`),!1}}function Ee(t=_(),e={}){if(t?.transaction_id&&_()?.transaction_id!==t.transaction_id)return!1;let r=!0,n=process.platform!=="win32";if(t?.npm_lock_file||t?.npm_prefix){if(!t.transaction_id||!t.npm_lock_file||!t.npm_prefix)return!1;const o=J(t.npm_prefix);if(u(t.npm_lock_file)!==o)return!1;if(d(o)){const c=K(o);if(c?.transaction_id!==t.transaction_id||u(c.pending_file)!==u(I()))return!1;n=!0}else{if(t.backup_dir&&d(t.backup_dir))return!1;n=!1}}const i=t?.package_dir,a=t?.backup_dir;return n&&i&&a&&G(i,a)&&(r=V(a,e)&&r),z(t)&&(r=V(u(t.staging_prefix),e)&&r),ft(t)&&(r=V(u(t.runtime_backup_dir),e)&&r,r=V(u(t.runtime_next_dir),e)&&r),r}function ke(t=_()){const e=t?.package_dir,r=t?.backup_dir;if(!e||!r||!G(e,r)||!d(r))return!1;const n=`${e}${Ft}`;try{return g(n,{recursive:!0,force:!0}),d(e)&&h(e,n),h(r,e),g(n,{recursive:!0,force:!0}),m(`atomic rollback restored ${e}`),!0}catch(i){try{!d(e)&&d(n)&&h(n,e)}catch{}return m(`atomic rollback failed: ${i instanceof Error?i.message:String(i)}`),!1}}function dt(t,e={}){const r=I();if(t){const n=_();if(!n)return!0;if(n.transaction_id!==t)return!1}if(d(r))try{(e.unlink??H)(r)}catch{return!1}return!d(r)}function Ie(t=_(),e={}){if(!t?.transaction_id)return dt(void 0,{unlink:e.unlinkPending});const r=_();if(r?.transaction_id!==t.transaction_id)return!1;const n=r.phase==="finalizing"?r:D({phase:"finalizing"},t.transaction_id);return Yt(n,{remove:e.removeLock,sleep:e.sleep})?dt(t.transaction_id,{unlink:e.unlinkPending}):!1}function m(t){const e=`[${new Date().toISOString()}] ${t}
2
+ `;try{At(ut(),e)}catch{}}function Pe(t=4096){const e=ut();if(!d(e))return"";try{const r=P(e,"utf-8");return r.length<=t?r:r.slice(-t)}catch{return""}}function pt(){try{const t=M(["--version"]);return R(t.command,t.args,{encoding:"utf-8",timeout:1e4,windowsHide:!0}).trim()}catch{throw new f("NPM_NOT_FOUND","npm is not available or timed out")}}const T=1e6;function gt(){let t;try{t=X(["prefix","-g"])}catch{return T}try{const e=Dt(t),r=Math.floor(Number(e.bavail)*Number(e.bsize)/(1024*1024));return!Number.isFinite(r)||r<0?T:Math.min(r,T)}catch{return T}}function ve(){let t;try{t=pt()}catch(r){return{ok:!1,errorCode:"NPM_NOT_FOUND",errorMsg:r instanceof Error?r.message:"npm not available"}}const e=gt();return e<100?{ok:!1,errorCode:"DISK_FULL",errorMsg:`Only ${e}MB free disk space (need >= 100MB)`,npmVersion:t,diskFreeMb:e}:{ok:!0,npmVersion:t,diskFreeMb:e}}function xe(){let t="";try{t=pt()}catch{}let e=T;try{e=gt()}catch{}return{npm_version:t,node_version:process.version,disk_free_mb:e,platform:process.platform,arch:process.arch,host_name:Rt(),install_id:bt()}}function U(t,e,r){const n=l(t,"package.json");let i;try{i=JSON.parse(P(n,"utf-8"))}catch{throw new f("VERSION_VERIFY_FAILED",`Unable to read staged package metadata: ${n}`)}if(i.name!==e||i.version?.replace(/^v(?=\d)/,"")!==r)throw new f("VERSION_MISMATCH",`Staged package ${String(i.name)}@${String(i.version)} does not match ${e}@${r}`);return i}function Xt(t){return typeof t.bin=="string"?[[v(t.name),t.bin]]:!t.bin||typeof t.bin!="object"?[]:Object.entries(t.bin).filter(e=>typeof e[1]=="string")}function L(t,e){const r=Xt(e);if(r.length===0)throw new f("VERSION_VERIFY_FAILED",`Staged package ${e.name} has no executable bin`);for(const[,n]of r){const i=l(t,n);if(!d(i))throw new f("VERSION_VERIFY_FAILED",`Staged package entrypoint is missing: ${i}`)}return r}function qt(t,e,r){if(process.platform==="win32")return;const n=l(t,"bin");E(n,{recursive:!0});for(const[i,a]of r){const o=l(n,i);if(d(o))continue;const c=`${o}.grix-upgrade-${process.pid}`;try{H(c)}catch{}Nt(et(n,l(e,a)),c),h(c,o)}}function Zt(t){const e=u(t.activePackageDir),r=u(t.stagedPackageDir),n=`${e}${Y}`,i=U(r,t.packageName,t.version),a=L(r,i);d(n)&&(d(e)?g(n,{recursive:!0,force:!0}):h(n,e)),Jt(e,n);let o=!1;try{d(e)&&(h(e,n),o=!0),h(r,e);const c=U(e,t.packageName,t.version),s=L(e,c);return qt(t.npmPrefix,e,s),{packageDir:e,backupDir:n}}catch(c){try{d(e)&&g(e,{recursive:!0,force:!0}),o&&d(n)&&h(n,e)}catch{}throw c}}function X(t,e=1e4){try{const r=M(t);return R(r.command,r.args,{encoding:"utf-8",timeout:e,windowsHide:!0}).trim()}catch{throw new f("NPM_NOT_FOUND",`Unable to resolve npm ${t.join(" ")}`)}}function W(t){return X(t)}const _t=3e5,mt=Tt.find(t=>t.id==="official")?.url??"https://registry.npmjs.org";async function Qt(t,e,r){const n=["view",`${t}@${e}`,"dist.integrity","--registry",r,"--no-audit","--no-fund"],i=nt();i&&n.push("--cache",i);const a=M(n),{stdout:o}=await ot(a.command,a.args,{timeout:1e4,windowsHide:!0});return o.trim()}async function ht(t,e,r,n={}){if(!r)return;let i;try{i=new URL(r).origin}catch{return}if(i===new URL(mt).origin)return;const a=n.fetchIntegrity??Qt;let o;try{o=await a(t,e,mt)}catch(s){m(`integrity cross-check skipped: official registry unreachable (${s instanceof Error?s.message:String(s)})`);return}if(!o){m("integrity cross-check skipped: official registry returned no dist.integrity");return}let c;try{c=await a(t,e,r)}catch(s){m(`integrity cross-check skipped: mirror metadata unreadable (${s instanceof Error?s.message:String(s)})`);return}if(!c){m("integrity cross-check skipped: mirror returned no dist.integrity");return}if(c!==o)throw new f("INTEGRITY_MISMATCH",`Mirror ${r} reports dist.integrity ${c} but official npm reports ${o} for ${t}@${e}`);m(`integrity cross-check passed for ${t}@${e} via ${r}`)}async function wt(t,e,r,n={},i=process.platform==="win32"?"staged":"atomic"){const a=`${t}@${e}`,o=W(["prefix","-g"]),c=W(["root","-g"]);E(o,{recursive:!0}),i==="staged"&&Ht(o);const s=tt(l(o,".grix-upgrade-stage-"));try{m(`staging npm install ${a} under ${s}`);const p=n.installWithMirror??rt,{registry:k,registryUrl:S}=await p(a,r,10*1024*1024,{prefix:s,...i==="staged"?{env:{...process.env,GRIX_UPGRADE_STAGING:"1"}}:{}});await(n.verifyIntegrityConsensus??ht)(t,e,S);const N=W(["root","-g","--prefix",s]),A=l(N,t),B=U(A,t,e),F=L(A,B),St=l(A,F[0][1]),q=R(process.execPath,[St,"--version"],{encoding:"utf-8",timeout:15e3,maxBuffer:2*1024*1024,windowsHide:!0}).trim().replace(/^v(?=\d)/,"");if(q!==e)throw new f("VERSION_MISMATCH",`Staged CLI reported ${q||"<empty>"}, expected ${e}`);const Z=l(c,t);return{npmPrefix:o,packageDir:Z,backupDir:`${u(Z)}${Y}`,stagedPackageDir:A,stagingPrefix:s,registry:k}}catch(p){try{g(s,{recursive:!0,force:!0})}catch{}throw p}}async function te(t,e,r,n){const i=await wt(t,e,r,n,"atomic");try{const a=Zt({packageName:t,version:e,npmPrefix:i.npmPrefix,activePackageDir:i.packageDir,stagedPackageDir:i.stagedPackageDir});m(`atomic package switch succeeded via ${i.registry}; backup=${a.backupDir}`)}finally{try{g(i.stagingPrefix,{recursive:!0,force:!0})}catch{}}}async function $e(t,e,r=_t,n={}){e=O(e);const i=_()?.transaction_id,a=`${t}@${e}`,o=n.activationMode??(process.platform==="win32"?"staged":"atomic");m(`npm install -g ${a} starting (${o} staging with mirror fallback)`);try{if(o==="staged"){const c=await wt(t,e,r,n,o);try{Kt({...c,activationStrategy:process.platform==="win32"?"wrapper-runtime":"service-start"}),process.platform==="win32"&&zt(c,e)}catch(s){try{g(c.stagingPrefix,{recursive:!0,force:!0})}catch{}throw s}return m(`staged package verified via ${c.registry}; waiting for guardian activation`),{activationRequired:!0,packageDir:c.packageDir,backupDir:c.backupDir,stagedPackageDir:c.stagedPackageDir,stagingPrefix:c.stagingPrefix}}else return await te(t,e,r,n),{activationRequired:!1}}catch(c){if(o==="staged"){const p=_();i&&p?.transaction_id===i&&Bt(p)}if(c instanceof f)throw c;const s=c instanceof Error?c.message:String(c);throw m(`npm install failed: ${s}`),/timed out|ETIMEDOUT/i.test(s)?new f("NPM_TIMEOUT",`npm install timed out after ${r/1e3}s (tried all mirrors): ${s}`):s.includes("EACCES")||s.includes("permission denied")?new f("NPM_INSTALL_FAILED",`Permission denied: ${s}`):s.includes("ENOSPC")||s.includes("no space left")?new f("DISK_FULL",`Disk full: ${s}`):s.includes("404")||s.includes("not found")?new f("NPM_INSTALL_FAILED",`Package not found: ${s}`):new f("NPM_INSTALL_FAILED",s)}}function De(t){let e;try{e=X(["root","-g"])}catch{throw new f("VERSION_VERIFY_FAILED","Unable to resolve the global npm package directory")}let r;try{const n=l(e,"grix-connector","package.json"),i=JSON.parse(P(n,"utf-8"));if(i.name!=="grix-connector"||typeof i.version!="string"||!i.version.trim())throw new Error("invalid package metadata");r=i.version.trim().replace(/^v(?=\d)/,"")}catch{throw new f("VERSION_VERIFY_FAILED","Unable to read the installed grix-connector version")}if(r!==t)throw new f("VERSION_MISMATCH",`Installed version ${r} does not match expected ${t}`);return r}async function Ne(t,e){e=O(e);let r=!1;for(const n of await Ut())try{const i=["view",`${t}@${e}`,"version","--registry",n.url,"--no-audit","--no-fund"],a=nt();a&&i.push("--cache",a);const o=M(i),{stdout:c}=await ot(o.command,o.args,{timeout:8e3,windowsHide:!0});if(c.trim())return!0}catch(i){const a=i,o=a.stderr||a.message||String(i);/ETARGET|No matching version|notarget|E404/i.test(o)&&(r=!0)}return!r}async function Ae(t,e,r,n=_t,i={}){r=O(r);const a=`${e}@${r}`,o=l(t,"versions",r);E(l(t,"versions"),{recursive:!0});const c=tt(l(t,"versions",`.stage-${r}-`));m(`installing ${a} into version store under ${c}`);try{const s=i.installWithMirror??rt,{registry:p,registryUrl:k}=await s(a,n,10*1024*1024,{prefix:c,env:{...process.env,GRIX_UPGRADE_STAGING:"1"},ignoreScripts:!0});await(i.verifyIntegrityConsensus??ht)(e,r,k);const y=W(["root","-g","--prefix",c]),N=l(y,e),A=U(N,e,r),B=L(N,A),F=R(process.execPath,[l(N,B[0][1]),"--version"],{encoding:"utf-8",timeout:15e3,maxBuffer:2*1024*1024,windowsHide:!0}).trim().replace(/^v(?=\d)/,"");if(F!==r)throw new f("VERSION_MISMATCH",`Installed CLI reported ${F||"<empty>"}, expected ${r}`);return g(o,{recursive:!0,force:!0}),h(N,o),m(`${a} verified via ${p}; placed at ${o}`),{registry:p,versionDir:o}}catch(s){if(s instanceof f)throw s;const p=s instanceof Error?s.message:String(s);throw m(`version store install failed: ${p}`),/timed out|ETIMEDOUT/i.test(p)?new f("NPM_TIMEOUT",`npm install timed out after ${n/1e3}s (tried all mirrors): ${p}`):p.includes("ENOSPC")||p.includes("no space left")?new f("DISK_FULL",`Disk full: ${p}`):new f("NPM_INSTALL_FAILED",p)}finally{try{g(c,{recursive:!0,force:!0})}catch{}}}export{_t as NPM_INSTALL_TIMEOUT_MS,f as UpgradeError,Ht as acquireNpmPrefixUpgradeLock,_e as archivePendingJournal,we as armWindowsUpgradeHandoff,Se as armWindowsUpgradeRollback,gt as checkDiskSpace,pt as checkNpmAvailable,Ee as cleanupPendingBackup,xe as collectEnvInfo,Zt as commitStagedGlobalPackage,Bt as discardPendingStaging,Ie as finalizePendingTransaction,Pe as getUpgradeLogTail,Ae as installVersionIntoStore,Ne as isVersionAvailable,O as normalizeUpgradeVersion,$e as npmInstall,ge as pendingExists,ve as preflightCheck,zt as prepareStagedWindowsRuntime,_ as readPending,he as readPendingPackageVersion,Yt as releasePendingUpgradeLock,dt as removePending,ye as removeWindowsHandoffFiles,ke as rollbackPendingInstall,D as updatePending,m as upgradeLog,pe as upgradeStatusSnapshot,De as verifyInstalledVersion,ht as verifyMirrorIntegrityConsensus,Vt as windowsRollbackIntentPath,j as windowsWrapperPausePath,me as writePending,Gt as writePendingData};
@@ -1,3 +1,3 @@
1
- import{closeSync as C,existsSync as v,mkdirSync as W,openSync as me,readFileSync as P,realpathSync as we,renameSync as ve,writeFileSync as ye}from"node:fs";import{join as _,dirname as be}from"node:path";import{spawn as H}from"node:child_process";import{log as m}from"../log/index.js";import{GRIX_PATHS as y}from"../log/index.js";import{resolveClientVersion as A}from"../util/client-version.js";import{UpgradeError as S,armWindowsUpgradeHandoff as x,archivePendingJournal as Se,armWindowsUpgradeRollback as Te,cleanupPendingBackup as q,collectEnvInfo as Ae,discardPendingStaging as U,finalizePendingTransaction as F,getUpgradeLogTail as $,isVersionAvailable as B,npmInstall as ke,normalizeUpgradeVersion as Re,pendingExists as z,preflightCheck as j,readPending as D,readPendingPackageVersion as K,removeWindowsHandoffFiles as X,rollbackPendingInstall as Pe,updatePending as N,upgradeLog as a,verifyInstalledVersion as $e,writePending as Ee}from"./npm-upgrader.js";import{isRetriableRegistryError as Y,isTransientInstallError as J}from"../installer/npm-registry.js";import{installVersionIntoStore as Ie}from"./npm-upgrader.js";import{ensureLauncher as Ue,healthMarkerPath as De,markHealthy as Ne,pruneVersions as Me,readPointer as M,readRollbackRecord as Ge,readSwitchRecord as Le,resolveLauncherStore as V,rollbackRecordPath as Z,switchCurrent as Oe,switchRecordPath as Q,takeCrashNote as ee,versionDir as te,versionEntry as re,writeSwitchRecord as ae}from"./version-store.js";import{rmSync as k}from"node:fs";import{randomUUID as Ce}from"node:crypto";const We=360*60*1e3,He=300*1e3,ie=1800*1e3,xe=2,qe=3,Fe=10,E="grix-connector",ne=1e4,G=15,se=2e3,oe=8e3,Be=1e3,ze=2e3,je=120*1e3,ce=1e4,Ke=6e4,Xe=3,Ye=600*1e3,Je=9e4,Ve=3e4,Ze=9e4,Qe=new Set(["preparing","staged","handoff_ready","activating","verifying","healthy","rolling_back","rolled_back","finalizing","failed"]),L=600*1e3,O=1800*1e3;function I(d,e=L){const t=Date.parse(d.activation_started_at??d.upgraded_at??"");return Number.isNaN(t)?!0:Date.now()-t>e}function de(d){const e=Date.parse(d.verification_started_at??d.activation_started_at??"");return Number.isNaN(e)||Date.now()-e>je}function et(d){if((d.guardian_handback_count??0)>=Xe)return!1;const e=Date.parse(d.guardian_handback_at??"");return Number.isNaN(e)?!0:Date.now()-e>=Ye}function tt(d){if(!Number.isInteger(d)||(d??0)<=0)return!1;try{return process.kill(d,0),!0}catch{return!1}}function le(d){try{return we(d)}catch{return d}}function ue(){try{W(_(y.base,"log"),{recursive:!0});const d=me(_(y.base,"log","upgrade.log"),"a");return{stdio:["ignore",d,d],logFd:d}}catch{return{stdio:"ignore"}}}function R(){const d=_(y.base,"bin"),e=_(d,"upgrade-guardian.mjs");if(v(e))return le(e);const t=_(d,"upgrade-guardian.fallback.mjs");return v(t)?le(t):null}function he(d){if(!tt(d.guardian_pid))return!1;try{const t=JSON.parse(P(_(y.data,"upgrade-monitor-heartbeat.json"),"utf-8"));if(t.transaction_id===d.transaction_id&&t.pid===d.guardian_pid&&typeof t.updated_at=="number"&&Date.now()-t.updated_at<=ce)return!0}catch{}const e=Date.parse(d.guardian_started_at??"");return Number.isFinite(e)&&Date.now()-e<=ce}function pe(d){return new URL(d.replace(/^wss:/,"https:").replace(/^ws:/,"http:")).origin}function fe(){return _(y.data,"upgrade-state.json")}function ge(){const d=fe();if(!v(d))return{daily_attempts:{},version_attempts:{}};try{return JSON.parse(P(d,"utf-8"))}catch{return{daily_attempts:{},version_attempts:{}}}}function rt(d){const e=fe();W(be(e),{recursive:!0});const t=e+".tmp";ye(t,JSON.stringify(d),"utf-8"),ve(t,e)}function _e(){return new Date().toISOString().slice(0,10)}class mt{agentConfigs;isBusy;closeAdmission;options;timer=null;initialTimer=null;pendingTimer=null;healthyTimer=null;guardianWaitLoggedAt=0;guardianWaitLoggedPhase="";recordedRollbackFailures=new Set;posixGuardianResumeAttempted=new Set;running=!1;stopped=!1;constructor(e,t,r,i={}){this.agentConfigs=e,this.isBusy=t,this.closeAdmission=r,this.options=i}async start(){await this.handleLauncherStartup(),await this.handlePendingOnStartup(),this.initialTimer=setTimeout(()=>{this.stopped||(this.runCheck(),!this.stopped&&(this.timer=setInterval(()=>this.runCheck(),We)))},He)}stop(){this.stopped=!0,this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.timer&&(clearInterval(this.timer),this.timer=null),this.pendingTimer&&(clearTimeout(this.pendingTimer),this.pendingTimer=null),this.healthyTimer&&(clearTimeout(this.healthyTimer),this.healthyTimer=null)}triggerCheck(){this.stopped||this.runCheck()}async checkForUpdate(){return this.agentConfigs.length===0?{available:!1}:(await Promise.all(this.agentConfigs.map(r=>this.queryUpgrade(r)))).find(r=>r.available&&r.release)??{available:!1}}async handlePendingOnStartup(){if(!z())return;let e=D();if(!e){a("daemon startup: pending journal is unreadable; preserving it and blocking automatic upgrade for manual recovery");return}if(e.phase&&!Qe.has(e.phase)&&(e=N({phase:"failed",error_code:"INVALID_UPGRADE_STATE",error_msg:`Unknown upgrade transaction phase: ${String(e.phase)}`},e.transaction_id)),e.phase==="finalizing"){this.settleTransaction(e)||(a(`terminal transaction ${e.transaction_id??"legacy"} is waiting for its shared lock to be released`),this.schedulePendingReconcile());return}if(e.phase==="preparing"||e.phase==="staged"){const c=!!(e.wrapper_pause_file&&v(e.wrapper_pause_file));if(e.phase==="staged"&&c){this.schedulePendingReconcile();return}U(e),e=N({phase:"rolled_back",error_code:"UPGRADE_INTERRUPTED",error_msg:"Upgrade stopped before Windows activation started"})}if(e.phase==="verifying"){if(he(e)&&!de(e)){this.schedulePendingReconcile();return}if(de(e)&&e.transaction_id&&["win32","darwin"].includes(this.options.platform??process.platform)&&this.options.requestGracefulShutdown){const c=`Target ${e.target_version} did not become healthy before the Windows verification deadline`;Te(e.transaction_id,c),a(`${c}; requesting graceful shutdown for offline rollback`),await this.options.requestGracefulShutdown("upgrade");return}await this.resumeWindowsGuardian(),this.schedulePendingReconcile();return}const t=new Set(["handoff_ready","activating","rolling_back"]);if(e.phase&&t.has(e.phase)){if(he(e)){this.logGuardianWait(e),this.schedulePendingReconcile();return}if(I(e)&&e.transaction_id&&(this.options.platform??process.platform)==="win32"&&this.options.requestGracefulShutdown&&et(e)){const c=`Guardian did not settle ${e.phase} for ${e.target_version} before the Windows activation deadline`;N({guardian_handback_count:(e.guardian_handback_count??0)+1,guardian_handback_at:new Date().toISOString()},e.transaction_id),a(`${c}; requesting graceful shutdown so the wrapper re-runs the guardian`),await this.options.requestGracefulShutdown("upgrade");return}if(I(e))a(`daemon startup: guardian did not settle ${e.phase} for ${e.target_version} and cannot be resumed; collapsing the transaction by version verdict`),X(),U(e);else{await this.resumeWindowsGuardian(),this.logGuardianWait(e),this.schedulePendingReconcile();return}}if(e.phase==="failed"){const c=K(e),l=A();if(!c||c!==l){a(`daemon startup: upgrade transaction requires manual recovery: ${e.error_msg??e.error_code??"unknown error"} (runtime=${l}, active package=${c??"unknown"})`);return}const f=Se(e);a(`daemon startup: failed transaction ${e.transaction_id??"legacy"} (${e.error_code??"unknown error"}) is converging on the runnable ${l}${f?`; diagnostics kept at ${f}`:""}`)}const r=K(e),i=A(),n=e.phase==="healthy",u=e.phase==="rolled_back",o=!r||r===e.target_version,s=n?i===e.target_version&&r===e.target_version:!u&&i===e.target_version&&o;if(!s&&o&&!u){if(!I(e)){if((this.options.platform??process.platform)!=="win32"&&r===e.target_version){const c=e.transaction_id??`${e.target_version}@${e.upgraded_at}`;this.posixGuardianResumeAttempted.has(c)||(this.posixGuardianResumeAttempted.add(c),a(`resuming POSIX guardian for stalled activation of ${e.target_version}`),this.startGuardian())}this.logThrottled("posix-activation-wait",`daemon startup: runtime ${i} is waiting for guardian activation of ${e.target_version} (active package=${r??"unknown"})`),this.schedulePendingReconcile();return}a(`daemon startup: activation wait for ${e.target_version} expired (> ${L/6e4}min); no guardian will finish the switch, reporting by version verdict`)}const h=s?{from_version:e.from_version,to_version:e.target_version,status:"success"}:{from_version:e.from_version,to_version:e.target_version,status:"rolled_back",error_code:e.error_code??"STARTUP_CRASH",error_msg:e.error_msg,crash_count:e.crash_count};if(a(s?`daemon startup: version matches target ${e.target_version}, upgrade succeeded`:`daemon startup: runtime=${i}, active package=${r??"unknown"}, target=${e.target_version}; rolled back`),!s){const c=e.transaction_id??`${e.target_version}@${e.upgraded_at}`;this.recordedRollbackFailures.has(c)||(this.recordedRollbackFailures.add(c),this.recordFailure(e.target_version))}if(s){const c=await this.confirmHealthz(oe,n?e.target_version:void 0,n?e.old_pid:void 0,n?e.activation_started_at:void 0);if(n&&!c){if(!I(e)){a("guardian marked healthy but target-version healthz is not yet observable; retrying reconciliation"),this.schedulePendingReconcile();return}a(`guardian marked healthy for ${e.target_version} but healthz stayed unobservable past the ${L/6e4}min activation window; collapsing the transaction by version verdict`)}else a(c?"healthz confirmed healthy, reporting success":"healthz not confirmed within window; reporting success on version-match (guardian still guards crashes)")}if(!q(e)){a(`terminal transaction ${e.transaction_id??"legacy"} is waiting for antivirus-held artifact cleanup`),this.schedulePendingReconcile();return}if(await this.reportUpgrade(h)){this.settleTransaction(e)||(a(`terminal transaction ${e.transaction_id??"legacy"} could not release its shared lock; retrying reconciliation`),this.schedulePendingReconcile());return}this.retryStartupReport(h,e,!1)}settleTransaction(e){if(!F(e))return!1;try{this.options.onTransactionSettled?.()}catch(t){a(`onTransactionSettled hook failed: ${t instanceof Error?t.message:String(t)}`)}return!0}schedulePendingReconcile(){this.stopped||this.pendingTimer||(this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,!this.stopped&&this.handlePendingOnStartup().catch(e=>{m.warn("upgrade",`Pending reconciliation failed: ${e instanceof Error?e.message:e}`),this.schedulePendingReconcile()})},ze))}logThrottled(e,t){const r=Date.now();e===this.guardianWaitLoggedPhase&&r-this.guardianWaitLoggedAt<Ke||(this.guardianWaitLoggedPhase=e,this.guardianWaitLoggedAt=r,a(t))}logGuardianWait(e){const t=String(e.phase??"");this.logThrottled(`guardian:${t}`,`transaction ${e.transaction_id??"legacy"} is ${t}; waiting for guardian verdict`)}async resumeWindowsGuardian(){if(this.options.resumeWindowsGuardian){await this.options.resumeWindowsGuardian();return}const e=R();if(!e)return;const{stdio:t,logFd:r}=ue();try{H(process.execPath,[e,"activate","--root",y.base],{detached:!0,stdio:t,windowsHide:!0}).unref()}finally{if(r!==void 0)try{C(r)}catch{}}}async retryStartupReport(e,t,r){const i=t?.transaction_id,n=()=>{const u=D();if(!(i&&u?.transaction_id!==i)){if(r&&!q(t)){a(`terminal backup cleanup is still blocked for ${i??"legacy transaction"}`),this.schedulePendingReconcile();return}this.settleTransaction(t)||(a(`terminal shared lock release is still blocked for ${i??"legacy transaction"}`),this.schedulePendingReconcile())}};for(let u=2;u<=G;u++){if(this.stopped)return;const o=se*(u-1)+Math.floor(Math.random()*1e3);if(await new Promise(s=>setTimeout(s,o)),this.stopped)return;if(await this.reportUpgrade(e)){n();return}}a(`startup report (${e.status}) not delivered after ${G} attempts; clearing pending to unblock future checks`),n()}async confirmHealthz(e,t,r,i){let n="19579";try{const s=_(y.data,"health-port");v(s)&&(n=P(s,"utf-8").trim()||n)}catch{}const u=`http://127.0.0.1:${n}/healthz`,o=Date.now()+e;for(;Date.now()<o&&!this.stopped;){try{const s=await fetch(u,{signal:AbortSignal.timeout(2e3)});if(s.ok){if(!t)return!0;const h=await s.json();if(h.status==="ok"&&h.version===t&&typeof h.pid=="number"&&h.pid>0&&h.pid!==r)try{const c=JSON.parse(P(_(y.base,"daemon-status.json"),"utf-8")),l=Date.parse(i??"");return!!(c.state==="running"&&c.pid===h.pid&&typeof c.updated_at=="number"&&Number.isFinite(l)&&c.updated_at>=l)}catch{return!1}}}catch{}await new Promise(s=>setTimeout(s,Be))}return!1}async runCheck(){if(!this.running){this.running=!0;try{await this.check()}catch(e){m.error("upgrade",`Check failed: ${e instanceof Error?e.message:e}`)}finally{this.running=!1}}}async check(){if(z()){await this.handlePendingOnStartup();return}if(this.agentConfigs.length===0)return;const r=(await Promise.all(this.agentConfigs.map(p=>this.queryUpgrade(p)))).find(p=>p.available&&p.release)?.release;if(!r)return;const i=A();let n;try{n=Re(r.version)}catch(p){const g=p;await this.reportUpgrade({from_version:i,to_version:String(r.version),status:"failed",error_code:g.code??"INVALID_VERSION",error_msg:g.message});return}const u=r.force,o=this.options.platform??process.platform,s=this.options.env??process.env,h=V(s);if(h&&this.options.requestGracefulShutdown){await this.runLauncherUpgrade(h,i,n,!!u);return}if(o==="win32"){const p=R(),g=s.GRIX_WRAPPER_SUPERVISED==="1";if(!g||!p||!this.options.requestGracefulShutdown){const b=`Windows automatic upgrade requires a refreshed service installation (${[...g?[]:["managed wrapper"],...p?[]:["external guardian"],...this.options.requestGracefulShutdown?[]:["graceful shutdown hook"]].join(", ")})`;a(b),await this.reportUpgrade({from_version:i,to_version:n,status:"failed",error_code:"WINDOWS_UPGRADE_UNSUPPORTED",error_msg:b});return}}const c=o==="darwin"&&!!R()&&!!this.options.requestGracefulShutdown;if(o==="darwin"&&!c&&a("macOS transactional upgrade prerequisites missing; falling back to the legacy guardian flow"),!u&&!this.checkRateLimit(n))return;const l=j();if(!l.ok){await this.reportUpgrade({from_version:i,to_version:n,status:"failed",error_code:l.errorCode,error_msg:l.errorMsg});return}if(!await B(E,n)){a(`target ${n} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}a(`upgrade start: ${i} -> ${n}`);const f=Date.now();let w;try{w=Ee(i,n,o==="win32"||c?"preparing":void 0).transaction_id,(await ke(E,n,void 0,c?{activationMode:"staged"}:{}))?.activationRequired||$e(n),a("npm install verified, reporting installed"),await this.reportUpgrade({from_version:i,to_version:n,status:"installed",duration_ms:Date.now()-f}),a("shutting down for restart");const g=await this.waitUntilIdle();if(g!=="idle")throw a(`upgrade aborted before lifecycle handoff: ${g}`),this.options.reopenLifecycleAdmission?.(),new S("UPGRADE_ABORTED",`Upgrade was aborted before lifecycle handoff (${g})`);if(o==="win32"){if(!R())throw new S("WINDOWS_UPGRADE_UNSUPPORTED","Windows external guardian disappeared before lifecycle handoff");x(process.pid,w),a("Windows handoff armed; requesting graceful daemon shutdown"),await this.options.requestGracefulShutdown("upgrade")}else if(c){if(!R())throw new S("MACOS_UPGRADE_UNSUPPORTED","macOS guardian helper disappeared before lifecycle handoff");x(process.pid,w),a("macOS handoff armed; spawning guardian before graceful daemon shutdown"),await this.resumeWindowsGuardian(),await this.options.requestGracefulShutdown("upgrade")}else this.startGuardian(),process.kill(process.pid,"SIGTERM")}catch(p){const g=p instanceof S?p.code:"NPM_INSTALL_FAILED",T=p instanceof Error?p.message:String(p);a(`upgrade failed: ${g} ${T}`);const b=D();if(w&&b?.transaction_id===w&&(o==="win32"||c?(X(),U(b)):Pe(b)&&a("upgrade failed before restart; previous package restored atomically"),F(b)||(a(`failed transaction ${w} is waiting for shared lock release`),this.schedulePendingReconcile()),this.options.reopenLifecycleAdmission?.()),g==="UPGRADE_IN_PROGRESS")return;Y(T)||J(T)||g==="NPM_TIMEOUT"?a(`failure is retriable (${g}); skipping cooldown, will retry next cycle`):this.recordFailure(n),await this.reportUpgrade({from_version:i,to_version:n,status:"failed",error_code:g,error_msg:T,duration_ms:Date.now()-f,upgrade_log:$()})}}async runLauncherUpgrade(e,t,r,i){if(!i&&!this.checkRateLimit(r))return;const n=j();if(!n.ok){await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:n.errorCode,error_msg:n.errorMsg});return}if(!await B(E,r)){a(`target ${r} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}a(`launcher upgrade start: ${t} -> ${r} (store=${e})`);const u=Date.now();try{v(re(e,r))?a(`${r} already present in version store; skipping install`):await Ie(e,E,r),await this.reportUpgrade({from_version:t,to_version:r,status:"installed",duration_ms:Date.now()-u});const o=await this.waitUntilIdle();if(o!=="idle")throw this.options.reopenLifecycleAdmission?.(),new S("UPGRADE_ABORTED",`Upgrade was aborted before lifecycle handoff (${o})`);const s={transaction_id:Ce(),from_version:t,to_version:r,started_at:new Date().toISOString()};ae(e,{...s,switched:!1}),Oe(e,r),ae(e,{...s,switched:!0}),a(`current pointer switched to ${r}; requesting restart via launcher`),await this.options.requestGracefulShutdown("upgrade-switch")}catch(o){const s=o instanceof S?o.code:"NPM_INSTALL_FAILED",h=o instanceof Error?o.message:String(o);if(a(`launcher upgrade failed: ${s} ${h}`),s==="UPGRADE_ABORTED"){a("machine stayed busy; keeping the verified version dir and retrying next cycle without penalty"),await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:s,error_msg:h,duration_ms:Date.now()-u,upgrade_log:$()});return}if(M(e,"current")!==r)try{k(te(e,r),{recursive:!0,force:!0})}catch{}Y(h)||J(h)||s==="NPM_TIMEOUT"?a(`failure is retriable (${s}); skipping cooldown, will retry next cycle`):this.recordFailure(r),await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:s,error_msg:h,duration_ms:Date.now()-u,upgrade_log:$()})}}async handleLauncherStartup(){const e=this.options.env??process.env,t=V(e);if(!t)return;const r=A();try{Ue(t,te(t,r))}catch(l){a(`failed to refresh launcher: ${l instanceof Error?l.message:String(l)}`)}const i=Date.now(),n=()=>{if(v(De(t,r)))return!1;const l=M(t,"previous");return!!l&&l!==r&&v(re(t,l))},u=l=>{this.healthyTimer=setTimeout(()=>{if(this.healthyTimer=null,!this.stopped){if(this.options.isConnected&&!this.options.isConnected()){if(Date.now()-i>=Ze&&this.options.requestGracefulShutdown&&n()){a(`${r} has been up ${Math.round((Date.now()-i)/1e3)}s without any agent websocket ready; exiting so the launcher counts a crash and can roll back`),this.options.requestGracefulShutdown("launcher-unhealthy");return}a(`uptime reached but no agent websocket is ready yet; deferring health marker for ${r}`),u(Ve);return}try{Ne(t,r),ee(t,r)}catch(f){a(`failed to write health marker: ${f instanceof Error?f.message:String(f)}`)}}},l),this.healthyTimer.unref?.()};u(Je);const o=Ge(t),s=Le(t);if(!o&&!s)return;const h=()=>{try{k(Z(t),{force:!0})}catch{}try{k(Q(t),{force:!0})}catch{}const l=Me(t);l.length>0&&a(`pruned version directories: ${l.join(", ")}`)};let c;if(o&&o.from_version===r){const l=`exit_code=${o.exit_code??"n/a"} crashes=${o.crash_count??"n/a"} uptime_ms=${o.uptime_ms??"n/a"}`;a(`daemon startup: launcher rolled back ${o.to_version} -> ${r} (${l})`),this.recordFailure(o.to_version);const f=ee(t,o.to_version),w=f?.split(/\r?\n/)[0]?.slice(0,200);c={from_version:o.from_version,to_version:o.to_version,status:"rolled_back",error_code:"STARTUP_CRASH",error_msg:`Target ${o.to_version} crashed before becoming healthy (${l}); launcher restored ${r}`+(w?`; cause: ${w}`:""),crash_count:o.crash_count,upgrade_log:$()+(f?`
1
+ import{closeSync as x,existsSync as m,mkdirSync as F,openSync as me,readFileSync as P,realpathSync as we,renameSync as ve,writeFileSync as ye}from"node:fs";import{join as w,dirname as be}from"node:path";import{spawn as q}from"node:child_process";import{log as v}from"../log/index.js";import{GRIX_PATHS as y}from"../log/index.js";import{resolveClientVersion as A}from"../util/client-version.js";import{UpgradeError as k,armWindowsUpgradeHandoff as B,archivePendingJournal as Se,armWindowsUpgradeRollback as Te,cleanupPendingBackup as z,collectEnvInfo as ke,discardPendingStaging as N,finalizePendingTransaction as j,getUpgradeLogTail as E,isVersionAvailable as K,npmInstall as Ae,normalizeUpgradeVersion as $e,pendingExists as X,preflightCheck as Y,readPending as M,readPendingPackageVersion as J,removeWindowsHandoffFiles as V,rollbackPendingInstall as Re,updatePending as G,upgradeLog as a,verifyInstalledVersion as Pe,writePending as Ee}from"./npm-upgrader.js";import{isRetriableRegistryError as Z,isTransientInstallError as Q}from"../installer/npm-registry.js";import{installVersionIntoStore as Ie}from"./npm-upgrader.js";import{ensureLauncher as Ue,healthMarkerPath as De,markHealthy as Ne,pruneVersions as Me,readPointer as $,readRollbackRecord as Ge,readSwitchRecord as Le,resolveLauncherStore as ee,rollbackRecordPath as L,switchCurrent as Oe,switchRecordPath as O,takeCrashNote as te,versionDir as re,versionEntry as I,writeSwitchRecord as ae}from"./version-store.js";import{rmSync as T}from"node:fs";import{randomUUID as Ce}from"node:crypto";const We=360*60*1e3,He=300*1e3,ie=1800*1e3,xe=2,Fe=3,qe=10,U="grix-connector",ne=1e4,C=15,se=2e3,oe=8e3,Be=1e3,ze=2e3,je=120*1e3,ce=1e4,Ke=6e4,Xe=3,Ye=600*1e3,Je=9e4,Ve=3e4,Ze=9e4,Qe=3600*1e3,et=new Set(["preparing","staged","handoff_ready","activating","verifying","healthy","rolling_back","rolled_back","finalizing","failed"]),W=600*1e3,H=1800*1e3;function D(c,e=W){const t=Date.parse(c.activation_started_at??c.upgraded_at??"");return Number.isNaN(t)?!0:Date.now()-t>e}function de(c){const e=Date.parse(c.verification_started_at??c.activation_started_at??"");return Number.isNaN(e)||Date.now()-e>je}function tt(c){if((c.guardian_handback_count??0)>=Xe)return!1;const e=Date.parse(c.guardian_handback_at??"");return Number.isNaN(e)?!0:Date.now()-e>=Ye}function rt(c){if(!Number.isInteger(c)||(c??0)<=0)return!1;try{return process.kill(c,0),!0}catch{return!1}}function le(c){try{return we(c)}catch{return c}}function ue(){try{F(w(y.base,"log"),{recursive:!0});const c=me(w(y.base,"log","upgrade.log"),"a");return{stdio:["ignore",c,c],logFd:c}}catch{return{stdio:"ignore"}}}function R(){const c=w(y.base,"bin"),e=w(c,"upgrade-guardian.mjs");if(m(e))return le(e);const t=w(c,"upgrade-guardian.fallback.mjs");return m(t)?le(t):null}function he(c){if(!rt(c.guardian_pid))return!1;try{const t=JSON.parse(P(w(y.data,"upgrade-monitor-heartbeat.json"),"utf-8"));if(t.transaction_id===c.transaction_id&&t.pid===c.guardian_pid&&typeof t.updated_at=="number"&&Date.now()-t.updated_at<=ce)return!0}catch{}const e=Date.parse(c.guardian_started_at??"");return Number.isFinite(e)&&Date.now()-e<=ce}function pe(c){return new URL(c.replace(/^wss:/,"https:").replace(/^ws:/,"http:")).origin}function fe(){return w(y.data,"upgrade-state.json")}function ge(){const c=fe();if(!m(c))return{daily_attempts:{},version_attempts:{}};try{return JSON.parse(P(c,"utf-8"))}catch{return{daily_attempts:{},version_attempts:{}}}}function at(c){const e=fe();F(be(e),{recursive:!0});const t=e+".tmp";ye(t,JSON.stringify(c),"utf-8"),ve(t,e)}function _e(){return new Date().toISOString().slice(0,10)}class wt{agentConfigs;isBusy;closeAdmission;options;timer=null;initialTimer=null;pendingTimer=null;healthyTimer=null;guardianWaitLoggedAt=0;guardianWaitLoggedPhase="";recordedRollbackFailures=new Set;posixGuardianResumeAttempted=new Set;running=!1;stopped=!1;constructor(e,t,r,i={}){this.agentConfigs=e,this.isBusy=t,this.closeAdmission=r,this.options=i}async start(){await this.handleLauncherStartup(),await this.handlePendingOnStartup(),this.initialTimer=setTimeout(()=>{this.stopped||(this.runCheck(),!this.stopped&&(this.timer=setInterval(()=>this.runCheck(),We)))},He)}stop(){this.stopped=!0,this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.timer&&(clearInterval(this.timer),this.timer=null),this.pendingTimer&&(clearTimeout(this.pendingTimer),this.pendingTimer=null),this.healthyTimer&&(clearTimeout(this.healthyTimer),this.healthyTimer=null)}triggerCheck(){this.stopped||this.runCheck()}async checkForUpdate(){return this.agentConfigs.length===0?{available:!1}:(await Promise.all(this.agentConfigs.map(r=>this.queryUpgrade(r)))).find(r=>r.available&&r.release)??{available:!1}}async handlePendingOnStartup(){if(!X())return;let e=M();if(!e){a("daemon startup: pending journal is unreadable; preserving it and blocking automatic upgrade for manual recovery");return}if(e.phase&&!et.has(e.phase)&&(e=G({phase:"failed",error_code:"INVALID_UPGRADE_STATE",error_msg:`Unknown upgrade transaction phase: ${String(e.phase)}`},e.transaction_id)),e.phase==="finalizing"){this.settleTransaction(e)||(a(`terminal transaction ${e.transaction_id??"legacy"} is waiting for its shared lock to be released`),this.schedulePendingReconcile());return}if(e.phase==="preparing"||e.phase==="staged"){const d=!!(e.wrapper_pause_file&&m(e.wrapper_pause_file));if(e.phase==="staged"&&d){this.schedulePendingReconcile();return}N(e),e=G({phase:"rolled_back",error_code:"UPGRADE_INTERRUPTED",error_msg:"Upgrade stopped before Windows activation started"})}if(e.phase==="verifying"){if(he(e)&&!de(e)){this.schedulePendingReconcile();return}if(de(e)&&e.transaction_id&&["win32","darwin"].includes(this.options.platform??process.platform)&&this.options.requestGracefulShutdown){const d=`Target ${e.target_version} did not become healthy before the Windows verification deadline`;Te(e.transaction_id,d),a(`${d}; requesting graceful shutdown for offline rollback`),await this.options.requestGracefulShutdown("upgrade");return}await this.resumeWindowsGuardian(),this.schedulePendingReconcile();return}const t=new Set(["handoff_ready","activating","rolling_back"]);if(e.phase&&t.has(e.phase)){if(he(e)){this.logGuardianWait(e),this.schedulePendingReconcile();return}if(D(e)&&e.transaction_id&&(this.options.platform??process.platform)==="win32"&&this.options.requestGracefulShutdown&&tt(e)){const d=`Guardian did not settle ${e.phase} for ${e.target_version} before the Windows activation deadline`;G({guardian_handback_count:(e.guardian_handback_count??0)+1,guardian_handback_at:new Date().toISOString()},e.transaction_id),a(`${d}; requesting graceful shutdown so the wrapper re-runs the guardian`),await this.options.requestGracefulShutdown("upgrade");return}if(D(e))a(`daemon startup: guardian did not settle ${e.phase} for ${e.target_version} and cannot be resumed; collapsing the transaction by version verdict`),V(),N(e);else{await this.resumeWindowsGuardian(),this.logGuardianWait(e),this.schedulePendingReconcile();return}}if(e.phase==="failed"){const d=J(e),_=A();if(!d||d!==_){a(`daemon startup: upgrade transaction requires manual recovery: ${e.error_msg??e.error_code??"unknown error"} (runtime=${_}, active package=${d??"unknown"})`);return}const l=Se(e);a(`daemon startup: failed transaction ${e.transaction_id??"legacy"} (${e.error_code??"unknown error"}) is converging on the runnable ${_}${l?`; diagnostics kept at ${l}`:""}`)}const r=J(e),i=A(),s=e.phase==="healthy",u=e.phase==="rolled_back",o=!r||r===e.target_version,n=s?i===e.target_version&&r===e.target_version:!u&&i===e.target_version&&o;if(!n&&o&&!u){if(!D(e)){if((this.options.platform??process.platform)!=="win32"&&r===e.target_version){const d=e.transaction_id??`${e.target_version}@${e.upgraded_at}`;this.posixGuardianResumeAttempted.has(d)||(this.posixGuardianResumeAttempted.add(d),a(`resuming POSIX guardian for stalled activation of ${e.target_version}`),this.startGuardian())}this.logThrottled("posix-activation-wait",`daemon startup: runtime ${i} is waiting for guardian activation of ${e.target_version} (active package=${r??"unknown"})`),this.schedulePendingReconcile();return}a(`daemon startup: activation wait for ${e.target_version} expired (> ${W/6e4}min); no guardian will finish the switch, reporting by version verdict`)}const p=n?{from_version:e.from_version,to_version:e.target_version,status:"success"}:{from_version:e.from_version,to_version:e.target_version,status:"rolled_back",error_code:e.error_code??"STARTUP_CRASH",error_msg:e.error_msg,crash_count:e.crash_count};if(a(n?`daemon startup: version matches target ${e.target_version}, upgrade succeeded`:`daemon startup: runtime=${i}, active package=${r??"unknown"}, target=${e.target_version}; rolled back`),!n){const d=e.transaction_id??`${e.target_version}@${e.upgraded_at}`;this.recordedRollbackFailures.has(d)||(this.recordedRollbackFailures.add(d),this.recordFailure(e.target_version))}if(n){const d=await this.confirmHealthz(oe,s?e.target_version:void 0,s?e.old_pid:void 0,s?e.activation_started_at:void 0);if(s&&!d){if(!D(e)){a("guardian marked healthy but target-version healthz is not yet observable; retrying reconciliation"),this.schedulePendingReconcile();return}a(`guardian marked healthy for ${e.target_version} but healthz stayed unobservable past the ${W/6e4}min activation window; collapsing the transaction by version verdict`)}else a(d?"healthz confirmed healthy, reporting success":"healthz not confirmed within window; reporting success on version-match (guardian still guards crashes)")}if(!z(e)){a(`terminal transaction ${e.transaction_id??"legacy"} is waiting for antivirus-held artifact cleanup`),this.schedulePendingReconcile();return}if(await this.reportUpgrade(p)){this.settleTransaction(e)||(a(`terminal transaction ${e.transaction_id??"legacy"} could not release its shared lock; retrying reconciliation`),this.schedulePendingReconcile());return}this.retryStartupReport(p,e,!1)}settleTransaction(e){if(!j(e))return!1;try{this.options.onTransactionSettled?.()}catch(t){a(`onTransactionSettled hook failed: ${t instanceof Error?t.message:String(t)}`)}return!0}schedulePendingReconcile(){this.stopped||this.pendingTimer||(this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,!this.stopped&&this.handlePendingOnStartup().catch(e=>{v.warn("upgrade",`Pending reconciliation failed: ${e instanceof Error?e.message:e}`),this.schedulePendingReconcile()})},ze))}logThrottled(e,t){const r=Date.now();e===this.guardianWaitLoggedPhase&&r-this.guardianWaitLoggedAt<Ke||(this.guardianWaitLoggedPhase=e,this.guardianWaitLoggedAt=r,a(t))}logGuardianWait(e){const t=String(e.phase??"");this.logThrottled(`guardian:${t}`,`transaction ${e.transaction_id??"legacy"} is ${t}; waiting for guardian verdict`)}async resumeWindowsGuardian(){if(this.options.resumeWindowsGuardian){await this.options.resumeWindowsGuardian();return}const e=R();if(!e)return;const{stdio:t,logFd:r}=ue();try{q(process.execPath,[e,"activate","--root",y.base],{detached:!0,stdio:t,windowsHide:!0}).unref()}finally{if(r!==void 0)try{x(r)}catch{}}}async retryStartupReport(e,t,r){const i=t?.transaction_id,s=()=>{const u=M();if(!(i&&u?.transaction_id!==i)){if(r&&!z(t)){a(`terminal backup cleanup is still blocked for ${i??"legacy transaction"}`),this.schedulePendingReconcile();return}this.settleTransaction(t)||(a(`terminal shared lock release is still blocked for ${i??"legacy transaction"}`),this.schedulePendingReconcile())}};for(let u=2;u<=C;u++){if(this.stopped)return;const o=se*(u-1)+Math.floor(Math.random()*1e3);if(await new Promise(n=>setTimeout(n,o)),this.stopped)return;if(await this.reportUpgrade(e)){s();return}}a(`startup report (${e.status}) not delivered after ${C} attempts; clearing pending to unblock future checks`),s()}async confirmHealthz(e,t,r,i){let s="19579";try{const n=w(y.data,"health-port");m(n)&&(s=P(n,"utf-8").trim()||s)}catch{}const u=`http://127.0.0.1:${s}/healthz`,o=Date.now()+e;for(;Date.now()<o&&!this.stopped;){try{const n=await fetch(u,{signal:AbortSignal.timeout(2e3)});if(n.ok){if(!t)return!0;const p=await n.json();if(p.status==="ok"&&p.version===t&&typeof p.pid=="number"&&p.pid>0&&p.pid!==r)try{const d=JSON.parse(P(w(y.base,"daemon-status.json"),"utf-8")),_=Date.parse(i??"");return!!(d.state==="running"&&d.pid===p.pid&&typeof d.updated_at=="number"&&Number.isFinite(_)&&d.updated_at>=_)}catch{return!1}}}catch{}await new Promise(n=>setTimeout(n,Be))}return!1}async runCheck(){if(!this.running){this.running=!0;try{await this.check()}catch(e){v.error("upgrade",`Check failed: ${e instanceof Error?e.message:e}`)}finally{this.running=!1}}}async check(){if(X()){await this.handlePendingOnStartup();return}if(this.agentConfigs.length===0)return;const r=(await Promise.all(this.agentConfigs.map(h=>this.queryUpgrade(h)))).find(h=>h.available&&h.release)?.release;if(!r)return;const i=A();let s;try{s=$e(r.version)}catch(h){const g=h;await this.reportUpgrade({from_version:i,to_version:String(r.version),status:"failed",error_code:g.code??"INVALID_VERSION",error_msg:g.message});return}const u=r.force,o=this.options.platform??process.platform,n=this.options.env??process.env,p=ee(n);if(p&&this.options.requestGracefulShutdown){await this.runLauncherUpgrade(p,i,s,!!u);return}if(o==="win32"){const h=R(),g=n.GRIX_WRAPPER_SUPERVISED==="1";if(!g||!h||!this.options.requestGracefulShutdown){const S=`Windows automatic upgrade requires a refreshed service installation (${[...g?[]:["managed wrapper"],...h?[]:["external guardian"],...this.options.requestGracefulShutdown?[]:["graceful shutdown hook"]].join(", ")})`;a(S),await this.reportUpgrade({from_version:i,to_version:s,status:"failed",error_code:"WINDOWS_UPGRADE_UNSUPPORTED",error_msg:S});return}}const d=o==="darwin"&&!!R()&&!!this.options.requestGracefulShutdown;if(o==="darwin"&&!d&&a("macOS transactional upgrade prerequisites missing; falling back to the legacy guardian flow"),!u&&!this.checkRateLimit(s))return;const _=Y();if(!_.ok){await this.reportUpgrade({from_version:i,to_version:s,status:"failed",error_code:_.errorCode,error_msg:_.errorMsg});return}if(!await K(U,s)){a(`target ${s} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}a(`upgrade start: ${i} -> ${s}`);const l=Date.now();let f;try{f=Ee(i,s,o==="win32"||d?"preparing":void 0).transaction_id,(await Ae(U,s,void 0,d?{activationMode:"staged"}:{}))?.activationRequired||Pe(s),a("npm install verified, reporting installed"),await this.reportUpgrade({from_version:i,to_version:s,status:"installed",duration_ms:Date.now()-l}),a("shutting down for restart");const g=await this.waitUntilIdle();if(g!=="idle")throw a(`upgrade aborted before lifecycle handoff: ${g}`),this.options.reopenLifecycleAdmission?.(),new k("UPGRADE_ABORTED",`Upgrade was aborted before lifecycle handoff (${g})`);if(o==="win32"){if(!R())throw new k("WINDOWS_UPGRADE_UNSUPPORTED","Windows external guardian disappeared before lifecycle handoff");B(process.pid,f),a("Windows handoff armed; requesting graceful daemon shutdown"),await this.options.requestGracefulShutdown("upgrade")}else if(d){if(!R())throw new k("MACOS_UPGRADE_UNSUPPORTED","macOS guardian helper disappeared before lifecycle handoff");B(process.pid,f),a("macOS handoff armed; spawning guardian before graceful daemon shutdown"),await this.resumeWindowsGuardian(),await this.options.requestGracefulShutdown("upgrade")}else this.startGuardian(),process.kill(process.pid,"SIGTERM")}catch(h){const g=h instanceof k?h.code:"NPM_INSTALL_FAILED",b=h instanceof Error?h.message:String(h);a(`upgrade failed: ${g} ${b}`);const S=M();if(f&&S?.transaction_id===f&&(o==="win32"||d?(V(),N(S)):Re(S)&&a("upgrade failed before restart; previous package restored atomically"),j(S)||(a(`failed transaction ${f} is waiting for shared lock release`),this.schedulePendingReconcile()),this.options.reopenLifecycleAdmission?.()),g==="UPGRADE_IN_PROGRESS")return;Z(b)||Q(b)||g==="NPM_TIMEOUT"?a(`failure is retriable (${g}); skipping cooldown, will retry next cycle`):this.recordFailure(s),await this.reportUpgrade({from_version:i,to_version:s,status:"failed",error_code:g,error_msg:b,duration_ms:Date.now()-l,upgrade_log:E()})}}async runLauncherUpgrade(e,t,r,i){if(!i&&!this.checkRateLimit(r))return;const s=Y();if(!s.ok){await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:s.errorCode,error_msg:s.errorMsg});return}if(!await K(U,r)){a(`target ${r} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}a(`launcher upgrade start: ${t} -> ${r} (store=${e})`);const u=Date.now();try{m(I(e,r))?a(`${r} already present in version store; skipping install`):await Ie(e,U,r),await this.reportUpgrade({from_version:t,to_version:r,status:"installed",duration_ms:Date.now()-u});const o=await this.waitUntilIdle();if(o!=="idle")throw this.options.reopenLifecycleAdmission?.(),new k("UPGRADE_ABORTED",`Upgrade was aborted before lifecycle handoff (${o})`);const n={transaction_id:Ce(),from_version:t,to_version:r,started_at:new Date().toISOString()};ae(e,{...n,switched:!1}),Oe(e,r),ae(e,{...n,switched:!0}),a(`current pointer switched to ${r}; requesting restart via launcher`),await this.options.requestGracefulShutdown("upgrade-switch")}catch(o){const n=o instanceof k?o.code:"NPM_INSTALL_FAILED",p=o instanceof Error?o.message:String(o);if(a(`launcher upgrade failed: ${n} ${p}`),n==="UPGRADE_ABORTED"){a("machine stayed busy; keeping the verified version dir and retrying next cycle without penalty"),await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:n,error_msg:p,duration_ms:Date.now()-u,upgrade_log:E()});return}if($(e,"current")!==r)try{T(re(e,r),{recursive:!0,force:!0})}catch{}Z(p)||Q(p)||n==="NPM_TIMEOUT"?a(`failure is retriable (${n}); skipping cooldown, will retry next cycle`):this.recordFailure(r),await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:n,error_msg:p,duration_ms:Date.now()-u,upgrade_log:E()})}}async handleLauncherStartup(){const e=this.options.env??process.env,t=ee(e);if(!t)return;const r=A();try{Ue(t,re(t,r))}catch(l){a(`failed to refresh launcher: ${l instanceof Error?l.message:String(l)}`)}const i=Date.now(),s=()=>{if(m(De(t,r)))return!1;const l=$(t,"previous");return!!l&&l!==r&&m(I(t,l))},u=l=>{this.healthyTimer=setTimeout(()=>{if(this.healthyTimer=null,!this.stopped){if(this.options.isConnected&&!this.options.isConnected()){if(Date.now()-i>=Ze&&this.options.requestGracefulShutdown&&s()){a(`${r} has been up ${Math.round((Date.now()-i)/1e3)}s without any agent websocket ready; exiting so the launcher counts a crash and can roll back`),this.options.requestGracefulShutdown("launcher-unhealthy");return}a(`uptime reached but no agent websocket is ready yet; deferring health marker for ${r}`),u(Ve);return}try{Ne(t,r),te(t,r)}catch(f){a(`failed to write health marker: ${f instanceof Error?f.message:String(f)}`)}}},l),this.healthyTimer.unref?.()};u(Je);const o=Ge(t),n=Le(t);if(!o&&!n)return;const p=()=>{try{T(L(t),{force:!0})}catch{}try{T(O(t),{force:!0})}catch{}const l=Me(t,e);l.length>0&&a(`pruned version directories: ${l.join(", ")}`)},d=()=>{const l=g=>{const b=g?Date.parse(g):Number.NaN;return Number.isFinite(b)&&Date.now()-b<Qe},f=!!(o&&o.from_version!==r&&m(I(t,o.from_version))&&l(o.rolled_back_at)),h=!!(n&&n.to_version!==r&&n.from_version!==r&&m(I(t,n.from_version))&&l(n.started_at));if(!f)try{T(L(t),{force:!0})}catch{}if(!h)try{T(O(t),{force:!0})}catch{}(f||h)&&a(`kept launcher records addressed to another installed version (rollback=${f} switch=${h})`)};let _;if(o&&o.from_version===r){const l=`exit_code=${o.exit_code??"n/a"} crashes=${o.crash_count??"n/a"} uptime_ms=${o.uptime_ms??"n/a"}`;a(`daemon startup: launcher rolled back ${o.to_version} -> ${r} (${l})`),this.recordFailure(o.to_version);const f=te(t,o.to_version),h=f?.split(/\r?\n/)[0]?.slice(0,200);_={from_version:o.from_version,to_version:o.to_version,status:"rolled_back",error_code:"STARTUP_CRASH",error_msg:`Target ${o.to_version} crashed before becoming healthy (${l}); launcher restored ${r}`+(h?`; cause: ${h}`:""),crash_count:o.crash_count,upgrade_log:E()+(f?`
2
2
  --- ${o.to_version} crash note ---
3
- ${f}`:"")}}else if(s&&s.to_version===r&&M(t,"current")===r){a(`daemon startup: running switched target ${r}, upgrade succeeded`);const l=await this.confirmHealthz(oe);a(l?"healthz confirmed healthy, reporting success":"healthz not confirmed within window; reporting success on version-match"),c={from_version:s.from_version,to_version:s.to_version,status:"success"}}else if(s&&s.from_version===r&&s.switched===!1){a(`daemon startup: switch record for ${s.to_version} was never applied; discarding`);try{k(Q(t),{force:!0})}catch{}try{k(Z(t),{force:!0})}catch{}return}else if(s&&s.from_version===r)a(`daemon startup: expected ${s.to_version} but ${r} is running; reporting rolled_back`),this.recordFailure(s.to_version),c={from_version:s.from_version,to_version:s.to_version,status:"rolled_back",error_code:"STARTUP_CRASH",error_msg:`Launcher is running ${r} instead of switched target ${s.to_version}`};else{a(`daemon startup: stale launcher records (self=${r}); discarding`),h();return}if(await this.reportUpgrade(c)){h();return}(async()=>{for(let l=2;l<=G;l++){if(this.stopped||(await new Promise(f=>setTimeout(f,se*(l-1)+Math.floor(Math.random()*1e3))),this.stopped))return;if(await this.reportUpgrade(c))break}h()})()}async waitUntilIdle(){if(this.isBusy?.()){a(`active tasks detected, waiting up to ${Math.round(O/6e4)}min until idle before restart (admission stays open while waiting)`);const e=Date.now()+O,t=5e3,r=600*1e3;let i=Date.now();for(;this.isBusy()&&!this.stopped;){if(Date.now()>=e)return m.warn("upgrade",`Idle wait exceeded ${Math.round(O/6e4)}min; abandoning this upgrade attempt. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),a("idle wait timed out; upgrade attempt abandoned without ever closing admission"),"timeout";await new Promise(n=>setTimeout(n,t)),Date.now()-i>=r&&(i=Date.now(),a("still waiting for active tasks to finish before restart"))}}return this.stopped?"stopped":(this.closeAdmission?.(),this.isBusy?.()?(a("work arrived while closing admission; reopening and abandoning this upgrade attempt"),this.options.reopenLifecycleAdmission?.(),"busy-again"):(a("all tasks completed, proceeding with restart"),"idle"))}checkRateLimit(e){const t=ge();if(t.last_failure_at){const u=Date.now()-new Date(t.last_failure_at).getTime();if(u<ie)return m.info("upgrade",`In cooldown, ${(ie-u)/6e4}m remaining`),!1}const r=t.version_attempts[e]??0;if(r>=qe)return m.info("upgrade",`Version ${e} already tried ${r} times, skipping`),!1;const i=_e(),n=t.daily_attempts[i]??0;return n>=xe?(m.info("upgrade",`Already ${n} attempts today, skipping`),!1):!0}recordFailure(e){const t=ge(),r=_e();t.last_failure_at=new Date().toISOString(),t.last_failure_version=e,t.daily_attempts[r]=(t.daily_attempts[r]??0)+1,t.version_attempts[e]=(t.version_attempts[e]??0)+1;for(const n of Object.keys(t.daily_attempts))n<r&&delete t.daily_attempts[n];const i=Object.keys(t.version_attempts);for(const n of i.slice(0,Math.max(0,i.length-Fe)))n!==e&&delete t.version_attempts[n];rt(t)}async queryUpgrade(e){const r=`${pe(e.wsUrl)}/v1/agent-api/upgrade/check?`+new URLSearchParams({client_type:"grix-connector",client_version:A(),channel:e.channel??"stable",platform:process.platform,arch:process.arch}).toString();try{const i=await fetch(r,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(ne)});if(!i.ok)return m.warn("upgrade",`Check API returned ${i.status}`),{available:!1};const n=await i.json();return n.code!==0?{available:!1}:n.data}catch(i){return m.warn("upgrade",`Check API error: ${i instanceof Error?i.message:i}`),{available:!1}}}async reportUpgrade(e){if(this.agentConfigs.length===0)return!1;const t={client_type:"grix-connector",...e.npm_version?e:{...e,...Ae()}};return(await Promise.all(this.agentConfigs.map(async i=>{const u=`${pe(i.wsUrl)}/v1/agent-api/upgrade/report`;try{return(await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${i.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(ne)})).ok}catch{return!1}}))).some(i=>i)}startGuardian(){const e=_(y.base,"bin","upgrade-guardian.sh");if(process.platform==="win32"||!v(e)){m.info("upgrade","Guardian not available on this platform, skipping");return}const{stdio:t,logFd:r}=ue();try{const i=H(e,[],{detached:!0,stdio:t});i.unref(),a(`guardian started (pid ${i.pid})`)}catch(i){m.warn("upgrade",`Failed to start guardian: ${i instanceof Error?i.message:i}`)}finally{if(r!==void 0)try{C(r)}catch{}}}}export{mt as UpgradeChecker};
3
+ ${f}`:"")}}else if(n&&n.to_version===r&&$(t,"current")===r){a(`daemon startup: running switched target ${r}, upgrade succeeded`);const l=await this.confirmHealthz(oe);a(l?"healthz confirmed healthy, reporting success":"healthz not confirmed within window; reporting success on version-match"),_={from_version:n.from_version,to_version:n.to_version,status:"success"}}else if(n&&n.from_version===r&&n.switched===!1){a(`daemon startup: switch record for ${n.to_version} was never applied; discarding`);try{T(O(t),{force:!0})}catch{}try{T(L(t),{force:!0})}catch{}return}else if(n&&n.from_version===r)a(`daemon startup: expected ${n.to_version} but ${r} is running; reporting rolled_back`),this.recordFailure(n.to_version),_={from_version:n.from_version,to_version:n.to_version,status:"rolled_back",error_code:"STARTUP_CRASH",error_msg:`Launcher is running ${r} instead of switched target ${n.to_version}`};else{a(`daemon startup: launcher records do not match this process (self=${r} current=${$(t,"current")??"<none>"} previous=${$(t,"previous")??"<none>"} switch=${n?`${n.from_version}->${n.to_version}/switched=${n.switched!==!1}`:"<none>"} rollback=${o?`${o.to_version}->${o.from_version}`:"<none>"}); discarding records without pruning`),d();return}if(await this.reportUpgrade(_)){p();return}(async()=>{for(let l=2;l<=C;l++){if(this.stopped||(await new Promise(f=>setTimeout(f,se*(l-1)+Math.floor(Math.random()*1e3))),this.stopped))return;if(await this.reportUpgrade(_))break}p()})()}async waitUntilIdle(){if(this.isBusy?.()){a(`active tasks detected, waiting up to ${Math.round(H/6e4)}min until idle before restart (admission stays open while waiting)`);const e=Date.now()+H,t=5e3,r=600*1e3;let i=Date.now();for(;this.isBusy()&&!this.stopped;){if(Date.now()>=e)return v.warn("upgrade",`Idle wait exceeded ${Math.round(H/6e4)}min; abandoning this upgrade attempt. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),a("idle wait timed out; upgrade attempt abandoned without ever closing admission"),"timeout";await new Promise(s=>setTimeout(s,t)),Date.now()-i>=r&&(i=Date.now(),a("still waiting for active tasks to finish before restart"))}}return this.stopped?"stopped":(this.closeAdmission?.(),this.isBusy?.()?(a("work arrived while closing admission; reopening and abandoning this upgrade attempt"),this.options.reopenLifecycleAdmission?.(),"busy-again"):(a("all tasks completed, proceeding with restart"),"idle"))}checkRateLimit(e){const t=ge();if(t.last_failure_at){const u=Date.now()-new Date(t.last_failure_at).getTime();if(u<ie)return v.info("upgrade",`In cooldown, ${(ie-u)/6e4}m remaining`),!1}const r=t.version_attempts[e]??0;if(r>=Fe)return v.info("upgrade",`Version ${e} already tried ${r} times, skipping`),!1;const i=_e(),s=t.daily_attempts[i]??0;return s>=xe?(v.info("upgrade",`Already ${s} attempts today, skipping`),!1):!0}recordFailure(e){const t=ge(),r=_e();t.last_failure_at=new Date().toISOString(),t.last_failure_version=e,t.daily_attempts[r]=(t.daily_attempts[r]??0)+1,t.version_attempts[e]=(t.version_attempts[e]??0)+1;for(const s of Object.keys(t.daily_attempts))s<r&&delete t.daily_attempts[s];const i=Object.keys(t.version_attempts);for(const s of i.slice(0,Math.max(0,i.length-qe)))s!==e&&delete t.version_attempts[s];at(t)}async queryUpgrade(e){const r=`${pe(e.wsUrl)}/v1/agent-api/upgrade/check?`+new URLSearchParams({client_type:"grix-connector",client_version:A(),channel:e.channel??"stable",platform:process.platform,arch:process.arch}).toString();try{const i=await fetch(r,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(ne)});if(!i.ok)return v.warn("upgrade",`Check API returned ${i.status}`),{available:!1};const s=await i.json();return s.code!==0?{available:!1}:s.data}catch(i){return v.warn("upgrade",`Check API error: ${i instanceof Error?i.message:i}`),{available:!1}}}async reportUpgrade(e){if(this.agentConfigs.length===0)return!1;const t={client_type:"grix-connector",...e.npm_version?e:{...e,...ke()}};return(await Promise.all(this.agentConfigs.map(async i=>{const u=`${pe(i.wsUrl)}/v1/agent-api/upgrade/report`;try{return(await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${i.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(ne)})).ok}catch{return!1}}))).some(i=>i)}startGuardian(){const e=w(y.base,"bin","upgrade-guardian.sh");if(process.platform==="win32"||!m(e)){v.info("upgrade","Guardian not available on this platform, skipping");return}const{stdio:t,logFd:r}=ue();try{const i=q(e,[],{detached:!0,stdio:t});i.unref(),a(`guardian started (pid ${i.pid})`)}catch(i){v.warn("upgrade",`Failed to start guardian: ${i instanceof Error?i.message:i}`)}finally{if(r!==void 0)try{x(r)}catch{}}}}export{wt as UpgradeChecker};
@@ -1,2 +1,2 @@
1
- import{cpSync as w,existsSync as l,mkdirSync as f,readdirSync as x,readFileSync as i,renameSync as S,rmSync as a,writeFileSync as y}from"node:fs";import{join as o}from"node:path";const m="launcher.mjs",b=75,V=76,C=/LAUNCHER_TEMPLATE_VERSION\s*=\s*(\d+)/;function v(r){return o(r,m)}function g(r,t){return o(r,"versions",t)}function L(r,t){return o(g(r,t),"dist","grix.js")}function O(r,t){return o(r,"health",`${t}.ok`)}function E(r){return o(r,"upgrade.json")}function P(r){return o(r,"rollback.json")}function d(r,t){try{return i(o(r,t),"utf8").trim()||null}catch{return null}}function p(r,t){const e=`${r}.tmp-${process.pid}`;y(e,t,"utf8"),S(e,r)}function R(r,t,e){f(r,{recursive:!0}),p(o(r,t),`${e}
2
- `)}function N(r){try{const t=i(r,"utf8").match(C);return t?Number(t[1]):0}catch{return-1}}function T(r){for(const t of[o(r,"scripts",m),o(r,"dist",m)])if(l(t))return t;return null}function j(r,t){const e=T(t);if(!e)return!1;const n=v(r),c=N(e);return N(n)>=c||(f(r,{recursive:!0}),p(n,i(e,"utf8"))),!0}function M(r,t,e){const n=g(r,e);if(l(L(r,e)))return n;const c=`${n}.staging-${process.pid}`;a(c,{recursive:!0,force:!0}),f(c,{recursive:!0});try{for(const s of["package.json","dist","node_modules","scripts"]){const u=o(t,s);l(u)&&w(u,o(c,s),{recursive:!0,force:!0})}a(n,{recursive:!0,force:!0}),S(c,n)}finally{a(c,{recursive:!0,force:!0})}return n}function U(r,t){const e=d(r,"current");return e&&e!==t&&R(r,"previous",e),R(r,"current",t),e}function X(r,t){p(E(r),JSON.stringify(t))}function F(r){return _(E(r))}function J(r){return _(P(r))}function _(r){try{return JSON.parse(i(r,"utf8"))}catch{return null}}function G(r){try{y(o(r,"managed-stop"),new Date().toISOString(),"utf8")}catch{}}function B(r,t){f(o(r,"health"),{recursive:!0}),p(O(r,t),new Date().toISOString())}function Y(r){const t=new Set([d(r,"current"),d(r,"previous")].filter(Boolean)),e=o(r,"versions"),n=[];let c=[];try{c=x(e)}catch{return n}for(const u of c)if(!t.has(u))try{a(o(e,u),{recursive:!0,force:!0}),n.push(u)}catch{}const s=o(r,"health");try{for(const u of x(s)){const h=u.replace(/\.ok$/,"");t.has(h)||a(o(s,u),{force:!0})}}catch{}return n}function q(r=process.env){if(r.GRIX_LAUNCHER_MANAGED!=="1")return null;const t=String(r.GRIX_LAUNCHER_STORE??"").trim();return t&&l(v(t))?t:null}function z(r,t){const e=s=>{const[u,h]=s.replace(/^v(?=\d)/,"").split("-",2);return{nums:u.split(".").map(A=>Number.parseInt(A,10)||0),pre:h??""}},n=e(r),c=e(t);for(let s=0;s<Math.max(n.nums.length,c.nums.length);s+=1){const u=(n.nums[s]??0)-(c.nums[s]??0);if(u!==0)return u<0?-1:1}return n.pre===c.pre?0:n.pre?c.pre?n.pre<c.pre?-1:1:-1:1}const I=4096;function k(r,t){return o(r,"crashes",`${t}.txt`)}function K(r,t,e){try{f(o(r,"crashes"),{recursive:!0});const n=`[${new Date().toISOString()}] ${e}`.slice(0,I);p(k(r,t),n)}catch{}}function Q(r,t){const e=k(r,t);try{const n=i(e,"utf8").trim();return a(e,{force:!0}),n||null}catch{return null}}function W(r){try{const t=JSON.parse(i(o(r,"package.json"),"utf8"));return typeof t.version=="string"?t.version.replace(/^v(?=\d)/,""):null}catch{return null}}export{m as LAUNCHER_FILE,b as RESTART_EXIT_CODE,V as UNHEALTHY_EXIT_CODE,M as bootstrapVersionFromPackage,z as compareVersions,k as crashNotePath,j as ensureLauncher,O as healthMarkerPath,v as launcherPath,B as markHealthy,G as markManagedStop,T as packagedLauncherPath,Y as pruneVersions,N as readLauncherTemplateVersion,W as readPackageVersionAt,d as readPointer,J as readRollbackRecord,F as readSwitchRecord,q as resolveLauncherStore,P as rollbackRecordPath,U as switchCurrent,E as switchRecordPath,Q as takeCrashNote,g as versionDir,L as versionEntry,K as writeCrashNote,R as writePointer,X as writeSwitchRecord};
1
+ import{cpSync as C,existsSync as d,mkdirSync as p,readdirSync as v,readFileSync as a,renameSync as g,rmSync as f,writeFileSync as R}from"node:fs";import{dirname as I,isAbsolute as O,join as o,relative as P}from"node:path";import{fileURLToPath as T}from"node:url";const x="launcher.mjs",J=75,B=76,V=/LAUNCHER_TEMPLATE_VERSION\s*=\s*(\d+)/;function y(r){return o(r,x)}function E(r,t){return o(r,"versions",t)}function H(r,t){return o(E(r,t),"dist","grix.js")}function $(r,t){return o(r,"health",`${t}.ok`)}function N(r){return o(r,"upgrade.json")}function b(r){return o(r,"rollback.json")}function S(r,t){try{return a(o(r,t),"utf8").trim()||null}catch{return null}}function l(r,t){const e=`${r}.tmp-${process.pid}`;R(e,t,"utf8"),g(e,r)}function _(r,t,e){p(r,{recursive:!0}),l(o(r,t),`${e}
2
+ `)}function A(r){try{const t=a(r,"utf8").match(V);return t?Number(t[1]):0}catch{return-1}}function U(r){for(const t of[o(r,"scripts",x),o(r,"dist",x)])if(d(t))return t;return null}function W(r,t){const e=U(t);if(!e)return!1;const n=y(r),c=A(e);return A(n)>=c||(p(r,{recursive:!0}),l(n,a(e,"utf8"))),!0}function Y(r,t,e){const n=E(r,e);if(d(H(r,e)))return n;const c=`${n}.staging-${process.pid}`;f(c,{recursive:!0,force:!0}),p(c,{recursive:!0});try{for(const u of["package.json","dist","node_modules","scripts"]){const s=o(t,u);d(s)&&C(s,o(c,u),{recursive:!0,force:!0})}f(n,{recursive:!0,force:!0}),g(c,n)}finally{f(c,{recursive:!0,force:!0})}return n}function q(r,t){const e=S(r,"current");return e&&e!==t&&_(r,"previous",e),_(r,"current",t),e}function z(r,t){l(N(r),JSON.stringify(t))}function K(r){return k(N(r))}function Q(r){return k(b(r))}function k(r){try{return JSON.parse(a(r,"utf8"))}catch{return null}}function Z(r){try{R(o(r,"managed-stop"),new Date().toISOString(),"utf8")}catch{}}function D(r,t){p(o(r,"health"),{recursive:!0}),l($(r,t),new Date().toISOString())}function j(r,t=process.env){const e=I(T(import.meta.url)),n=P(o(r,"versions"),e);if(n&&!n.startsWith("..")&&!O(n)){const[u]=n.split(/[\\/]/);if(u)return u}return String(t.GRIX_LAUNCHER_VERSION??"").trim()||null}function rr(r,t=process.env){const e=j(r,t),n=[S(r,"current"),S(r,"previous")].filter(Boolean);if(n.length===0&&!e)return[];const c=new Set([...n,e].filter(Boolean)),u=o(r,"versions"),s=[];let h=[];try{h=v(u)}catch{return s}for(const i of h)if(!c.has(i))try{f(o(u,i),{recursive:!0,force:!0}),s.push(i)}catch{}const m=o(r,"health");try{for(const i of v(m)){const w=i.replace(/\.ok$/,"");c.has(w)||f(o(m,i),{force:!0})}}catch{}return s}function tr(r=process.env){if(r.GRIX_LAUNCHER_MANAGED!=="1")return null;const t=String(r.GRIX_LAUNCHER_STORE??"").trim();return t&&d(y(t))?t:null}function er(r,t){const e=u=>{const[s,h]=u.replace(/^v(?=\d)/,"").split("-",2);return{nums:s.split(".").map(m=>Number.parseInt(m,10)||0),pre:h??""}},n=e(r),c=e(t);for(let u=0;u<Math.max(n.nums.length,c.nums.length);u+=1){const s=(n.nums[u]??0)-(c.nums[u]??0);if(s!==0)return s<0?-1:1}return n.pre===c.pre?0:n.pre?c.pre?n.pre<c.pre?-1:1:-1:1}const M=4096;function L(r,t){return o(r,"crashes",`${t}.txt`)}function nr(r,t,e){try{p(o(r,"crashes"),{recursive:!0});const n=`[${new Date().toISOString()}] ${e}`.slice(0,M);l(L(r,t),n)}catch{}}function or(r,t){const e=L(r,t);try{const n=a(e,"utf8").trim();return f(e,{force:!0}),n||null}catch{return null}}function cr(r){try{const t=JSON.parse(a(o(r,"package.json"),"utf8"));return typeof t.version=="string"?t.version.replace(/^v(?=\d)/,""):null}catch{return null}}export{x as LAUNCHER_FILE,J as RESTART_EXIT_CODE,B as UNHEALTHY_EXIT_CODE,Y as bootstrapVersionFromPackage,er as compareVersions,L as crashNotePath,W as ensureLauncher,$ as healthMarkerPath,y as launcherPath,D as markHealthy,Z as markManagedStop,U as packagedLauncherPath,rr as pruneVersions,A as readLauncherTemplateVersion,cr as readPackageVersionAt,S as readPointer,Q as readRollbackRecord,K as readSwitchRecord,tr as resolveLauncherStore,j as resolveRunningVersion,b as rollbackRecordPath,q as switchCurrent,N as switchRecordPath,or as takeCrashNote,E as versionDir,H as versionEntry,nr as writeCrashNote,_ as writePointer,z as writeSwitchRecord};
@@ -1 +1 @@
1
- import{existsSync as i,readFileSync as s}from"node:fs";import o from"node:path";const c="0.1.0",a="grix-connector";function m(n=process.env){return p()??t(n.npm_package_version)??c}function p(){for(const n of u())if(i(n))try{const e=JSON.parse(s(n,"utf8"));if(typeof e.name=="string"&&e.name!==a)continue;const r=t(e.version);if(r)return r}catch{continue}return null}function u(){const n=[];let e=import.meta.dirname??__dirname;for(;;){n.push(o.join(e,"package.json"));const r=o.dirname(e);if(r===e)break;e=r}return n.push(o.resolve(process.cwd(),"package.json")),n}function t(n){if(typeof n!="string")return null;const e=n.trim();return e===""?null:e}export{m as resolveClientVersion};
1
+ import{existsSync as c,readFileSync as a}from"node:fs";import e from"node:path";import{fileURLToPath as u}from"node:url";const l="0.1.0",f="grix-connector";let t=null;function C(n=process.env){if(t)return t;const r=p()??o(n.GRIX_LAUNCHER_MANAGED==="1"?n.GRIX_LAUNCHER_VERSION:void 0)??m()??o(n.npm_package_version);return r?(t=r,r):l}function V(){t=null}function s(n){if(!c(n))return null;try{const r=JSON.parse(a(n,"utf8"));return typeof r.name=="string"&&r.name!==f?null:o(r.version)}catch{return null}}function p(){let n=e.dirname(u(import.meta.url));for(;;){const r=s(e.join(n,"package.json"));if(r)return r;const i=e.dirname(n);if(i===n)return null;n=i}}function m(){return s(e.resolve(process.cwd(),"package.json"))}function o(n){if(typeof n!="string")return null;const r=n.trim();return r===""?null:r}export{V as resetClientVersionCache,C as resolveClientVersion};
@@ -1 +1 @@
1
- function a(t){const o=new Set([`http://127.0.0.1:${t.serverPort}`,`http://localhost:${t.serverPort}`,...t.allowedOrigins]),e=new Set([`127.0.0.1:${t.serverPort}`,`localhost:${t.serverPort}`,...t.allowedHosts]);return{validateRequest(s){const r=i(s,o);if(!r.ok)return r;const n=l(s,e);return n.ok?{ok:!0}:n}}}function i(t,o){const e=t.headers.origin;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${e}`}:{ok:!0}}function l(t,o){const e=t.headers.host;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${e}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
1
+ function a(o){const e=new Set([`http://127.0.0.1:${o.serverPort}`,`http://localhost:${o.serverPort}`,...o.allowedOrigins]),t=new Set([`127.0.0.1:${o.serverPort}`,`localhost:${o.serverPort}`,...o.allowedHosts]);return{validateRequest(s){const r=i(s,e);if(!r.ok)return r;const n=l(s,t);return n.ok?{ok:!0}:n}}}function i(o,e){const t=o.headers.origin;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${t}`}:{ok:!0}}function l(o,e){const t=o.headers.host;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${t}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "4.7.0",
3
+ "version": "4.7.2",
4
4
  "description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",