@chatpanel/gateway 0.6.105 → 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.105",
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.105';
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
@@ -981,6 +999,7 @@ export function createGateway(cfg = loadConfig()) {
981
999
  // POST /v1/teams/runs/:id/answer { threadId, text, by } → { ok, run } a person answers an ask (0.6.81)
982
1000
  // POST /v1/teams/runs/:id/decide { postId, status, by } → { ok, run } approve / reject a post
983
1001
  // POST /v1/teams/runs/:id/post { threadId, text, kind?, replyTo?, by } → { ok, run }
1002
+ // DELETE /v1/teams/runs/:id/threads/:threadId → { ok, run } a person removes a thread from the board (0.6.106)
984
1003
  // POST /v1/teams/runs/:id/handoff { taskId, model, by, reason } → { ok, run } continue a task on another model (0.6.85)
985
1004
  // GET /v1/teams/runs/:id/checkpoint → { ok, checkpoint } what resumeTeam needs, from the record
986
1005
  // POST /v1/teams/runs/:id/claim { client } → { ok, run } a client takes a stopped/stale run over
@@ -998,7 +1017,7 @@ export function createGateway(cfg = loadConfig()) {
998
1017
  }
999
1018
  }
1000
1019
  {
1001
- const m = /^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim)?$/.exec(pathname);
1020
+ const m = /^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(pathname);
1002
1021
  if (m) {
1003
1022
  const id = m[1];
1004
1023
  const sub = m[2] || '';
@@ -1027,6 +1046,9 @@ export function createGateway(cfg = loadConfig()) {
1027
1046
  return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
1028
1047
  }
1029
1048
  }
1049
+ if (sub.startsWith('/threads/') && req.method === 'DELETE') {
1050
+ try { return sendJson(res, 200, { ok: true, run: teamStore.removeThread(id, { threadId: sub.slice('/threads/'.length), by: 'person' }) }); } catch (e) { return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } }); }
1051
+ }
1030
1052
  if ((sub === '/answer' || sub === '/decide' || sub === '/post') && req.method === 'POST') {
1031
1053
  try {
1032
1054
  const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
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/team-board.js CHANGED
@@ -105,6 +105,7 @@ export function foldBoard(state, ev) {
105
105
  if (type === 'board.thread' && p.thread?.id) {
106
106
  if (!s.threads.some((t) => t.id === p.thread.id)) s.threads.push({ ...p.thread });
107
107
  } else if (type === 'board.post' && p.post?.id) {
108
+ if (Array.isArray(s.removed) && s.removed.includes(p.post.threadId)) return s;
108
109
  if (!s.posts.some((x) => x.id === p.post.id)) s.posts.push({ ...p.post });
109
110
  const t = s.threads.find((x) => x.id === p.post.threadId);
110
111
  if (t) { t.lastAt = p.post.at; t.lastBy = p.post.by; t.posts = (t.posts || 0) + 1; }
@@ -114,6 +115,13 @@ export function foldBoard(state, ev) {
114
115
  } else if (type === 'board.thread-status' && p.threadId) {
115
116
  const t = s.threads.find((x) => x.id === p.threadId);
116
117
  if (t) { t.status = p.status; if (p.status !== 'waiting') t.waitingOn = null; if (p.holder) t.holder = p.holder; }
118
+ } else if (type === 'board.thread-removed' && p.threadId) {
119
+ // A person took the thread off the board: it and its posts go, and its id is kept so a
120
+ // post a member still makes in it (its runner did not see the removal) lands nowhere.
121
+ s.threads = s.threads.filter((x) => x.id !== p.threadId);
122
+ s.posts = s.posts.filter((x) => x.threadId !== p.threadId);
123
+ if (!Array.isArray(s.removed)) s.removed = [];
124
+ if (!s.removed.includes(p.threadId)) s.removed.push(p.threadId);
117
125
  }
118
126
  return s;
119
127
  }
@@ -124,7 +132,7 @@ export function foldBoard(state, ev) {
124
132
  * stays: a finding is a post of kind `finding` in its task's thread.
125
133
  */
126
134
  export function createBoard({ now = () => Date.now(), newId = null, state = null, onEvent = null } = {}) {
127
- const st = state && Array.isArray(state.threads) ? { threads: state.threads.map((t) => ({ ...t })), posts: (state.posts || []).map((x) => ({ ...x })) } : emptyBoardState();
135
+ const st = state && Array.isArray(state.threads) ? { threads: state.threads.map((t) => ({ ...t })), posts: (state.posts || []).map((x) => ({ ...x })), ...(Array.isArray(state.removed) && state.removed.length ? { removed: [...state.removed] } : {}) } : emptyBoardState();
128
136
  const listeners = new Set();
129
137
  let seq = st.posts.length + st.threads.length;
130
138
  const mk = (prefix) => (newId ? newId(prefix) : `${prefix}_${(++seq).toString(36)}${Math.random().toString(36).slice(2, 6)}`);
@@ -182,6 +190,20 @@ export function createBoard({ now = () => Date.now(), newId = null, state = null
182
190
  say('board.thread-status', { threadId, status, ...extra });
183
191
  return t;
184
192
  },
193
+ /**
194
+ * A person takes a thread off the board (from either client — the store appends the
195
+ * event, the running client's tail applies it here). Its posts go with it; a member's
196
+ * later post in it lands nowhere. A waiting ask is not removed: answer it or stop the run.
197
+ */
198
+ removeThread(threadId, { by = PERSON } = {}) {
199
+ const t = threadOf(threadId);
200
+ if (!t || (t.kind === 'ask' && t.status === 'waiting')) return null;
201
+ st.threads = st.threads.filter((x) => x.id !== threadId);
202
+ st.posts = st.posts.filter((x) => x.threadId !== threadId);
203
+ (st.removed ||= []).push(threadId);
204
+ say('board.thread-removed', { threadId, by });
205
+ return t;
206
+ },
185
207
  /**
186
208
  * A member is stuck: open an ask thread (status `waiting`) with the question as its
187
209
  * first post. The runner waits on it; a person answers from either client.
@@ -209,7 +231,7 @@ export function createBoard({ now = () => Date.now(), newId = null, state = null
209
231
  /** Every ask still waiting — what a client pins at the top. */
210
232
  waiting: () => st.threads.filter((t) => t.kind === 'ask' && t.status === 'waiting').map((t) => ({ ...t })),
211
233
  /** The whole board, for the run record and for a resume. */
212
- state: () => ({ threads: st.threads.map((t) => ({ ...t })), posts: st.posts.map((x) => ({ ...x })) }),
234
+ state: () => ({ threads: st.threads.map((t) => ({ ...t })), posts: st.posts.map((x) => ({ ...x })), ...(st.removed?.length ? { removed: [...st.removed] } : {}) }),
213
235
 
214
236
  // ── findings, as before: a finding is a post in its task's thread ──
215
237
  add(list, { by = null } = {}) {
@@ -71,7 +71,10 @@ export function foldRun(run, ev) {
71
71
  if (t) { t.status = 'running'; t.startedAt = at; t.error = null; }
72
72
  run.status = 'running'; break;
73
73
  }
74
- case 'task.model': { const t = taskOf(run, p.taskId); if (t) { t.model = p.model; t.attempts = [...(t.attempts || []), { model: p.model, at, attempt: p.attempt }]; } break; }
74
+ case 'task.model': { const t = taskOf(run, p.taskId); if (t) { t.model = p.model; t.attempts = [...(t.attempts || []), { model: p.model, ...(p.label ? { label: p.label } : {}), at, attempt: p.attempt }]; } break; }
75
+ // Which engine the attempt runs on (pillars §13): kept on the attempt, so a record folded
76
+ // from events names the model the way the runner's own `attempts` do.
77
+ case 'task.routed': { const t = taskOf(run, p.taskId); const a = t?.attempts?.at?.(-1); if (a && p.engine && (a.attempt == null || a.attempt === p.attempt)) a.engine = p.engine; break; }
75
78
  case 'task.step': { const t = taskOf(run, p.taskId); if (t && Array.isArray(p.steps)) t.transcript = [...(t.transcript || []), ...p.steps]; break; }
76
79
  case 'task.handoff': { const t = taskOf(run, p.taskId); if (t) { t.model = p.to; t.handoffs = [...(t.handoffs || []), { from: p.from, to: p.to, by: p.by, reason: p.reason, at }]; } break; }
77
80
  case 'task.tool': { const t = taskOf(run, p.taskId); if (t) t.tools = (t.tools || 0) + 1; break; }
@@ -97,7 +100,7 @@ export function foldRun(run, ev) {
97
100
  if (p.checkpoint) run.checkpoint = p.checkpoint;
98
101
  break;
99
102
  case 'run.stop-requested': run.stopRequested = at; break;
100
- case 'board.thread': case 'board.post': case 'board.decision': case 'board.thread-status':
103
+ case 'board.thread': case 'board.post': case 'board.decision': case 'board.thread-status': case 'board.thread-removed':
101
104
  run.threads = foldBoard(run.threads || emptyBoardState(), ev);
102
105
  if (type === 'board.thread-status' && p.status !== 'waiting' && run.status === 'waiting' && !(run.threads.threads || []).some((t) => t.kind === 'ask' && t.status === 'waiting')) run.status = 'answered';
103
106
  break;
package/src/team-store.js CHANGED
@@ -197,6 +197,19 @@ export class TeamStore {
197
197
  const post = { id: `pp_${randomBytes(4).toString('hex')}`, threadId, by: String(by || 'person').slice(0, 40), kind: ['note', 'question', 'decision'].includes(kind) ? kind : 'note', text: String(text || '').slice(0, 4000), refs: [], replyTo: replyTo || null, status: 'open', at };
198
198
  return this.append(id, [{ type: 'board.post', at, post }]);
199
199
  }
200
+ /**
201
+ * A person takes a thread off the board, from any client: the thread and its posts leave the
202
+ * record, and the running client's tail applies the same event to its live board. A waiting
203
+ * ask stays — the member behind it is blocked on an answer, not on tidiness.
204
+ */
205
+ removeThread(id, { threadId, by = 'person' } = {}) {
206
+ const run = this.runs.get(String(id || ''));
207
+ if (!run) throw new Error(`no run ${id}`);
208
+ const thread = (run.threads?.threads || []).find((t) => t.id === threadId);
209
+ if (!thread) throw new Error(`no thread ${threadId}`);
210
+ if (thread.kind === 'ask' && thread.status === 'waiting') throw new Error('an ask that is waiting cannot be removed — answer it, or stop the run');
211
+ return this.append(id, [{ type: 'board.thread-removed', at: this.now(), threadId, by: String(by || 'person').slice(0, 40) }]);
212
+ }
200
213
  /** The checkpoint a client resumes from — the runner's own when the run ended with one, else built from the record. */
201
214
  checkpoint(id) {
202
215
  const run = this.runs.get(String(id || ''));
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 }); }