@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.
Files changed (81) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +2 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/policy.js +2 -0
  47. package/src/prefs-store.js +1 -149
  48. package/src/project-store.js +1 -139
  49. package/src/project.js +1 -171
  50. package/src/recruit.js +3 -424
  51. package/src/recruiting.js +1 -93
  52. package/src/redact.js +2 -123
  53. package/src/responses.js +2 -80
  54. package/src/router.js +1 -292
  55. package/src/rrf.js +1 -93
  56. package/src/scorecard-store.js +1 -92
  57. package/src/scorecard.js +1 -336
  58. package/src/search-index.js +2 -134
  59. package/src/secure-fetch.js +1 -58
  60. package/src/sentencepiece.js +1 -184
  61. package/src/server.js +10 -2296
  62. package/src/service.js +11 -189
  63. package/src/shape.js +5 -121
  64. package/src/sqlite-store.js +3 -212
  65. package/src/stream.js +5 -182
  66. package/src/structured.js +4 -902
  67. package/src/stt-engine.js +1 -486
  68. package/src/stt-models.js +1 -144
  69. package/src/subject-kinds.js +1 -6
  70. package/src/subject-name.js +1 -97
  71. package/src/team-board.js +6 -338
  72. package/src/team-record.js +1 -226
  73. package/src/team-store.js +1 -261
  74. package/src/team.js +1 -303
  75. package/src/toolrelay.js +3 -122
  76. package/src/tts-engine.js +1 -453
  77. package/src/tts-models.js +1 -254
  78. package/src/tts-remote.js +1 -109
  79. package/src/tts-voice-resolve.js +1 -78
  80. package/src/tts-voices.js +1 -192
  81. package/src/update.js +1 -305
@@ -1,45 +1 @@
1
- // Decrypt a ChatPanel backup envelope — the gateway counterpart to the extension's
2
- // crypto-backup.js. Same wire format so the gateway can read the user's own daily
3
- // encrypted backups (with the passphrase they hand off) even when the extension
4
- // isn't running. WebCrypto (PBKDF2 + AES-GCM) + native zlib codecs; no dependencies.
5
- //
6
- // Envelope: { type, version, kdf:{iterations,salt}, cipher:'AES-GCM',
7
- // compression:'brotli'|'gzip'|'none'|absent, iv, ct }.
8
-
9
- import { brotliDecompressSync, gunzipSync } from 'node:zlib';
10
-
11
- const ENCRYPTED_TYPE = 'chatpanel-backup-encrypted';
12
- const b64 = (s) => Buffer.from(String(s || ''), 'base64');
13
-
14
- async function deriveKey(passphrase, salt, iterations) {
15
- const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, ['deriveKey']);
16
- return crypto.subtle.deriveKey(
17
- { name: 'PBKDF2', salt, iterations, hash: 'SHA-256' },
18
- base,
19
- { name: 'AES-GCM', length: 256 },
20
- false,
21
- ['decrypt'],
22
- );
23
- }
24
-
25
- export function isEncryptedBackup(obj) {
26
- return !!obj && typeof obj === 'object' && obj.type === ENCRYPTED_TYPE;
27
- }
28
-
29
- // Envelope + passphrase → the original backup data object. Throws a friendly error
30
- // on a wrong passphrase or a tampered file (AES-GCM auth-tag mismatch catches both).
31
- export async function decryptBackupEnvelope(envelope, passphrase) {
32
- if (!isEncryptedBackup(envelope)) throw new Error('not an encrypted ChatPanel backup');
33
- if (!passphrase) throw new Error('a passphrase is required to decrypt this backup');
34
- const key = await deriveKey(passphrase, b64(envelope.kdf?.salt), envelope.kdf?.iterations || 250000);
35
- let payload;
36
- try {
37
- payload = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64(envelope.iv) }, key, b64(envelope.ct)));
38
- } catch {
39
- throw new Error('wrong passphrase, or the backup file is corrupted');
40
- }
41
- // v1 is plaintext, v2 gzip, v3 may use Brotli for a smaller portable file.
42
- if (envelope.compression === 'gzip') payload = new Uint8Array(gunzipSync(Buffer.from(payload)));
43
- else if (envelope.compression === 'brotli') payload = new Uint8Array(brotliDecompressSync(Buffer.from(payload)));
44
- return JSON.parse(Buffer.from(payload).toString('utf8'));
45
- }
1
+ import{brotliDecompressSync as c,gunzipSync as o}from"node:zlib";const i="chatpanel-backup-encrypted",a=r=>Buffer.from(String(r||""),"base64");async function s(r,e,n){const t=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:n,hash:"SHA-256"},t,{name:"AES-GCM",length:256},!1,["decrypt"])}function p(r){return!!r&&typeof r=="object"&&r.type===i}async function y(r,e){if(!p(r))throw new Error("not an encrypted ChatPanel backup");if(!e)throw new Error("a passphrase is required to decrypt this backup");const n=await s(e,a(r.kdf?.salt),r.kdf?.iterations||25e4);let t;try{t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:a(r.iv)},n,a(r.ct)))}catch{throw new Error("wrong passphrase, or the backup file is corrupted")}return r.compression==="gzip"?t=new Uint8Array(o(Buffer.from(t))):r.compression==="brotli"&&(t=new Uint8Array(c(Buffer.from(t)))),JSON.parse(Buffer.from(t).toString("utf8"))}export{y as decryptBackupEnvelope,p as isEncryptedBackup};
@@ -1,123 +1,9 @@
1
- // Backup-ingest: seed the warm store from the user's own daily encrypted backup so
2
- // the gateway holds the full corpus even when the extension isn't running. Finds the
3
- // newest backup file, decrypts it with the handed-off passphrase, and turns it into
4
- // warm records.
5
- //
6
- // The record extraction here is a SIMPLIFIED mirror of the extension's rich
7
- // conversationSource/meetingSource — same ids (chat:<id> / meeting:<id>), so when the
8
- // extension IS running its live-sync upserts its exact records right over these. This
9
- // path only needs "searchable text + title + date + id"; it is the fallback, not the
10
- // source of truth.
1
+ import{readFileSync as d,existsSync as A,readdirSync as m,statSync as h}from"node:fs";import{join as f}from"node:path";import S from"node:os";import{decryptBackupEnvelope as g}from"./backup-decrypt.js";const l=process.env.CHATPANEL_BACKUP_DIR||f(S.homedir(),"Downloads","ChatPanel Backups"),k=/^chatpanel-backup-(?:[a-z0-9]{12,16}-)?(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\.encrypted\.json$/;function $(o=l){try{let e=null;for(const t of m(o)){if(!k.test(t))continue;const n=f(o,t),s=h(n).mtimeMs;(!e||s>e.mtime)&&(e={path:n,mtime:s})}return e?.path||null}catch{return null}}function b(o=l){try{return m(o).filter(e=>k.test(e)).map(e=>({path:f(o,e),mtime:h(f(o,e)).mtimeMs})).sort((e,t)=>e.mtime-t.mtime).map(e=>e.path)}catch{return[]}}function y(o){const e=[];for(const t of o?.conversations||[]){if(!t?.id)continue;const n=t.title||"Chat",s=t.updatedAt||t.createdAt||0,i=(t.messages||[]).filter(r=>r&&r.content).map(r=>`${r.role==="assistant"?"Assistant":r.role==="system"?"System":"You"}: ${r.content}`).join(`
11
2
 
12
- import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
13
- import { join } from 'node:path';
14
- import os from 'node:os';
15
- import { decryptBackupEnvelope } from './backup-decrypt.js';
3
+ `);e.push({id:`chat:${t.id}`,type:"chat",title:n,date:s,text:`CHAT: ${n}
16
4
 
17
- const BACKUP_DIR = process.env.CHATPANEL_BACKUP_DIR || join(os.homedir(), 'Downloads', 'ChatPanel Backups');
18
- // Current extension builds scope each weekday slot to a stable per-device id so
19
- // several machines can share one Drive account without overwriting one another.
20
- // Keep accepting the seven pre-0.19.4 legacy slots for recovery.
21
- const BACKUP_RE = /^chatpanel-backup-(?:[a-z0-9]{12,16}-)?(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\.encrypted\.json$/;
5
+ ${i}`.trim()})}for(const t of o?.meetings||[]){const n=t?.record||t,s=n?.id;if(!s)continue;const i=n.title||"Meeting",r=n.startedAt||n.date||0,p=typeof t?.notes=="string"?t.notes:"",a=(n.segments||[]).map(u=>`${u.speaker||"?"}: ${u.text||""}`).join(`
6
+ `),c=[`MEETING: ${i}`];n.platform&&c.push(`Platform: ${n.platform}`),p&&c.push("","SUMMARY:",p),a&&c.push("","TRANSCRIPT:",a),e.push({id:`meeting:${s}`,type:"meeting",title:i,date:r,text:c.join(`
7
+ `).trim()})}for(const t of o?.notes||[]){if(!t?.id)continue;const n=t.title||"Note",s=t.updatedAt||t.createdAt||0;e.push({id:`note:${t.id}`,type:"note",title:n,date:s,text:`NOTE: ${n}
22
8
 
23
- // Newest chatpanel-backup-*.encrypted.json in the backups dir, or null.
24
- export function findLatestBackup(dir = BACKUP_DIR) {
25
- try {
26
- let best = null;
27
- for (const f of readdirSync(dir)) {
28
- if (!BACKUP_RE.test(f)) continue;
29
- const path = join(dir, f);
30
- const mtime = statSync(path).mtimeMs;
31
- if (!best || mtime > best.mtime) best = { path, mtime };
32
- }
33
- return best?.path || null;
34
- } catch {
35
- return null;
36
- }
37
- }
38
-
39
- export function findBackups(dir = BACKUP_DIR) {
40
- try {
41
- return readdirSync(dir)
42
- .filter((f) => BACKUP_RE.test(f))
43
- .map((f) => ({ path: join(dir, f), mtime: statSync(join(dir, f)).mtimeMs }))
44
- .sort((a, b) => a.mtime - b.mtime)
45
- .map((x) => x.path);
46
- } catch { return []; }
47
- }
48
-
49
- // Decrypted backup data → warm records [{ id, text, title, type, date }].
50
- export function backupToRecords(data) {
51
- const out = [];
52
- for (const c of data?.conversations || []) {
53
- if (!c?.id) continue;
54
- const title = c.title || 'Chat';
55
- const date = c.updatedAt || c.createdAt || 0;
56
- const body = (c.messages || [])
57
- .filter((m) => m && m.content)
58
- .map((m) => `${m.role === 'assistant' ? 'Assistant' : m.role === 'system' ? 'System' : 'You'}: ${m.content}`)
59
- .join('\n\n');
60
- out.push({ id: `chat:${c.id}`, type: 'chat', title, date, text: `CHAT: ${title}\n\n${body}`.trim() });
61
- }
62
- for (const m of data?.meetings || []) {
63
- // Meetings are exported wrapped: { record: {...meeting}, notes: <summary>, topics }.
64
- const rec = m?.record || m;
65
- const id = rec?.id;
66
- if (!id) continue;
67
- const title = rec.title || 'Meeting';
68
- const date = rec.startedAt || rec.date || 0;
69
- const notes = typeof m?.notes === 'string' ? m.notes : '';
70
- const segs = (rec.segments || []).map((s) => `${s.speaker || '?'}: ${s.text || ''}`).join('\n');
71
- const parts = [`MEETING: ${title}`];
72
- if (rec.platform) parts.push(`Platform: ${rec.platform}`);
73
- if (notes) parts.push('', 'SUMMARY:', notes);
74
- if (segs) parts.push('', 'TRANSCRIPT:', segs);
75
- out.push({ id: `meeting:${id}`, type: 'meeting', title, date, text: parts.join('\n').trim() });
76
- }
77
- // Notes (backup v5+) — plain markdown; the whole body is searchable.
78
- for (const n of data?.notes || []) {
79
- if (!n?.id) continue;
80
- const title = n.title || 'Note';
81
- const date = n.updatedAt || n.createdAt || 0;
82
- out.push({ id: `note:${n.id}`, type: 'note', title, date, text: `NOTE: ${title}\n\n${String(n.body || '')}`.trim() });
83
- }
84
- return out;
85
- }
86
-
87
- // Decrypt the latest (or given) backup and upsert its records into the store.
88
- // Returns { ok, ingested, size } or { ok:false, reason }. Never throws on a missing
89
- // file / passphrase; surfaces a decrypt failure as reason:'decrypt'.
90
- export async function ingestBackup(store, passphrase, { path = '' } = {}) {
91
- const file = path || findLatestBackup();
92
- if (!file || !existsSync(file)) return { ok: false, reason: 'no-backup' };
93
- if (!passphrase) return { ok: false, reason: 'no-passphrase' };
94
- let data;
95
- try {
96
- data = await decryptBackupEnvelope(JSON.parse(readFileSync(file, 'utf8')), passphrase);
97
- } catch (e) {
98
- return { ok: false, reason: 'decrypt', error: String(e?.message || e) };
99
- }
100
- const records = backupToRecords(data);
101
- store.bulk({ upserts: records });
102
- return { ok: true, file, ingested: records.length, size: store.size };
103
- }
104
-
105
- export async function ingestBackups(store, passphrase, { dir = BACKUP_DIR } = {}) {
106
- if (!passphrase) return { ok: false, reason: 'no-passphrase' };
107
- const files = findBackups(dir);
108
- if (!files.length) return { ok: false, reason: 'no-backup' };
109
- const byId = new Map();
110
- const accepted = [];
111
- const errors = [];
112
- for (const file of files) {
113
- try {
114
- const data = await decryptBackupEnvelope(JSON.parse(readFileSync(file, 'utf8')), passphrase);
115
- for (const record of backupToRecords(data)) byId.set(record.id, record);
116
- accepted.push(file);
117
- } catch (e) { errors.push({ file, error: String(e?.message || e) }); }
118
- }
119
- if (!accepted.length) return { ok: false, reason: 'decrypt', error: errors[0]?.error || 'no backup matched the stored passphrase' };
120
- const records = [...byId.values()];
121
- store.bulk({ upserts: records });
122
- return { ok: true, file: accepted.at(-1), files: accepted.length, skippedFiles: errors.length, ingested: records.length, size: store.size };
123
- }
9
+ ${String(t.body||"")}`.trim()})}return e}async function M(o,e,{path:t=""}={}){const n=t||$();if(!n||!A(n))return{ok:!1,reason:"no-backup"};if(!e)return{ok:!1,reason:"no-passphrase"};let s;try{s=await g(JSON.parse(d(n,"utf8")),e)}catch(r){return{ok:!1,reason:"decrypt",error:String(r?.message||r)}}const i=y(s);return o.bulk({upserts:i}),{ok:!0,file:n,ingested:i.length,size:o.size}}async function N(o,e,{dir:t=l}={}){if(!e)return{ok:!1,reason:"no-passphrase"};const n=b(t);if(!n.length)return{ok:!1,reason:"no-backup"};const s=new Map,i=[],r=[];for(const a of n)try{const c=await g(JSON.parse(d(a,"utf8")),e);for(const u of y(c))s.set(u.id,u);i.push(a)}catch(c){r.push({file:a,error:String(c?.message||c)})}if(!i.length)return{ok:!1,reason:"decrypt",error:r[0]?.error||"no backup matched the stored passphrase"};const p=[...s.values()];return o.bulk({upserts:p}),{ok:!0,file:i.at(-1),files:i.length,skippedFiles:r.length,ingested:p.length,size:o.size}}export{y as backupToRecords,b as findBackups,$ as findLatestBackup,M as ingestBackup,N as ingestBackups};
@@ -1,212 +1,3 @@
1
- // The gateway carries the bridge — one install, two processes.
2
- //
3
- // A user installs ONE thing (this gateway: the binary, or `npm i -g @chatpanel/gateway`) and
4
- // gets the bridge with it: `@chatpanel/bridge` is a dependency, bundled into the same binary,
5
- // and the gateway STARTS it as a child process when nothing already answers on the bridge
6
- // port. Two processes on purpose: the bridge spawns CLIs, holds SCM tokens and runs shells —
7
- // a small zero-dependency process with its own failure domain — and the NER / STT / TTS
8
- // runtimes that crash or eat memory live here, not there. A gateway restart never takes a
9
- // running Claude Code task down with it.
10
- //
11
- // What is already there is ADOPTED, never fought: a bridge the desktop app installed, a
12
- // standalone the user put in ~/.local/bin (preferred when it is NEWER than the embedded copy,
13
- // so a bridge fix keeps shipping on its own tag), a remote bridge named in config. The plan
14
- // is a pure function (`planBridge`) so the rule is testable without spawning anything.
15
- //
16
- // An embedded child is started with CHATPANEL_BRIDGE_EMBEDDED=1: its `process.execPath` is
17
- // the GATEWAY binary, so the bridge's self-update is disabled there (it would overwrite the
18
- // gateway with a bridge) and its /health says `update.embedded: 'gateway'`. Both children get
19
- // CHATPANEL_MANAGED_BY=gateway so a client can say who runs it instead of offering install.sh.
20
-
21
- import os from 'node:os';
22
- import path from 'node:path';
23
- import { existsSync } from 'node:fs';
24
- import { spawn, spawnSync } from 'node:child_process';
25
- import { resolveLaunch } from './service.js';
26
- import { DEFAULT_BRIDGE_URL } from './bridge.js';
27
-
28
- const LOOPBACK = /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i;
29
- const BACKOFF_MS = [1000, 2000, 5000, 10000, 30000];
30
- const STABLE_MS = 60_000; // a child up this long resets the back-off
31
- const PROBE_TIMEOUT_MS = 1200;
32
-
33
- /** Where the standalone bridge installer puts its binary (scripts/install.sh / install.ps1 in the bridge repo). */
34
- export function standaloneCandidates({ home = os.homedir(), platform = process.platform, env = process.env } = {}) {
35
- if (platform === 'win32') return [path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'ChatPanel', 'chatpanel-bridge.exe')];
36
- return [path.join(home, '.local', 'bin', 'chatpanel-bridge')];
37
- }
38
-
39
- /** semver-ish: 1 when a > b, -1 when a < b, 0 when equal or unreadable. */
40
- export function compareVersions(a, b) {
41
- const pa = String(a || '').split('.').map((x) => parseInt(x, 10)); const pb = String(b || '').split('.').map((x) => parseInt(x, 10));
42
- if (pa.some(Number.isNaN) || pb.some(Number.isNaN) || pa.length < 3 || pb.length < 3) return 0;
43
- for (let i = 0; i < 3; i += 1) { if (pa[i] !== pb[i]) return pa[i] > pb[i] ? 1 : -1; }
44
- return 0;
45
- }
46
-
47
- /**
48
- * What to do about the bridge — pure.
49
- * managed: false / 'off' → off (the host runs its own, e.g. the desktop app)
50
- * a non-loopback bridge.url → off (a remote bridge is the user's; never start one here)
51
- * something answers the port → adopt
52
- * a standalone newer than the embedded copy → spawn-standalone
53
- * an embedded copy → spawn-embedded
54
- * only a standalone → spawn-standalone
55
- */
56
- export function planBridge({ managed = true, cfgUrl = '', healthy = null, standalone = null, embeddedVersion = null } = {}) {
57
- if (managed === false || managed === 'off') return { action: 'off', why: 'bridge supervision is off (the host runs its own)' };
58
- const url = String(cfgUrl || DEFAULT_BRIDGE_URL);
59
- if (!LOOPBACK.test(url)) return { action: 'off', why: `bridge.url ${url} is not on this machine; nothing to start here` };
60
- if (healthy) return { action: 'adopt', why: `a bridge already answers at ${url}${healthy.version ? ` (v${healthy.version}${healthy.managedBy ? `, run by ${healthy.managedBy}` : ''})` : ''}` };
61
- const sv = standalone?.version || null;
62
- if (standalone?.path && embeddedVersion && compareVersions(sv, embeddedVersion) > 0) return { action: 'spawn-standalone', why: `the installed bridge (v${sv}) is newer than the embedded one (v${embeddedVersion})`, path: standalone.path };
63
- if (embeddedVersion) return { action: 'spawn-embedded', why: `starting the embedded bridge (v${embeddedVersion})${standalone?.path ? ` — the installed one is v${sv || '?'}` : ''}` };
64
- if (standalone?.path) return { action: 'spawn-standalone', why: `starting the installed bridge${sv ? ` (v${sv})` : ''}`, path: standalone.path };
65
- return { action: 'off', why: 'no bridge to start (no embedded copy, no standalone install)' };
66
- }
67
-
68
- /** `GET /health` on the bridge, or null. */
69
- export async function probeBridge(url, { timeoutMs = PROBE_TIMEOUT_MS, fetchImpl = fetch } = {}) {
70
- const ctrl = new AbortController();
71
- const t = setTimeout(() => ctrl.abort(), timeoutMs);
72
- try {
73
- const res = await fetchImpl(`${String(url).replace(/\/$/, '')}/health`, { signal: ctrl.signal });
74
- if (!res.ok) return null;
75
- const j = await res.json().catch(() => null);
76
- return j && j.ok !== false ? { version: j.version || null, managedBy: j.managedBy || null } : null;
77
- } catch { return null; } finally { clearTimeout(t); }
78
- }
79
-
80
- /** `<program> [...args] --version`, or null — one process, bounded. */
81
- export function versionOf(program, args = [], { timeoutMs = 8000 } = {}) {
82
- try {
83
- const r = spawnSync(program, [...args, '--version'], { encoding: 'utf8', timeout: timeoutMs, env: { ...process.env, CHATPANEL_BRIDGE_EMBEDDED: '1' } });
84
- const v = String(r.stdout || '').trim().split('\n').pop();
85
- return /^\d+\.\d+\.\d+/.test(v) ? v : null;
86
- } catch { return null; }
87
- }
88
-
89
- /** How THIS gateway starts its embedded bridge: itself, with `--bridge` (bin/chatpanel-gateway.js). */
90
- export function embeddedLaunch() {
91
- const { program, args } = resolveLaunch();
92
- return { program, args: [...args, '--bridge'] };
93
- }
94
-
95
- const portOf = (url) => { const m = LOOPBACK.exec(String(url || DEFAULT_BRIDGE_URL)); return m?.[3] || '4319'; };
96
-
97
- /**
98
- * Make sure a bridge is running for this gateway, and keep it running. Returns a controller:
99
- * `status()` → `{ mode: 'adopted'|'embedded'|'standalone'|'off', version, pid, restarts, why }`,
100
- * `stop()` ends a child we started. Everything that touches the machine is injectable so the
101
- * rule can be tested without a process: `probe`, `spawnImpl`, `version`, `candidates`, `exists`.
102
- */
103
- export async function ensureBridge(cfg, {
104
- log = (line) => console.log(line),
105
- probe = probeBridge,
106
- spawnImpl = spawn,
107
- version = versionOf,
108
- candidates = standaloneCandidates(),
109
- exists = existsSync,
110
- launch = embeddedLaunch,
111
- managed = process.env.CHATPANEL_BRIDGE_MANAGED === 'off' ? false : cfg?.bridge?.managed,
112
- waitForSiblingMs = 2500,
113
- now = Date.now,
114
- setTimer = setTimeout,
115
- // The watch on an ADOPTED bridge: its own timer seam (a test's immediate `setTimer` would
116
- // spin it), unref'd so a pending watch never keeps the process alive.
117
- setWatch = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; },
118
- watchEveryMs = 10_000,
119
- } = {}) {
120
- const url = String(cfg?.bridge?.url || DEFAULT_BRIDGE_URL).replace(/\/$/, '');
121
- const state = { mode: 'off', version: null, pid: null, restarts: 0, why: '', child: null, stopping: false, backoff: 0 };
122
- const settle = (mode, why, extra = {}) => { Object.assign(state, { mode, why }, extra); log(` bridge : ${why}`); };
123
-
124
- // Someone else (the desktop's supervisor, launchd) may be starting a bridge this very
125
- // second; wait a moment before deciding it is absent, or two bridges race for one port.
126
- let healthy = await probe(url);
127
- if (!healthy && managed !== false && managed !== 'off' && LOOPBACK.test(url) && waitForSiblingMs > 0) {
128
- const until = now() + waitForSiblingMs;
129
- while (!healthy && now() < until) { await new Promise((r) => setTimer(r, 500)); healthy = await probe(url); }
130
- }
131
- const emb = launch();
132
- const embeddedVersion = managed === false || managed === 'off' || healthy ? null : version(emb.program, emb.args);
133
- const standalonePath = candidates.find((p) => exists(p)) || null;
134
- const standalone = standalonePath && !healthy ? { path: standalonePath, version: version(standalonePath, []) } : null;
135
- const plan = planBridge({ managed, cfgUrl: url, healthy, standalone, embeddedVersion });
136
-
137
- if (plan.action === 'off') { settle('off', plan.why); return controller(); }
138
-
139
- // What WE would run, decided once and kept: an adopted bridge that goes away is replaced
140
- // by this without re-planning from scratch.
141
- const specFor = (p) => (p.action === 'spawn-embedded'
142
- ? { ...emb, env: { CHATPANEL_BRIDGE_EMBEDDED: '1' }, mode: 'embedded', version: p.version || embeddedVersion }
143
- : { program: p.path, args: [], env: {}, mode: 'standalone', version: standalone?.version || null });
144
- let spec = plan.action === 'adopt' ? null : specFor(plan);
145
- let startedAt = 0;
146
- let watch = null;
147
- let misses = 0;
148
-
149
- // AN ADOPTED BRIDGE IS WATCHED, NOT TRUSTED FOREVER. The gateway carries the bridge: when
150
- // the one it adopted goes away — the desktop app that ran it quit, an old login unit was
151
- // removed, a standalone was stopped — the port is quiet and every agent turn fails with
152
- // "bridge unreachable" until someone restarts the gateway. Two missed probes (a refused
153
- // port counts at once) and ours starts.
154
- const adopt = (why, ver) => {
155
- settle('adopted', why, { version: ver || null });
156
- misses = 0;
157
- const tick = async () => {
158
- if (state.stopping || state.mode !== 'adopted') return;
159
- const h = await probe(url);
160
- if (h) { misses = 0; state.version = h.version || state.version; watch = setWatch(tick, watchEveryMs); return; }
161
- misses += 1;
162
- if (misses < 2) { watch = setWatch(tick, Math.min(watchEveryMs, 3000)); return; }
163
- if (!spec) {
164
- const ev = embeddedVersion || version(emb.program, emb.args);
165
- const p = planBridge({ managed, cfgUrl: url, healthy: null, standalone, embeddedVersion: ev });
166
- if (p.action === 'off') { settle('off', `the adopted bridge went away and ${p.why}`); return; }
167
- spec = specFor({ ...p, version: ev });
168
- }
169
- log(` bridge : the adopted bridge at ${url} went away — ${spec.mode === 'embedded' ? `starting the embedded bridge (v${spec.version || '?'})` : `starting the installed bridge (v${spec.version || '?'})`}`);
170
- settle(spec.mode, `the adopted bridge went away; ${spec.mode} bridge started in its place`, { version: spec.version });
171
- start();
172
- };
173
- watch = setWatch(tick, watchEveryMs);
174
- };
175
-
176
- const start = () => {
177
- if (state.stopping) return;
178
- const child = spawnImpl(spec.program, spec.args, {
179
- stdio: ['ignore', 'pipe', 'pipe'],
180
- env: { ...process.env, ...spec.env, CHATPANEL_MANAGED_BY: 'gateway', CHATPANEL_BRIDGE_PORT: portOf(url) },
181
- });
182
- startedAt = now();
183
- state.child = child; state.pid = child.pid || null;
184
- const relay = (stream, tag) => stream?.on('data', (buf) => { for (const line of String(buf).split('\n')) if (line.trim()) log(`[bridge] ${line}`); });
185
- relay(child.stdout, 'out'); relay(child.stderr, 'err');
186
- child.on('error', (e) => log(`[bridge] could not start ${spec.program}: ${e?.message || e}`));
187
- child.on('exit', async (code, sig) => {
188
- state.child = null; state.pid = null;
189
- if (state.stopping) return;
190
- // The port may have been taken by a bridge someone else started while ours came up —
191
- // that is not a failure to restart from, it is a bridge to adopt.
192
- const other = await probe(url);
193
- if (other) { adopt(`a bridge already answers at ${url} (v${other.version || '?'}${other.managedBy ? `, run by ${other.managedBy}` : ''}) — ours stepped aside`, other.version); return; }
194
- if (now() - startedAt > STABLE_MS) state.backoff = 0;
195
- const delay = BACKOFF_MS[Math.min(state.backoff, BACKOFF_MS.length - 1)];
196
- state.backoff += 1; state.restarts += 1;
197
- log(`[bridge] exited (${sig || code}); restarting in ${delay / 1000}s`);
198
- setTimer(start, delay);
199
- });
200
- };
201
- if (plan.action === 'adopt') { adopt(plan.why, healthy.version); return controller(); }
202
- settle(spec.mode, plan.why, { version: spec.version });
203
- start();
204
- return controller();
205
-
206
- function controller() {
207
- return {
208
- status: () => ({ mode: state.mode, version: state.version, pid: state.pid, restarts: state.restarts, why: state.why }),
209
- stop: () => { state.stopping = true; if (watch) { clearTimeout(watch); watch = null; } if (state.child && !state.child.killed) { try { state.child.kill('SIGTERM'); } catch { /* gone */ } } },
210
- };
211
- }
212
- }
1
+ import U from"node:os";import P from"node:path";import{existsSync as F}from"node:fs";import{spawn as K,spawnSync as Y}from"node:child_process";import{resolveLaunch as q}from"./service.js";import{DEFAULT_BRIDGE_URL as x}from"./bridge.js";const C=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,M=[1e3,2e3,5e3,1e4,3e4],z=6e4,J=1200;function Q({home:r=U.homedir(),platform:o=process.platform,env:n=process.env}={}){return o==="win32"?[P.join(n.LOCALAPPDATA||P.join(r,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[P.join(r,".local","bin","chatpanel-bridge")]}function X(r,o){const n=String(r||"").split(".").map(e=>parseInt(e,10)),i=String(o||"").split(".").map(e=>parseInt(e,10));if(n.some(Number.isNaN)||i.some(Number.isNaN)||n.length<3||i.length<3)return 0;for(let e=0;e<3;e+=1)if(n[e]!==i[e])return n[e]>i[e]?1:-1;return 0}function j({managed:r=!0,cfgUrl:o="",healthy:n=null,standalone:i=null,embeddedVersion:e=null}={}){if(r===!1||r==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const g=String(o||x);if(!C.test(g))return{action:"off",why:`bridge.url ${g} is not on this machine; nothing to start here`};if(n)return{action:"adopt",why:`a bridge already answers at ${g}${n.version?` (v${n.version}${n.managedBy?`, run by ${n.managedBy}`:""})`:""}`};const d=i?.version||null;return i?.path&&e&&X(d,e)>0?{action:"spawn-standalone",why:`the installed bridge (v${d}) is newer than the embedded one (v${e})`,path:i.path}:e?{action:"spawn-embedded",why:`starting the embedded bridge (v${e})${i?.path?` — the installed one is v${d||"?"}`:""}`}:i?.path?{action:"spawn-standalone",why:`starting the installed bridge${d?` (v${d})`:""}`,path:i.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function Z(r,{timeoutMs:o=J,fetchImpl:n=fetch}={}){const i=new AbortController,e=setTimeout(()=>i.abort(),o);try{const g=await n(`${String(r).replace(/\/$/,"")}/health`,{signal:i.signal});if(!g.ok)return null;const d=await g.json().catch(()=>null);return d&&d.ok!==!1?{version:d.version||null,managedBy:d.managedBy||null}:null}catch{return null}finally{clearTimeout(e)}}function V(r,o=[],{timeoutMs:n=8e3}={}){try{const i=Y(r,[...o,"--version"],{encoding:"utf8",timeout:n,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),e=String(i.stdout||"").trim().split(`
2
+ `).pop();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function W(){const{program:r,args:o}=q();return{program:r,args:[...o,"--bridge"]}}const tt=r=>C.exec(String(r||x))?.[3]||"4319";async function at(r,{log:o=a=>console.log(a),probe:n=Z,spawnImpl:i=K,version:e=V,candidates:g=Q(),exists:d=F,launch:H=W,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:r?.bridge?.managed,waitForSiblingMs:O=2500,now:A=Date.now,setTimer:k=setTimeout,setWatch:E=(a,t)=>{const h=setTimeout(a,t);return h.unref?.(),h},watchEveryMs:_=1e4}={}){const a=String(r?.bridge?.url||x).replace(/\/$/,""),t={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},h=(s,u,c={})=>{Object.assign(t,{mode:s,why:u},c),o(` bridge : ${u}`)};let m=await n(a);if(!m&&b!==!1&&b!=="off"&&C.test(a)&&O>0){const s=A()+O;for(;!m&&A()<s;)await new Promise(u=>k(u,500)),m=await n(a)}const y=H(),D=b===!1||b==="off"||m?null:e(y.program,y.args),T=g.find(s=>d(s))||null,L=T&&!m?{path:T,version:e(T,[])}:null,v=j({managed:b,cfgUrl:a,healthy:m,standalone:L,embeddedVersion:D});if(v.action==="off")return h("off",v.why),N();const I=s=>s.action==="spawn-embedded"?{...y,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:s.version||D}:{program:s.path,args:[],env:{},mode:"standalone",version:L?.version||null};let l=v.action==="adopt"?null:I(v),R=0,w=null,B=0;const G=(s,u)=>{h("adopted",s,{version:u||null}),B=0;const c=async()=>{if(t.stopping||t.mode!=="adopted")return;const $=await n(a);if($){B=0,t.version=$.version||t.version,w=E(c,_);return}if(B+=1,B<2){w=E(c,Math.min(_,3e3));return}if(!l){const p=D||e(y.program,y.args),f=j({managed:b,cfgUrl:a,healthy:null,standalone:L,embeddedVersion:p});if(f.action==="off"){h("off",`the adopted bridge went away and ${f.why}`);return}l=I({...f,version:p})}o(` bridge : the adopted bridge at ${a} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),h(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),S()};w=E(c,_)},S=()=>{if(t.stopping)return;const s=i(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:tt(a)}});R=A(),t.child=s,t.pid=s.pid||null;const u=(c,$)=>c?.on("data",p=>{for(const f of String(p).split(`
3
+ `))f.trim()&&o(`[bridge] ${f}`)});u(s.stdout,"out"),u(s.stderr,"err"),s.on("error",c=>o(`[bridge] could not start ${l.program}: ${c?.message||c}`)),s.on("exit",async(c,$)=>{if(t.child=null,t.pid=null,t.stopping)return;const p=await n(a);if(p){G(`a bridge already answers at ${a} (v${p.version||"?"}${p.managedBy?`, run by ${p.managedBy}`:""}) — ours stepped aside`,p.version);return}A()-R>z&&(t.backoff=0);const f=M[Math.min(t.backoff,M.length-1)];t.backoff+=1,t.restarts+=1,o(`[bridge] exited (${$||c}); restarting in ${f/1e3}s`),k(S,f)})};if(v.action==="adopt")return G(v.why,m.version),N();return h(l.mode,v.why,{version:l.version}),S(),N();function N(){return{status:()=>({mode:t.mode,version:t.version,pid:t.pid,restarts:t.restarts,why:t.why}),stop:()=>{if(t.stopping=!0,w&&(clearTimeout(w),w=null),t.child&&!t.child.killed)try{t.child.kill("SIGTERM")}catch{}}}}}export{X as compareVersions,W as embeddedLaunch,at as ensureBridge,j as planBridge,Z as probeBridge,Q as standaloneCandidates,V as versionOf};