@chatpanel/gateway 0.6.106 → 0.6.107

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.6.106",
3
+ "version": "0.6.107",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/server.js CHANGED
@@ -40,6 +40,7 @@ import { createEngineLedgerStore } from './engine-ledger-store.js';
40
40
  import { createProjectStore } from './project-store.js';
41
41
  import { applicationsFor, recruitPass } from './recruiting.js';
42
42
  import { ensureBridge } from './bridge-supervisor.js';
43
+ import { checkForUpdate, startUpdate, updateJob } from './update.js';
43
44
  import { createHistoryStore } from './sqlite-store.js';
44
45
  import { ingestBackups } from './backup-ingest.js';
45
46
  import * as nerEngine from './ner-engine.js';
@@ -63,7 +64,7 @@ import * as openai from './openai.js';
63
64
  import * as responses from './responses.js';
64
65
  import * as anthropic from './anthropic.js';
65
66
 
66
- export const VERSION = '0.6.106';
67
+ export const VERSION = '0.6.107';
67
68
 
68
69
  // WARM search tier — SQLite + FTS5 record store (falls back to an encrypted-JSON
69
70
  // store if SQLite can't load), fed by the extension's ingest sync + backup-ingest.
@@ -698,9 +699,22 @@ export function createGateway(cfg = loadConfig()) {
698
699
  // logs (GET /logs). Unlike the /v1 data plane (open to any local client — the
699
700
  // product), these must not be reachable by a no-Origin local process or a drive-by
700
701
  // localhost web page. Require the extension Origin or the gateway token.
701
- if ((pathname === '/config' || pathname === '/logs') && !isAdminAuthorized(req)) {
702
+ if ((pathname === '/config' || pathname === '/logs' || pathname === '/update') && !isAdminAuthorized(req)) {
702
703
  return sendJson(res, 403, { error: 'admin route: extension origin or gateway token required' });
703
704
  }
705
+ // SELF-UPDATE (0.6.107) — src/update.js. Admin-gated: it installs software. Nothing in the
706
+ // request chooses WHAT is installed (the package and the release host are pinned), so the
707
+ // most a caller can do is move this gateway to its channel's latest.
708
+ // GET /update[?force=1] → { ok, update: { current, latest, updateAvailable, mode, canSelfUpdate, npmCommand, stale, error }, job }
709
+ // POST /update → 202 { ok, job } starts it; watch GET /update, then /status until `version` moves
710
+ if (pathname === '/update' && req.method === 'GET') {
711
+ const update = await checkForUpdate(VERSION, { force: url.searchParams.get('force') === '1' }).catch((e) => ({ current: VERSION, updateAvailable: false, error: String(e?.message || e) }));
712
+ return sendJson(res, 200, { ok: true, update, job: updateJob() });
713
+ }
714
+ if (pathname === '/update' && req.method === 'POST') {
715
+ const job = startUpdate(VERSION);
716
+ return sendJson(res, job.already ? 409 : 202, { ok: true, job });
717
+ }
704
718
  if ((pathname === '/v1/history/key' || pathname === '/v1/history/ingest-backup')
705
719
  && req.method === 'POST' && !isAdminAuthorized(req)) {
706
720
  return sendJson(res, 403, { error: { message: 'history key route: extension origin or gateway token required', type: 'forbidden' } });
@@ -779,6 +793,10 @@ export function createGateway(cfg = loadConfig()) {
779
793
  detector: detectorStatus(cfg),
780
794
  pro: { unlocked: proUnlocked }, usage: usage(cfg),
781
795
  uptimeSeconds: Math.floor((Date.now() - STARTED_AT) / 1000),
796
+ // ADDITIVE (0.6.107): is there a newer gateway on this install's channel, and can this
797
+ // process apply it itself (POST /update)? Throttled to one network check per 6 h and
798
+ // never slower than its timeout; an older extension ignores the key.
799
+ update: await checkForUpdate(VERSION).catch(() => ({ current: VERSION, updateAvailable: false })),
782
800
  });
783
801
  }
784
802
  // --- WARM search tier. The extension pushes its DECRYPTED records to this LOCAL
package/src/service.js CHANGED
@@ -10,7 +10,7 @@
10
10
  import os from 'node:os';
11
11
  import path from 'node:path';
12
12
  import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
13
- import { spawnSync } from 'node:child_process';
13
+ import { spawnSync, spawn } from 'node:child_process';
14
14
 
15
15
  const LABEL = 'net.chatpanel.gateway';
16
16
  const DISPLAY = 'ChatPanel Privacy Gateway';
@@ -164,6 +164,43 @@ function byPlatform(mac, win, lin) {
164
164
  throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`);
165
165
  }
166
166
 
167
+ /**
168
+ * Relaunch the registered service into whatever is now installed (src/update.js). Returns
169
+ * `false` when this gateway is not run by a service it can restart — the caller then says
170
+ * "installed; start it again yourself" rather than exiting into nothing.
171
+ *
172
+ * macOS / Linux: the service manager stops this process and starts the new one. Windows has
173
+ * no supervisor: a detached helper waits for THIS process to exit (freeing the port and the
174
+ * onnxruntime DLL npm cannot overwrite while it is loaded), optionally runs the npm install
175
+ * that had to wait for that, relaunches through the registered VBS, and cleans up a renamed
176
+ * .exe. The caller exits after spawning it.
177
+ */
178
+ export function restartService({ winInstall: winInstallCmd = '' } = {}) {
179
+ try {
180
+ if (process.platform === 'darwin') {
181
+ if (!existsSync(macPlist())) return false;
182
+ spawn('launchctl', ['kickstart', '-k', `gui/${process.getuid?.() ?? 0}/${LABEL}`], { detached: true, stdio: 'ignore' }).unref();
183
+ return true;
184
+ }
185
+ if (process.platform === 'linux') {
186
+ if (!existsSync(linUnit())) return false;
187
+ spawn('systemctl', ['--user', 'restart', 'chatpanel-gateway'], { detached: true, stdio: 'ignore' }).unref();
188
+ return true;
189
+ }
190
+ if (process.platform === 'win32') {
191
+ const vbs = winVbs();
192
+ if (!existsSync(vbs)) return false;
193
+ const dir = path.dirname(process.execPath);
194
+ const cmd = `timeout /t 3 >nul & ${winInstallCmd ? `${winInstallCmd} & ` : ''}wscript.exe "${vbs}" & del /q "${path.join(dir, 'chatpanel-gateway.old-*.exe')}" >nul 2>&1`;
195
+ spawn('cmd', ['/c', cmd], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
196
+ setTimeout(() => process.exit(0), 300);
197
+ return true;
198
+ }
199
+ } catch { /* fall through */ }
200
+ return false;
201
+ }
202
+ export function serviceRegistered() { try { return byPlatform(() => existsSync(macPlist()), () => existsSync(winVbs()), () => existsSync(linUnit())); } catch { return false; } }
203
+
167
204
  export function installService() { return byPlatform(macInstall, winInstall, linInstall); }
168
205
  export function uninstallService() { return byPlatform(macUninstall, winUninstall, linUninstall); }
169
206
  export function serviceStatus() { return byPlatform(macStatus, winStatus, linStatus); }
package/src/update.js ADDED
@@ -0,0 +1,273 @@
1
+ // In-app updater for the gateway — the one install (0.6.92+), so its update is the update.
2
+ //
3
+ // The gateway is a background service the user never opens. The EXTENSION (and the desktop)
4
+ // surface "update available" from /status and offer a one-click Update that POSTs /update.
5
+ // The bridge has had this for its standalone binary (chatpanel-bridge/src/update.js); the
6
+ // gateway needs it for BOTH of its delivery channels, because they are not interchangeable:
7
+ //
8
+ // • binary — the compiled Bun build install.sh / dl.chatpanel.net serve. Latest = the
9
+ // newest GitHub release; the update downloads the asset, swaps it over the running file
10
+ // (atomic rename; Windows renames the running .exe aside first) and restarts the service.
11
+ // • npm — `npm i -g @chatpanel/gateway`, launched as `node …/bin/chatpanel-gateway.js`.
12
+ // Latest = the npm registry; the update runs `npm install -g @chatpanel/gateway@latest`
13
+ // with the npm that ships beside the node running this process — the same install tree
14
+ // the service launches — and restarts the service.
15
+ //
16
+ // Two rules carried over from the desktop's updater (electron/runtime/updater.js), learned
17
+ // the hard way there: the npm registry is PINNED to the public one (a corporate ~/.npmrc
18
+ // served a stale mirror minutes after a publish), and nothing here reports success on its
19
+ // own say-so — the caller restarts and the client watches /status until the version moves.
20
+ //
21
+ // The install can take minutes (a cold global install has been measured at five), so
22
+ // POST /update starts a JOB and answers at once; GET /update reports it. A request that
23
+ // waited on npm would have been the extension's fetch timing out mid-install.
24
+
25
+ import os from 'node:os';
26
+ import path from 'node:path';
27
+ import { execFile } from 'node:child_process';
28
+ import { chmod, rename, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
29
+ import { existsSync, readFileSync } from 'node:fs';
30
+ import { restartService, serviceRegistered } from './service.js';
31
+
32
+ const PACKAGE = '@chatpanel/gateway';
33
+ const REPO = 'chatpanel/chatpanel-gateway';
34
+ const LATEST_RELEASE = `https://api.github.com/repos/${REPO}/releases/latest`;
35
+ const LATEST_NPM = `https://registry.npmjs.org/${PACKAGE}/latest`;
36
+ const NPM_REGISTRY = 'https://registry.npmjs.org';
37
+ const CHECK_EVERY_MS = 6 * 60 * 60 * 1000; // 6h
38
+ const RETRY_AFTER_FAILURE_MS = 10 * 60 * 1000; // 10min
39
+ const FETCH_TIMEOUT_MS = Math.max(500, Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS) || 5000);
40
+ const DOWNLOAD_TIMEOUT_MS = 15 * 60_000;
41
+ const INSTALL_TIMEOUT_MS = 20 * 60_000;
42
+ const CACHE = process.env.CHATPANEL_UPDATE_CACHE || path.join(os.homedir(), '.chatpanel', 'gateway-update-check.json');
43
+ /** `CHATPANEL_SELF_UPDATE=off`: no network check, no install — the test runner sets it, and a
44
+ * deployment that manages the gateway itself can. `/status` then says `disabled: true`. */
45
+ const DISABLED = String(process.env.CHATPANEL_SELF_UPDATE || '').toLowerCase() === 'off';
46
+ const UA = { 'User-Agent': 'chatpanel-gateway-updater' };
47
+
48
+ /** Where a binary download may END UP. dl.chatpanel.net and the GitHub API both redirect
49
+ * to the release CDN; the final url is checked, because that is where the bytes come from
50
+ * and the file is about to be made executable. Same trust model as install.sh. */
51
+ const DL_HOSTS = new Set(['dl.chatpanel.net', 'github.com', 'api.github.com', 'objects.githubusercontent.com', 'release-assets.githubusercontent.com']);
52
+ export function downloadHostAllowed(url) {
53
+ try { const u = new URL(url); return u.protocol === 'https:' && DL_HOSTS.has(u.hostname); } catch { return false; }
54
+ }
55
+
56
+ let lastFailure = { at: 0, error: '' };
57
+ /** Test seam: forget the last failure so the next unforced check reaches the network. */
58
+ export function resetUpdateBackoff() { lastFailure = { at: 0, error: '' }; }
59
+
60
+ /** A compiled single-file build, or node running the npm package. Mirrors service.js's resolveLaunch. */
61
+ export function isCompiledBinary() {
62
+ const base = path.basename(process.execPath).toLowerCase();
63
+ return !(base.startsWith('node') || base.startsWith('bun'));
64
+ }
65
+
66
+ /** Release asset for THIS platform (scripts/build.mjs outputs). */
67
+ function assetName() {
68
+ if (process.platform === 'darwin') return `chatpanel-gateway-macos-${process.arch === 'arm64' ? 'arm64' : 'x64'}`;
69
+ if (process.platform === 'linux') return process.arch === 'x64' ? 'chatpanel-gateway-linux-x64' : null;
70
+ if (process.platform === 'win32') return 'chatpanel-gateway-windows-x64.exe';
71
+ return null;
72
+ }
73
+
74
+ function parseVersion(s = '') { const m = /(\d+(?:\.\d+){0,3})/.exec(s || ''); return m ? m[1] : null; }
75
+ /** >0 if a is newer than b. */
76
+ export function cmpVersions(a, b) {
77
+ const pa = String(a).split('.').map(Number); const pb = String(b).split('.').map(Number);
78
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) { const d = (pa[i] || 0) - (pb[i] || 0); if (d) return d > 0 ? 1 : -1; }
79
+ return 0;
80
+ }
81
+
82
+ async function readCache() { try { return JSON.parse(await readFile(CACHE, 'utf8')); } catch { return null; } }
83
+ async function writeCache(obj) { try { await mkdir(path.dirname(CACHE), { recursive: true }); await writeFile(CACHE, JSON.stringify(obj)); } catch { /* best effort */ } }
84
+
85
+ /** One fetch with a real timer (AbortSignal.timeout's is unref'd and can never fire in an idle process). */
86
+ async function fetchJson(url, timeoutMs = FETCH_TIMEOUT_MS) {
87
+ const ctl = new AbortController();
88
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
89
+ try {
90
+ const res = await fetch(url, { headers: { Accept: 'application/json, application/vnd.github+json', ...UA }, signal: ctl.signal });
91
+ if (!res.ok) throw new Error(res.status === 403 && /github/.test(url) ? 'GitHub rate limit (60/hour per IP) — try again later' : `HTTP ${res.status}`);
92
+ return await res.json();
93
+ } catch (e) {
94
+ // Node's `fetch failed` hides the reason (a VPN's TLS block, DNS); the cause names it.
95
+ const why = e?.cause?.code || e?.cause?.message || e?.message || String(e);
96
+ throw new Error(ctl.signal.aborted ? `the update server did not answer within ${Math.round(timeoutMs / 1000)}s` : `${new URL(url).hostname}: ${why}`);
97
+ } finally { clearTimeout(timer); }
98
+ }
99
+
100
+ // ── the npm install, as the service launches it ───────────────────────────────────────
101
+
102
+ /** The package root of the running npm install (…/node_modules/@chatpanel/gateway), or ''. */
103
+ function npmPackageRoot() {
104
+ const script = process.argv[1] ? path.resolve(process.argv[1]) : '';
105
+ const m = /^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(script);
106
+ return m ? m[1] : '';
107
+ }
108
+ /** The version the npm install on disk reports — what the NEXT start will run. */
109
+ function installedNpmVersion() {
110
+ const root = npmPackageRoot();
111
+ if (!root) return '';
112
+ try { return String(JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')).version || ''); } catch { return ''; }
113
+ }
114
+ /**
115
+ * The npm that belongs to the node running this process. A login service inherits no shell
116
+ * PATH, so `npm` bare is not findable; but npm's cli ships beside node in every layout this
117
+ * meets (nvm, Homebrew, the official installer, fnm): <prefix>/lib/node_modules/npm.
118
+ */
119
+ function npmCli() {
120
+ const bin = path.dirname(process.execPath);
121
+ const candidates = [
122
+ path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
123
+ path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'), // the Windows layout
124
+ ];
125
+ return candidates.find((p) => existsSync(p)) || '';
126
+ }
127
+ function runNpmInstall() {
128
+ const cli = npmCli();
129
+ const env = { ...process.env, npm_config_registry: NPM_REGISTRY, npm_config_fund: 'false', npm_config_audit: 'false' };
130
+ delete env.ELECTRON_RUN_AS_NODE; // leaked from a desktop host, it makes npm's node shims boot as Electron
131
+ const [cmd, args] = cli ? [process.execPath, [cli, 'install', '-g', `${PACKAGE}@latest`]] : ['npm', ['install', '-g', `${PACKAGE}@latest`]];
132
+ return new Promise((resolve) => {
133
+ execFile(cmd, args, { env, timeout: INSTALL_TIMEOUT_MS, maxBuffer: 8 << 20, windowsHide: true }, (err, stdout, stderr) => {
134
+ const out = `${stdout || ''}${stderr || ''}`.trim();
135
+ if (!err) return resolve({ ok: true, out });
136
+ if (err.killed && !out) return resolve({ ok: false, out: `npm was still running after ${Math.round(INSTALL_TIMEOUT_MS / 60000)} minutes and was stopped` });
137
+ return resolve({ ok: false, out: out || (cli ? err.message : 'could not run npm: it is not beside the node running this gateway and not on the service\'s PATH') });
138
+ });
139
+ });
140
+ }
141
+
142
+ // ── check ───────────────────────────────────────────────────────────────────────────
143
+
144
+ /**
145
+ * Returns { current, latest, updateAvailable, mode, canSelfUpdate, assetUrl, stale, error, npmCommand, channel }.
146
+ * `mode` binary | npm — each checks ITS channel (the release, the registry), because a fix
147
+ * published to npm does not exist as a binary until its tag is cut. `stale` says `latest`
148
+ * is yesterday's cache, not an answer. Throttled to CHECK_EVERY_MS unless `force`.
149
+ */
150
+ export async function checkForUpdate(current, { force = false } = {}) {
151
+ const mode = isCompiledBinary() ? 'binary' : 'npm';
152
+ if (DISABLED) return { current, latest: null, updateAvailable: false, mode, canSelfUpdate: false, assetUrl: null, stale: false, error: '', npmCommand: null, channel: mode === 'npm' ? 'npm' : 'release', service: false, disabled: true };
153
+ const want = assetName();
154
+ let latest = null; let assetUrl = null; let stale = false; let error = '';
155
+ const cache = await readCache();
156
+ const cacheFits = cache && cache.mode === mode;
157
+ const fallBack = () => { latest = cacheFits ? cache.latest || null : null; assetUrl = cacheFits ? cache.assetUrl || null : null; stale = true; };
158
+ if (!force && cacheFits && Date.now() - cache.checkedAt < CHECK_EVERY_MS) {
159
+ latest = cache.latest; assetUrl = cache.assetUrl;
160
+ } else if (!force && lastFailure.at && Date.now() - lastFailure.at < RETRY_AFTER_FAILURE_MS) {
161
+ error = lastFailure.error; fallBack();
162
+ } else {
163
+ try {
164
+ if (mode === 'npm') {
165
+ const data = await fetchJson(LATEST_NPM);
166
+ latest = parseVersion(data.version);
167
+ } else {
168
+ const data = await fetchJson(LATEST_RELEASE);
169
+ latest = parseVersion(data.tag_name) || parseVersion(data.name);
170
+ assetUrl = want ? (data.assets || []).find((a) => a.name === want)?.browser_download_url || null : null;
171
+ }
172
+ await writeCache({ checkedAt: Date.now(), mode, latest, assetUrl });
173
+ lastFailure = { at: 0, error: '' };
174
+ } catch (e) {
175
+ error = e.message; lastFailure = { at: Date.now(), error }; fallBack();
176
+ }
177
+ }
178
+ const updateAvailable = !!latest && cmpVersions(latest, current) > 0;
179
+ // Windows npm: a running gateway holds onnxruntime's DLL and npm's copy fails with EBUSY, so
180
+ // the install runs AFTER this process exits, from the restart helper — which needs the
181
+ // registered service to relaunch it. No service, no self-update: the command is shown.
182
+ const canSelfUpdate = mode === 'binary' ? !!assetUrl && (process.platform !== 'win32' || serviceRegistered())
183
+ : !!npmPackageRoot() && (process.platform !== 'win32' || (serviceRegistered() && !!npmCli()));
184
+ const npmCommand = mode === 'npm' ? (process.platform === 'win32' ? `chatpanel-gateway --stop; npm i -g ${PACKAGE}@latest; chatpanel-gateway --install` : `npm i -g ${PACKAGE}@latest`) : null;
185
+ return { current, latest, updateAvailable, mode, canSelfUpdate, assetUrl, stale, error, npmCommand, channel: mode === 'npm' ? 'npm' : 'release', service: serviceRegistered() };
186
+ }
187
+
188
+ // ── apply ───────────────────────────────────────────────────────────────────────────
189
+
190
+ async function swapBinary(info) {
191
+ const target = process.execPath;
192
+ const dir = path.dirname(target);
193
+ const tmp = path.join(dir, `.chatpanel-gateway.new-${Date.now()}`);
194
+ const ctl = new AbortController();
195
+ const timer = setTimeout(() => ctl.abort(), DOWNLOAD_TIMEOUT_MS);
196
+ let buf;
197
+ try {
198
+ const res = await fetch(info.assetUrl, { headers: UA, redirect: 'follow', signal: ctl.signal });
199
+ if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`);
200
+ if (!downloadHostAllowed(res.url || info.assetUrl)) throw new Error(`refused: the download was redirected to ${res.url}, which is not a ChatPanel release host`);
201
+ buf = Buffer.from(await res.arrayBuffer());
202
+ } finally { clearTimeout(timer); }
203
+ // These binaries are tens of megabytes; anything small is an error page or a truncated body.
204
+ if (buf.length < 5 << 20) throw new Error(`the download was only ${(buf.length / 1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);
205
+ await writeFile(tmp, buf);
206
+ if (process.platform !== 'win32') await chmod(tmp, 0o755);
207
+ if (process.platform === 'darwin') await new Promise((r) => execFile('xattr', ['-c', tmp], () => r()));
208
+ // The new file must answer --version before it may become the real one.
209
+ const said = await new Promise((r) => execFile(tmp, ['--version'], { timeout: 60_000, windowsHide: true }, (err, stdout) => r(err ? '' : String(stdout || '').trim())));
210
+ if (!parseVersion(said)) { await rm(tmp, { force: true }); throw new Error('the downloaded gateway would not run, so it was discarded'); }
211
+ if (process.platform === 'win32') {
212
+ // A running .exe cannot be overwritten but can be renamed: move it aside, drop the new one in.
213
+ await rename(target, path.join(dir, `chatpanel-gateway.old-${Date.now()}.exe`));
214
+ }
215
+ await rename(tmp, target); // POSIX: atomic over the running file; this process keeps its inode
216
+ return parseVersion(said);
217
+ }
218
+
219
+ /**
220
+ * Apply the update for this install's channel. Throws on any failure, leaving the running
221
+ * install untouched. Does NOT restart — the caller answers its request first, then restarts.
222
+ * Returns { from, to, mode } where `to` is what is now ON DISK (the running process is still `from`).
223
+ */
224
+ export async function selfUpdate(current) {
225
+ if (DISABLED) throw new Error('Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).');
226
+ const info = await checkForUpdate(current, { force: true });
227
+ // A forced check that fell back to the cache checked nothing. Acting on it is how an
228
+ // update lands on a superseded version and calls it a success.
229
+ if (info.stale) throw new Error(`Could not reach the update server${info.error ? ` (${info.error})` : ''}. Refusing to act on a stale check — try again in a few minutes.`);
230
+ if (!info.updateAvailable) throw new Error(`Already on the latest ${info.channel} version (v${current}).`);
231
+ if (!info.canSelfUpdate) throw new Error(info.mode === 'npm' ? `This gateway cannot update itself here. Run: ${info.npmCommand}` : 'No downloadable build for this platform — install it with npm instead.');
232
+ if (info.mode === 'binary') return { from: current, to: await swapBinary(info), mode: 'binary' };
233
+ if (process.platform === 'win32') {
234
+ // The install happens after exit (see restartService); `to` is what the registry says.
235
+ return { from: current, to: info.latest, mode: 'npm', deferred: `"${process.execPath}" "${npmCli()}" install -g ${PACKAGE}@latest --registry=${NPM_REGISTRY} --no-fund --no-audit` };
236
+ }
237
+ const r = await runNpmInstall();
238
+ if (!r.ok) throw new Error(`npm install failed: ${r.out.slice(0, 800)}`);
239
+ // Success is the copy on disk moving, not npm exiting zero — npm reports success when it
240
+ // updated a copy the service never launches.
241
+ const to = installedNpmVersion();
242
+ if (!to || cmpVersions(to, current) <= 0) throw new Error(`npm ran, but the install at ${npmPackageRoot()} is still ${to || 'unreadable'} — the service launches a copy npm did not update. Run: ${info.npmCommand}`);
243
+ return { from: current, to, mode: 'npm' };
244
+ }
245
+
246
+ // ── the job ─────────────────────────────────────────────────────────────────────────
247
+
248
+ const job = { state: 'idle', mode: '', from: '', to: '', detail: '', startedAt: 0, endedAt: 0 };
249
+ /** What GET /update reports. `restarting` is the last thing this process says. */
250
+ export function updateJob() { return { ...job }; }
251
+ /**
252
+ * Start the update in the background. The restart runs after the install landed, on a later
253
+ * tick, so the caller's response is out before the process goes. Returns the job, or the
254
+ * running one if one is already going (an update twice at once is a corrupt install).
255
+ * `restart` is a test seam; the real one is service.js's restartService.
256
+ */
257
+ export function startUpdate(current, { restart = restartService, apply = selfUpdate } = {}) {
258
+ if (job.state === 'installing' || job.state === 'restarting') return { ...job, already: true };
259
+ Object.assign(job, { state: 'installing', mode: isCompiledBinary() ? 'binary' : 'npm', from: current, to: '', detail: '', startedAt: Date.now(), endedAt: 0 });
260
+ apply(current).then((r) => {
261
+ Object.assign(job, { state: 'restarting', to: r.to, mode: r.mode, detail: r.deferred ? `stopping to install v${r.to}, then relaunching` : `v${r.to} is installed; restarting the gateway into it` });
262
+ setTimeout(() => {
263
+ const how = restart({ winInstall: r.deferred || '' });
264
+ if (!how) Object.assign(job, { state: 'done', endedAt: Date.now(), detail: `v${r.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.` });
265
+ }, 400);
266
+ }).catch((e) => {
267
+ Object.assign(job, { state: 'failed', endedAt: Date.now(), detail: String(e?.message || e).slice(0, 1200) });
268
+ });
269
+ return { ...job };
270
+ }
271
+
272
+ /** Test seam. */
273
+ export function _resetUpdateJob() { Object.assign(job, { state: 'idle', mode: '', from: '', to: '', detail: '', startedAt: 0, endedAt: 0 }); }