grix-connector 4.6.0 → 4.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/dsh-bridge/{grix-dsh-bridge-4.6.0.tgz → grix-dsh-bridge-4.6.1.tgz} +0 -0
- package/dist/assets/dsh-bridge/manifest.json +5 -5
- package/dist/core/upgrade/upgrade-checker.js +3 -1
- package/dist/core/upgrade/version-store.js +2 -2
- package/dist/grix.js +7 -7
- package/dist/mcp/stream-http/security.js +1 -1
- package/package.json +1 -1
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.6.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.6.
|
|
5
|
-
"size":
|
|
3
|
+
"bridgeVersion": "4.6.1",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.6.1.tgz",
|
|
5
|
+
"size": 23090,
|
|
6
6
|
"unpackedSize": 92668,
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
7
|
+
"shasum": "86e1995131371aaf4b84a4a4879eea61c34829c7",
|
|
8
|
+
"integrity": "sha512-BeWE/LIVXFZy1NxAcUfWu5+5rX8skUxQEYnLeACwRj+x+kCgpZEF9xQ6OwwsZqfFLe2fZpW61IQEi/2b1aER8g=="
|
|
9
9
|
}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{closeSync as O,existsSync as v,mkdirSync as L,openSync as ge,readFileSync as R,realpathSync as _e,renameSync as me,writeFileSync as we}from"node:fs";import{join as g,dirname as ve}from"node:path";import{spawn as C}from"node:child_process";import{log as _}from"../log/index.js";import{GRIX_PATHS as m}from"../log/index.js";import{resolveClientVersion as A}from"../util/client-version.js";import{UpgradeError as b,armWindowsUpgradeHandoff as W,archivePendingJournal as ye,armWindowsUpgradeRollback as be,cleanupPendingBackup as H,collectEnvInfo as Se,discardPendingStaging as I,finalizePendingTransaction as x,getUpgradeLogTail as $,isVersionAvailable as F,npmInstall as Te,normalizeUpgradeVersion as Ae,pendingExists as q,preflightCheck as B,readPending as U,readPendingPackageVersion as j,removeWindowsHandoffFiles as z,rollbackPendingInstall as ke,updatePending as D,upgradeLog as n,verifyInstalledVersion as Pe,writePending as Re}from"./npm-upgrader.js";import{isRetriableRegistryError as K,isTransientInstallError as X}from"../installer/npm-registry.js";import{installVersionIntoStore as $e}from"./npm-upgrader.js";import{ensureLauncher as Ee,markHealthy as Ie,pruneVersions as Ue,readPointer as Y,readRollbackRecord as De,readSwitchRecord as Ne,resolveLauncherStore as J,rollbackRecordPath as V,switchCurrent as Me,switchRecordPath as Z,versionDir as Q,versionEntry as Ge,writeSwitchRecord as ee}from"./version-store.js";import{rmSync as k}from"node:fs";import{randomUUID as Oe}from"node:crypto";const Le=360*60*1e3,Ce=300*1e3,te=1800*1e3,We=2,He=3,xe=10,E="grix-connector",re=1e4,N=15,ie=2e3,ae=8e3,Fe=1e3,qe=2e3,Be=120*1e3,ne=1e4,je=6e4,ze=3,Ke=600*1e3,Xe=9e4,Ye=3e4,Je=new Set(["preparing","staged","handoff_ready","activating","verifying","healthy","rolling_back","rolled_back","finalizing","failed"]),se=600*1e3,M=1800*1e3;function G(d,e=se){const t=Date.parse(d.activation_started_at??d.upgraded_at??"");return Number.isNaN(t)?!0:Date.now()-t>e}function oe(d){const e=Date.parse(d.verification_started_at??d.activation_started_at??"");return Number.isNaN(e)||Date.now()-e>Be}function Ve(d){if((d.guardian_handback_count??0)>=ze)return!1;const e=Date.parse(d.guardian_handback_at??"");return Number.isNaN(e)?!0:Date.now()-e>=Ke}function Ze(d){if(!Number.isInteger(d)||(d??0)<=0)return!1;try{return process.kill(d,0),!0}catch{return!1}}function ce(d){try{return _e(d)}catch{return d}}function de(){try{L(g(m.base,"log"),{recursive:!0});const d=ge(g(m.base,"log","upgrade.log"),"a");return{stdio:["ignore",d,d],logFd:d}}catch{return{stdio:"ignore"}}}function P(){const d=g(m.base,"bin"),e=g(d,"upgrade-guardian.mjs");if(v(e))return ce(e);const t=g(d,"upgrade-guardian.fallback.mjs");return v(t)?ce(t):null}function le(d){if(!Ze(d.guardian_pid))return!1;try{const t=JSON.parse(R(g(m.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<=ne)return!0}catch{}const e=Date.parse(d.guardian_started_at??"");return Number.isFinite(e)&&Date.now()-e<=ne}function ue(d){return new URL(d.replace(/^wss:/,"https:").replace(/^ws:/,"http:")).origin}function he(){return g(m.data,"upgrade-state.json")}function pe(){const d=he();if(!v(d))return{daily_attempts:{},version_attempts:{}};try{return JSON.parse(R(d,"utf-8"))}catch{return{daily_attempts:{},version_attempts:{}}}}function Qe(d){const e=he();L(ve(e),{recursive:!0});const t=e+".tmp";we(t,JSON.stringify(d),"utf-8"),me(t,e)}function fe(){return new Date().toISOString().slice(0,10)}class ft{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,a={}){this.agentConfigs=e,this.isBusy=t,this.closeAdmission=r,this.options=a}async start(){await this.handleLauncherStartup(),await this.handlePendingOnStartup(),this.initialTimer=setTimeout(()=>{this.stopped||(this.runCheck(),!this.stopped&&(this.timer=setInterval(()=>this.runCheck(),Le)))},Ce)}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(!q())return;let e=U();if(!e){n("daemon startup: pending journal is unreadable; preserving it and blocking automatic upgrade for manual recovery");return}if(e.phase&&!Je.has(e.phase)&&(e=D({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)||(n(`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 o=!!(e.wrapper_pause_file&&v(e.wrapper_pause_file));if(e.phase==="staged"&&o){this.schedulePendingReconcile();return}I(e),e=D({phase:"rolled_back",error_code:"UPGRADE_INTERRUPTED",error_msg:"Upgrade stopped before Windows activation started"})}if(e.phase==="verifying"){if(le(e)&&!oe(e)){this.schedulePendingReconcile();return}if(oe(e)&&e.transaction_id&&["win32","darwin"].includes(this.options.platform??process.platform)&&this.options.requestGracefulShutdown){const o=`Target ${e.target_version} did not become healthy before the Windows verification deadline`;be(e.transaction_id,o),n(`${o}; 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(le(e)){this.logGuardianWait(e),this.schedulePendingReconcile();return}if(G(e)&&e.transaction_id&&(this.options.platform??process.platform)==="win32"&&this.options.requestGracefulShutdown&&Ve(e)){const o=`Guardian did not settle ${e.phase} for ${e.target_version} before the Windows activation deadline`;D({guardian_handback_count:(e.guardian_handback_count??0)+1,guardian_handback_at:new Date().toISOString()},e.transaction_id),n(`${o}; requesting graceful shutdown so the wrapper re-runs the guardian`),await this.options.requestGracefulShutdown("upgrade");return}if(G(e))n(`daemon startup: guardian did not settle ${e.phase} for ${e.target_version} and cannot be resumed; collapsing the transaction by version verdict`),z(),I(e);else{await this.resumeWindowsGuardian(),this.logGuardianWait(e),this.schedulePendingReconcile();return}}if(e.phase==="failed"){const o=j(e),f=A();if(!o||o!==f){n(`daemon startup: upgrade transaction requires manual recovery: ${e.error_msg??e.error_code??"unknown error"} (runtime=${f}, active package=${o??"unknown"})`);return}const S=ye(e);n(`daemon startup: failed transaction ${e.transaction_id??"legacy"} (${e.error_code??"unknown error"}) is converging on the runnable ${f}${S?`; diagnostics kept at ${S}`:""}`)}const r=j(e),a=A(),i=e.phase==="healthy",s=e.phase==="rolled_back",u=!r||r===e.target_version,l=i?a===e.target_version&&r===e.target_version:!s&&a===e.target_version&&u;if(!l&&u&&!s){if(!G(e)){if((this.options.platform??process.platform)!=="win32"&&r===e.target_version){const o=e.transaction_id??`${e.target_version}@${e.upgraded_at}`;this.posixGuardianResumeAttempted.has(o)||(this.posixGuardianResumeAttempted.add(o),n(`resuming POSIX guardian for stalled activation of ${e.target_version}`),this.startGuardian())}this.logThrottled("posix-activation-wait",`daemon startup: runtime ${a} is waiting for guardian activation of ${e.target_version} (active package=${r??"unknown"})`),this.schedulePendingReconcile();return}n(`daemon startup: activation wait for ${e.target_version} expired (> ${se/6e4}min); no guardian will finish the switch, reporting by version verdict`)}const c=l?{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(n(l?`daemon startup: version matches target ${e.target_version}, upgrade succeeded`:`daemon startup: runtime=${a}, active package=${r??"unknown"}, target=${e.target_version}; rolled back`),!l){const o=e.transaction_id??`${e.target_version}@${e.upgraded_at}`;this.recordedRollbackFailures.has(o)||(this.recordedRollbackFailures.add(o),this.recordFailure(e.target_version))}if(l){const o=await this.confirmHealthz(ae,i?e.target_version:void 0,i?e.old_pid:void 0,i?e.activation_started_at:void 0);if(i&&!o){n("guardian marked healthy but target-version healthz is not yet observable; retrying reconciliation"),this.schedulePendingReconcile();return}n(o?"healthz confirmed healthy, reporting success":"healthz not confirmed within window; reporting success on version-match (guardian still guards crashes)")}if(!H(e)){n(`terminal transaction ${e.transaction_id??"legacy"} is waiting for antivirus-held artifact cleanup`),this.schedulePendingReconcile();return}if(await this.reportUpgrade(c)){this.settleTransaction(e)||(n(`terminal transaction ${e.transaction_id??"legacy"} could not release its shared lock; retrying reconciliation`),this.schedulePendingReconcile());return}this.retryStartupReport(c,e,!1)}settleTransaction(e){if(!x(e))return!1;try{this.options.onTransactionSettled?.()}catch(t){n(`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=>{_.warn("upgrade",`Pending reconciliation failed: ${e instanceof Error?e.message:e}`),this.schedulePendingReconcile()})},qe))}logThrottled(e,t){const r=Date.now();e===this.guardianWaitLoggedPhase&&r-this.guardianWaitLoggedAt<je||(this.guardianWaitLoggedPhase=e,this.guardianWaitLoggedAt=r,n(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=P();if(!e)return;const{stdio:t,logFd:r}=de();try{C(process.execPath,[e,"activate","--root",m.base],{detached:!0,stdio:t,windowsHide:!0}).unref()}finally{if(r!==void 0)try{O(r)}catch{}}}async retryStartupReport(e,t,r){const a=t?.transaction_id,i=()=>{const s=U();if(!(a&&s?.transaction_id!==a)){if(r&&!H(t)){n(`terminal backup cleanup is still blocked for ${a??"legacy transaction"}`),this.schedulePendingReconcile();return}this.settleTransaction(t)||(n(`terminal shared lock release is still blocked for ${a??"legacy transaction"}`),this.schedulePendingReconcile())}};for(let s=2;s<=N;s++){if(this.stopped)return;const u=ie*(s-1)+Math.floor(Math.random()*1e3);if(await new Promise(l=>setTimeout(l,u)),this.stopped)return;if(await this.reportUpgrade(e)){i();return}}n(`startup report (${e.status}) not delivered after ${N} attempts; clearing pending to unblock future checks`),i()}async confirmHealthz(e,t,r,a){let i="19579";try{const l=g(m.data,"health-port");v(l)&&(i=R(l,"utf-8").trim()||i)}catch{}const s=`http://127.0.0.1:${i}/healthz`,u=Date.now()+e;for(;Date.now()<u&&!this.stopped;){try{const l=await fetch(s,{signal:AbortSignal.timeout(2e3)});if(l.ok){if(!t)return!0;const c=await l.json();if(c.status==="ok"&&c.version===t&&typeof c.pid=="number"&&c.pid>0&&c.pid!==r)try{const o=JSON.parse(R(g(m.base,"daemon-status.json"),"utf-8")),f=Date.parse(a??"");return!!(o.state==="running"&&o.pid===c.pid&&typeof o.updated_at=="number"&&Number.isFinite(f)&&o.updated_at>=f)}catch{return!1}}}catch{}await new Promise(l=>setTimeout(l,Fe))}return!1}async runCheck(){if(!this.running){this.running=!0;try{await this.check()}catch(e){_.error("upgrade",`Check failed: ${e instanceof Error?e.message:e}`)}finally{this.running=!1}}}async check(){if(q()){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 a=A();let i;try{i=Ae(r.version)}catch(h){const p=h;await this.reportUpgrade({from_version:a,to_version:String(r.version),status:"failed",error_code:p.code??"INVALID_VERSION",error_msg:p.message});return}const s=r.force,u=this.options.platform??process.platform,l=this.options.env??process.env,c=J(l);if(c&&this.options.requestGracefulShutdown){await this.runLauncherUpgrade(c,a,i,!!s);return}if(u==="win32"){const h=P(),p=l.GRIX_WRAPPER_SUPERVISED==="1";if(!p||!h||!this.options.requestGracefulShutdown){const w=`Windows automatic upgrade requires a refreshed service installation (${[...p?[]:["managed wrapper"],...h?[]:["external guardian"],...this.options.requestGracefulShutdown?[]:["graceful shutdown hook"]].join(", ")})`;n(w),await this.reportUpgrade({from_version:a,to_version:i,status:"failed",error_code:"WINDOWS_UPGRADE_UNSUPPORTED",error_msg:w});return}}const o=u==="darwin"&&!!P()&&!!this.options.requestGracefulShutdown;if(u==="darwin"&&!o&&n("macOS transactional upgrade prerequisites missing; falling back to the legacy guardian flow"),!s&&!this.checkRateLimit(i))return;const f=B();if(!f.ok){await this.reportUpgrade({from_version:a,to_version:i,status:"failed",error_code:f.errorCode,error_msg:f.errorMsg});return}if(!await F(E,i)){n(`target ${i} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}n(`upgrade start: ${a} -> ${i}`);const S=Date.now();let y;try{y=Re(a,i,u==="win32"||o?"preparing":void 0).transaction_id,(await Te(E,i,void 0,o?{activationMode:"staged"}:{}))?.activationRequired||Pe(i),n("npm install verified, reporting installed"),await this.reportUpgrade({from_version:a,to_version:i,status:"installed",duration_ms:Date.now()-S}),n("shutting down for restart");const p=await this.waitUntilIdle();if(p!=="idle")throw n(`upgrade aborted before lifecycle handoff: ${p}`),this.options.reopenLifecycleAdmission?.(),new b("UPGRADE_ABORTED",`Upgrade was aborted before lifecycle handoff (${p})`);if(u==="win32"){if(!P())throw new b("WINDOWS_UPGRADE_UNSUPPORTED","Windows external guardian disappeared before lifecycle handoff");W(process.pid,y),n("Windows handoff armed; requesting graceful daemon shutdown"),await this.options.requestGracefulShutdown("upgrade")}else if(o){if(!P())throw new b("MACOS_UPGRADE_UNSUPPORTED","macOS guardian helper disappeared before lifecycle handoff");W(process.pid,y),n("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 p=h instanceof b?h.code:"NPM_INSTALL_FAILED",T=h instanceof Error?h.message:String(h);n(`upgrade failed: ${p} ${T}`);const w=U();if(y&&w?.transaction_id===y&&(u==="win32"||o?(z(),I(w)):ke(w)&&n("upgrade failed before restart; previous package restored atomically"),x(w)||(n(`failed transaction ${y} is waiting for shared lock release`),this.schedulePendingReconcile()),this.options.reopenLifecycleAdmission?.()),p==="UPGRADE_IN_PROGRESS")return;K(T)||X(T)||p==="NPM_TIMEOUT"?n(`failure is retriable (${p}); skipping cooldown, will retry next cycle`):this.recordFailure(i),await this.reportUpgrade({from_version:a,to_version:i,status:"failed",error_code:p,error_msg:T,duration_ms:Date.now()-S,upgrade_log:$()})}}async runLauncherUpgrade(e,t,r,a){if(!a&&!this.checkRateLimit(r))return;const i=B();if(!i.ok){await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:i.errorCode,error_msg:i.errorMsg});return}if(!await F(E,r)){n(`target ${r} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}n(`launcher upgrade start: ${t} -> ${r} (store=${e})`);const s=Date.now();try{v(Ge(e,r))?n(`${r} already present in version store; skipping install`):await $e(e,E,r),await this.reportUpgrade({from_version:t,to_version:r,status:"installed",duration_ms:Date.now()-s});const u=await this.waitUntilIdle();if(u!=="idle")throw this.options.reopenLifecycleAdmission?.(),new b("UPGRADE_ABORTED",`Upgrade was aborted before lifecycle handoff (${u})`);const l={transaction_id:Oe(),from_version:t,to_version:r,started_at:new Date().toISOString()};ee(e,{...l,switched:!1}),Me(e,r),ee(e,{...l,switched:!0}),n(`current pointer switched to ${r}; requesting restart via launcher`),await this.options.requestGracefulShutdown("upgrade-switch")}catch(u){const l=u instanceof b?u.code:"NPM_INSTALL_FAILED",c=u instanceof Error?u.message:String(u);if(n(`launcher upgrade failed: ${l} ${c}`),l==="UPGRADE_ABORTED"){n("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:l,error_msg:c,duration_ms:Date.now()-s,upgrade_log:$()});return}if(Y(e,"current")!==r)try{k(Q(e,r),{recursive:!0,force:!0})}catch{}K(c)||X(c)||l==="NPM_TIMEOUT"?n(`failure is retriable (${l}); skipping cooldown, will retry next cycle`):this.recordFailure(r),await this.reportUpgrade({from_version:t,to_version:r,status:"failed",error_code:l,error_msg:c,duration_ms:Date.now()-s,upgrade_log:$()})}}async handleLauncherStartup(){const e=this.options.env??process.env,t=J(e);if(!t)return;const r=A();try{Ee(t,Q(t,r))}catch(c){n(`failed to refresh launcher: ${c instanceof Error?c.message:String(c)}`)}const a=c=>{this.healthyTimer=setTimeout(()=>{if(this.healthyTimer=null,!this.stopped){if(this.options.isConnected&&!this.options.isConnected()){n(`uptime reached but no agent websocket is ready yet; deferring health marker for ${r}`),a(Ye);return}try{Ie(t,r)}catch(o){n(`failed to write health marker: ${o instanceof Error?o.message:String(o)}`)}}},c),this.healthyTimer.unref?.()};a(Xe);const i=De(t),s=Ne(t);if(!i&&!s)return;const u=()=>{try{k(V(t),{force:!0})}catch{}try{k(Z(t),{force:!0})}catch{}const c=Ue(t);c.length>0&&n(`pruned version directories: ${c.join(", ")}`)};let l;if(i&&i.from_version===r){const c=`exit_code=${i.exit_code??"n/a"} crashes=${i.crash_count??"n/a"} uptime_ms=${i.uptime_ms??"n/a"}`;n(`daemon startup: launcher rolled back ${i.to_version} -> ${r} (${c})`),this.recordFailure(i.to_version),l={from_version:i.from_version,to_version:i.to_version,status:"rolled_back",error_code:"STARTUP_CRASH",error_msg:`Target ${i.to_version} crashed before becoming healthy (${c}); launcher restored ${r}`,crash_count:i.crash_count,upgrade_log:$()}}else if(s&&s.to_version===r&&Y(t,"current")===r){n(`daemon startup: running switched target ${r}, upgrade succeeded`);const c=await this.confirmHealthz(ae);n(c?"healthz confirmed healthy, reporting success":"healthz not confirmed within window; reporting success on version-match"),l={from_version:s.from_version,to_version:s.to_version,status:"success"}}else if(s&&s.from_version===r&&s.switched===!1){n(`daemon startup: switch record for ${s.to_version} was never applied; discarding`);try{k(Z(t),{force:!0})}catch{}try{k(V(t),{force:!0})}catch{}return}else if(s&&s.from_version===r)n(`daemon startup: expected ${s.to_version} but ${r} is running; reporting rolled_back`),this.recordFailure(s.to_version),l={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{n(`daemon startup: stale launcher records (self=${r}); discarding`),u();return}if(await this.reportUpgrade(l)){u();return}(async()=>{for(let c=2;c<=N;c++){if(this.stopped||(await new Promise(o=>setTimeout(o,ie*(c-1)+Math.floor(Math.random()*1e3))),this.stopped))return;if(await this.reportUpgrade(l))break}u()})()}async waitUntilIdle(){if(this.isBusy?.()){n(`active tasks detected, waiting up to ${Math.round(M/6e4)}min until idle before restart (admission stays open while waiting)`);const e=Date.now()+M,t=5e3,r=600*1e3;let a=Date.now();for(;this.isBusy()&&!this.stopped;){if(Date.now()>=e)return _.warn("upgrade",`Idle wait exceeded ${Math.round(M/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.`),n("idle wait timed out; upgrade attempt abandoned without ever closing admission"),"timeout";await new Promise(i=>setTimeout(i,t)),Date.now()-a>=r&&(a=Date.now(),n("still waiting for active tasks to finish before restart"))}}return this.stopped?"stopped":(this.closeAdmission?.(),this.isBusy?.()?(n("work arrived while closing admission; reopening and abandoning this upgrade attempt"),this.options.reopenLifecycleAdmission?.(),"busy-again"):(n("all tasks completed, proceeding with restart"),"idle"))}checkRateLimit(e){const t=pe();if(t.last_failure_at){const s=Date.now()-new Date(t.last_failure_at).getTime();if(s<te)return _.info("upgrade",`In cooldown, ${(te-s)/6e4}m remaining`),!1}const r=t.version_attempts[e]??0;if(r>=He)return _.info("upgrade",`Version ${e} already tried ${r} times, skipping`),!1;const a=fe(),i=t.daily_attempts[a]??0;return i>=We?(_.info("upgrade",`Already ${i} attempts today, skipping`),!1):!0}recordFailure(e){const t=pe(),r=fe();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 i of Object.keys(t.daily_attempts))i<r&&delete t.daily_attempts[i];const a=Object.keys(t.version_attempts);for(const i of a.slice(0,Math.max(0,a.length-xe)))i!==e&&delete t.version_attempts[i];Qe(t)}async queryUpgrade(e){const r=`${ue(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 a=await fetch(r,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(re)});if(!a.ok)return _.warn("upgrade",`Check API returned ${a.status}`),{available:!1};const i=await a.json();return i.code!==0?{available:!1}:i.data}catch(a){return _.warn("upgrade",`Check API error: ${a instanceof Error?a.message:a}`),{available:!1}}}async reportUpgrade(e){if(this.agentConfigs.length===0)return!1;const t={client_type:"grix-connector",...e.npm_version?e:{...e,...Se()}};return(await Promise.all(this.agentConfigs.map(async a=>{const s=`${ue(a.wsUrl)}/v1/agent-api/upgrade/report`;try{return(await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(re)})).ok}catch{return!1}}))).some(a=>a)}startGuardian(){const e=g(m.base,"bin","upgrade-guardian.sh");if(process.platform==="win32"||!v(e)){_.info("upgrade","Guardian not available on this platform, skipping");return}const{stdio:t,logFd:r}=de();try{const a=C(e,[],{detached:!0,stdio:t});a.unref(),n(`guardian started (pid ${a.pid})`)}catch(a){_.warn("upgrade",`Failed to start guardian: ${a instanceof Error?a.message:a}`)}finally{if(r!==void 0)try{O(r)}catch{}}}}export{ft as UpgradeChecker};
|
|
1
|
+
import{closeSync as O,existsSync as v,mkdirSync as C,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 W}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 H,archivePendingJournal as Se,armWindowsUpgradeRollback as Te,cleanupPendingBackup as x,collectEnvInfo as Ae,discardPendingStaging as I,finalizePendingTransaction as q,getUpgradeLogTail as $,isVersionAvailable as F,npmInstall as ke,normalizeUpgradeVersion as Re,pendingExists as B,preflightCheck as j,readPending as U,readPendingPackageVersion as z,removeWindowsHandoffFiles as K,rollbackPendingInstall as Pe,updatePending as D,upgradeLog as i,verifyInstalledVersion as $e,writePending as Ee}from"./npm-upgrader.js";import{isRetriableRegistryError as X,isTransientInstallError as Y}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 N,readRollbackRecord as Ge,readSwitchRecord as Le,resolveLauncherStore as J,rollbackRecordPath as V,switchCurrent as Oe,switchRecordPath as Z,takeCrashNote as Q,versionDir as ee,versionEntry as te,writeSwitchRecord as re}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,ae=1800*1e3,xe=2,qe=3,Fe=10,E="grix-connector",ie=1e4,M=15,ne=2e3,se=8e3,Be=1e3,je=2e3,ze=120*1e3,oe=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"]),ce=600*1e3,G=1800*1e3;function L(d,e=ce){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>ze}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{C(_(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<=oe)return!0}catch{}const e=Date.parse(d.guardian_started_at??"");return Number.isFinite(e)&&Date.now()-e<=oe}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();C(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,a={}){this.agentConfigs=e,this.isBusy=t,this.closeAdmission=r,this.options=a}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(!B())return;let e=U();if(!e){i("daemon startup: pending journal is unreadable; preserving it and blocking automatic upgrade for manual recovery");return}if(e.phase&&!Qe.has(e.phase)&&(e=D({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)||(i(`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}I(e),e=D({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),i(`${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(L(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`;D({guardian_handback_count:(e.guardian_handback_count??0)+1,guardian_handback_at:new Date().toISOString()},e.transaction_id),i(`${c}; requesting graceful shutdown so the wrapper re-runs the guardian`),await this.options.requestGracefulShutdown("upgrade");return}if(L(e))i(`daemon startup: guardian did not settle ${e.phase} for ${e.target_version} and cannot be resumed; collapsing the transaction by version verdict`),K(),I(e);else{await this.resumeWindowsGuardian(),this.logGuardianWait(e),this.schedulePendingReconcile();return}}if(e.phase==="failed"){const c=z(e),l=A();if(!c||c!==l){i(`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);i(`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=z(e),a=A(),n=e.phase==="healthy",u=e.phase==="rolled_back",o=!r||r===e.target_version,s=n?a===e.target_version&&r===e.target_version:!u&&a===e.target_version&&o;if(!s&&o&&!u){if(!L(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),i(`resuming POSIX guardian for stalled activation of ${e.target_version}`),this.startGuardian())}this.logThrottled("posix-activation-wait",`daemon startup: runtime ${a} is waiting for guardian activation of ${e.target_version} (active package=${r??"unknown"})`),this.schedulePendingReconcile();return}i(`daemon startup: activation wait for ${e.target_version} expired (> ${ce/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(i(s?`daemon startup: version matches target ${e.target_version}, upgrade succeeded`:`daemon startup: runtime=${a}, 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(se,n?e.target_version:void 0,n?e.old_pid:void 0,n?e.activation_started_at:void 0);if(n&&!c){i("guardian marked healthy but target-version healthz is not yet observable; retrying reconciliation"),this.schedulePendingReconcile();return}i(c?"healthz confirmed healthy, reporting success":"healthz not confirmed within window; reporting success on version-match (guardian still guards crashes)")}if(!x(e)){i(`terminal transaction ${e.transaction_id??"legacy"} is waiting for antivirus-held artifact cleanup`),this.schedulePendingReconcile();return}if(await this.reportUpgrade(h)){this.settleTransaction(e)||(i(`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(!q(e))return!1;try{this.options.onTransactionSettled?.()}catch(t){i(`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()})},je))}logThrottled(e,t){const r=Date.now();e===this.guardianWaitLoggedPhase&&r-this.guardianWaitLoggedAt<Ke||(this.guardianWaitLoggedPhase=e,this.guardianWaitLoggedAt=r,i(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{W(process.execPath,[e,"activate","--root",y.base],{detached:!0,stdio:t,windowsHide:!0}).unref()}finally{if(r!==void 0)try{O(r)}catch{}}}async retryStartupReport(e,t,r){const a=t?.transaction_id,n=()=>{const u=U();if(!(a&&u?.transaction_id!==a)){if(r&&!x(t)){i(`terminal backup cleanup is still blocked for ${a??"legacy transaction"}`),this.schedulePendingReconcile();return}this.settleTransaction(t)||(i(`terminal shared lock release is still blocked for ${a??"legacy transaction"}`),this.schedulePendingReconcile())}};for(let u=2;u<=M;u++){if(this.stopped)return;const o=ne*(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}}i(`startup report (${e.status}) not delivered after ${M} attempts; clearing pending to unblock future checks`),n()}async confirmHealthz(e,t,r,a){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(a??"");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(B()){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 a=A();let n;try{n=Re(r.version)}catch(p){const g=p;await this.reportUpgrade({from_version:a,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=J(s);if(h&&this.options.requestGracefulShutdown){await this.runLauncherUpgrade(h,a,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(", ")})`;i(b),await this.reportUpgrade({from_version:a,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&&i("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:a,to_version:n,status:"failed",error_code:l.errorCode,error_msg:l.errorMsg});return}if(!await F(E,n)){i(`target ${n} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}i(`upgrade start: ${a} -> ${n}`);const f=Date.now();let w;try{w=Ee(a,n,o==="win32"||c?"preparing":void 0).transaction_id,(await ke(E,n,void 0,c?{activationMode:"staged"}:{}))?.activationRequired||$e(n),i("npm install verified, reporting installed"),await this.reportUpgrade({from_version:a,to_version:n,status:"installed",duration_ms:Date.now()-f}),i("shutting down for restart");const g=await this.waitUntilIdle();if(g!=="idle")throw i(`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");H(process.pid,w),i("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");H(process.pid,w),i("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);i(`upgrade failed: ${g} ${T}`);const b=U();if(w&&b?.transaction_id===w&&(o==="win32"||c?(K(),I(b)):Pe(b)&&i("upgrade failed before restart; previous package restored atomically"),q(b)||(i(`failed transaction ${w} is waiting for shared lock release`),this.schedulePendingReconcile()),this.options.reopenLifecycleAdmission?.()),g==="UPGRADE_IN_PROGRESS")return;X(T)||Y(T)||g==="NPM_TIMEOUT"?i(`failure is retriable (${g}); skipping cooldown, will retry next cycle`):this.recordFailure(n),await this.reportUpgrade({from_version:a,to_version:n,status:"failed",error_code:g,error_msg:T,duration_ms:Date.now()-f,upgrade_log:$()})}}async runLauncherUpgrade(e,t,r,a){if(!a&&!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 F(E,r)){i(`target ${r} not resolvable on any registry yet; skipping this cycle (no failure recorded)`);return}i(`launcher upgrade start: ${t} -> ${r} (store=${e})`);const u=Date.now();try{v(te(e,r))?i(`${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()};re(e,{...s,switched:!1}),Oe(e,r),re(e,{...s,switched:!0}),i(`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(i(`launcher upgrade failed: ${s} ${h}`),s==="UPGRADE_ABORTED"){i("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(N(e,"current")!==r)try{k(ee(e,r),{recursive:!0,force:!0})}catch{}X(h)||Y(h)||s==="NPM_TIMEOUT"?i(`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=J(e);if(!t)return;const r=A();try{Ue(t,ee(t,r))}catch(l){i(`failed to refresh launcher: ${l instanceof Error?l.message:String(l)}`)}const a=Date.now(),n=()=>{if(v(De(t,r)))return!1;const l=N(t,"previous");return!!l&&l!==r&&v(te(t,l))},u=l=>{this.healthyTimer=setTimeout(()=>{if(this.healthyTimer=null,!this.stopped){if(this.options.isConnected&&!this.options.isConnected()){if(Date.now()-a>=Ze&&this.options.requestGracefulShutdown&&n()){i(`${r} has been up ${Math.round((Date.now()-a)/1e3)}s without any agent websocket ready; exiting so the launcher counts a crash and can roll back`),this.options.requestGracefulShutdown("launcher-unhealthy");return}i(`uptime reached but no agent websocket is ready yet; deferring health marker for ${r}`),u(Ve);return}try{Ne(t,r),Q(t,r)}catch(f){i(`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(V(t),{force:!0})}catch{}try{k(Z(t),{force:!0})}catch{}const l=Me(t);l.length>0&&i(`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"}`;i(`daemon startup: launcher rolled back ${o.to_version} -> ${r} (${l})`),this.recordFailure(o.to_version);const f=Q(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?`
|
|
2
|
+
--- ${o.to_version} crash note ---
|
|
3
|
+
${f}`:"")}}else if(s&&s.to_version===r&&N(t,"current")===r){i(`daemon startup: running switched target ${r}, upgrade succeeded`);const l=await this.confirmHealthz(se);i(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){i(`daemon startup: switch record for ${s.to_version} was never applied; discarding`);try{k(Z(t),{force:!0})}catch{}try{k(V(t),{force:!0})}catch{}return}else if(s&&s.from_version===r)i(`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{i(`daemon startup: stale launcher records (self=${r}); discarding`),h();return}if(await this.reportUpgrade(c)){h();return}(async()=>{for(let l=2;l<=M;l++){if(this.stopped||(await new Promise(f=>setTimeout(f,ne*(l-1)+Math.floor(Math.random()*1e3))),this.stopped))return;if(await this.reportUpgrade(c))break}h()})()}async waitUntilIdle(){if(this.isBusy?.()){i(`active tasks detected, waiting up to ${Math.round(G/6e4)}min until idle before restart (admission stays open while waiting)`);const e=Date.now()+G,t=5e3,r=600*1e3;let a=Date.now();for(;this.isBusy()&&!this.stopped;){if(Date.now()>=e)return m.warn("upgrade",`Idle wait exceeded ${Math.round(G/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.`),i("idle wait timed out; upgrade attempt abandoned without ever closing admission"),"timeout";await new Promise(n=>setTimeout(n,t)),Date.now()-a>=r&&(a=Date.now(),i("still waiting for active tasks to finish before restart"))}}return this.stopped?"stopped":(this.closeAdmission?.(),this.isBusy?.()?(i("work arrived while closing admission; reopening and abandoning this upgrade attempt"),this.options.reopenLifecycleAdmission?.(),"busy-again"):(i("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<ae)return m.info("upgrade",`In cooldown, ${(ae-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 a=_e(),n=t.daily_attempts[a]??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 a=Object.keys(t.version_attempts);for(const n of a.slice(0,Math.max(0,a.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 a=await fetch(r,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(ie)});if(!a.ok)return m.warn("upgrade",`Check API returned ${a.status}`),{available:!1};const n=await a.json();return n.code!==0?{available:!1}:n.data}catch(a){return m.warn("upgrade",`Check API error: ${a instanceof Error?a.message:a}`),{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 a=>{const u=`${pe(a.wsUrl)}/v1/agent-api/upgrade/report`;try{return(await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(ie)})).ok}catch{return!1}}))).some(a=>a)}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 a=W(e,[],{detached:!0,stdio:t});a.unref(),i(`guardian started (pid ${a.pid})`)}catch(a){m.warn("upgrade",`Failed to start guardian: ${a instanceof Error?a.message:a}`)}finally{if(r!==void 0)try{O(r)}catch{}}}}export{mt as UpgradeChecker};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{cpSync as
|
|
2
|
-
`)}function
|
|
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};
|
package/dist/grix.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import D from"node:path";import{writeFileSync as
|
|
3
|
-
Run \`grix-connector --help\` to see the supported commands and options.`),process.exit(1)),
|
|
2
|
+
import D from"node:path";import{writeFileSync as ne}from"node:fs";import{Manager as be}from"./manager.js";import{ensureGrixDirs as Ie,initLogger as Pe,log as i,installProcessLogRotation as Ce,setConsoleOutput as oe}from"./core/log/index.js";import{HealthServer as ke,bindPortOrFail as ae}from"./core/runtime/index.js";import{writePidFile as _e,removePidFile as F,readDaemonPid as Te}from"./core/runtime/index.js";import{resolveRuntimePaths as K}from"./core/config/index.js";import{supportsNonMitmRelayConfig as Ue}from"./core/config/provider-env.js";import{ServiceManager as ie}from"./service/service-manager.js";import{RESTART_EXIT_CODE as $e,UNHEALTHY_EXIT_CODE as Le,markManagedStop as Oe,resolveLauncherStore as se,writeCrashNote as Fe}from"./core/upgrade/version-store.js";import{migrateWindowsWrapper as X}from"./service/windows-wrapper-migration.js";const He=300*1e3;import{killProcessesByCommandLine as Me,isWindowsElevated as Ne,shouldSweepWindowsWrappers as Ge}from"./service/process-control.js";import{buildServiceID as Be}from"./service/service-paths.js";import{acquireDaemonLock as je,isLockHolderSameProcess as We,readDaemonLock as V,releaseDaemonLock as H}from"./runtime/daemon-lock.js";import{writeDaemonStatus as G,removeDaemonStatus as Ke}from"./runtime/service-state.js";import{AdminServer as Xe,generateToken as Ve,writeTokenFile as qe}from"./core/admin/index.js";import{initSentry as Ye,closeSentry as q,reportFatal as Y}from"./core/observability/sentry.js";import{initProxyManager as Je,getProxyManager as f,relayHostsForClientType as ce,RelayStateStore as ze,SecretStore as Qe}from"./core/proxy/index.js";import{stopProxyIfNobodyNeedsIt as le,switchAgentRelayMode as J,reconcileRelayStates as de}from"./core/proxy/relay-orchestration.js";import{setAgentRelayCredential as pe,RelayCredentialError as ue}from"./core/proxy/relay-credential.js";import{RelayFetchError as ge,RelayToggleCoordinator as Ze}from"./core/proxy/relay-credential-fetch.js";import{applyHermesProfileRelay as et,clearHermesProfileRelay as tt,discoverHermesProfiles as rt}from"./core/proxy/hermes-profile-relay.js";import{disableRelayCredential as nt,enableRelayCredential as ot,RelayRouteError as fe}from"./core/proxy/relay-credential-router.js";import{upgradeStatusSnapshot as at}from"./core/upgrade/npm-upgrader.js";import{resolveClientVersion as it}from"./core/util/client-version.js";import{parseCliArgs as st}from"./core/util/cli-args.js";const{command:x,flags:S,unknownFlags:z}=st(process.argv.slice(2));if(z.length>0&&(console.error(`Unknown option${z.length>1?"s":""}: ${z.map(r=>`--${r}`).join(", ")}
|
|
3
|
+
Run \`grix-connector --help\` to see the supported commands and options.`),process.exit(1)),S.version&&(console.log(it()),process.exit(0)),S.help&&(console.log(`grix-connector \u2014 Unified AI Agent Bridge
|
|
4
4
|
|
|
5
5
|
Usage: grix-connector <command> [options]
|
|
6
6
|
|
|
@@ -34,9 +34,9 @@ Examples:
|
|
|
34
34
|
grix-connector start # Start as system service
|
|
35
35
|
grix-connector status # Check service status
|
|
36
36
|
grix-connector restart # Restart the service
|
|
37
|
-
`),process.exit(0)),x==="reload"){const r=Te();r||(console.error("reload failed: daemon is not running (no pid file)"),process.exit(1));try{process.kill(r,0)}catch{console.error(`reload failed: daemon process ${r} is not running (stale pid file)`),process.exit(1)}{const
|
|
37
|
+
`),process.exit(0)),x==="reload"){const r=Te();r||(console.error("reload failed: daemon is not running (no pid file)"),process.exit(1));try{process.kill(r,0)}catch{console.error(`reload failed: daemon process ${r} is not running (stale pid file)`),process.exit(1)}{const c=V(K().daemonLockFile);c&&c.pid===r&&!We(c)&&(console.error(`reload failed: pid ${r} has been reused by another process (stale pid file)`),process.exit(1))}try{process.kill(r,"SIGHUP"),console.log(JSON.stringify({ok:!0,signaled:r},null,2)),process.exit(0)}catch(c){console.error(`reload failed: ${c instanceof Error?c.message:c}`),process.exit(1)}}const me=["start","stop","restart","status"];if(x&&me.includes(x)){process.platform==="win32"&&["start","stop","restart"].includes(x)&&!Ne()&&console.warn(`Warning: Not running as administrator. Task Scheduler registration is skipped;
|
|
38
38
|
using Startup folder auto-start instead. For full Task Scheduler integration,
|
|
39
|
-
right-click the terminal and select "Run as administrator".`);const r=
|
|
40
|
-
Valid commands: ${
|
|
41
|
-
`),i.error("main",r.message.replace(/\n/g," \u2014 "));const p=X(s.daemonLockFile);p?.pid===process.pid&&p.instance_id===C&&await N(s.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:C,updated_at:Date.now(),reason:`port_bind_${r.kind}:${r.label}:${r.port}`}).catch(()=>{}),await V(),H(s.daemonLockFile).catch(()=>{}),O(),process.exit(1)}async function P(r){if(B)return;B=!0,i.info("main",`Received ${r}, shutting down...`),M.markShuttingDown();const p=$e();p&&Ue(p);const w=r==="upgrade-switch"?ie:2,u=setTimeout(()=>{i.error("main","Shutdown timed out, forcing exit"),H(s.daemonLockFile).catch(()=>{}),O(),process.exit(w)},1e4);try{await n.stop(),await f()?.stop().catch(()=>{}),await b.stop(),await M.stop(),await V(),await H(s.daemonLockFile),await Be(s.daemonStatusFile).catch(()=>{}),clearTimeout(u),O(),i.info("main","Shutdown complete"),process.exit(r==="upgrade-switch"?ie:0)}catch(c){i.error("main",`Shutdown error: ${c}`),H(s.daemonLockFile).catch(()=>{}),O(),process.exit(w)}}async function it(){if(be(),Pe(),Ie(s.stdoutLogFile,s.stderrLogFile),ne(!1),He()){const e=Me(s.rootDir,"win32");await Fe(e,{platform:"win32"})}try{C=(await Ge(s.daemonLockFile,s.rootDir)).instance_id}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}if(await Xe(),Ce(),i.info("main",`grix-connector starting (PID ${process.pid})`),await N(s.daemonStatusFile,{state:"starting",pid:process.pid,instance_id:C,updated_at:Date.now()}),process.env.GRIX_LAUNCHER_MANAGED!=="1"&&await new ae({cliPath:D.resolve(process.argv[1]??""),nodePath:process.execPath}).adoptLauncher(s.rootDir).then(e=>{e&&i.info("main","Service definition now points at the version-store launcher")}).catch(e=>{i.warn("main",`Launcher adoption failed: ${e instanceof Error?e.message:e}`)}),(await K({rootDir:s.rootDir,requestGracefulShutdown:()=>{P("wrapper-migration")}}).catch(e=>(i.warn("main",`Windows wrapper migration failed: ${e instanceof Error?e.message:e}`),null)))?.handoffStarted)return;process.platform==="win32"&&process.env.GRIX_LAUNCHER_MANAGED!=="1"&&setInterval(()=>{B||K({rootDir:s.rootDir,requestGracefulShutdown:()=>{P("wrapper-migration")}}).then(o=>{o.handoffStarted&&i.info("main","Wrapper handoff started by the periodic migration retry")}).catch(o=>{i.warn("main",`Periodic wrapper migration failed: ${o instanceof Error?o.message:o}`)})},Le).unref();const p=parseInt(R["health-port"]??process.env.GRIX_HEALTH_PORT??"19579",10);{const e=await oe({label:"health",port:p,envVar:"GRIX_HEALTH_PORT",cliFlag:"health-port",start:o=>M.start(o)});e&&await he(e)}const w=D.join(s.dataDir,"health-port");re(w,String(p),"utf-8"),process.on("SIGINT",()=>P("SIGINT")),process.on("SIGTERM",()=>P("SIGTERM")),process.on("SIGHUP",()=>{B||(i.info("main","Received SIGHUP, reloading config..."),n.reload().then(e=>i.info("main",`reload done: ${JSON.stringify(e)}`)).catch(e=>i.error("main",`reload failed: ${e instanceof Error?e.message:e}`)))});let u="",c=0,T;process.on("uncaughtException",e=>{const o=e instanceof Error?e.stack??e.message:String(e);o===u?(c++,(c<=3||c%100===0)&&i.error("main",`Uncaught exception (x${c}): ${o}`)):(c>3&&i.error("main",`Previous exception repeated ${c} times total`),u=o,c=1,i.error("main",`Uncaught exception: ${e instanceof Error?e.stack:e}`),T||(T=setTimeout(()=>{c>3&&i.error("main",`Previous exception repeated ${c} times total`),u="",c=0,T=void 0},1e4).unref())),!ye(e)&&(q(e,"uncaughtException"),P("uncaughtException"))}),process.on("unhandledRejection",e=>{i.error("main",`Unhandled rejection: ${e}`),!ye(e)&&(q(e,"unhandledRejection"),P("unhandledRejection"))});const _=Ve(s.dataDir);await _.clearRuntimeState();const I=new qe(D.join(s.dataDir,"proxy","relay-state.json"),{warn:e=>i.warn("main",e)}),G=new Ye(D.join(s.dataDir,"secrets"));n.setRelaySecretResolver(e=>G.get(e));const U={hasDirectConfig:e=>n.hasDirectRelayConfig(e),clearDirectConfig:(e,o)=>n.setAgentProvider(e,void 0,{deferRestart:o?.deferRestart===!0})},j=()=>({pm:f(),agents:n,direct:U,store:I,secrets:G}),$=_.getRelayAgents();if($.length>0)try{await _.startIfAnyRelayAgent(),i.info("main",`mitm proxy started for relay agents: ${$.join(", ")} (per-agent; others stay direct)`)}catch(e){i.error("main",`mitm proxy FAILED to start (relay agents: ${$.join(", ")}): ${e}. These agents will REFUSE to start (they must not silently fall back to your own account). Fix the proxy or turn relay off for them. Other agents are unaffected.`)}else i.info("main",'mitm proxy idle (no agent has Grix relay enabled; enable: PUT /api/proxy/agents/<name>/enabled {"enabled":true})');let L=null;if(f()){const e=async()=>{const t=f();t&&await le(t,n)&&i.info("main","no agent uses Grix relay anymore; mitm proxy stopped")};n.setRelayEnvSettledHandler(()=>{const t=f();t&&ce(t,U,I),e().catch(a=>{i.warn("main",`failed to stop idle mitm proxy: ${a}`)})});const o=()=>{const t=f(),a=t.getRelayAgents(),l=t.getDegradedRelayAgents();return{enabled:a.length>0,relayAgents:a,staleRelayAgents:n.getAgentsWithStaleRelayEnv(),degradedRelayAgents:l,relayState:I.list(),runtime:t.getRuntimeInfo(),config:t.getConfigSnapshot()}},d=new Je,A={status:()=>o(),setAgentRelay:async(t,a,l)=>{const g=f(),S={info:h=>i.info("main",h),warn:h=>i.warn("main",h)},y=h=>n.getAgentsStatus().find(E=>E.name===h),m=y(t);if(!a){d.cancel(t);const h=await d.runExclusive(t,async()=>{const E=await Y(j(),S,{agentName:t,target:"off"});return{...o(),restarted:E.restarted,busy:E.busy,...E.pending?{pending:E.pending}:{}}});return n.reportRelayStateLocalChange(t),h}if(!m)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});if(!_e(m.clientType)&&se(m.clientType).length===0)throw Object.assign(new Error(`client type "${m.clientType??""}" does not support Grix relay`),{code:"UNSUPPORTED_CLIENT_TYPE"});const F=await d.runExclusive(t,async()=>{const h=d.epoch(t),E=y(t);if(!E)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});const Z=String(E.agentId??"").trim();if(!Z)throw new pe(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");const ee=d.waitCancelled(t,h);let k;try{k=await Promise.race([n.fetchRelayCredential(t,{model:l}),ee.promise.then(()=>{throw new ge("relay enable cancelled by a later disable","CANCELLED")})])}finally{ee.dispose()}d.assertCurrent(t,h);const{restarted:Re,busy:Ae,pending:te}=await de(g,n,y,S,{localName:t,agentId:Z,virtualKey:k.apiKey,anthropicBaseUrl:k.anthropicBaseUrl,openaiBaseUrl:k.openaiBaseUrl,model:l,...k.directRelay!==void 0?{directRelay:k.directRelay}:{}},(Ee,ve,De)=>n.setAgentProvider(Ee,ve,{deferRestart:De?.deferRestart===!0}),{store:I,secrets:G,direct:U});if(d.epoch(t)!==h)throw await Y(j(),S,{agentName:t,target:"off"}),new ge("relay enable cancelled by a later disable","CANCELLED");return{...o(),restarted:Re,busy:Ae,...te?{pending:te}:{}}});return n.reportRelayStateLocalChange(t),F},setAgentRelayCredential:async(t,a)=>{const l=f(),g=n.getAgentsStatus(),{restarted:S,busy:y,pending:m}=await de(l,n,v=>g.find(F=>F.name===v),{info:v=>i.info("main",v),warn:v=>i.warn("main",v)},{localName:t,agentId:a.agentId,virtualKey:a.virtualKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}},(v,F,h)=>n.setAgentProvider(v,F,{deferRestart:h?.deferRestart===!0}),{store:I,secrets:G,direct:U});return n.reportRelayStateLocalChange(t),{...o(),restarted:S,busy:y,...m?{pending:m}:{}}},disableAll:async()=>{const t=f(),a={info:g=>i.info("main",g),warn:g=>i.warn("main",g)},l=new Set([...t.getRelayAgents(),...n.getDirectRelayConfigAgentNames(),...Object.keys(I.list())]);for(const g of l)d.cancel(g);for(const g of l)await d.runExclusive(g,()=>Y(j(),a,{agentName:g,target:"off"})),n.reportRelayStateLocalChange(g);return await le(t,n),o()},setRoute:async(t,a)=>{const l=a,g=f();return g.setRoute({routeKey:t,targetBaseUrl:l.targetBaseUrl,...l.headers?{headers:l.headers}:{},...l.model?{model:l.model}:{},...l.modelMap?{modelMap:l.modelMap}:{},...l.passthrough?{passthrough:!0}:{},...l.relayOnly?{relayOnly:!0}:{},...l.codexResponsesToChat?{codexResponsesToChat:!0}:{}}),await g.persistConfig(),o()},deleteRoute:async t=>{const a=f();a.deleteRoute(t),await a.persistConfig()},setDefaultRoute:async t=>{const a=f();return a.setDefaultRouteKey(t),await a.persistConfig(),o()},setInterceptHosts:async t=>{const a=f();return a.setInterceptHosts(t),await a.persistConfig(),o()}};L=A,b.setProxyHandler(A),n.setRelayStateApplier({getLocalState:t=>{const a=f();if(a.getRelayAgents().includes(t)){const g=n.getAgentsStatus().find(m=>m.name===t),S=`grix-gateway-${String(g?.clientType??"").trim().toLowerCase()}`;return{enabled:!0,model:a.getConfigSnapshot().routes?.find(m=>m.routeKey===S)?.model?.trim()||void 0}}const l=n.getAgentProvider(t);return l?.api_key?.trim()?{enabled:!0,model:l.model?.trim()||void 0}:{enabled:!1}},applyEnable:async(t,a,l)=>{const g=n.getAgentsStatus().find(m=>m.name===t),S=String(g?.agentId??"").trim();if(!S)throw new pe(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");const y=await A.setAgentRelayCredential(t,{agentId:S,virtualKey:a.apiKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:l??a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}});return{restarted:y.restarted===!0,busy:y.busy===!0,...y.pending?{pending:y.pending}:{}}},applyDisable:async t=>{const a=await A.setAgentRelay(t,!1);return{restarted:a.restarted===!0,busy:a.busy===!0,...a.pending?{pending:a.pending}:{}}}})}if(M.setStatusProvider(()=>n.getAgentsStatus()),M.setMetaProvider(()=>{const e=n.getAgentsStatus();return{ws:{connected:e.filter(o=>o.wsConnected===!0).length,total:e.length},upgrade:rt()}}),await n.start(at),$.length>0){const e=n.getAgentsStatus();for(const o of $){const d=e.find(t=>t.name===o);if(!d)continue;const A=se(d.clientType);A.length!==0&&await _.setAgentRelayEnabled(o,!0,{relayHosts:A}).catch(t=>{i.warn("main",`failed to reconcile relay hosts for "${o}": ${t}`)})}}ce(_,U,I);const z=parseInt(R["admin-port"]??process.env.GRIX_ADMIN_PORT??"19580",10);b.setAgentHandler({list:()=>n.getAgentsStatus(),add:e=>n.addAgent(e),remove:e=>n.removeAgent(e),restart:e=>n.restartAgent(e),reload:()=>n.reload()}),b.setUpgradeHandler({check:()=>n.checkUpgrade(),trigger:()=>n.triggerUpgrade()}),b.setProbeHandler({probeAll:e=>n.probeAll(e),probeOne:(e,o)=>n.probeOne(e,o)}),b.setInstallHandler({listInstallable:()=>n.listInstallable(),installAgent:e=>n.installAgent(e),getInstallProgress:e=>n.getInstallProgress(e)});const Q={listAgents:()=>n.getAgentsStatus(),enableManaged:(e,o,d)=>{if(!L)throw new ue(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelayCredential(e,{agentId:o,virtualKey:d.virtualKey,anthropicBaseUrl:d.anthropicBaseUrl,openaiBaseUrl:d.openaiBaseUrl,model:d.model,...d.directRelay!==void 0?{directRelay:d.directRelay}:{}})},disableManaged:e=>{if(!L)throw new ue(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelay(e,!1)},enableHermesProfile:(e,o)=>ze({agentId:e,baseUrl:o.openaiBaseUrl??"",virtualKey:o.virtualKey,model:o.model??""}),disableHermesProfile:e=>Qe(e)};b.setRelayCredentialHandler({listHermesProfiles:()=>Ze(),enable:async(e,o)=>{const{target:d,result:A}=await tt(Q,e,o);return{target:d,...A}},disable:async e=>{const{target:o,result:d}=await et(Q,e);return{target:o,...d}}});{const e=await oe({label:"admin",port:z,envVar:"GRIX_ADMIN_PORT",cliFlag:"admin-port",start:o=>b.start(o)});e&&await he(e)}const we=D.join(s.dataDir,"admin-token"),Se=D.join(s.dataDir,"admin-port");Ke(we,me),re(Se,String(z),"utf-8"),await N(s.daemonStatusFile,{state:"running",pid:process.pid,instance_id:C,updated_at:Date.now()}),process.send&&process.send("ready"),i.info("main","grix-connector ready")}it().catch(async r=>{const p=`Fatal: ${r instanceof Error?r.stack??r.message:String(r)}`;try{process.stderr.write(`${p}
|
|
42
|
-
`)}catch{}
|
|
39
|
+
right-click the terminal and select "Run as administrator".`);const r=K(),c=S["config-dir"]??(S.profile?D.join(r.configDir,S.profile):void 0),m=D.resolve(process.argv[1]||`${r.rootDir}/dist/grix.js`),g=new ie({cliPath:m,nodePath:process.execPath});try{let l;switch(x){case"start":(await g.status({rootDir:r.rootDir})).installed?l=await g.start({rootDir:r.rootDir}):l=await g.install({rootDir:r.rootDir,configDir:c});break;case"stop":l=await g.stop({rootDir:r.rootDir});break;case"restart":(await g.status({rootDir:r.rootDir})).installed?l=await g.restart({rootDir:r.rootDir}):l=await g.install({rootDir:r.rootDir,configDir:c});break;case"status":l=await g.status({rootDir:r.rootDir});break}console.log(JSON.stringify(l,null,2)),process.exit(0)}catch(l){console.error(`${x} failed: ${l instanceof Error?l.message:l}`),process.exit(1)}}else x&&(console.error(`Unknown command: ${x}
|
|
40
|
+
Valid commands: ${me.join(", ")}`),process.exit(1));const s=K(),ct=S["config-dir"]??(S.profile?`${s.configDir}/${S.profile}`:void 0),n=new be({requestGracefulShutdown:r=>{I(r)},onTransactionSettled:()=>{X({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).then(r=>{r.handoffStarted&&i.info("main","Wrapper handoff started after the upgrade transaction settled")}).catch(r=>{i.warn("main",`Post-upgrade wrapper migration failed: ${r instanceof Error?r.message:r}`)})}}),M=new ke,he=Ve(),b=new Xe(he);let B=!1,T;function j(r,c){const m=se(),g=process.env.GRIX_LAUNCHER_VERSION;if(!m||!g)return;const l=c instanceof Error?c.stack??c.message:String(c);Fe(m,g,`${r}: ${l}`)}async function ye(r){process.stderr.write(r.message+`
|
|
41
|
+
`),i.error("main",r.message.replace(/\n/g," \u2014 ")),j("port_bind",r.message);const c=V(s.daemonLockFile);c?.pid===process.pid&&c.instance_id===T&&await G(s.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:T,updated_at:Date.now(),reason:`port_bind_${r.kind}:${r.label}:${r.port}`}).catch(()=>{}),await q(),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(1)}async function I(r){if(B)return;B=!0,i.info("main",`Received ${r}, shutting down...`),M.markShuttingDown();const c=se();c&&Oe(c);const m=r==="upgrade-switch"?$e:r==="launcher-unhealthy"?Le:null,g=m??2,l=r==="uncaughtException"||r==="unhandledRejection",P=setTimeout(()=>{i.error("main","Shutdown timed out, forcing exit"),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(g)},1e4);try{await n.stop(),await f()?.stop().catch(()=>{}),await b.stop(),await M.stop(),await q(),await H(s.daemonLockFile),await Ke(s.daemonStatusFile).catch(()=>{}),clearTimeout(P),F(),i.info("main","Shutdown complete"),process.exit(m??(l?2:0))}catch(C){i.error("main",`Shutdown error: ${C}`),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(g)}}async function lt(){if(Ie(),Pe(),Ce(s.stdoutLogFile,s.stderrLogFile),oe(!1),Ge()){const e=Be(s.rootDir,"win32");await Me(e,{platform:"win32"})}try{T=(await je(s.daemonLockFile,s.rootDir)).instance_id}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}if(await Ye(),_e(),i.info("main",`grix-connector starting (PID ${process.pid})`),await G(s.daemonStatusFile,{state:"starting",pid:process.pid,instance_id:T,updated_at:Date.now()}),process.env.GRIX_LAUNCHER_MANAGED!=="1"&&await new ie({cliPath:D.resolve(process.argv[1]??""),nodePath:process.execPath}).adoptLauncher(s.rootDir).then(e=>{e&&i.info("main","Service definition now points at the version-store launcher")}).catch(e=>{i.warn("main",`Launcher adoption failed: ${e instanceof Error?e.message:e}`)}),(await X({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).catch(e=>(i.warn("main",`Windows wrapper migration failed: ${e instanceof Error?e.message:e}`),null)))?.handoffStarted)return;process.platform==="win32"&&process.env.GRIX_LAUNCHER_MANAGED!=="1"&&setInterval(()=>{B||X({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).then(o=>{o.handoffStarted&&i.info("main","Wrapper handoff started by the periodic migration retry")}).catch(o=>{i.warn("main",`Periodic wrapper migration failed: ${o instanceof Error?o.message:o}`)})},He).unref();const c=parseInt(S["health-port"]??process.env.GRIX_HEALTH_PORT??"19579",10);{const e=await ae({label:"health",port:c,envVar:"GRIX_HEALTH_PORT",cliFlag:"health-port",start:o=>M.start(o)});e&&await ye(e)}const m=D.join(s.dataDir,"health-port");ne(m,String(c),"utf-8"),process.on("SIGINT",()=>I("SIGINT")),process.on("SIGTERM",()=>I("SIGTERM")),process.on("SIGHUP",()=>{B||(i.info("main","Received SIGHUP, reloading config..."),n.reload().then(e=>i.info("main",`reload done: ${JSON.stringify(e)}`)).catch(e=>i.error("main",`reload failed: ${e instanceof Error?e.message:e}`)))});let g="",l=0,P;process.on("uncaughtException",e=>{const o=e instanceof Error?e.stack??e.message:String(e);o===g?(l++,(l<=3||l%100===0)&&i.error("main",`Uncaught exception (x${l}): ${o}`)):(l>3&&i.error("main",`Previous exception repeated ${l} times total`),g=o,l=1,i.error("main",`Uncaught exception: ${e instanceof Error?e.stack:e}`),P||(P=setTimeout(()=>{l>3&&i.error("main",`Previous exception repeated ${l} times total`),g="",l=0,P=void 0},1e4).unref())),!we(e)&&(Y(e,"uncaughtException"),j("uncaughtException",e),I("uncaughtException"))}),process.on("unhandledRejection",e=>{i.error("main",`Unhandled rejection: ${e}`),!we(e)&&(Y(e,"unhandledRejection"),j("unhandledRejection",e),I("unhandledRejection"))});const C=Je(s.dataDir);await C.clearRuntimeState();const k=new ze(D.join(s.dataDir,"proxy","relay-state.json"),{warn:e=>i.warn("main",e)}),N=new Qe(D.join(s.dataDir,"secrets"));n.setRelaySecretResolver(e=>N.get(e));const U={hasDirectConfig:e=>n.hasDirectRelayConfig(e),clearDirectConfig:(e,o)=>n.setAgentProvider(e,void 0,{deferRestart:o?.deferRestart===!0})},W=()=>({pm:f(),agents:n,direct:U,store:k,secrets:N}),$=C.getRelayAgents();if($.length>0)try{await C.startIfAnyRelayAgent(),i.info("main",`mitm proxy started for relay agents: ${$.join(", ")} (per-agent; others stay direct)`)}catch(e){i.error("main",`mitm proxy FAILED to start (relay agents: ${$.join(", ")}): ${e}. These agents will REFUSE to start (they must not silently fall back to your own account). Fix the proxy or turn relay off for them. Other agents are unaffected.`)}else i.info("main",'mitm proxy idle (no agent has Grix relay enabled; enable: PUT /api/proxy/agents/<name>/enabled {"enabled":true})');let L=null;if(f()){const e=async()=>{const t=f();t&&await le(t,n)&&i.info("main","no agent uses Grix relay anymore; mitm proxy stopped")};n.setRelayEnvSettledHandler(()=>{const t=f();t&&de(t,U,k),e().catch(a=>{i.warn("main",`failed to stop idle mitm proxy: ${a}`)})});const o=()=>{const t=f(),a=t.getRelayAgents(),d=t.getDegradedRelayAgents();return{enabled:a.length>0,relayAgents:a,staleRelayAgents:n.getAgentsWithStaleRelayEnv(),degradedRelayAgents:d,relayState:k.list(),runtime:t.getRuntimeInfo(),config:t.getConfigSnapshot()}},p=new Ze,E={status:()=>o(),setAgentRelay:async(t,a,d)=>{const u=f(),R={info:y=>i.info("main",y),warn:y=>i.warn("main",y)},w=y=>n.getAgentsStatus().find(A=>A.name===y),h=w(t);if(!a){p.cancel(t);const y=await p.runExclusive(t,async()=>{const A=await J(W(),R,{agentName:t,target:"off"});return{...o(),restarted:A.restarted,busy:A.busy,...A.pending?{pending:A.pending}:{}}});return n.reportRelayStateLocalChange(t),y}if(!h)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});if(!Ue(h.clientType)&&ce(h.clientType).length===0)throw Object.assign(new Error(`client type "${h.clientType??""}" does not support Grix relay`),{code:"UNSUPPORTED_CLIENT_TYPE"});const O=await p.runExclusive(t,async()=>{const y=p.epoch(t),A=w(t);if(!A)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});const ee=String(A.agentId??"").trim();if(!ee)throw new ue(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");const te=p.waitCancelled(t,y);let _;try{_=await Promise.race([n.fetchRelayCredential(t,{model:d}),te.promise.then(()=>{throw new ge("relay enable cancelled by a later disable","CANCELLED")})])}finally{te.dispose()}p.assertCurrent(t,y);const{restarted:Ee,busy:Ae,pending:re}=await pe(u,n,w,R,{localName:t,agentId:ee,virtualKey:_.apiKey,anthropicBaseUrl:_.anthropicBaseUrl,openaiBaseUrl:_.openaiBaseUrl,model:d,..._.directRelay!==void 0?{directRelay:_.directRelay}:{}},(ve,De,xe)=>n.setAgentProvider(ve,De,{deferRestart:xe?.deferRestart===!0}),{store:k,secrets:N,direct:U});if(p.epoch(t)!==y)throw await J(W(),R,{agentName:t,target:"off"}),new ge("relay enable cancelled by a later disable","CANCELLED");return{...o(),restarted:Ee,busy:Ae,...re?{pending:re}:{}}});return n.reportRelayStateLocalChange(t),O},setAgentRelayCredential:async(t,a)=>{const d=f(),u=n.getAgentsStatus(),{restarted:R,busy:w,pending:h}=await pe(d,n,v=>u.find(O=>O.name===v),{info:v=>i.info("main",v),warn:v=>i.warn("main",v)},{localName:t,agentId:a.agentId,virtualKey:a.virtualKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}},(v,O,y)=>n.setAgentProvider(v,O,{deferRestart:y?.deferRestart===!0}),{store:k,secrets:N,direct:U});return n.reportRelayStateLocalChange(t),{...o(),restarted:R,busy:w,...h?{pending:h}:{}}},disableAll:async()=>{const t=f(),a={info:u=>i.info("main",u),warn:u=>i.warn("main",u)},d=new Set([...t.getRelayAgents(),...n.getDirectRelayConfigAgentNames(),...Object.keys(k.list())]);for(const u of d)p.cancel(u);for(const u of d)await p.runExclusive(u,()=>J(W(),a,{agentName:u,target:"off"})),n.reportRelayStateLocalChange(u);return await le(t,n),o()},setRoute:async(t,a)=>{const d=a,u=f();return u.setRoute({routeKey:t,targetBaseUrl:d.targetBaseUrl,...d.headers?{headers:d.headers}:{},...d.model?{model:d.model}:{},...d.modelMap?{modelMap:d.modelMap}:{},...d.passthrough?{passthrough:!0}:{},...d.relayOnly?{relayOnly:!0}:{},...d.codexResponsesToChat?{codexResponsesToChat:!0}:{}}),await u.persistConfig(),o()},deleteRoute:async t=>{const a=f();a.deleteRoute(t),await a.persistConfig()},setDefaultRoute:async t=>{const a=f();return a.setDefaultRouteKey(t),await a.persistConfig(),o()},setInterceptHosts:async t=>{const a=f();return a.setInterceptHosts(t),await a.persistConfig(),o()}};L=E,b.setProxyHandler(E),n.setRelayStateApplier({getLocalState:t=>{const a=f();if(a.getRelayAgents().includes(t)){const u=n.getAgentsStatus().find(h=>h.name===t),R=`grix-gateway-${String(u?.clientType??"").trim().toLowerCase()}`;return{enabled:!0,model:a.getConfigSnapshot().routes?.find(h=>h.routeKey===R)?.model?.trim()||void 0}}const d=n.getAgentProvider(t);return d?.api_key?.trim()?{enabled:!0,model:d.model?.trim()||void 0}:{enabled:!1}},applyEnable:async(t,a,d)=>{const u=n.getAgentsStatus().find(h=>h.name===t),R=String(u?.agentId??"").trim();if(!R)throw new ue(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");const w=await E.setAgentRelayCredential(t,{agentId:R,virtualKey:a.apiKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:d??a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}});return{restarted:w.restarted===!0,busy:w.busy===!0,...w.pending?{pending:w.pending}:{}}},applyDisable:async t=>{const a=await E.setAgentRelay(t,!1);return{restarted:a.restarted===!0,busy:a.busy===!0,...a.pending?{pending:a.pending}:{}}}})}if(M.setStatusProvider(()=>n.getAgentsStatus()),M.setMetaProvider(()=>{const e=n.getAgentsStatus();return{ws:{connected:e.filter(o=>o.wsConnected===!0).length,total:e.length},upgrade:at()}}),await n.start(ct),$.length>0){const e=n.getAgentsStatus();for(const o of $){const p=e.find(t=>t.name===o);if(!p)continue;const E=ce(p.clientType);E.length!==0&&await C.setAgentRelayEnabled(o,!0,{relayHosts:E}).catch(t=>{i.warn("main",`failed to reconcile relay hosts for "${o}": ${t}`)})}}de(C,U,k);const Q=parseInt(S["admin-port"]??process.env.GRIX_ADMIN_PORT??"19580",10);b.setAgentHandler({list:()=>n.getAgentsStatus(),add:e=>n.addAgent(e),remove:e=>n.removeAgent(e),restart:e=>n.restartAgent(e),reload:()=>n.reload()}),b.setUpgradeHandler({check:()=>n.checkUpgrade(),trigger:()=>n.triggerUpgrade()}),b.setProbeHandler({probeAll:e=>n.probeAll(e),probeOne:(e,o)=>n.probeOne(e,o)}),b.setInstallHandler({listInstallable:()=>n.listInstallable(),installAgent:e=>n.installAgent(e),getInstallProgress:e=>n.getInstallProgress(e)});const Z={listAgents:()=>n.getAgentsStatus(),enableManaged:(e,o,p)=>{if(!L)throw new fe(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelayCredential(e,{agentId:o,virtualKey:p.virtualKey,anthropicBaseUrl:p.anthropicBaseUrl,openaiBaseUrl:p.openaiBaseUrl,model:p.model,...p.directRelay!==void 0?{directRelay:p.directRelay}:{}})},disableManaged:e=>{if(!L)throw new fe(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelay(e,!1)},enableHermesProfile:(e,o)=>et({agentId:e,baseUrl:o.openaiBaseUrl??"",virtualKey:o.virtualKey,model:o.model??""}),disableHermesProfile:e=>tt(e)};b.setRelayCredentialHandler({listHermesProfiles:()=>rt(),enable:async(e,o)=>{const{target:p,result:E}=await ot(Z,e,o);return{target:p,...E}},disable:async e=>{const{target:o,result:p}=await nt(Z,e);return{target:o,...p}}});{const e=await ae({label:"admin",port:Q,envVar:"GRIX_ADMIN_PORT",cliFlag:"admin-port",start:o=>b.start(o)});e&&await ye(e)}const Re=D.join(s.dataDir,"admin-token"),Se=D.join(s.dataDir,"admin-port");qe(Re,he),ne(Se,String(Q),"utf-8"),await G(s.daemonStatusFile,{state:"running",pid:process.pid,instance_id:T,updated_at:Date.now()}),process.send&&process.send("ready"),i.info("main","grix-connector ready")}lt().catch(async r=>{const c=`Fatal: ${r instanceof Error?r.stack??r.message:String(r)}`;try{process.stderr.write(`${c}
|
|
42
|
+
`)}catch{}oe(!1),i.error("main",c),Y(r,"startup"),j("startup",r);const m=V(s.daemonLockFile);m?.pid===process.pid&&m.instance_id===T&&await G(s.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:m.instance_id,updated_at:Date.now(),reason:"startup_error"}).catch(()=>{}),await q(),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(1)});const dt=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","EAI_AGAIN","ENOTFOUND","EHOSTUNREACH","ENETUNREACH","EIO"]);function we(r){return r instanceof Error&&"code"in r?dt.has(r.code):!1}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(
|
|
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.6.
|
|
3
|
+
"version": "4.6.1",
|
|
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",
|