@marcingadomski94/switchboard 0.0.0-stage → 2.3.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 CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @marcingadomski94/switchboard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Installs [Switchboard](https://github.com/MarcinGadomski94/switchboard), a local web app to run, supervise and switch many Claude Code, Codex CLI and OpenCode sessions at once.
4
+
5
+ ```sh
6
+ npx @marcingadomski94/switchboard
7
+ ```
8
+
9
+ This package is only the installer. It downloads the latest GitHub release of Switchboard and verifies its SHA-256 checksum. It unpacks the release into `~/Applications/Switchboard` (macOS), `~/.local/opt/switchboard` (Linux) or `%LOCALAPPDATA%\Programs\Switchboard` (Windows) and runs `npm ci --omit=dev`. It can register the login service, then starts Switchboard on http://127.0.0.1:13001. After that, Switchboard updates itself from Settings → Updates.
10
+
11
+ Options: `--dir <folder>`, `--version <x.y.z>`, `--service` / `--no-service`, `--no-start`, `--uninstall` (keeps your data), `--uninstall --purge` and `--help`. Running it again upgrades or repairs the install. It needs Node.js 24 or newer, never uses sudo, never edits shell profiles and sends no telemetry.
12
+
13
+ The same installer as a shell one-liner, and the manual steps, are in the [setup guide](https://github.com/MarcinGadomski94/switchboard/blob/master/docs/setup.md).
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // `npx @marcingadomski94/switchboard [--help]`: installs, upgrades or removes Switchboard
4
+ // (lib/installer.mjs; the same steps as the repo's install.sh / install.ps1).
5
+ import { main } from '../lib/installer.mjs';
6
+
7
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,721 @@
1
+ // @ts-check
2
+ /**
3
+ * The installer behind `npx @marcingadomski94/switchboard` (docs/publishing.md): the
4
+ * same steps as the repo's install.sh / install.ps1, in Node, so it runs on macOS,
5
+ * Linux and Windows. It downloads a GitHub release of Switchboard and its .sha256,
6
+ * verifies the checksum (nothing is unpacked on a mismatch), unpacks it into
7
+ * `<dir>/switchboard-<version>` (the manual install's layout, which the in-app
8
+ * updater takes over from: docs/updates.md), runs `npm ci --omit=dev`, optionally
9
+ * registers the login service and starts Switchboard.
10
+ *
11
+ * Plain JavaScript with no dependencies: Node does not strip types under
12
+ * node_modules, and a launcher should install nothing but Switchboard. The pure
13
+ * helpers are exported for tests (`tests/tools/installer.test.ts`).
14
+ */
15
+ import { spawn } from 'node:child_process';
16
+ import { createHash } from 'node:crypto';
17
+ import { closeSync, createReadStream, openSync } from 'node:fs';
18
+ import { copyFile, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { createInterface } from 'node:readline/promises';
22
+ import { fileURLToPath } from 'node:url';
23
+
24
+ /** The repository releases come from (`owner/name`); `SWITCHBOARD_UPDATE_REPO` overrides it, as for the updater. */
25
+ export const DEFAULT_REPO = 'MarcinGadomski94/switchboard';
26
+ /** The port Switchboard listens on unless `SWITCHBOARD_PORT` says otherwise. */
27
+ export const DEFAULT_PORT = 13001;
28
+ /** The file in the install folder that says which version this installer installed. */
29
+ export const MARKER_NAME = '.switchboard-install';
30
+
31
+ /**
32
+ * @typedef {object} Options
33
+ * @property {string | null} dir
34
+ * @property {string | null} version
35
+ * @property {'ask' | 'yes' | 'no'} service
36
+ * @property {boolean} start
37
+ * @property {boolean} uninstall
38
+ * @property {boolean} purge
39
+ * @property {boolean} help
40
+ */
41
+
42
+ /**
43
+ * Reads the command line (`--dir`, `--version`, `--service`, `--no-service`,
44
+ * `--no-start`, `--uninstall`, `--purge`, `--help`).
45
+ * @param {readonly string[]} argv
46
+ * @returns {Options | string} the options, or the problem
47
+ */
48
+ export function parseArgs(argv) {
49
+ /** @type {Options} */
50
+ const out = { dir: null, version: null, service: 'ask', start: true, uninstall: false, purge: false, help: false };
51
+ for (let i = 0; i < argv.length; i++) {
52
+ const arg = /** @type {string} */ (argv[i]);
53
+ const eq = arg.indexOf('=');
54
+ const name = arg.startsWith('--') && eq > 0 ? arg.slice(0, eq) : arg;
55
+ const inline = arg.startsWith('--') && eq > 0 ? arg.slice(eq + 1) : null;
56
+ const value = () => {
57
+ const next = inline ?? argv[++i];
58
+ if (next === undefined || next === '') throw new Error(`${name} needs a value`);
59
+ return next;
60
+ };
61
+ try {
62
+ if (name === '--dir') out.dir = value();
63
+ else if (name === '--version') out.version = value();
64
+ else if (name === '--service') out.service = 'yes';
65
+ else if (name === '--no-service') out.service = 'no';
66
+ else if (name === '--no-start') out.start = false;
67
+ else if (name === '--uninstall') out.uninstall = true;
68
+ else if (name === '--purge') out.purge = true;
69
+ else if (name === '--help' || name === '-h') out.help = true;
70
+ else return `unknown option ${arg} (try --help)`;
71
+ } catch (error) {
72
+ return error instanceof Error ? error.message : String(error);
73
+ }
74
+ }
75
+ if (out.purge && !out.uninstall) return '--purge only goes with --uninstall';
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * `x.y.z` from a release version or tag (`2.0.2`, `v2.0.2`); `null` for anything
81
+ * else, pre-releases included (the updater ignores those too).
82
+ * @param {string | null | undefined} text
83
+ * @returns {string | null}
84
+ */
85
+ export function releaseVersion(text) {
86
+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec((text ?? '').trim());
87
+ return match ? `${Number(match[1])}.${Number(match[2])}.${Number(match[3])}` : null;
88
+ }
89
+
90
+ /**
91
+ * Compares two `x.y.z` versions.
92
+ * @param {string} a
93
+ * @param {string} b
94
+ * @returns {number} negative, zero or positive
95
+ */
96
+ export function compareVersions(a, b) {
97
+ const pa = a.split('.').map(Number);
98
+ const pb = b.split('.').map(Number);
99
+ for (let i = 0; i < 3; i++) {
100
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
101
+ if (diff !== 0) return diff;
102
+ }
103
+ return 0;
104
+ }
105
+
106
+ /**
107
+ * The version of GitHub's `releases/latest` answer (its `tag_name`); `null` for a
108
+ * draft, a pre-release or a tag that is not `x.y.z`.
109
+ * @param {unknown} json
110
+ * @returns {string | null}
111
+ */
112
+ export function versionFromLatestRelease(json) {
113
+ if (typeof json !== 'object' || json === null) return null;
114
+ const release = /** @type {Record<string, unknown>} */ (json);
115
+ if (release['draft'] === true || release['prerelease'] === true) return null;
116
+ return typeof release['tag_name'] === 'string' ? releaseVersion(release['tag_name']) : null;
117
+ }
118
+
119
+ /**
120
+ * The version in the URL `https://github.com/<repo>/releases/latest` redirects to
121
+ * (`…/releases/tag/v2.0.2`); the fallback when the API is rate limited.
122
+ * @param {string} url
123
+ * @returns {string | null}
124
+ */
125
+ export function versionFromTagUrl(url) {
126
+ const match = /\/releases\/tag\/([^/?#]+)$/.exec(url);
127
+ return match ? releaseVersion(decodeURIComponent(/** @type {string} */ (match[1]))) : null;
128
+ }
129
+
130
+ /**
131
+ * The newest release among the file names of a folder (`switchboard-<x.y.z>.tar.gz`).
132
+ * @param {readonly string[]} names
133
+ * @returns {string | null}
134
+ */
135
+ export function newestTarball(names) {
136
+ let best = /** @type {string | null} */ (null);
137
+ for (const name of names) {
138
+ const match = /^switchboard-(\d+\.\d+\.\d+)\.tar\.gz$/.exec(name);
139
+ const version = match ? releaseVersion(match[1]) : null;
140
+ if (version && (best === null || compareVersions(version, best) > 0)) best = version;
141
+ }
142
+ return best;
143
+ }
144
+
145
+ /**
146
+ * Reads a `.sha256` file for `file`: exactly one line `<64 hex> <name>` (or
147
+ * `<64 hex> *<name>`, the binary marker), the name being `file`, as the updater
148
+ * accepts it (`src/core/release.ts`). `null` when the text is anything else.
149
+ * @param {string} text
150
+ * @param {string} file
151
+ * @returns {string | null} the lower-case hash
152
+ */
153
+ export function parseChecksum(text, file) {
154
+ const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '');
155
+ if (lines.length !== 1) return null;
156
+ const match = /^([0-9a-fA-F]{64}) [ *](.+)$/.exec(/** @type {string} */ (lines[0]).trim());
157
+ if (!match || match[2] !== file) return null;
158
+ return /** @type {string} */ (match[1]).toLowerCase();
159
+ }
160
+
161
+ /**
162
+ * The default install folder: `~/Applications/Switchboard` (macOS),
163
+ * `~/.local/opt/switchboard` (Linux), `%LOCALAPPDATA%\Programs\Switchboard` (Windows).
164
+ * @param {NodeJS.Platform} platform
165
+ * @param {NodeJS.ProcessEnv} env
166
+ * @param {string} home
167
+ * @returns {string}
168
+ */
169
+ export function defaultInstallDir(platform, env, home) {
170
+ if (platform === 'darwin') return path.posix.join(home, 'Applications', 'Switchboard');
171
+ if (platform === 'win32') {
172
+ const local = env['LOCALAPPDATA'] && path.win32.isAbsolute(env['LOCALAPPDATA']) ? env['LOCALAPPDATA'] : path.win32.join(home, 'AppData', 'Local');
173
+ return path.win32.join(local, 'Programs', 'Switchboard');
174
+ }
175
+ return path.posix.join(home, '.local', 'opt', 'switchboard');
176
+ }
177
+
178
+ /**
179
+ * Switchboard's data folder, as `defaultDataDir` in `src/server/config.ts` computes
180
+ * it (`SWITCHBOARD_DATA_DIR` first).
181
+ * @param {NodeJS.Platform} platform
182
+ * @param {NodeJS.ProcessEnv} env
183
+ * @param {string} home
184
+ * @returns {string}
185
+ */
186
+ export function dataDir(platform, env, home) {
187
+ if (env['SWITCHBOARD_DATA_DIR']) return env['SWITCHBOARD_DATA_DIR'];
188
+ if (platform === 'darwin') return path.posix.join(home, 'Library', 'Application Support', 'Switchboard');
189
+ if (platform === 'win32') {
190
+ const local = env['LOCALAPPDATA'] && path.win32.isAbsolute(env['LOCALAPPDATA']) ? env['LOCALAPPDATA'] : path.win32.join(home, 'AppData', 'Local');
191
+ return path.win32.join(local, 'Switchboard');
192
+ }
193
+ const xdg = env['XDG_DATA_HOME'];
194
+ return path.posix.join(xdg && path.posix.isAbsolute(xdg) ? xdg : path.posix.join(home, '.local', 'share'), 'switchboard');
195
+ }
196
+
197
+ /**
198
+ * The login service's definition file, where `tools/service` writes it
199
+ * (`src/core/service-files.ts`; `SWITCHBOARD_SERVICE_HOME` is its test redirect).
200
+ * @param {NodeJS.Platform} platform
201
+ * @param {NodeJS.ProcessEnv} env
202
+ * @param {string} home
203
+ * @returns {string | null}
204
+ */
205
+ export function serviceDefinition(platform, env, home) {
206
+ const serviceHome = env['SWITCHBOARD_SERVICE_HOME'] || home;
207
+ if (platform === 'darwin') return path.posix.join(serviceHome, 'Library', 'LaunchAgents', 'local.switchboard.plist');
208
+ if (platform === 'linux') {
209
+ const xdg = env['SWITCHBOARD_SERVICE_HOME'] ? null : env['XDG_CONFIG_HOME'];
210
+ const config = xdg && path.posix.isAbsolute(xdg) ? xdg : path.posix.join(serviceHome, '.config');
211
+ return path.posix.join(config, 'systemd', 'user', 'switchboard.service');
212
+ }
213
+ if (platform === 'win32') return path.win32.join(dataDir(platform, env, home), 'service', 'switchboard-task.xml');
214
+ return null;
215
+ }
216
+
217
+ /**
218
+ * The URLs (or file paths, for a `file://` source) of a release's tarball and checksum.
219
+ * @param {string | null} source `SWITCHBOARD_INSTALL_SOURCE`: a folder URL, or null for GitHub
220
+ * @param {string} repo
221
+ * @param {string} version
222
+ * @returns {{ tarball: string, checksum: string, name: string }}
223
+ */
224
+ export function releaseUrls(source, repo, version) {
225
+ const name = `switchboard-${version}.tar.gz`;
226
+ const base = source ? source.replace(/\/+$/, '') : `https://github.com/${repo}/releases/download/v${version}`;
227
+ return { tarball: `${base}/${name}`, checksum: `${base}/${name}.sha256`, name };
228
+ }
229
+
230
+ /**
231
+ * The npm command as an argv prefix: `npm-cli.js` through this node (npx sets
232
+ * `npm_execpath`; else next to node), because Windows' `npm.cmd` cannot be
233
+ * spawned without a shell; plain `npm` as a last resort outside Windows.
234
+ * @param {string} execPath
235
+ * @param {NodeJS.ProcessEnv} env
236
+ * @param {NodeJS.Platform} platform
237
+ * @returns {string[]} candidates, the first existing one wins
238
+ */
239
+ export function npmCandidates(execPath, env, platform) {
240
+ const lib = platform === 'win32' ? path.win32 : path.posix;
241
+ const out = [];
242
+ const fromNpm = env['npm_execpath'];
243
+ if (fromNpm && /npm-cli\.js$/.test(fromNpm) && lib.isAbsolute(fromNpm)) out.push(fromNpm);
244
+ const dir = lib.dirname(execPath);
245
+ if (platform === 'win32') out.push(lib.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js'));
246
+ else out.push(lib.join(lib.dirname(dir), 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'));
247
+ return out;
248
+ }
249
+
250
+ export const HELP = `Install, upgrade or remove Switchboard (https://github.com/${DEFAULT_REPO}).
251
+
252
+ Usage: npx @marcingadomski94/switchboard [options]
253
+
254
+ --dir <folder> install folder (default: ~/Applications/Switchboard on macOS,
255
+ ~/.local/opt/switchboard on Linux, %LOCALAPPDATA%\\Programs\\Switchboard on Windows)
256
+ --version <x.y.z> install that release instead of the latest (or SWITCHBOARD_VERSION)
257
+ --service also start Switchboard at login (the login service)
258
+ --no-service do not register the login service (default without a terminal)
259
+ --no-start install only; do not start Switchboard
260
+ --uninstall stop it, remove the login service and the install folder; keeps your data
261
+ --purge with --uninstall: also remove the data folder
262
+ --help this text
263
+
264
+ Running it again upgrades to the latest release or repairs the installed one.
265
+ No sudo, no shell profile changes, no telemetry.`;
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Side effects
269
+
270
+ class InstallError extends Error {}
271
+
272
+ /**
273
+ * @param {string} message
274
+ * @returns {never}
275
+ */
276
+ function fail(message) {
277
+ throw new InstallError(message);
278
+ }
279
+
280
+ /** @param {string} file */
281
+ async function exists(file) {
282
+ try {
283
+ await stat(file);
284
+ return true;
285
+ } catch {
286
+ return false;
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Runs a command (never through a shell), its output passed through.
292
+ * @param {string} command
293
+ * @param {readonly string[]} args
294
+ * @param {{ cwd: string, env?: NodeJS.ProcessEnv, quiet?: boolean }} options
295
+ * @returns {Promise<{ code: number | null, stdout: string }>}
296
+ */
297
+ function run(command, args, options) {
298
+ return new Promise((resolve, reject) => {
299
+ const child = spawn(command, args, { cwd: options.cwd, env: options.env ?? process.env, shell: false, stdio: ['ignore', options.quiet ? 'pipe' : 'inherit', options.quiet ? 'pipe' : 'inherit'], windowsHide: true });
300
+ let stdout = '';
301
+ child.stdout?.setEncoding('utf8').on('data', (chunk) => (stdout += chunk));
302
+ child.stderr?.resume();
303
+ child.once('error', reject);
304
+ child.once('close', (code) => resolve({ code, stdout }));
305
+ });
306
+ }
307
+
308
+ /** @param {string} file */
309
+ async function sha256(file) {
310
+ const hash = createHash('sha256');
311
+ for await (const chunk of createReadStream(file)) hash.update(/** @type {Buffer} */ (chunk));
312
+ return hash.digest('hex');
313
+ }
314
+
315
+ /**
316
+ * @param {string} url
317
+ * @param {string} file
318
+ */
319
+ async function download(url, file) {
320
+ if (url.startsWith('file://')) {
321
+ await copyFile(fileURLToPath(url), file).catch(() => fail(`cannot read ${fileURLToPath(url)}`));
322
+ return;
323
+ }
324
+ const response = await fetch(url, { headers: { 'user-agent': 'switchboard-installer' }, signal: AbortSignal.timeout(10 * 60_000) }).catch((error) => fail(`download failed: ${url} (${error instanceof Error ? error.message : String(error)})`));
325
+ if (!response.ok) fail(`download failed: ${url} answered HTTP ${response.status}`);
326
+ if (url.startsWith('https:') && !response.url.startsWith('https:')) fail(`download of ${url} was redirected off HTTPS`);
327
+ await writeFile(file, Buffer.from(await response.arrayBuffer()));
328
+ }
329
+
330
+ /**
331
+ * @param {string | null} source
332
+ * @param {string} repo
333
+ * @param {(line: string) => void} log
334
+ * @returns {Promise<string>}
335
+ */
336
+ async function latestVersion(source, repo, log) {
337
+ if (source) {
338
+ if (!source.startsWith('file://')) fail('SWITCHBOARD_INSTALL_SOURCE needs --version unless it is a file:// folder');
339
+ const folder = fileURLToPath(source);
340
+ const version = newestTarball(await readdir(folder).catch(() => []));
341
+ return version ?? fail(`no switchboard-<version>.tar.gz in ${folder}`);
342
+ }
343
+ log(`Looking up the latest release of ${repo}...`);
344
+ try {
345
+ const response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, { headers: { accept: 'application/vnd.github+json', 'user-agent': 'switchboard-installer' }, signal: AbortSignal.timeout(15_000) });
346
+ if (response.ok) {
347
+ const version = versionFromLatestRelease(await response.json());
348
+ if (version) return version;
349
+ }
350
+ } catch {
351
+ // fall through to the redirect
352
+ }
353
+ try {
354
+ const response = await fetch(`https://github.com/${repo}/releases/latest`, { method: 'HEAD', redirect: 'manual', headers: { 'user-agent': 'switchboard-installer' }, signal: AbortSignal.timeout(15_000) });
355
+ const version = versionFromTagUrl(response.headers.get('location') ?? '');
356
+ if (version) return version;
357
+ } catch {
358
+ // reported below
359
+ }
360
+ return fail(`could not find the latest release of ${repo} (GitHub rate limit?); pass --version x.y.z`);
361
+ }
362
+
363
+ /**
364
+ * The HTTP status of `url`, 0 when nothing answers.
365
+ * @param {string} url
366
+ */
367
+ async function httpStatus(url) {
368
+ try {
369
+ const response = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(3000) });
370
+ await response.body?.cancel();
371
+ return response.status;
372
+ } catch {
373
+ return 0;
374
+ }
375
+ }
376
+
377
+ /** @param {number} ms */
378
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
379
+
380
+ /** @param {number} pid */
381
+ function alive(pid) {
382
+ try {
383
+ process.kill(pid, 0);
384
+ return true;
385
+ } catch (error) {
386
+ return /** @type {NodeJS.ErrnoException} */ (error).code === 'EPERM';
387
+ }
388
+ }
389
+
390
+ /**
391
+ * The command line of `pid` (empty when unknown).
392
+ * @param {number} pid
393
+ */
394
+ async function commandOf(pid) {
395
+ try {
396
+ if (process.platform === 'win32') {
397
+ const result = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], { cwd: os.tmpdir(), quiet: true });
398
+ return result.stdout.trim();
399
+ }
400
+ const result = await run('ps', ['-p', String(pid), '-o', 'command='], { cwd: os.tmpdir(), quiet: true });
401
+ return result.stdout.trim();
402
+ } catch {
403
+ return '';
404
+ }
405
+ }
406
+
407
+ /** Everything one run needs. */
408
+ class Installer {
409
+ /**
410
+ * @param {Options} options
411
+ * @param {{ env: NodeJS.ProcessEnv, platform: NodeJS.Platform, home: string, log: (line: string) => void, interactive: boolean }} context
412
+ */
413
+ constructor(options, context) {
414
+ this.options = options;
415
+ this.env = context.env;
416
+ this.platform = context.platform;
417
+ this.home = context.home;
418
+ this.log = context.log;
419
+ this.interactive = context.interactive;
420
+ this.lib = this.platform === 'win32' ? path.win32 : path.posix;
421
+ this.dir = this.lib.resolve(options.dir ?? defaultInstallDir(this.platform, this.env, this.home));
422
+ this.dataDir = dataDir(this.platform, this.env, this.home);
423
+ this.repo = this.env['SWITCHBOARD_UPDATE_REPO'] || DEFAULT_REPO;
424
+ this.source = this.env['SWITCHBOARD_INSTALL_SOURCE'] || null;
425
+ const port = this.env['SWITCHBOARD_PORT'] || String(DEFAULT_PORT);
426
+ if (!/^\d+$/.test(port)) fail(`SWITCHBOARD_PORT must be a number, got ${port}`);
427
+ this.url = `http://127.0.0.1:${port}`;
428
+ this.definition = serviceDefinition(this.platform, this.env, this.home);
429
+ if (this.dir === this.lib.resolve(this.home) || this.dir === this.lib.parse(this.dir).root) fail(`refusing to use ${this.dir} as the install folder`);
430
+ }
431
+
432
+ /** The service definition's text (UTF-16 for the Windows task XML), or null. */
433
+ async serviceText() {
434
+ if (!this.definition) return null;
435
+ try {
436
+ const bytes = await readFile(this.definition);
437
+ return bytes[0] === 0xff && bytes[1] === 0xfe ? bytes.subarray(2).toString('utf16le') : bytes.toString('utf8');
438
+ } catch {
439
+ return null;
440
+ }
441
+ }
442
+
443
+ /** True when the login service starts a Switchboard from this install (or a version the updater put in the data folder). */
444
+ async servicePointsHere() {
445
+ const text = await this.serviceText();
446
+ if (text === null) return false;
447
+ return text.includes(this.dir + this.lib.sep) || text.includes(this.lib.join(this.dataDir, 'versions') + this.lib.sep);
448
+ }
449
+
450
+ get pidFile() {
451
+ return this.lib.join(this.dir, 'switchboard.pid');
452
+ }
453
+
454
+ /** The pid of a Switchboard this installer started from this folder, or null. */
455
+ async startedPid() {
456
+ const text = await readFile(this.pidFile, 'utf8').catch(() => '');
457
+ const pid = Number(text.trim());
458
+ if (!Number.isInteger(pid) || pid <= 0 || !alive(pid)) return null;
459
+ const command = await commandOf(pid);
460
+ return command.includes(this.dir) && command.includes('main.ts') ? pid : null;
461
+ }
462
+
463
+ async stopStarted() {
464
+ const pid = await this.startedPid();
465
+ if (pid !== null) {
466
+ this.log(`Stopping the Switchboard this installer started (pid ${pid})...`);
467
+ try {
468
+ process.kill(pid, 'SIGTERM');
469
+ } catch {
470
+ // gone already
471
+ }
472
+ for (let waited = 0; waited < 60 && alive(pid); waited++) await sleep(500);
473
+ if (alive(pid)) {
474
+ this.log(`pid ${pid} did not stop within 30 s; stopping it hard`);
475
+ try {
476
+ process.kill(pid, 'SIGKILL');
477
+ } catch {
478
+ // gone already
479
+ }
480
+ }
481
+ }
482
+ await rm(this.pidFile, { force: true });
483
+ }
484
+
485
+ /** @param {string} app */
486
+ async npmCi(app) {
487
+ let command = /** @type {string[] | null} */ (null);
488
+ for (const candidate of npmCandidates(process.execPath, this.env, this.platform)) {
489
+ if (await exists(candidate)) {
490
+ command = [process.execPath, candidate];
491
+ break;
492
+ }
493
+ }
494
+ if (!command) command = this.platform === 'win32' ? fail('npm was not found next to node') : ['npm'];
495
+ /** @type {NodeJS.ProcessEnv} */
496
+ const env = {};
497
+ for (const [key, value] of Object.entries(this.env)) if (!/^npm_/i.test(key)) env[key] = value;
498
+ const result = await run(/** @type {string} */ (command[0]), [...command.slice(1), 'ci', '--omit=dev', '--no-audit', '--no-fund'], { cwd: app, env: { ...env, npm_config_update_notifier: 'false' } });
499
+ if (result.code !== 0) fail('npm ci failed; nothing was installed');
500
+ }
501
+
502
+ async wantService() {
503
+ if (this.options.service !== 'ask') return this.options.service === 'yes';
504
+ if (await this.servicePointsHere()) {
505
+ this.log('The login service already starts this install: keeping it, pointed at the new version.');
506
+ return true;
507
+ }
508
+ if (!this.interactive) return false;
509
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
510
+ try {
511
+ const answer = await rl.question('Start Switchboard at login (a per-user login service)? [y/N] ');
512
+ return /^y(es)?$/i.test(answer.trim());
513
+ } finally {
514
+ rl.close();
515
+ }
516
+ }
517
+
518
+ /** @param {string} app */
519
+ async startDetached(app) {
520
+ const log = openSync(this.lib.join(this.dir, 'switchboard.log'), 'a');
521
+ try {
522
+ const child = spawn(process.execPath, [this.lib.join(app, 'src', 'server', 'main.ts')], { cwd: app, env: this.env, detached: true, stdio: ['ignore', log, log], shell: false, windowsHide: true });
523
+ if (child.pid === undefined) fail('could not start Switchboard');
524
+ await writeFile(this.pidFile, `${child.pid}\n`);
525
+ child.unref();
526
+ } finally {
527
+ closeSync(log);
528
+ }
529
+ }
530
+
531
+ async waitForAnswer() {
532
+ for (let waited = 0; waited < 120; waited++) {
533
+ if ((await httpStatus(`${this.url}/`)) !== 0) return true;
534
+ await sleep(500);
535
+ }
536
+ return false;
537
+ }
538
+
539
+ /** Uses the real paths (no symlinks) of existing folders, as the login service and the process list name them. */
540
+ async canonical() {
541
+ this.dir = await realpath(this.dir).catch(() => this.dir);
542
+ this.dataDir = await realpath(this.dataDir).catch(() => this.dataDir);
543
+ }
544
+
545
+ async install() {
546
+ const major = Number(process.versions.node.split('.')[0]);
547
+ if (major < 24) fail(`Node.js ${process.version} is too old: Switchboard needs Node.js 24 or newer (nvm install 24, or brew install node). Nothing was installed.`);
548
+ const version = (this.options.version ?? this.env['SWITCHBOARD_VERSION'] ?? null) !== null ? releaseVersion(this.options.version ?? this.env['SWITCHBOARD_VERSION']) ?? fail(`"${this.options.version ?? this.env['SWITCHBOARD_VERSION']}" is not a release version (x.y.z)`) : await latestVersion(this.source, this.repo, this.log);
549
+ const urls = releaseUrls(this.source, this.repo, version);
550
+ await mkdir(this.dir, { recursive: true });
551
+ await this.canonical();
552
+ const app = this.lib.join(this.dir, `switchboard-${version}`);
553
+ const marker = this.lib.join(this.dir, MARKER_NAME);
554
+ const previous = (await readFile(marker, 'utf8').catch(() => '')).match(/^version=(.+)$/m)?.[1]?.trim() ?? null;
555
+ this.log((await exists(app)) ? `Repairing Switchboard ${version} in ${app}` : `Installing Switchboard ${version} into ${app}`);
556
+ await mkdir(this.dir, { recursive: true });
557
+ const work = this.lib.join(this.dir, `.staging-${process.pid}`);
558
+ await rm(work, { recursive: true, force: true });
559
+ await mkdir(this.lib.join(work, 'unpacked'), { recursive: true });
560
+ try {
561
+ this.log(`Downloading ${urls.name}...`);
562
+ const checksumFile = this.lib.join(work, `${urls.name}.sha256`);
563
+ const tarball = this.lib.join(work, urls.name);
564
+ await download(urls.checksum, checksumFile);
565
+ await download(urls.tarball, tarball);
566
+ const expected = parseChecksum(await readFile(checksumFile, 'utf8'), urls.name) ?? fail(`${urls.name}.sha256 is not a sha256 line for ${urls.name}; nothing was installed`);
567
+ const actual = await sha256(tarball);
568
+ if (actual !== expected) fail(`checksum mismatch for ${urls.name} (expected ${expected}, got ${actual}); nothing was installed`);
569
+ this.log(`Checksum OK (${actual})`);
570
+ const listing = await run('tar', ['-tzf', tarball], { cwd: work, quiet: true });
571
+ if (listing.code !== 0) fail(`${urls.name} is not a readable tar.gz`);
572
+ const prefix = `switchboard-${version}/`;
573
+ for (const entry of listing.stdout.split(/\r?\n/).filter(Boolean)) {
574
+ if (!entry.startsWith(prefix) || /(^|[/\\])\.\.([/\\]|$)/.test(entry)) fail(`${urls.name} has entries outside ${prefix}; nothing was installed`);
575
+ }
576
+ const unpack = await run('tar', ['-xzf', urls.name, '-C', 'unpacked'], { cwd: work });
577
+ if (unpack.code !== 0) fail(`unpacking ${urls.name} failed`);
578
+ const staged = this.lib.join(work, 'unpacked', `switchboard-${version}`);
579
+ const packaged = JSON.parse(await readFile(this.lib.join(staged, 'package.json'), 'utf8').catch(() => '{}')).version;
580
+ if (packaged !== version) fail(`the package says version "${packaged}", not ${version}`);
581
+ if (!(await exists(this.lib.join(staged, 'src', 'server', 'main.ts'))) || !(await exists(this.lib.join(staged, 'dist', 'web', 'index.html')))) fail('the package misses src/server/main.ts or dist/web; nothing was installed');
582
+ this.log('Installing dependencies (npm ci --omit=dev)...');
583
+ await this.npmCi(staged);
584
+ if (this.options.start || (await exists(app))) await this.stopStarted();
585
+ if (await exists(app)) await rename(app, this.lib.join(work, 'replaced'));
586
+ await rename(staged, app);
587
+ await writeFile(marker, `version=${version}\n`);
588
+ this.log(`Installed Switchboard ${version} in ${app}`);
589
+ } finally {
590
+ await rm(work, { recursive: true, force: true });
591
+ }
592
+
593
+ let startedByService = false;
594
+ if (await this.wantService()) {
595
+ this.log('Registering the login service...');
596
+ const result = await run(process.execPath, [this.lib.join('tools', 'service', 'install.ts'), ...(this.options.start ? ['--start'] : [])], { cwd: app, env: this.env });
597
+ if (result.code !== 0) fail('registering the login service failed (see above)');
598
+ startedByService = this.options.start;
599
+ }
600
+
601
+ const serviceText = (await this.serviceText()) ?? '';
602
+ for (const name of await readdir(this.dir)) {
603
+ const folder = this.lib.join(this.dir, name);
604
+ if (!name.startsWith('switchboard-') || folder === app || (previous && name === `switchboard-${previous}`)) continue;
605
+ if (!(await stat(folder)).isDirectory() || serviceText.includes(folder + this.lib.sep)) continue;
606
+ await rm(folder, { recursive: true, force: true });
607
+ this.log(`Removed the older ${folder}`);
608
+ }
609
+
610
+ if (!this.options.start) {
611
+ this.log(`\nDone. Start it with "npm start" in ${app}, then open ${this.url}`);
612
+ return 0;
613
+ }
614
+ if (!startedByService) {
615
+ if ((await httpStatus(`${this.url}/`)) !== 0) {
616
+ this.log(`Something already answers on ${this.url} (another Switchboard?); not starting a second one. Stop it first, or set SWITCHBOARD_PORT, then run "npm start" in ${app}.`);
617
+ return 0;
618
+ }
619
+ this.log('Starting Switchboard...');
620
+ await this.startDetached(app);
621
+ }
622
+ if (!(await this.waitForAnswer())) fail(`Switchboard did not answer on ${this.url} within 60 s; see ${this.lib.join(this.dir, 'switchboard.log')}`);
623
+ this.log(`\nSwitchboard ${version} is running: open ${this.url}`);
624
+ if (!startedByService) this.log(`It runs in the background (log: ${this.lib.join(this.dir, 'switchboard.log')}). Run this again with --service to start it at login.`);
625
+ return 0;
626
+ }
627
+
628
+ /** A folder this installer may delete: it made it, or it holds only release folders and the installer's files. */
629
+ async removable() {
630
+ if (await exists(this.lib.join(this.dir, MARKER_NAME))) return true;
631
+ const names = await readdir(this.dir);
632
+ return names.every((name) => /^(switchboard-|\.staging-)/.test(name) || name === 'switchboard.log' || name === 'switchboard.pid');
633
+ }
634
+
635
+ async uninstall() {
636
+ await this.canonical();
637
+ this.log(`Uninstalling Switchboard from ${this.dir}`);
638
+ const installed = await exists(this.dir);
639
+ if (installed) await this.stopStarted();
640
+ if (await this.servicePointsHere()) {
641
+ const candidates = [
642
+ ...(installed ? (await readdir(this.dir)).filter((name) => name.startsWith('switchboard-')).map((name) => this.lib.join(this.dir, name)) : []),
643
+ ...(await readdir(this.lib.join(this.dataDir, 'versions')).catch(() => [])).map((name) => this.lib.join(this.dataDir, 'versions', name)),
644
+ ];
645
+ let app = null;
646
+ for (const candidate of candidates) {
647
+ if (await exists(this.lib.join(candidate, 'tools', 'service', 'uninstall.ts'))) {
648
+ app = candidate;
649
+ break;
650
+ }
651
+ }
652
+ if (app) {
653
+ this.log('Removing the login service...');
654
+ const result = await run(process.execPath, [this.lib.join('tools', 'service', 'uninstall.ts')], { cwd: app, env: this.env });
655
+ if (result.code !== 0) this.log(`Removing the login service failed; run "npm run service:uninstall" in ${app}`);
656
+ } else {
657
+ this.log(`The login service ${this.definition} points here but no install is left to remove it; delete it by hand.`);
658
+ }
659
+ } else if (this.definition && (await exists(this.definition))) {
660
+ this.log(`Leaving the login service alone: it starts a Switchboard from another folder (${this.definition}).`);
661
+ }
662
+ if (installed) {
663
+ if (!(await this.removable())) fail(`${this.dir} holds files this installer did not make; remove it by hand`);
664
+ await rm(this.dir, { recursive: true, force: true });
665
+ this.log(`Removed ${this.dir}`);
666
+ } else {
667
+ this.log(`Nothing installed in ${this.dir}`);
668
+ }
669
+ for (const folder of [this.lib.join(this.dataDir, 'versions'), this.lib.join(this.dataDir, 'updates')]) {
670
+ if (await exists(folder)) {
671
+ await rm(folder, { recursive: true, force: true });
672
+ this.log(`Removed ${folder} (versions the in-app updater installed)`);
673
+ }
674
+ }
675
+ if (this.options.purge) {
676
+ const resolved = this.lib.resolve(this.dataDir);
677
+ if (resolved === this.lib.resolve(this.home) || resolved === this.lib.parse(resolved).root) fail(`refusing to purge ${resolved}`);
678
+ if (await exists(resolved)) {
679
+ await rm(resolved, { recursive: true, force: true });
680
+ this.log(`Removed your data in ${resolved}`);
681
+ }
682
+ } else if (await exists(this.dataDir)) {
683
+ this.log(`Kept your data in ${this.dataDir} (run with --uninstall --purge to remove it too)`);
684
+ }
685
+ return 0;
686
+ }
687
+ }
688
+
689
+ /**
690
+ * Runs the installer.
691
+ * @param {readonly string[]} argv the arguments after the command
692
+ * @param {{ env?: NodeJS.ProcessEnv, log?: (line: string) => void }} [io]
693
+ * @returns {Promise<number>} the exit code
694
+ */
695
+ export async function main(argv, io = {}) {
696
+ const log = io.log ?? ((line) => console.log(line));
697
+ const options = parseArgs(argv);
698
+ if (typeof options === 'string') {
699
+ console.error(`switchboard install: ${options}`);
700
+ return 2;
701
+ }
702
+ if (options.help) {
703
+ log(HELP);
704
+ return 0;
705
+ }
706
+ if (!['darwin', 'linux', 'win32'].includes(process.platform)) {
707
+ console.error(`switchboard install: ${process.platform} is not supported (macOS, Linux and Windows are)`);
708
+ return 1;
709
+ }
710
+ const env = io.env ?? process.env;
711
+ try {
712
+ const installer = new Installer(options, { env, platform: process.platform, home: env['HOME'] && process.platform !== 'win32' ? env['HOME'] : os.homedir(), log, interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY) });
713
+ return options.uninstall ? await installer.uninstall() : await installer.install();
714
+ } catch (error) {
715
+ if (error instanceof InstallError) {
716
+ console.error(`switchboard install: ${error.message}`);
717
+ return 1;
718
+ }
719
+ throw error;
720
+ }
721
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@marcingadomski94/switchboard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.3.0",
4
+ "description": "Installs Switchboard, the local web app to run, supervise and switch many Claude Code, Codex CLI and OpenCode sessions at once: npx @marcingadomski94/switchboard",
5
+ "license": "MIT",
6
+ "mcpName": "io.github.MarcinGadomski94/switchboard",
7
+ "homepage": "https://github.com/MarcinGadomski94/switchboard#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/MarcinGadomski94/switchboard.git",
11
+ "directory": "packages/npx"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/MarcinGadomski94/switchboard/issues"
15
+ },
16
+ "keywords": [
17
+ "claude-code",
18
+ "codex-cli",
19
+ "opencode",
20
+ "ai-agents",
21
+ "mcp",
22
+ "installer"
23
+ ],
24
+ "type": "module",
25
+ "bin": {
26
+ "switchboard": "bin/switchboard.mjs"
27
+ },
28
+ "files": [
29
+ "bin/",
30
+ "lib/",
31
+ "README.md"
32
+ ],
33
+ "engines": {
34
+ "node": ">=24"
35
+ }
36
+ }