@chatpanel/gateway 0.6.110 → 0.8.0
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/README.md +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +2 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/policy.js +2 -0
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2296
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/src/tts-voices.js
CHANGED
|
@@ -1,192 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// A voice print is biometric-adjacent data about a specific person, so the rules
|
|
4
|
-
// here are deliberately tighter than for anything else this gateway stores:
|
|
5
|
-
// • It NEVER leaves the machine. The embedding is computed in-process by the
|
|
6
|
-
// speaker model already on disk (the one diarization uses), written under
|
|
7
|
-
// ~/.chatpanel, and read back only to condition local synthesis.
|
|
8
|
-
// • The SAMPLE is never persisted. Only the 512 floats derived from it — audio
|
|
9
|
-
// of someone speaking is far more revealing than the vector, and keeping it
|
|
10
|
-
// would serve no purpose once the embedding exists.
|
|
11
|
-
// • Deleting means the file is gone, not flagged. There is no soft-delete for
|
|
12
|
-
// someone's voice.
|
|
13
|
-
//
|
|
14
|
-
// What this can and cannot do is stated plainly in the UI, and the reason lives
|
|
15
|
-
// here: SpeechT5 was trained against speechbrain x-vectors and we embed with
|
|
16
|
-
// wavlm-base-plus-sv, which is a different 512-d space. The result is a distinct,
|
|
17
|
-
// STABLE voice derived from the sample — the same sample always gives the same
|
|
18
|
-
// voice, and different speakers give clearly different ones — but it is not a
|
|
19
|
-
// faithful reproduction of the speaker. Calling that "cloning" without saying so
|
|
20
|
-
// would be a lie told by a feature name.
|
|
21
|
-
|
|
22
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, rmSync } from 'node:fs';
|
|
23
|
-
import { join } from 'node:path';
|
|
24
|
-
import { randomUUID } from 'node:crypto';
|
|
25
|
-
import os from 'node:os';
|
|
26
|
-
|
|
27
|
-
export const EMBED_DIM = 512;
|
|
28
|
-
|
|
29
|
-
// A voice print is engine-specific: SpeechT5 wants a 512-d wavlm x-vector, Pocket
|
|
30
|
-
// TTS wants its Mimi encoder's [1, N, 1024] conditioning. They are NOT
|
|
31
|
-
// interchangeable, and the sample is discarded after saving, so whatever a voice
|
|
32
|
-
// might later need has to be computed WHILE the audio is still in hand.
|
|
33
|
-
//
|
|
34
|
-
// The pocket conditioning is ~100k floats — small on disk, absurd inside a JSON
|
|
35
|
-
// document that a settings page lists — so it lives beside the record as raw
|
|
36
|
-
// Float32 and only its shape is stored in the JSON.
|
|
37
|
-
export const KIND_SPEECHT5 = 'wavlm-512';
|
|
38
|
-
export const KIND_POCKET = 'pocket-mimi';
|
|
39
|
-
const MAX_VOICES = 20;
|
|
40
|
-
const MAX_NAME = 60;
|
|
41
|
-
|
|
42
|
-
export function voicesDir() {
|
|
43
|
-
return process.env.CHATPANEL_TTS_VOICES || join(os.homedir(), '.chatpanel', 'tts-voices');
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// An id becomes a FILENAME and arrives from the wire, so it is shape-checked, not
|
|
47
|
-
// trusted. UUIDs are what we mint; the pattern is what we accept.
|
|
48
|
-
export function isValidVoiceRef(id) {
|
|
49
|
-
return /^[A-Za-z0-9_-]{1,64}$/.test(String(id || ''));
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// The wire form is `custom:<id>` so one `voice` field can name either a built-in
|
|
53
|
-
// Kokoro voice or a saved one, with no ambiguity between the two namespaces.
|
|
54
|
-
export function parseCustomVoice(voice) {
|
|
55
|
-
const s = String(voice || '');
|
|
56
|
-
if (!s.startsWith('custom:')) return null;
|
|
57
|
-
const id = s.slice(7);
|
|
58
|
-
return isValidVoiceRef(id) ? id : null;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function fileFor(id) {
|
|
62
|
-
return join(voicesDir(), `${id}.json`);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export function listVoices() {
|
|
66
|
-
const dir = voicesDir();
|
|
67
|
-
if (!existsSync(dir)) return [];
|
|
68
|
-
const out = [];
|
|
69
|
-
for (const f of readdirSync(dir)) {
|
|
70
|
-
if (!f.endsWith('.json')) continue;
|
|
71
|
-
try {
|
|
72
|
-
const v = JSON.parse(readFileSync(join(dir, f), 'utf8'));
|
|
73
|
-
// The vector is deliberately NOT returned by the listing: the UI needs a
|
|
74
|
-
// name and an id, and 512 floats of someone's voice print have no business
|
|
75
|
-
// in a settings page's JSON.
|
|
76
|
-
if (v?.id && v?.name) {
|
|
77
|
-
out.push({
|
|
78
|
-
id: v.id, name: v.name, createdAt: v.createdAt || 0, updatedAt: v.updatedAt || 0, dim: v.vec?.length || 0,
|
|
79
|
-
kinds: v.pocketShape ? [KIND_SPEECHT5, KIND_POCKET] : [KIND_SPEECHT5],
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
} catch { /* a corrupt file must not break the list */ }
|
|
83
|
-
}
|
|
84
|
-
return out.sort((a, b) => b.createdAt - a.createdAt);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function pocketFileFor(id) {
|
|
88
|
-
return join(voicesDir(), `${id}.pocket.bin`);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export function getVoice(id) {
|
|
92
|
-
if (!isValidVoiceRef(id)) return null;
|
|
93
|
-
try {
|
|
94
|
-
const v = JSON.parse(readFileSync(fileFor(id), 'utf8'));
|
|
95
|
-
if (!Array.isArray(v?.vec) || v.vec.length !== EMBED_DIM) return null;
|
|
96
|
-
return v;
|
|
97
|
-
} catch { return null; }
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** The Pocket TTS conditioning for a voice, or null if it has none saved. */
|
|
101
|
-
export function getPocketVoice(id) {
|
|
102
|
-
if (!isValidVoiceRef(id)) return null;
|
|
103
|
-
const meta = getVoice(id);
|
|
104
|
-
if (!meta?.pocketShape) return null;
|
|
105
|
-
try {
|
|
106
|
-
const buf = readFileSync(pocketFileFor(id));
|
|
107
|
-
return { data: new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)), shape: meta.pocketShape };
|
|
108
|
-
} catch { return null; }
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** Which engines can speak as this voice. Drives what the UI may offer. */
|
|
112
|
-
export function voiceKinds(id) {
|
|
113
|
-
const v = getVoice(id);
|
|
114
|
-
if (!v) return [];
|
|
115
|
-
return v.pocketShape ? [KIND_SPEECHT5, KIND_POCKET] : [KIND_SPEECHT5];
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/** Persist an embedding under a user-chosen name. Returns the stored record. */
|
|
119
|
-
export function saveVoice({ name, vec, pocket = null }) {
|
|
120
|
-
const clean = String(name || '').trim().slice(0, MAX_NAME);
|
|
121
|
-
if (!clean) throw new Error('a name is required');
|
|
122
|
-
if (!vec || vec.length !== EMBED_DIM) throw new Error(`expected a ${EMBED_DIM}-value embedding, got ${vec?.length || 0}`);
|
|
123
|
-
if (listVoices().length >= MAX_VOICES) throw new Error(`at most ${MAX_VOICES} saved voices — delete one first`);
|
|
124
|
-
const dir = voicesDir();
|
|
125
|
-
mkdirSync(dir, { recursive: true });
|
|
126
|
-
const rec = { id: randomUUID(), name: clean, createdAt: Date.now(), vec: Array.from(vec, (x) => Number(x) || 0) };
|
|
127
|
-
if (pocket?.data?.length && Array.isArray(pocket.shape)) {
|
|
128
|
-
rec.pocketShape = pocket.shape;
|
|
129
|
-
const f32 = pocket.data instanceof Float32Array ? pocket.data : Float32Array.from(pocket.data);
|
|
130
|
-
writeFileSync(pocketFileFor(rec.id), Buffer.from(f32.buffer, f32.byteOffset, f32.byteLength));
|
|
131
|
-
}
|
|
132
|
-
writeFileSync(fileFor(rec.id), JSON.stringify(rec));
|
|
133
|
-
return { id: rec.id, name: rec.name, createdAt: rec.createdAt, dim: rec.vec.length, kinds: rec.pocketShape ? [KIND_SPEECHT5, KIND_POCKET] : [KIND_SPEECHT5] };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Rename in place. The id is untouched on purpose: `custom:<id>` is what the
|
|
138
|
-
* gateway config and every client store, so a rename must not invalidate them.
|
|
139
|
-
*/
|
|
140
|
-
export function renameVoice(id, name) {
|
|
141
|
-
const rec = getVoice(id);
|
|
142
|
-
if (!rec) return null;
|
|
143
|
-
const clean = String(name || '').trim().slice(0, MAX_NAME);
|
|
144
|
-
if (!clean) throw new Error('a name is required');
|
|
145
|
-
rec.name = clean;
|
|
146
|
-
rec.updatedAt = Date.now();
|
|
147
|
-
writeFileSync(fileFor(id), JSON.stringify(rec));
|
|
148
|
-
return { id, name: rec.name, createdAt: rec.createdAt || 0, updatedAt: rec.updatedAt, dim: rec.vec?.length || 0 };
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Re-record: swap in prints derived from a NEW sample, keeping the id and name.
|
|
153
|
-
*
|
|
154
|
-
* Keeping the id is the whole point. A first take is often poor — too quiet, a
|
|
155
|
-
* cough, the wrong room — and the fix should be "record that again", not "delete
|
|
156
|
-
* it, record a new one, and go re-select it everywhere". Anything already pointing
|
|
157
|
-
* at this voice keeps working and simply sounds different.
|
|
158
|
-
*/
|
|
159
|
-
export function replaceVoice(id, { vec, pocket = null }) {
|
|
160
|
-
const rec = getVoice(id);
|
|
161
|
-
if (!rec) return null;
|
|
162
|
-
if (!vec || vec.length !== EMBED_DIM) throw new Error(`expected a ${EMBED_DIM}-value embedding, got ${vec?.length || 0}`);
|
|
163
|
-
rec.vec = Array.from(vec, (x) => Number(x) || 0);
|
|
164
|
-
rec.updatedAt = Date.now();
|
|
165
|
-
if (pocket?.data?.length && Array.isArray(pocket.shape)) {
|
|
166
|
-
rec.pocketShape = pocket.shape;
|
|
167
|
-
const f32 = pocket.data instanceof Float32Array ? pocket.data : Float32Array.from(pocket.data);
|
|
168
|
-
writeFileSync(pocketFileFor(id), Buffer.from(f32.buffer, f32.byteOffset, f32.byteLength));
|
|
169
|
-
} else if (rec.pocketShape) {
|
|
170
|
-
// The new take produced no Pocket conditioning (its bundle is missing), so the
|
|
171
|
-
// OLD one must go — leaving it would pair a stale voice with a fresh print and
|
|
172
|
-
// the voice would change depending on which engine spoke.
|
|
173
|
-
delete rec.pocketShape;
|
|
174
|
-
rmSync(pocketFileFor(id), { force: true });
|
|
175
|
-
}
|
|
176
|
-
writeFileSync(fileFor(id), JSON.stringify(rec));
|
|
177
|
-
return {
|
|
178
|
-
id, name: rec.name, createdAt: rec.createdAt || 0, updatedAt: rec.updatedAt,
|
|
179
|
-
dim: rec.vec.length, kinds: rec.pocketShape ? [KIND_SPEECHT5, KIND_POCKET] : [KIND_SPEECHT5],
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/** Remove one permanently. Returns whether there was anything to remove. */
|
|
184
|
-
export function deleteVoice(id) {
|
|
185
|
-
if (!isValidVoiceRef(id)) return false;
|
|
186
|
-
const p = fileFor(id);
|
|
187
|
-
if (!existsSync(p)) return false;
|
|
188
|
-
rmSync(p, { force: true });
|
|
189
|
-
// Both halves, or the conditioning outlives the record that named it.
|
|
190
|
-
rmSync(pocketFileFor(id), { force: true });
|
|
191
|
-
return true;
|
|
192
|
-
}
|
|
1
|
+
import{existsSync as g,mkdirSync as w,readFileSync as y,writeFileSync as u,readdirSync as b,rmSync as S}from"node:fs";import{join as l}from"node:path";import{randomUUID as E}from"node:crypto";import V from"node:os";const s=512,a="wavlm-512",p="pocket-mimi",x=20,v=60;function m(){return process.env.CHATPANEL_TTS_VOICES||l(V.homedir(),".chatpanel","tts-voices")}function h(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}function _(e){const r=String(e||"");if(!r.startsWith("custom:"))return null;const t=r.slice(7);return h(t)?t:null}function f(e){return l(m(),`${e}.json`)}function N(){const e=m();if(!g(e))return[];const r=[];for(const t of b(e))if(t.endsWith(".json"))try{const n=JSON.parse(y(l(e,t),"utf8"));n?.id&&n?.name&&r.push({id:n.id,name:n.name,createdAt:n.createdAt||0,updatedAt:n.updatedAt||0,dim:n.vec?.length||0,kinds:n.pocketShape?[a,p]:[a]})}catch{}return r.sort((t,n)=>n.createdAt-t.createdAt)}function d(e){return l(m(),`${e}.pocket.bin`)}function A(e){if(!h(e))return null;try{const r=JSON.parse(y(f(e),"utf8"));return!Array.isArray(r?.vec)||r.vec.length!==s?null:r}catch{return null}}function $(e){if(!h(e))return null;const r=A(e);if(!r?.pocketShape)return null;try{const t=y(d(e));return{data:new Float32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),shape:r.pocketShape}}catch{return null}}function C(e){const r=A(e);return r?r.pocketShape?[a,p]:[a]:[]}function I({name:e,vec:r,pocket:t=null}){const n=String(e||"").trim().slice(0,v);if(!n)throw new Error("a name is required");if(!r||r.length!==s)throw new Error(`expected a ${s}-value embedding, got ${r?.length||0}`);if(N().length>=x)throw new Error(`at most ${x} saved voices — delete one first`);const i=m();w(i,{recursive:!0});const o={id:E(),name:n,createdAt:Date.now(),vec:Array.from(r,c=>Number(c)||0)};if(t?.data?.length&&Array.isArray(t.shape)){o.pocketShape=t.shape;const c=t.data instanceof Float32Array?t.data:Float32Array.from(t.data);u(d(o.id),Buffer.from(c.buffer,c.byteOffset,c.byteLength))}return u(f(o.id),JSON.stringify(o)),{id:o.id,name:o.name,createdAt:o.createdAt,dim:o.vec.length,kinds:o.pocketShape?[a,p]:[a]}}function M(e,r){const t=A(e);if(!t)return null;const n=String(r||"").trim().slice(0,v);if(!n)throw new Error("a name is required");return t.name=n,t.updatedAt=Date.now(),u(f(e),JSON.stringify(t)),{id:e,name:t.name,createdAt:t.createdAt||0,updatedAt:t.updatedAt,dim:t.vec?.length||0}}function J(e,{vec:r,pocket:t=null}){const n=A(e);if(!n)return null;if(!r||r.length!==s)throw new Error(`expected a ${s}-value embedding, got ${r?.length||0}`);if(n.vec=Array.from(r,i=>Number(i)||0),n.updatedAt=Date.now(),t?.data?.length&&Array.isArray(t.shape)){n.pocketShape=t.shape;const i=t.data instanceof Float32Array?t.data:Float32Array.from(t.data);u(d(e),Buffer.from(i.buffer,i.byteOffset,i.byteLength))}else n.pocketShape&&(delete n.pocketShape,S(d(e),{force:!0}));return u(f(e),JSON.stringify(n)),{id:e,name:n.name,createdAt:n.createdAt||0,updatedAt:n.updatedAt,dim:n.vec.length,kinds:n.pocketShape?[a,p]:[a]}}function T(e){if(!h(e))return!1;const r=f(e);return g(r)?(S(r,{force:!0}),S(d(e),{force:!0}),!0):!1}export{s as EMBED_DIM,p as KIND_POCKET,a as KIND_SPEECHT5,T as deleteVoice,$ as getPocketVoice,A as getVoice,h as isValidVoiceRef,N as listVoices,_ as parseCustomVoice,M as renameVoice,J as replaceVoice,I as saveVoice,C as voiceKinds,m as voicesDir};
|
package/src/update.js
CHANGED
|
@@ -1,305 +1 @@
|
|
|
1
|
-
|
|
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, realpathSync } 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
|
-
/**
|
|
103
|
-
* The package root of the running npm install (…/node_modules/@chatpanel/gateway), or ''.
|
|
104
|
-
* The service launches the bin SYMLINK (<prefix>/bin/chatpanel-gateway), whose own path says
|
|
105
|
-
* nothing — the realpath is what is inside node_modules. (Reading it literally classified a
|
|
106
|
-
* global install as "not npm" and hid the Update button behind the command.)
|
|
107
|
-
*/
|
|
108
|
-
export function npmPackageRoot(script = process.argv[1]) {
|
|
109
|
-
let real = script ? path.resolve(script) : '';
|
|
110
|
-
try { real = realpathSync(real); } catch { /* a dangling link is still a clue */ }
|
|
111
|
-
const m = /^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(real);
|
|
112
|
-
return m ? m[1] : '';
|
|
113
|
-
}
|
|
114
|
-
/** The version the npm install on disk reports — what the NEXT start will run. */
|
|
115
|
-
function installedNpmVersion() {
|
|
116
|
-
const root = npmPackageRoot();
|
|
117
|
-
if (!root) return '';
|
|
118
|
-
try { return String(JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')).version || ''); } catch { return ''; }
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* The npm that belongs to the node running this process. A login service inherits no shell
|
|
122
|
-
* PATH, so `npm` bare is not findable; but npm's cli ships beside node in every layout this
|
|
123
|
-
* meets (nvm, Homebrew, the official installer, fnm): <prefix>/lib/node_modules/npm.
|
|
124
|
-
*/
|
|
125
|
-
function npmCli() {
|
|
126
|
-
const bin = path.dirname(process.execPath);
|
|
127
|
-
const candidates = [
|
|
128
|
-
path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
|
|
129
|
-
path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'), // the Windows layout
|
|
130
|
-
];
|
|
131
|
-
return candidates.find((p) => existsSync(p)) || '';
|
|
132
|
-
}
|
|
133
|
-
function runNpmInstall() {
|
|
134
|
-
const cli = npmCli();
|
|
135
|
-
const env = { ...process.env, npm_config_registry: NPM_REGISTRY, npm_config_fund: 'false', npm_config_audit: 'false' };
|
|
136
|
-
delete env.ELECTRON_RUN_AS_NODE; // leaked from a desktop host, it makes npm's node shims boot as Electron
|
|
137
|
-
const [cmd, args] = cli ? [process.execPath, [cli, 'install', '-g', `${PACKAGE}@latest`]] : ['npm', ['install', '-g', `${PACKAGE}@latest`]];
|
|
138
|
-
return new Promise((resolve) => {
|
|
139
|
-
execFile(cmd, args, { env, timeout: INSTALL_TIMEOUT_MS, maxBuffer: 8 << 20, windowsHide: true }, (err, stdout, stderr) => {
|
|
140
|
-
const out = `${stdout || ''}${stderr || ''}`.trim();
|
|
141
|
-
if (!err) return resolve({ ok: true, out });
|
|
142
|
-
if (err.killed && !out) return resolve({ ok: false, out: `npm was still running after ${Math.round(INSTALL_TIMEOUT_MS / 60000)} minutes and was stopped` });
|
|
143
|
-
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') });
|
|
144
|
-
});
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// ── check ───────────────────────────────────────────────────────────────────────────
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Returns { current, latest, updateAvailable, mode, canSelfUpdate, assetUrl, stale, error, npmCommand, channel }.
|
|
152
|
-
* `mode` binary | npm — each checks ITS channel (the release, the registry), because a fix
|
|
153
|
-
* published to npm does not exist as a binary until its tag is cut. `stale` says `latest`
|
|
154
|
-
* is yesterday's cache, not an answer. Throttled to CHECK_EVERY_MS unless `force`.
|
|
155
|
-
*/
|
|
156
|
-
export async function checkForUpdate(current, { force = false } = {}) {
|
|
157
|
-
const mode = isCompiledBinary() ? 'binary' : 'npm';
|
|
158
|
-
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 };
|
|
159
|
-
const want = assetName();
|
|
160
|
-
let latest = null; let assetUrl = null; let stale = false; let error = ''; let checkedAt = 0;
|
|
161
|
-
const cache = await readCache();
|
|
162
|
-
const cacheFits = cache && cache.mode === mode;
|
|
163
|
-
const fallBack = () => { latest = cacheFits ? cache.latest || null : null; assetUrl = cacheFits ? cache.assetUrl || null : null; checkedAt = cacheFits ? cache.checkedAt || 0 : 0; stale = true; };
|
|
164
|
-
if (!force && cacheFits && Date.now() - cache.checkedAt < CHECK_EVERY_MS) {
|
|
165
|
-
latest = cache.latest; assetUrl = cache.assetUrl; checkedAt = cache.checkedAt;
|
|
166
|
-
} else if (!force && lastFailure.at && Date.now() - lastFailure.at < RETRY_AFTER_FAILURE_MS) {
|
|
167
|
-
error = lastFailure.error; fallBack();
|
|
168
|
-
} else {
|
|
169
|
-
try {
|
|
170
|
-
if (mode === 'npm') {
|
|
171
|
-
const data = await fetchJson(LATEST_NPM);
|
|
172
|
-
latest = parseVersion(data.version);
|
|
173
|
-
} else {
|
|
174
|
-
const data = await fetchJson(LATEST_RELEASE);
|
|
175
|
-
latest = parseVersion(data.tag_name) || parseVersion(data.name);
|
|
176
|
-
assetUrl = want ? (data.assets || []).find((a) => a.name === want)?.browser_download_url || null : null;
|
|
177
|
-
}
|
|
178
|
-
checkedAt = Date.now();
|
|
179
|
-
await writeCache({ checkedAt, mode, latest, assetUrl });
|
|
180
|
-
lastFailure = { at: 0, error: '' };
|
|
181
|
-
} catch (e) {
|
|
182
|
-
error = e.message; lastFailure = { at: Date.now(), error }; fallBack();
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
const updateAvailable = !!latest && cmpVersions(latest, current) > 0;
|
|
186
|
-
// Windows npm: a running gateway holds onnxruntime's DLL and npm's copy fails with EBUSY, so
|
|
187
|
-
// the install runs AFTER this process exits, from the restart helper — which needs the
|
|
188
|
-
// registered service to relaunch it. No service, no self-update: the command is shown.
|
|
189
|
-
const canSelfUpdate = mode === 'binary' ? !!assetUrl && (process.platform !== 'win32' || serviceRegistered())
|
|
190
|
-
: !!npmPackageRoot() && (process.platform !== 'win32' || (serviceRegistered() && !!npmCli()));
|
|
191
|
-
const npmCommand = mode === 'npm' ? (process.platform === 'win32' ? `chatpanel-gateway --stop; npm i -g ${PACKAGE}@latest; chatpanel-gateway --install` : `npm i -g ${PACKAGE}@latest`) : null;
|
|
192
|
-
// `checkedAt`: when `latest` was last a real answer — so a client can say "as of 3 h ago"
|
|
193
|
-
// instead of an unqualified "up to date" minutes after a publish.
|
|
194
|
-
return { current, latest, updateAvailable, mode, canSelfUpdate, assetUrl, stale, error, npmCommand, channel: mode === 'npm' ? 'npm' : 'release', service: serviceRegistered(), checkedAt };
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
* What /status reports — NEVER waits on the network. The answer is the last check (in
|
|
199
|
-
* memory, else the disk cache — `stale: true` until a fresh one lands), and a fresh check is
|
|
200
|
-
* kicked off in the background when one is due. The first /status after a start therefore
|
|
201
|
-
* says "unknown yet"; the next says what the registry said. A /status that waited on a 5 s
|
|
202
|
-
* fetch behind a VPN missed the extension's 4 s deadline and drew "Not installed" for a
|
|
203
|
-
* gateway that was running.
|
|
204
|
-
*/
|
|
205
|
-
let known = null;
|
|
206
|
-
let inFlight = null;
|
|
207
|
-
export function updateStatus(current) {
|
|
208
|
-
const mode = isCompiledBinary() ? 'binary' : 'npm';
|
|
209
|
-
if (DISABLED) return { current, latest: null, updateAvailable: false, mode, canSelfUpdate: false, stale: false, error: '', npmCommand: null, channel: mode === 'npm' ? 'npm' : 'release', service: false, disabled: true };
|
|
210
|
-
const due = !known || (known.stale ? !(lastFailure.at && Date.now() - lastFailure.at < RETRY_AFTER_FAILURE_MS) : Date.now() - known.seenAt > CHECK_EVERY_MS);
|
|
211
|
-
if (due && !inFlight) {
|
|
212
|
-
inFlight = checkForUpdate(current).then((r) => { known = { ...r, seenAt: Date.now() }; }).catch(() => {}).finally(() => { inFlight = null; });
|
|
213
|
-
}
|
|
214
|
-
if (known) return { ...known, seenAt: undefined, current };
|
|
215
|
-
return { current, latest: null, updateAvailable: false, mode, canSelfUpdate: false, stale: true, checking: true, error: '', npmCommand: null, channel: mode === 'npm' ? 'npm' : 'release', service: serviceRegistered() };
|
|
216
|
-
}
|
|
217
|
-
/** Test seam. */
|
|
218
|
-
export function _resetUpdateStatus() { known = null; inFlight = null; }
|
|
219
|
-
|
|
220
|
-
// ── apply ───────────────────────────────────────────────────────────────────────────
|
|
221
|
-
|
|
222
|
-
async function swapBinary(info) {
|
|
223
|
-
const target = process.execPath;
|
|
224
|
-
const dir = path.dirname(target);
|
|
225
|
-
const tmp = path.join(dir, `.chatpanel-gateway.new-${Date.now()}`);
|
|
226
|
-
const ctl = new AbortController();
|
|
227
|
-
const timer = setTimeout(() => ctl.abort(), DOWNLOAD_TIMEOUT_MS);
|
|
228
|
-
let buf;
|
|
229
|
-
try {
|
|
230
|
-
const res = await fetch(info.assetUrl, { headers: UA, redirect: 'follow', signal: ctl.signal });
|
|
231
|
-
if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`);
|
|
232
|
-
if (!downloadHostAllowed(res.url || info.assetUrl)) throw new Error(`refused: the download was redirected to ${res.url}, which is not a ChatPanel release host`);
|
|
233
|
-
buf = Buffer.from(await res.arrayBuffer());
|
|
234
|
-
} finally { clearTimeout(timer); }
|
|
235
|
-
// These binaries are tens of megabytes; anything small is an error page or a truncated body.
|
|
236
|
-
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`);
|
|
237
|
-
await writeFile(tmp, buf);
|
|
238
|
-
if (process.platform !== 'win32') await chmod(tmp, 0o755);
|
|
239
|
-
if (process.platform === 'darwin') await new Promise((r) => execFile('xattr', ['-c', tmp], () => r()));
|
|
240
|
-
// The new file must answer --version before it may become the real one.
|
|
241
|
-
const said = await new Promise((r) => execFile(tmp, ['--version'], { timeout: 60_000, windowsHide: true }, (err, stdout) => r(err ? '' : String(stdout || '').trim())));
|
|
242
|
-
if (!parseVersion(said)) { await rm(tmp, { force: true }); throw new Error('the downloaded gateway would not run, so it was discarded'); }
|
|
243
|
-
if (process.platform === 'win32') {
|
|
244
|
-
// A running .exe cannot be overwritten but can be renamed: move it aside, drop the new one in.
|
|
245
|
-
await rename(target, path.join(dir, `chatpanel-gateway.old-${Date.now()}.exe`));
|
|
246
|
-
}
|
|
247
|
-
await rename(tmp, target); // POSIX: atomic over the running file; this process keeps its inode
|
|
248
|
-
return parseVersion(said);
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* Apply the update for this install's channel. Throws on any failure, leaving the running
|
|
253
|
-
* install untouched. Does NOT restart — the caller answers its request first, then restarts.
|
|
254
|
-
* Returns { from, to, mode } where `to` is what is now ON DISK (the running process is still `from`).
|
|
255
|
-
*/
|
|
256
|
-
export async function selfUpdate(current) {
|
|
257
|
-
if (DISABLED) throw new Error('Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).');
|
|
258
|
-
const info = await checkForUpdate(current, { force: true });
|
|
259
|
-
// A forced check that fell back to the cache checked nothing. Acting on it is how an
|
|
260
|
-
// update lands on a superseded version and calls it a success.
|
|
261
|
-
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.`);
|
|
262
|
-
if (!info.updateAvailable) throw new Error(`Already on the latest ${info.channel} version (v${current}).`);
|
|
263
|
-
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.');
|
|
264
|
-
if (info.mode === 'binary') return { from: current, to: await swapBinary(info), mode: 'binary' };
|
|
265
|
-
if (process.platform === 'win32') {
|
|
266
|
-
// The install happens after exit (see restartService); `to` is what the registry says.
|
|
267
|
-
return { from: current, to: info.latest, mode: 'npm', deferred: `"${process.execPath}" "${npmCli()}" install -g ${PACKAGE}@latest --registry=${NPM_REGISTRY} --no-fund --no-audit` };
|
|
268
|
-
}
|
|
269
|
-
const r = await runNpmInstall();
|
|
270
|
-
if (!r.ok) throw new Error(`npm install failed: ${r.out.slice(0, 800)}`);
|
|
271
|
-
// Success is the copy on disk moving, not npm exiting zero — npm reports success when it
|
|
272
|
-
// updated a copy the service never launches.
|
|
273
|
-
const to = installedNpmVersion();
|
|
274
|
-
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}`);
|
|
275
|
-
return { from: current, to, mode: 'npm' };
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// ── the job ─────────────────────────────────────────────────────────────────────────
|
|
279
|
-
|
|
280
|
-
const job = { state: 'idle', mode: '', from: '', to: '', detail: '', startedAt: 0, endedAt: 0 };
|
|
281
|
-
/** What GET /update reports. `restarting` is the last thing this process says. */
|
|
282
|
-
export function updateJob() { return { ...job }; }
|
|
283
|
-
/**
|
|
284
|
-
* Start the update in the background. The restart runs after the install landed, on a later
|
|
285
|
-
* tick, so the caller's response is out before the process goes. Returns the job, or the
|
|
286
|
-
* running one if one is already going (an update twice at once is a corrupt install).
|
|
287
|
-
* `restart` is a test seam; the real one is service.js's restartService.
|
|
288
|
-
*/
|
|
289
|
-
export function startUpdate(current, { restart = restartService, apply = selfUpdate } = {}) {
|
|
290
|
-
if (job.state === 'installing' || job.state === 'restarting') return { ...job, already: true };
|
|
291
|
-
Object.assign(job, { state: 'installing', mode: isCompiledBinary() ? 'binary' : 'npm', from: current, to: '', detail: '', startedAt: Date.now(), endedAt: 0 });
|
|
292
|
-
apply(current).then((r) => {
|
|
293
|
-
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` });
|
|
294
|
-
setTimeout(() => {
|
|
295
|
-
const how = restart({ winInstall: r.deferred || '' });
|
|
296
|
-
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.` });
|
|
297
|
-
}, 400);
|
|
298
|
-
}).catch((e) => {
|
|
299
|
-
Object.assign(job, { state: 'failed', endedAt: Date.now(), detail: String(e?.message || e).slice(0, 1200) });
|
|
300
|
-
});
|
|
301
|
-
return { ...job };
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/** Test seam. */
|
|
305
|
-
export function _resetUpdateJob() { Object.assign(job, { state: 'idle', mode: '', from: '', to: '', detail: '', startedAt: 0, endedAt: 0 }); }
|
|
1
|
+
import I from"node:os";import l from"node:path";import{execFile as A}from"node:child_process";import{chmod as B,rename as v,mkdir as J,readFile as V,writeFile as U,rm as G}from"node:fs/promises";import{existsSync as K,readFileSync as W,realpathSync as Y}from"node:fs";import{restartService as q,serviceRegistered as y}from"./service.js";const h="@chatpanel/gateway",z="chatpanel/chatpanel-gateway",Q=`https://api.github.com/repos/${z}/releases/latest`,X=`https://registry.npmjs.org/${h}/latest`,C="https://registry.npmjs.org",P=360*60*1e3,j=600*1e3,Z=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),tt=15*6e4,D=20*6e4,E=process.env.CHATPANEL_UPDATE_CACHE||l.join(I.homedir(),".chatpanel","gateway-update-check.json"),_=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",k={"User-Agent":"chatpanel-gateway-updater"},et=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function at(t){try{const e=new URL(t);return e.protocol==="https:"&&et.has(e.hostname)}catch{return!1}}let p={at:0,error:""};function ht(){p={at:0,error:""}}function S(){const t=l.basename(process.execPath).toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}function nt(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function g(t=""){const e=/(\d+(?:\.\d+){0,3})/.exec(t||"");return e?e[1]:null}function N(t,e){const n=String(t).split(".").map(Number),a=String(e).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const s=(n[r]||0)-(a[r]||0);if(s)return s>0?1:-1}return 0}async function rt(){try{return JSON.parse(await V(E,"utf8"))}catch{return null}}async function ot(t){try{await J(l.dirname(E),{recursive:!0}),await U(E,JSON.stringify(t))}catch{}}async function L(t,e=Z){const n=new AbortController,a=setTimeout(()=>n.abort(),e);try{const r=await fetch(t,{headers:{Accept:"application/json, application/vnd.github+json",...k},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(t)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const s=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(e/1e3)}s`:`${new URL(t).hostname}: ${s}`)}finally{clearTimeout(a)}}function T(t=process.argv[1]){let e=t?l.resolve(t):"";try{e=Y(e)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(e);return n?n[1]:""}function st(){const t=T();if(!t)return"";try{return String(JSON.parse(W(l.join(t,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const t=l.dirname(process.execPath);return[l.join(t,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(t,"node_modules","npm","bin","npm-cli.js")].find(n=>K(n))||""}function it(){const t=$(),e={...process.env,npm_config_registry:C,npm_config_fund:"false",npm_config_audit:"false"};delete e.ELECTRON_RUN_AS_NODE;const[n,a]=t?[process.execPath,[t,"install","-g",`${h}@latest`]]:["npm",["install","-g",`${h}@latest`]];return new Promise(r=>{A(n,a,{env:e,timeout:D,maxBuffer:8<<20,windowsHide:!0},(s,d,u)=>{const o=`${d||""}${u||""}`.trim();return s?s.killed&&!o?r({ok:!1,out:`npm was still running after ${Math.round(D/6e4)} minutes and was stopped`}):r({ok:!1,out:o||(t?s.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):r({ok:!0,out:o})})})}async function O(t,{force:e=!1}={}){const n=S()?"binary":"npm";if(_)return{current:t,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=nt();let r=null,s=null,d=!1,u="",o=0;const i=await rt(),w=i&&i.mode===n,x=()=>{r=w&&i.latest||null,s=w&&i.assetUrl||null,o=w&&i.checkedAt||0,d=!0};if(!e&&w&&Date.now()-i.checkedAt<P)r=i.latest,s=i.assetUrl,o=i.checkedAt;else if(!e&&p.at&&Date.now()-p.at<j)u=p.error,x();else try{if(n==="npm"){const m=await L(X);r=g(m.version)}else{const m=await L(Q);r=g(m.tag_name)||g(m.name),s=a&&(m.assets||[]).find(F=>F.name===a)?.browser_download_url||null}o=Date.now(),await ot({checkedAt:o,mode:n,latest:r,assetUrl:s}),p={at:0,error:""}}catch(m){u=m.message,p={at:Date.now(),error:u},x()}const R=!!r&&N(r,t)>0,H=n==="binary"?!!s&&(process.platform!=="win32"||y()):!!T()&&(process.platform!=="win32"||y()&&!!$()),M=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${h}@latest; chatpanel-gateway --install`:`npm i -g ${h}@latest`:null;return{current:t,latest:r,updateAvailable:R,mode:n,canSelfUpdate:H,assetUrl:s,stale:d,error:u,npmCommand:M,channel:n==="npm"?"npm":"release",service:y(),checkedAt:o}}let f=null,b=null;function gt(t){const e=S()?"binary":"npm";return _?{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:!1,disabled:!0}:((!f||(f.stale?!(p.at&&Date.now()-p.at<j):Date.now()-f.seenAt>P))&&!b&&(b=O(t).then(a=>{f={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{b=null})),f?{...f,seenAt:void 0,current:t}:{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:y()})}function yt(){f=null,b=null}async function lt(t){const e=process.execPath,n=l.dirname(e),a=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,s=setTimeout(()=>r.abort(),tt);let d;try{const o=await fetch(t.assetUrl,{headers:k,redirect:"follow",signal:r.signal});if(!o.ok)throw new Error(`download failed (HTTP ${o.status})`);if(!at(o.url||t.assetUrl))throw new Error(`refused: the download was redirected to ${o.url}, which is not a ChatPanel release host`);d=Buffer.from(await o.arrayBuffer())}finally{clearTimeout(s)}if(d.length<5<<20)throw new Error(`the download was only ${(d.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await U(a,d),process.platform!=="win32"&&await B(a,493),process.platform==="darwin"&&await new Promise(o=>A("xattr",["-c",a],()=>o()));const u=await new Promise(o=>A(a,["--version"],{timeout:6e4,windowsHide:!0},(i,w)=>o(i?"":String(w||"").trim())));if(!g(u))throw await G(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await v(e,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await v(a,e),g(u)}async function ct(t){if(_)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const e=await O(t,{force:!0});if(e.stale)throw new Error(`Could not reach the update server${e.error?` (${e.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!e.updateAvailable)throw new Error(`Already on the latest ${e.channel} version (v${t}).`);if(!e.canSelfUpdate)throw new Error(e.mode==="npm"?`This gateway cannot update itself here. Run: ${e.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(e.mode==="binary")return{from:t,to:await lt(e),mode:"binary"};if(process.platform==="win32")return{from:t,to:e.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${h}@latest --registry=${C} --no-fund --no-audit`};const n=await it();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=st();if(!a||N(a,t)<=0)throw new Error(`npm ran, but the install at ${T()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${e.npmCommand}`);return{from:t,to:a,mode:"npm"}}const c={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function bt(){return{...c}}function At(t,{restart:e=q,apply:n=ct}={}){return c.state==="installing"||c.state==="restarting"?{...c,already:!0}:(Object.assign(c,{state:"installing",mode:S()?"binary":"npm",from:t,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(t).then(a=>{Object.assign(c,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{e({winInstall:a.deferred||""})||Object.assign(c,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(c,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...c})}function Et(){Object.assign(c,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{Et as _resetUpdateJob,yt as _resetUpdateStatus,O as checkForUpdate,N as cmpVersions,at as downloadHostAllowed,S as isCompiledBinary,T as npmPackageRoot,ht as resetUpdateBackoff,ct as selfUpdate,At as startUpdate,bt as updateJob,gt as updateStatus};
|