@chatpanel/bridge 0.2.12 → 0.2.13

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/bridge",
3
- "version": "0.2.12",
3
+ "version": "0.2.13",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Gemini CLI — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
package/src/server.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  // ChatPanel Bridge — a tiny localhost server that exposes the coding agents
3
- // running on this machine (Claude Code via the Agent SDK, Codex and Gemini via
4
- // their CLIs) to the ChatPanel Chrome extension. Zero runtime dependencies
5
- // beyond the optional Claude Agent SDK.
3
+ // running on this machine (Claude Code, Codex and Gemini, each via its CLI) to
4
+ // the ChatPanel Chrome extension. Zero runtime dependencies.
6
5
  //
7
- // GET /health → { ok, version, agents: [{id,label,available,reason}] }
6
+ // GET /health → { ok, version, agents: [...], update: {current,latest,…} }
7
+ // POST /update → self-update to the latest release (compiled binary installs)
8
8
  // POST /chat → Server-Sent Events stream of { type, ... }:
9
9
  // {type:'delta', text} incremental assistant text
10
10
  // {type:'tool', name, summary}
@@ -19,10 +19,11 @@ import os from 'node:os';
19
19
  import * as claude from './engines/claude.js';
20
20
  import * as codex from './engines/codex.js';
21
21
  import * as gemini from './engines/gemini.js';
22
- import { installService, uninstallService, serviceStatus } from './service.js';
22
+ import { installService, uninstallService, serviceStatus, restartService } from './service.js';
23
23
  import { enrichPath, findAgentBin } from './env.js';
24
+ import { checkForUpdate, selfUpdate } from './update.js';
24
25
 
25
- const VERSION = '0.2.12';
26
+ const VERSION = '0.2.13';
26
27
  const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
27
28
  const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
28
29
 
@@ -81,7 +82,20 @@ async function handleHealth(res) {
81
82
  return { id, label, available: a.ok, reason: a.reason };
82
83
  }),
83
84
  );
84
- json(res, 200, { ok: true, version: VERSION, agents });
85
+ const update = await checkForUpdate(VERSION).catch(() => ({ current: VERSION, updateAvailable: false }));
86
+ json(res, 200, { ok: true, version: VERSION, agents, update });
87
+ }
88
+
89
+ // POST /update — self-update (compiled-binary installs). Swaps the binary, replies,
90
+ // then restarts the service into the new version. npm installs get instructions.
91
+ async function handleUpdate(res) {
92
+ try {
93
+ const result = await selfUpdate(VERSION); // throws on npm install / no update / failure
94
+ json(res, 200, { ok: true, updated: true, from: result.from, to: result.to });
95
+ res.on('finish', () => setTimeout(() => restartService(), 400));
96
+ } catch (e) {
97
+ json(res, 400, { ok: false, error: String(e?.message || e) });
98
+ }
85
99
  }
86
100
 
87
101
  async function handleChat(req, res) {
@@ -187,6 +201,7 @@ const server = createServer(async (req, res) => {
187
201
  }
188
202
  if (req.method === 'POST' && url.pathname === '/chat') return handleChat(req, res);
189
203
  if (req.method === 'POST' && url.pathname === '/complete') return handleComplete(req, res);
204
+ if (req.method === 'POST' && url.pathname === '/update') return handleUpdate(res);
190
205
  json(res, 404, { error: 'Not found' });
191
206
  } catch (e) {
192
207
  json(res, 500, { error: e?.message || String(e) });
@@ -218,6 +233,7 @@ Usage:
218
233
  chatpanel-bridge --install run automatically at login, in the background
219
234
  chatpanel-bridge --uninstall remove the login auto-start
220
235
  chatpanel-bridge --status show whether auto-start is set up
236
+ chatpanel-bridge --update download & install the latest version, then restart
221
237
  chatpanel-bridge --version print the version
222
238
 
223
239
  Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`);
@@ -269,4 +285,17 @@ function runCli() {
269
285
  return false;
270
286
  }
271
287
 
272
- if (!runCli()) startServer();
288
+ if (process.argv.includes('--update')) {
289
+ (async () => {
290
+ try {
291
+ const r = await selfUpdate(VERSION);
292
+ log('info', `Updated v${r.from} → v${r.to}. Restarting the background service…`);
293
+ restartService();
294
+ } catch (e) {
295
+ log('error', 'Update failed: ' + (e?.message || e));
296
+ process.exitCode = 1;
297
+ }
298
+ })();
299
+ } else if (!runCli()) {
300
+ startServer();
301
+ }
package/src/service.js CHANGED
@@ -12,7 +12,7 @@
12
12
  import os from 'node:os';
13
13
  import path from 'node:path';
14
14
  import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
15
- import { spawnSync } from 'node:child_process';
15
+ import { spawn, spawnSync } from 'node:child_process';
16
16
 
17
17
  const LABEL = 'net.chatpanel.bridge';
18
18
  const DISPLAY = 'ChatPanel Bridge';
@@ -157,3 +157,37 @@ export function uninstallService() {
157
157
  export function serviceStatus() {
158
158
  return byPlatform(macStatus, winStatus, linStatus);
159
159
  }
160
+
161
+ // Restart the installed service into a freshly-swapped binary (used by self-
162
+ // update). Detached so it survives the restart killing the caller — works whether
163
+ // invoked from inside the service (POST /update) or a CLI `--update`.
164
+ // • macOS — `launchctl kickstart -k` kills + relaunches the LaunchAgent.
165
+ // • Linux — `systemctl --user restart`.
166
+ // • Windows — kill the running bridge, wait ~2s (port frees), relaunch via the
167
+ // hidden VBS, then delete the renamed old-*.exe.
168
+ export function restartService() {
169
+ try {
170
+ if (process.platform === 'darwin') {
171
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
172
+ spawn('launchctl', ['kickstart', '-k', `gui/${uid}/${LABEL}`], { detached: true, stdio: 'ignore' }).unref();
173
+ return true;
174
+ }
175
+ if (process.platform === 'linux') {
176
+ spawn('systemctl', ['--user', 'restart', 'chatpanel-bridge'], { detached: true, stdio: 'ignore' }).unref();
177
+ return true;
178
+ }
179
+ if (process.platform === 'win32') {
180
+ const vbs = winVbs();
181
+ const dir = path.dirname(process.execPath);
182
+ const cmd =
183
+ `taskkill /IM chatpanel-bridge.exe /F >nul 2>&1 & ` +
184
+ `timeout /t 2 >nul & wscript.exe "${vbs}" & ` +
185
+ `del /q "${path.join(dir, 'chatpanel-bridge.old-*.exe')}" >nul 2>&1`;
186
+ spawn('cmd', ['/c', cmd], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
187
+ return true;
188
+ }
189
+ } catch {
190
+ /* fall through */
191
+ }
192
+ return false;
193
+ }
package/src/update.js ADDED
@@ -0,0 +1,154 @@
1
+ // In-app updater for the standalone binary.
2
+ //
3
+ // The bridge is a background service the user never opens, so the EXTENSION
4
+ // surfaces "update available" (from /health) and offers a one-click Update that
5
+ // calls POST /update. The bridge downloads the new binary, swaps it in, and the
6
+ // service relaunches into the new version.
7
+ //
8
+ // Cross-platform swap + relaunch (users come from anywhere):
9
+ // • macOS — atomic rename over the running file; KeepAlive relaunches on exit.
10
+ // • Linux — atomic rename; `systemctl --user restart` relaunches.
11
+ // • Windows — can't overwrite a running .exe, so we RENAME the running exe aside
12
+ // and drop the new one in its place, then a detached helper waits for
13
+ // this process to exit (freeing the port) and relaunches it.
14
+ //
15
+ // No-ops for npx/node installs — npm owns those; only compiled binaries self-update.
16
+
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import { chmod, rename, mkdir, readFile, writeFile } from 'node:fs/promises';
20
+ import { isCompiledBinary } from './env.js';
21
+
22
+ const REPO = 'chatpanel/chatpanel-bridge';
23
+ const LATEST_API = `https://api.github.com/repos/${REPO}/releases/latest`;
24
+ const CHECK_EVERY_MS = 6 * 60 * 60 * 1000; // 6h
25
+ const CACHE = path.join(os.homedir(), '.chatpanel', 'update-check.json');
26
+ const UA = { 'User-Agent': 'chatpanel-bridge-updater' };
27
+
28
+ // Release asset name for THIS platform (matches release-binaries.yml outputs).
29
+ // macOS publishes arm64 only; Intel Macs use `npx` (managed → no self-update).
30
+ function assetName() {
31
+ if (process.platform === 'darwin') return process.arch === 'arm64' ? 'chatpanel-bridge-macos-arm64' : null;
32
+ if (process.platform === 'linux') return 'chatpanel-bridge-linux-x64';
33
+ if (process.platform === 'win32') return 'chatpanel-bridge-windows-x64.exe';
34
+ return null;
35
+ }
36
+
37
+ function parseVersion(s = '') {
38
+ const m = /(\d+(?:\.\d+){0,3})/.exec(s || '');
39
+ return m ? m[1] : null;
40
+ }
41
+ // >0 if a is newer than b.
42
+ function cmp(a, b) {
43
+ const pa = String(a).split('.').map(Number);
44
+ const pb = String(b).split('.').map(Number);
45
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
46
+ const d = (pa[i] || 0) - (pb[i] || 0);
47
+ if (d) return d > 0 ? 1 : -1;
48
+ }
49
+ return 0;
50
+ }
51
+
52
+ async function readCache() {
53
+ try {
54
+ return JSON.parse(await readFile(CACHE, 'utf8'));
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+ async function writeCache(obj) {
60
+ try {
61
+ await mkdir(path.dirname(CACHE), { recursive: true });
62
+ await writeFile(CACHE, JSON.stringify(obj));
63
+ } catch {
64
+ /* best effort */
65
+ }
66
+ }
67
+
68
+ // Returns { current, latest, updateAvailable, mode, canSelfUpdate, assetUrl, npmCommand }.
69
+ // mode 'binary' → compiled standalone build (macOS/Linux curl install, or the
70
+ // optional Windows .exe). POST /update self-replaces in place.
71
+ // mode 'npm' → npx/node install (the default on Windows). The bridge can't
72
+ // swap its own files; the extension shows `npmCommand` instead.
73
+ // Both report updateAvailable so the user always gets the notice — only the action
74
+ // differs. Throttled to CHECK_EVERY_MS unless `force`.
75
+ export async function checkForUpdate(current, { force = false } = {}) {
76
+ const mode = isCompiledBinary() ? 'binary' : 'npm';
77
+ const want = assetName();
78
+
79
+ let latest = null;
80
+ let assetUrl = null;
81
+ const cache = await readCache();
82
+ if (!force && cache && Date.now() - cache.checkedAt < CHECK_EVERY_MS) {
83
+ latest = cache.latest;
84
+ assetUrl = cache.assetUrl;
85
+ } else {
86
+ try {
87
+ const res = await fetch(LATEST_API, { headers: { Accept: 'application/vnd.github+json', ...UA } });
88
+ if (res.ok) {
89
+ const data = await res.json();
90
+ latest = parseVersion(data.tag_name) || parseVersion(data.name);
91
+ assetUrl = want ? (data.assets || []).find((a) => a.name === want)?.browser_download_url || null : null;
92
+ await writeCache({ checkedAt: Date.now(), latest, assetUrl });
93
+ } else {
94
+ latest = cache?.latest || null;
95
+ assetUrl = cache?.assetUrl || null;
96
+ }
97
+ } catch {
98
+ latest = cache?.latest || null;
99
+ assetUrl = cache?.assetUrl || null;
100
+ }
101
+ }
102
+ const updateAvailable = !!latest && cmp(latest, current) > 0;
103
+ // One-click in-place update is only possible for a compiled binary with a
104
+ // matching release asset; npm installs update via the command.
105
+ const canSelfUpdate = mode === 'binary' && !!assetUrl;
106
+ return {
107
+ current,
108
+ latest,
109
+ updateAvailable,
110
+ mode,
111
+ canSelfUpdate,
112
+ assetUrl,
113
+ npmCommand: mode === 'npm' ? 'npm i -g @chatpanel/bridge@latest' : null,
114
+ };
115
+ }
116
+
117
+ // Download the latest binary and swap it in. Does NOT restart — the caller sends
118
+ // its HTTP response first, then triggers restartService(). Throws on any failure,
119
+ // leaving the running binary untouched.
120
+ export async function selfUpdate(current) {
121
+ if (!isCompiledBinary()) {
122
+ throw new Error('Self-update applies only to the standalone binary. Update the npm/npx version with npm.');
123
+ }
124
+ const info = await checkForUpdate(current, { force: true });
125
+ if (!info.assetUrl) throw new Error('No downloadable build for this platform — use `npx @chatpanel/bridge`.');
126
+ if (!info.updateAvailable) {
127
+ throw new Error(info.latest ? `Already on the latest version (v${current}).` : 'Could not reach the update server.');
128
+ }
129
+
130
+ const target = process.execPath; // the running binary's own path
131
+ const dir = path.dirname(target);
132
+ const tmp = path.join(dir, `.chatpanel-bridge.new-${Date.now()}`);
133
+
134
+ const res = await fetch(info.assetUrl, { headers: UA });
135
+ if (!res.ok || !res.body) throw new Error(`Download failed (${res.status}).`);
136
+ const buf = Buffer.from(await res.arrayBuffer());
137
+ if (buf.length < 1_000_000) throw new Error('Downloaded file looks too small — aborting to avoid a broken bridge.');
138
+
139
+ await writeFile(tmp, buf);
140
+ if (process.platform !== 'win32') await chmod(tmp, 0o755);
141
+
142
+ if (process.platform === 'win32') {
143
+ // A running .exe can't be overwritten, but it CAN be renamed. Move it aside,
144
+ // drop the new one in place; the old (renamed) file is cleaned up after exit.
145
+ const aside = path.join(dir, `chatpanel-bridge.old-${Date.now()}.exe`);
146
+ await rename(target, aside);
147
+ await rename(tmp, target);
148
+ } else {
149
+ // POSIX: atomic rename over the running file. The live process keeps the old
150
+ // inode; the path now points at the new binary.
151
+ await rename(tmp, target);
152
+ }
153
+ return { ok: true, from: current, to: info.latest };
154
+ }