Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1863 lines (1709 loc) · 73.7 KB
/
Copy pathserver.js
File metadata and controls
1863 lines (1709 loc) · 73.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const { HUB_VERSION, checkArgs, printedUrl } = require('./lib/cli');
// Before the other requires: -v and -h answer at once, and a bad flag never reaches the running-hub check,
// which prints the hub URL with its token.
const cli = checkArgs(process.argv.slice(2));
if (cli.exit !== undefined) {
(cli.exit ? console.error : console.log)(cli.out);
process.exit(cli.exit);
}
const { spawn } = require('child_process');
const crypto = require('crypto');
const express = require('express');
const fs = require('fs');
const http = require('http');
const tcp = require('net');
const os = require('os');
const path = require('path');
const { actionTable } = require('./lib/actions');
const { HUB_ROOT, selectApps, appRoot, loadApp, conflicts, readApp } = require('./lib/apps');
const { userKeys } = require('./lib/keymap');
const { stripCookie } = require('./lib/cookies');
const { createNetGuard, KEEP_ALIVE_MS } = require('./lib/net-guard');
const { ping, stats } = require('./lib/ipc');
const { killChild } = require('./lib/kill-child');
const { createPortHealth } = require('./lib/port-health');
const { readRegistry, themeConfig, modThemes } = require('./lib/themes');
const { resolveMods, modAssets, appModEnv, readSurface, hubModScript } = require('./lib/mods');
const { createUpdateCheck } = require('./lib/update-check');
const { liveHub, removeRecord, writeRecord } = require('./lib/hub-record');
const { HUB_PLUGIN } = require('./lib/install');
const { pluginChecker } = require('./lib/plugin-status');
const { readConfig, serializeConfig, writeConfigFile } = require('./lib/hub-config');
const { assignPorts, chooseLegacyDir, cleanDirPorts } = require('./lib/dir-ports');
const { ONBOARDING, findConfigDirs, pluginsToInstall, setupStatus } = require('./lib/onboarding');
const {
appSettings,
appsShape,
applySettings,
configDirSwitch,
poolSize,
copyLive,
MAX_POOL_SIZE,
settingValues,
} = require('./lib/settings');
function getArg(name) {
const idx = process.argv.findIndex((a) => a.startsWith(`--${name}`));
if (idx === -1) return null;
const arg = process.argv[idx];
if (arg.includes('=')) return arg.split('=').slice(1).join('=');
return process.argv[idx + 1] || null;
}
const DEFAULT_HUB_PORT = 3540;
const HUB_PORT = parseInt(getArg('port') || process.env.PORT || DEFAULT_HUB_PORT, 10);
let hubPort = HUB_PORT;
const POOL_SIZE_FLAG = getArg('pool-size');
const RESTART_DELAY_MS = 500;
// A rate window, not a total: a child may die and recover all session, but one that cannot stay up
// stops being restarted. A consecutive counter cannot express that — anything that starts at all
// clears it, so a child that starts and dies forever restarts forever.
const MAX_RESTARTS = 5;
const RESTART_WINDOW_MS = 60_000;
// One child set per config dir, kept alive after a switch so switching back is instant. Map
// insertion order doubles as LRU: activating a dir re-inserts it at the end.
const pools = new Map();
// Each hub window names its own dir and its previous one on every call; the global active dir is
// only the default for a window that has none yet. URI-encoded, because fetch throws on a header
// value outside Latin-1.
const DIR_HEADER = 'x-hub-config-dir';
const PREVIOUS_HEADER = 'x-hub-previous-config-dir';
const listedDir = (dir) => (typeof dir === 'string' && hubConfig.configDirs.includes(dir) ? dir : null);
function headerDir(req, name) {
const raw = req.get(name);
if (!raw) return undefined;
try {
return listedDir(decodeURIComponent(raw));
} catch {
return null;
}
}
// Sets req.dir and req.previous. A dir that is no longer listed gets a 409 the page answers with a
// reload; /api/config falls back to the global dir instead, and /api/events reads ?dir=.
function windowDirs(req, res, next) {
const dir = headerDir(req, DIR_HEADER);
req.dir = dir === undefined ? hubConfig.activeConfigDir : dir;
req.previous = headerDir(req, PREVIOUS_HEADER) ?? null;
if (req.dir || req.path === '/config' || req.path === '/events') return next();
res.status(409).json({ error: 'This config dir was removed', code: 'unknown_config_dir' });
}
// The global dir, which a new window opens on, and every dir an open window shows.
const shownDirs = () => new Set([hubConfig.activeConfigDir, ...eventClients.keys()]);
// Every sub-app resolves CLAUDE_CONFIG_DIR once at startup into a module constant, so switching
// the dir means restarting the children. Kept on the server, not in the browser: the dir has to
// be known before the first spawn, and the hub already has one localStorage key to reason about.
const HUB_DIR = path.resolve(expandHome(getArg('hub-dir') || process.env.CLAUDE_HUB_DIR || '~/.claude-hub'));
const HUB_CONFIG_FILE = path.join(HUB_DIR, 'config.json');
const TRAY_FLAG = ['--tray', '--autostart', '--no-autostart', '--tray-status'].find((f) => process.argv.includes(f));
if (TRAY_FLAG) {
const { runTrayCommand } = require('./lib/tray');
runTrayCommand({
flag: TRAY_FLAG,
hubDir: HUB_DIR,
port: HUB_PORT,
defaultPort: DEFAULT_HUB_PORT,
appId: getArg('app-id'),
configDir: resolveHubConfig().config.activeConfigDir,
}).then((ok) => process.exit(ok ? 0 : 1));
}
function cliConfigDir() {
const dir = getArg('dir') || process.env.CLAUDE_CONFIG_DIR || '~/.claude';
try {
return canonicalDir(dir);
} catch {
console.error(`Config dir not found: ${dir}`);
process.exit(1);
}
}
if (process.argv[2] === 'ext') {
const { runExt } = require('./lib/ext');
const ok = runExt(process.argv.slice(3), { hubDir: HUB_DIR, configDir: cliConfigDir, hubVersion: HUB_VERSION });
process.exit(ok ? 0 : 1);
}
if (process.argv.includes('--install') || process.argv.includes('--uninstall')) {
const { runInstall, runUninstall } = require('./lib/install');
const configDir = cliConfigDir();
let ok;
if (process.argv.includes('--install')) {
const { installBuiltInPlugins } = require('./lib/ext');
const hubOk = runInstall({ hubDir: HUB_DIR, configDir });
ok = installBuiltInPlugins({ hubDir: HUB_DIR, configDir: () => configDir }) && hubOk;
} else {
ok = runUninstall({ configDir });
}
process.exit(ok ? 0 : 1);
}
// The dir the hub would use with no saved config. Set by loadHubConfig; the client uses it to keep
// the default dir out of the window title.
let defaultConfigDir = null;
function expandHome(p) {
return p.startsWith('~') ? p.replace('~', os.homedir()) : p;
}
// Real on-disk spelling (true casing, native separators). One dir is one list entry and one child
// pool whichever way it was typed. Throws when the path does not exist.
function canonicalDir(p) {
return fs.realpathSync.native(path.resolve(expandHome(p)));
}
function loadHubConfig() {
const { config, raw, fallback } = resolveHubConfig();
defaultConfigDir = fallback;
// Configs saved before canonicalization can hold one dir under two spellings; persist the merge.
if (serializeConfig(config) !== raw) writeHubConfig(config);
return config;
}
function resolveHubConfig() {
const canonical = (p) => {
try {
return canonicalDir(p);
} catch {
return expandHome(p);
}
};
const fallback = canonical(
process.env.CLAUDE_CONFIG_DIR || process.env.CLAUDE_DIR || path.join(os.homedir(), '.claude'),
);
let raw = '';
let saved = {};
try {
raw = fs.readFileSync(HUB_CONFIG_FILE, 'utf8');
saved = JSON.parse(raw);
} catch {}
const savedDirs = Array.isArray(saved.configDirs) ? saved.configDirs.filter((d) => typeof d === 'string') : [];
const dirs = [...new Set(savedDirs.map(canonical))];
if (!dirs.includes(fallback)) dirs.unshift(fallback);
const savedActive = typeof saved.activeConfigDir === 'string' ? canonical(saved.activeConfigDir) : null;
const active = dirs.includes(savedActive) ? savedActive : fallback;
const config = { configDirs: dirs, activeConfigDir: active };
// Hand-edited only; kept verbatim so a rewrite of the file does not drop it.
if (saved.terminal && typeof saved.terminal === 'object') config.terminal = saved.terminal;
if (Array.isArray(saved.apps)) config.apps = saved.apps;
if (Array.isArray(saved.addons)) config.addons = saved.addons;
if (Array.isArray(saved.mods)) config.mods = saved.mods;
if (typeof saved.modsEnabled === 'boolean') config.modsEnabled = saved.modsEnabled;
if (saved.keys !== undefined) config.keys = saved.keys;
if (saved.voice && typeof saved.voice === 'object') config.voice = saved.voice;
if (ONBOARDING.includes(saved.onboarding)) config.onboarding = saved.onboarding;
copyLive(saved, config);
const savedPrevious = typeof saved.previousConfigDir === 'string' ? canonical(saved.previousConfigDir) : null;
if (dirs.includes(savedPrevious) && savedPrevious !== active) config.previousConfigDir = savedPrevious;
const savedLegacy = typeof saved.legacyConfigDir === 'string' ? canonical(saved.legacyConfigDir) : null;
const claudeHome = canonical(path.join(os.homedir(), '.claude'));
config.legacyConfigDir = chooseLegacyDir({ saved: savedLegacy, dirs, claudeHome });
const dirPorts = cleanDirPorts(saved.dirPorts);
if (Object.keys(dirPorts).length) config.dirPorts = dirPorts;
return { config, raw, fallback };
}
function writeHubConfig(config) {
writeConfigFile(HUB_CONFIG_FILE, config);
}
// `ext` and hand edits change the other keys while the hub runs, so a save keeps the file's copy of them.
// `patch` gets the file's copy and returns more keys to write.
function saveHubConfig(patch = () => ({})) {
let saved = hubConfig;
try {
saved = readSavedConfig();
} catch {}
writeHubConfig({
...saved,
configDirs: hubConfig.configDirs,
activeConfigDir: hubConfig.activeConfigDir,
previousConfigDir: hubConfig.previousConfigDir,
legacyConfigDir: hubConfig.legacyConfigDir,
...patch(saved),
});
}
function readSavedConfig() {
return readConfig(path.dirname(HUB_CONFIG_FILE)).config;
}
const hubConfig = loadHubConfig();
const currentPoolSize = () => poolSize(hubConfig, POOL_SIZE_FLAG);
const { apps: selectedApps, unknown: unknownApps } = selectApps(hubConfig.apps, path.dirname(HUB_CONFIG_FILE));
const ENABLED_APPS = selectedApps.map((a) => loadApp(a, { flagPort: getArg(`${a.id}-port`) })).filter(Boolean);
for (const id of unknownApps) console.log(`Unknown app "${id}" in ${HUB_CONFIG_FILE} has no "path", ignored`);
for (const a of selectedApps) if (a.path) console.log(`${a.id} runs from ${a.path}`);
for (const line of conflicts(ENABLED_APPS)) console.log(line);
if (!selectedApps.length) {
console.error(`Every app is disabled in ${HUB_CONFIG_FILE}. Enable at least one.`);
process.exit(1);
}
if (!ENABLED_APPS.length) {
const ids = selectedApps.map((a) => a.id).join(', ');
console.error(`No enabled app could load (${ids}). The reasons are logged above.`);
process.exit(1);
}
const SURFACES = {
hub: readSurface(__dirname),
...Object.fromEntries(ENABLED_APPS.map((a) => [a.id, readSurface(a.root)])),
};
const MODS_OFF = process.argv.includes('--no-mods') || hubConfig.modsEnabled === false;
if (MODS_OFF && hubConfig.mods?.length) console.log('mods are off (--no-mods or modsEnabled: false): no mod loads');
const MODS = resolveMods(hubConfig, path.dirname(HUB_CONFIG_FILE), {
warn: console.log,
surfaces: SURFACES,
off: MODS_OFF,
});
for (const m of MODS) console.log(`mod ${m.id} changes ${Object.keys(m.targets).join(', ')}`);
const ACTIONS = actionTable(ENABLED_APPS);
let { keys: userKeyMap, lines: keyLines } = userKeys(hubConfig.keys, ENABLED_APPS);
for (const line of keyLines) console.log(`${HUB_CONFIG_FILE}: ${line}`);
// The first enabled app in tab order that declares the capability in its manifest.
const provider = (cap) => ENABLED_APPS.find((a) => a.provides[cap]);
const PROJECTS_APP = provider('projects');
const TERMINAL_APP = provider('terminal');
// Every keystroke into cck's terminal passes through the upgrade proxy below. Windows only, for the
// reasons in cck/lib/priority.js; the children spawned after this still start at normal.
if (process.platform === 'win32' && process.env.CCK_PRIORITY_BOOST !== '0') {
try {
if (os.getPriority() > os.constants.priority.PRIORITY_ABOVE_NORMAL)
os.setPriority(os.constants.priority.PRIORITY_ABOVE_NORMAL);
} catch {
/* keep the default priority */
}
}
// Created before spawnApp so the same host/allowed-hosts decision reaches the
// children. Without that propagation, `--host 0.0.0.0` would expose the hub shell
// while every iframe 403'd on its own Host check.
const net = createNetGuard({ appName: 'Claude Code Hub' });
// cck's embedded terminal, on by default under the hub (standalone cck keeps it opt-in).
// `"terminal": {"enabled": false}` or --disable-terminal turns it off. One token per hub launch,
// shared by every pool: the hub puts it in the kanban iframe's URL fragment and cck checks it on
// the WebSocket. cck applies the rest of its policy (exposure refusal, Origin, session cap) itself.
const TERMINAL = {
...(hubConfig.terminal || {}),
enabled: !!TERMINAL_APP && !process.argv.includes('--disable-terminal') && hubConfig.terminal?.enabled !== false,
};
const TERMINAL_TOKEN = TERMINAL.enabled ? crypto.randomBytes(32).toString('hex') : null;
// Loopback is not a user boundary: any local account can reach the hub port, and /api/config carries
// the terminal token. Persisted, unlike the terminal token, so an installed PWA's cookie outlives a
// hub restart.
const HUB_TOKEN_FILE = path.join(HUB_DIR, 'token');
const TOKEN_COOKIE = 'hub_token';
const TOKEN_COOKIE_RE = /(?:^|;\s*)hub_token=([^;]*)/;
const TOKEN_COOKIE_MAX_AGE_MS = 400 * 24 * 60 * 60 * 1000;
const LOCKED_PAGE = path.join(__dirname, 'public', 'locked.html');
const HUB_SDK_SERVER = path.join(__dirname, 'packages', 'claude-hub-sdk', 'src', 'server.js');
function loadHubToken() {
try {
const saved = fs.readFileSync(HUB_TOKEN_FILE, 'utf8').trim();
if (/^[0-9a-f]{64}$/.test(saved)) return saved;
} catch {}
const token = crypto.randomBytes(32).toString('hex');
fs.mkdirSync(HUB_DIR, { recursive: true, mode: 0o700 });
fs.writeFileSync(HUB_TOKEN_FILE, `${token}\n`, { mode: 0o600 });
return token;
}
const HUB_TOKEN = loadHubToken();
const HUB_TOKEN_BUF = Buffer.from(HUB_TOKEN);
function tokenMatches(candidate) {
if (typeof candidate !== 'string' || candidate.length !== HUB_TOKEN.length) return false;
return crypto.timingSafeEqual(Buffer.from(candidate), HUB_TOKEN_BUF);
}
// Scripts, styles, icons and the manifest stay public: they hold no secrets, and Chrome fetches the
// manifest without cookies, so gating it would break PWA install.
function tokenGuard(req, res, next) {
const isApi = req.path.startsWith('/api/');
if (!isApi && req.path !== '/' && req.path !== '/index.html') return next();
if (tokenMatches(req.query.token)) {
res.cookie(TOKEN_COOKIE, HUB_TOKEN, { httpOnly: true, sameSite: 'strict', maxAge: TOKEN_COOKIE_MAX_AGE_MS });
if (isApi) return next();
const url = new URL(req.originalUrl, 'http://hub');
url.searchParams.delete('token');
return res.redirect(302, url.pathname + url.search);
}
if (tokenMatches(TOKEN_COOKIE_RE.exec(req.headers.cookie || '')?.[1])) return next();
res.setHeader('Cache-Control', 'no-store');
if (isApi) return res.status(401).json({ error: 'hub token required' });
res.status(401).sendFile(LOCKED_PAGE, { cacheControl: false });
}
function childEnv(pool, name) {
const env = {
...process.env,
PORT: '0',
CLAUDE_CONFIG_DIR: pool.dir,
CLAUDE_HUB: '1',
HUB_URL: `http://localhost:${hubPort}`,
CLAUDE_HUB_DIR: HUB_DIR,
HOST: net.BIND_HOST,
ALLOWED_HOSTS: net.ALLOWED_HOSTS,
HUB_SDK_SERVER,
};
// The app's own process serves its mod files (the SDK's mount), so they load from the app's origin.
const mods = appModEnv(MODS, name);
if (mods) env.HUB_MODS = mods;
else delete env.HUB_MODS;
// A setting the app's server needs before any page connects, such as cck's terminal host for
// the terminals it restores at start. A change later reaches the app through its pages.
const settings = appValues.get(name);
if (settings) env.HUB_APP_SETTINGS = JSON.stringify(settings);
else delete env.HUB_APP_SETTINGS;
if (TERMINAL.enabled && name === TERMINAL_APP.id) {
env.CCK_TERMINAL = JSON.stringify(TERMINAL);
env.CCK_TERMINAL_TOKEN = TERMINAL_TOKEN;
}
return env;
}
function spawnApp(pool, name, cmd, args) {
const child = spawn(cmd, args, {
cwd: __dirname,
env: childEnv(pool, name),
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
windowsHide: true,
});
let stdoutBuf = '';
let markReady;
child.ready = new Promise((resolve) => {
markReady = resolve;
});
child.stdout.on('data', (d) => {
stdoutBuf += d.toString();
let nl;
while ((nl = stdoutBuf.indexOf('\n')) !== -1) {
const line = stdoutBuf.slice(0, nl + 1);
stdoutBuf = stdoutBuf.slice(nl + 1);
process.stdout.write(`[${name}] ${line}`);
const match = line.match(/running at http:\/\/localhost:(\d+)/i);
if (match) {
pool.ports[name] = parseInt(match[1], 10);
markReady();
}
}
});
child.stderr.on('data', (d) => process.stderr.write(`[${name}] ${d}`));
child.on('exit', (code) => {
console.log(`[${name}] exited (code ${code})`);
// The port dies with the child and the OS may hand it to a stranger, so stop dialing it. A child
// that restartApp replaced can exit after its successor printed a port.
if (pool.children.get(name) === child) delete pool.ports[name];
markReady();
if (pool.retired || pool.children.get(name) !== child) return;
// Nothing else would ever bring this app back: a pool is only rebuilt when its dir is
// re-activated.
const recent = (pool.restarts[name] || []).filter((t) => Date.now() - t < RESTART_WINDOW_MS);
if (recent.length >= MAX_RESTARTS) {
console.log(`[${name}] gave up after ${MAX_RESTARTS} restarts in ${RESTART_WINDOW_MS / 1000}s`);
child.gaveUp = true;
return;
}
recent.push(Date.now());
pool.restarts[name] = recent;
setTimeout(() => {
if (pool.retired) return;
console.log(`[${name}] restarting (${recent.length}/${MAX_RESTARTS})`);
spawnApp(pool, name, cmd, args);
}, RESTART_DELAY_MS).unref();
});
pool.children.set(name, child);
return child;
}
// Asked for by the user, so it does not count toward MAX_RESTARTS and it brings back an app that gave up.
async function restartApp(pool, app) {
const { id } = app;
pool.restarts[id] = [];
pool.stopped.delete(id);
pool.deferred.delete(id);
await killApp(pool, id);
if (pool.retired) return false;
const child = spawnOne(pool, app);
await withTimeout(child.ready, 20000);
return !!pool.ports[id];
}
async function stopApp(pool, { id }) {
pool.stopped.add(id);
pool.deferred.delete(id);
await killApp(pool, id);
}
// A deferredStart app that nothing has started yet starts on its first page load: its tab, a pane,
// an action. One the user stopped stays stopped.
function startOnDemand(dir, name) {
const pool = pools.get(dir);
if (!pool?.deferred.delete(name)) return;
console.log(`[${name}] starting on first open`);
pool.stopped.delete(name);
const target = ENABLED_APPS.find((a) => a.id === name);
spawnOne(pool, target);
}
// Out of pool.children before the kill, so the exit handler does not restart it.
async function killApp(pool, id) {
const old = pool.children.get(id);
pool.children.delete(id);
delete pool.ports[id];
if (old) await killChild(old);
}
function killPool(pool) {
pool.retired = true;
return Promise.all([...pool.children.values()].map((child) => killChild(child)));
}
function killAll() {
return Promise.all([...pools.values()].map(killPool));
}
function withTimeout(promise, ms) {
let timer;
const gate = new Promise((resolve) => {
timer = setTimeout(resolve, ms);
});
return Promise.race([promise, gate]).finally(() => clearTimeout(timer));
}
// Returns the live pool for a dir, spawning one when absent and evicting the least recently used
// pool past the pool size. Resolves once every child has printed its port banner (or given up), so
// the caller can hand the client URLs that are actually live.
async function ensurePool(dir) {
let pool = pools.get(dir);
if (pool) {
pools.delete(dir);
pools.set(dir, pool);
return pool.ready;
}
if (pools.size >= currentPoolSize()) await evictPools(dir);
pool = pools.get(dir);
if (pool) return pool.ready;
// Removed while the eviction waited: its DELETE found no pool to drop.
if (!listedDir(dir)) return null;
const stopped = new Set(ENABLED_APPS.filter((a) => a.deferredStart).map((a) => a.id));
pool = { dir, children: new Map(), ports: {}, restarts: {}, stopped, deferred: new Set(stopped), retired: false };
pools.set(dir, pool);
spawnChildren(pool);
const ready = [...pool.children.values()].map((c) => c.ready);
pool.ready = withTimeout(Promise.all(ready), 20000).then(() => pool);
return pool.ready;
}
// Per pool, in order; zeros when the terminal is off.
function liveTerminals(poolList) {
return TERMINAL.enabled ? Promise.all(poolList.map(terminalCount)) : Promise.resolve(poolList.map(() => 0));
}
// Ending live terminals takes force: true. Without it, answers 409 with the count and returns true.
async function refuseLiveTerminals(req, res, poolList, error) {
if (req.body?.force === true) return false;
const terminals = (await liveTerminals(poolList)).reduce((a, b) => a + b, 0);
if (terminals) res.status(409).json({ error, terminals });
return terminals > 0;
}
async function terminalCount(pool) {
const port = pool.ports[TERMINAL_APP.id];
if (!port) return 0;
try {
const r = await fetch(`http://127.0.0.1:${port}${TERMINAL_APP.provides.terminal.liveWork}`, {
signal: AbortSignal.timeout(1500),
});
return r.ok ? (await r.json()).sessions?.length || 0 : 0;
} catch {
return 0;
}
}
// A pool whose cck holds live terminals is pinned: killing it would kill running claude sessions.
// When every candidate is pinned the pool size is exceeded rather than losing work.
// A dir an open window shows, and the global dir that a new window opens on, are pinned the same way.
async function evictPools(keepDir) {
const pinned = shownDirs();
const candidates = [...pools.values()].filter((p) => p.dir !== keepDir && !pinned.has(p.dir));
const counts = await liveTerminals(candidates);
for (const [i, p] of candidates.entries()) if (counts[i]) pinned.add(p.dir);
while (pools.size >= currentPoolSize()) {
const victim = [...pools.keys()].find((d) => d !== keepDir && !pinned.has(d));
if (!victim) {
console.log(`Pool size ${currentPoolSize()} exceeded: every other pool has live terminals or a window`);
return;
}
console.log(`Evicting children for ${victim}`);
dropPool(victim);
}
}
function dropPool(dir) {
const pool = pools.get(dir);
if (!pool) return;
pools.delete(dir);
killPool(pool);
}
// Waits for the children, so a POSIX child that ignores SIGTERM still gets SIGKILL before the hub exits.
let shuttingDown = false;
function shutdown() {
if (shuttingDown) return;
shuttingDown = true;
killAll().then(() => process.exit(0));
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
process.on('SIGHUP', shutdown);
process.on('exit', killAll);
process.on('exit', () => removeRecord(HUB_DIR));
// Git Bash + tmux on Windows doesn't deliver signals — read stdin directly. Only a hub that starts
// watches it: a closed stdin would end a CLI command or the running-hub check halfway.
function watchStdin() {
process.stdin.setEncoding('utf8');
process.stdin.resume();
process.stdin.on('data', (data) => {
const d = data.trim().toLowerCase();
// Ctrl+C (0x03), Ctrl+D (0x04), or typed "q"/"exit"
if (data.includes('\x03') || data.includes('\x04') || d === 'q' || d === 'exit') {
console.log('\nShutting down...');
shutdown();
}
});
process.stdin.on('end', shutdown);
process.stdin.on('close', shutdown);
}
// Raise header size limit to 64KB — localhost cookies from sibling apps can pile up and
// trip Node's default 16KB limit, breaking iframes with HTTP 431.
const HDR_BYTES = 65536;
const NODE_HDR = `--max-http-header-size=${HDR_BYTES}`;
// Children bind ephemeral ports; the public ports belong to the hub's proxies, one set per config
// dir. Browser localStorage is keyed by origin, so a dir's ports have to stay put across restarts
// or the user loses that dir's pins and filters.
function spawnOne(pool, app) {
return spawnApp(pool, app.id, process.execPath, [NODE_HDR, app.entry]);
}
function spawnChildren(pool) {
for (const a of ENABLED_APPS) if (!pool.stopped.has(a.id)) spawnOne(pool, a);
}
const basePorts = Object.fromEntries(ENABLED_APPS.map((a) => [a.id, a.port]));
function rewriteOrigin(origin, publicPort, childPort) {
try {
const u = new URL(origin);
if (Number(u.port) !== publicPort) return origin;
u.port = String(childPort);
return u.origin;
} catch {
return origin;
}
}
// The socket timeout drops idle sockets before the app's server closes them (KEEP_ALIVE_MS), so a
// request never lands on a socket being closed. It does not cut a slow response.
const proxyAgent = new http.Agent({ keepAlive: true, maxSockets: 64, timeout: KEEP_ALIVE_MS - 5000 });
// Two failures look the same from here and both recover on their own: a pooled socket the child
// closed under us, and a child that is restarting. The port is re-read per attempt, so a replay
// reaches the replacement child rather than the ephemeral port that died with the old one.
const RETRYABLE = new Set(['ECONNRESET', 'EPIPE', 'ECONNABORTED', 'ECONNREFUSED', 'ETIMEDOUT']);
const MAX_ATTEMPTS = 3;
const ATTEMPT_DELAY_MS = 250;
// A connect to a freshly-bound loopback port is sometimes black-holed on Windows (the child shows
// as LISTENING and answers nothing) and the OS gives up only after ~20s. This caps the connect
// alone, never the response: a sub-app handler may legitimately take minutes on a cold scan, and
// capping time-to-first-byte would kill that request, replay it, and then kill a healthy child.
const CONNECT_TIMEOUT_MS = 3000;
// A restart costs about a second, so a document load waits it out instead of showing an error.
const NAV_PORT_WAIT_MS = 10000;
const API_PORT_WAIT_MS = 2000;
const delay = (ms) => new Promise((r) => setTimeout(r, ms).unref());
// An iframe document load, as opposed to the sub-app's own fetch/XHR.
function isNavigation(req) {
if (req.headers['sec-fetch-mode']) return req.headers['sec-fetch-mode'] === 'navigate';
return (req.headers.accept || '').includes('text/html');
}
// Races the child's own ready promise rather than polling it, so a restarted app starts serving the
// moment it prints its port instead of on the next tick.
async function waitForPort(dir, name, deadline) {
for (;;) {
const pool = pools.get(dir);
const port = pool?.ports[name];
if (port) return port;
if (pool?.children.get(name)?.gaveUp || pool?.stopped.has(name)) return null;
// A listed dir with no pool yet may be in ensurePool's eviction wait, as on a window's first
// /api/config after a hub restart.
if (!pool && !listedDir(dir)) return null;
const remaining = deadline - Date.now();
if (remaining <= 0) return null;
await Promise.race([pool?.children.get(name)?.ready, delay(Math.min(remaining, 250))]);
}
}
function noPortReason(dir, name) {
const pool = pools.get(dir);
if (!pool) {
return {
headline: 'is not running for this config dir',
detail: 'Switch to this config dir in the hub',
final: true,
};
}
if (pool.stopped.has(name)) {
return { headline: 'is stopped', detail: `Start ${name} from the app launcher`, final: true };
}
const child = pool.children.get(name);
if (child?.gaveUp) {
const detail = `${name} exited after ${MAX_RESTARTS} restarts in ${RESTART_WINDOW_MS / 1000}s. The hub stopped restarting it`;
return { headline: 'stopped', detail, final: true };
}
return { headline: 'is starting', detail: `${name} is starting` };
}
const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
// A document load that fails gets a page that reloads itself — the reload the user would do by
// hand. The cap is small because the server already waited NAV_PORT_WAIT_MS before serving this,
// and each reload re-spends that wait. sessionStorage throws when site data is blocked, and a page
// whose only job is to reload must still reload there.
const RETRY_SCRIPT = `<script>
let n = 0;
const k = 'hub-retry:' + location.pathname;
try { n = +(sessionStorage.getItem(k) || 0); sessionStorage.setItem(k, n + 1); } catch {}
if (n < 3) setTimeout(() => location.reload(), 1000);
else { try { sessionStorage.removeItem(k); } catch {} document.getElementById('m').textContent = 'not responding'; }
</script>`;
// A final page (an app stopped by the user or given up on) does not reload: only the user brings that app back.
function retryPage(name, { headline, detail, final }) {
return `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(name)}</title>
<style>:root{color-scheme:light dark}body{font:14px system-ui,sans-serif;margin:0;display:grid;place-items:center;height:100vh}
div{text-align:center;opacity:.7}code{font-size:12px;opacity:.6}</style>
</head><body><div><p id="m">${escapeHtml(name)} ${escapeHtml(headline)}${final ? '' : '…'}</p><p><code>${escapeHtml(detail)}</code></p></div>
${final ? '' : RETRY_SCRIPT}</body></html>`;
}
function sendUnavailable(req, res, name, status, reason) {
if (res.destroyed || res.headersSent) return;
const { detail } = reason;
if (isNavigation(req)) {
res.writeHead(status, { 'Retry-After': '1', 'Content-Type': 'text/html; charset=utf-8' });
res.end(retryPage(name, reason));
return;
}
// The sub-app's own callers hand the body to .json(): plain text surfaces as a SyntaxError
// instead of the reason.
res.writeHead(status, { 'Retry-After': '1', 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: detail }));
}
// The child on childPort, or null when it has been replaced since the connect was tried.
function currentChild(dir, name, childPort) {
const pool = pools.get(dir);
return pool?.ports[name] === childPort ? pool.children.get(name) : null;
}
// A busy event loop (cck's cache warmup) must not read as a dead app.
const PING_TIMEOUT_MS = 3000;
// A drop burst fails many requests at once; they share one ping per child.
const pings = new WeakMap();
function pingChild(dir, name, childPort, err) {
const child = currentChild(dir, name, childPort);
if (!child) return Promise.resolve(false);
if (!pings.has(child)) {
const alive = ping(child, PING_TIMEOUT_MS).then((ok) => {
pings.delete(child);
if (ok) console.warn(`[${name}] answers over IPC at 127.0.0.1:${childPort} (${err.code}) - keeping it`);
return ok;
});
pings.set(child, alive);
}
return pings.get(child);
}
// A drop burst fails dozens of connects that the next attempt fixes, so retries are counted and
// logged as one line per app every RETRY_LOG_MS. The IPC check, a replace and a failure log at once.
const RETRY_LOG_MS = 5 * 60_000;
const retryCounts = new Map();
function countRetry(name, code) {
const key = `${name} ${code}`;
const entry = retryCounts.get(key) || { name, code, n: 0 };
entry.n++;
retryCounts.set(key, entry);
}
setInterval(() => {
for (const { name, code, n } of retryCounts.values()) {
console.log(`[${name}] ${n} connects failed (${code}) and were retried in the last ${RETRY_LOG_MS / 60_000} min`);
}
retryCounts.clear();
}, RETRY_LOG_MS).unref();
const ALIVE_WAIT_MS = 30000;
const MAX_BACKOFF_MS = 2000;
// Returns {wait} before the next connect attempt, or {headline, detail} to give up with. A pong
// moves budget.deadline to ALIVE_WAIT_MS from now: the child runs, so the request waits out the drop.
async function afterConnectFailure(dir, name, childPort, err, attempt, budget) {
const next = await nextAttempt(dir, name, childPort, err, attempt, budget);
if (next.wait) countRetry(name, err.code);
return next;
}
async function nextAttempt(dir, name, childPort, err, attempt, budget) {
if (attempt < MAX_ATTEMPTS) return { wait: ATTEMPT_DELAY_MS };
if (attempt === MAX_ATTEMPTS) {
if (!(await pingChild(dir, name, childPort, err))) {
replaceChild(dir, name, childPort, err);
return { headline: 'is restarting', detail: `${name} did not answer over TCP (${err.code}) or IPC` };
}
budget.deadline = Math.max(budget.deadline, Date.now() + ALIVE_WAIT_MS);
}
const wait = Math.min(ATTEMPT_DELAY_MS * 2 ** (attempt - MAX_ATTEMPTS + 1), MAX_BACKOFF_MS);
if (Date.now() + wait < budget.deadline) return { wait };
// Its listener is gone or stuck while the process lives on. A new process gets a new port.
if (currentChild(dir, name, childPort)) {
console.warn(`[${name}] answers over IPC, but connects to 127.0.0.1:${childPort} kept failing (${err.code})`);
replaceChild(dir, name, childPort, err);
}
return {
headline: 'is restarting',
detail: `${name} answers over IPC, but connects to it kept failing (${err.code}) for ${ALIVE_WAIT_MS / 1000}s`,
};
}
// A pooled socket the child closed under us is normal and recovers on the next attempt. A port that
// never completes a connect does not, so the child is replaced and the respawn gives it a new one.
function replaceChild(dir, name, childPort, err) {
const child = currentChild(dir, name, childPort);
if (!child) return;
console.log(`[${name}] unreachable at 127.0.0.1:${childPort} (${err.code}) - replacing it`);
delete pools.get(dir).ports[name];
killChild(child);
}
const connectTimeoutError = (name, childPort) =>
Object.assign(new Error(`no connect to ${name} at 127.0.0.1:${childPort}`), { code: 'ETIMEDOUT' });
// Fires only while the socket is still connecting, so a slow handler is never interrupted.
function capConnect(upstream, name, childPort) {
upstream.on('socket', (socket) => {
if (!socket.connecting) return;
const timer = setTimeout(() => upstream.destroy(connectTimeoutError(name, childPort)), CONNECT_TIMEOUT_MS);
const clear = () => clearTimeout(timer);
socket.once('connect', clear);
upstream.once('close', clear);
});
}
// Resolves null once the response is committed (or the client is gone), or the error when nothing
// has been written yet and the caller may still retry.
const MAX_REPLAY_BODY = 1024 * 1024;
// Resolves the whole body when it is small enough to keep for a retry, else null (the body then
// streams once). A chunked body has no length up front, so it streams too.
function readReplayBody(req) {
const te = req.headers['transfer-encoding'];
const cl = req.headers['content-length'];
if (te) return Promise.resolve(null);
if (cl === undefined) return Promise.resolve(Buffer.alloc(0));
const len = Number(cl);
if (!Number.isSafeInteger(len) || len > MAX_REPLAY_BODY) return Promise.resolve(null);
return new Promise((resolve) => {
const chunks = [];
req.on('data', (c) => chunks.push(c));
req.once('end', () => resolve(Buffer.concat(chunks)));
req.once('error', () => resolve(undefined));
req.once('close', () => {
if (!req.complete) resolve(undefined);
});
});
}
function forward(name, req, res, childPort, headers, body, onUpstream) {
return new Promise((resolve) => {
const upstream = http.request(
{ host: '127.0.0.1', port: childPort, method: req.method, path: req.url, headers, agent: proxyAgent },
(u) => {
res.writeHead(u.statusCode, u.headers);
u.pipe(res);
resolve(null);
},
);
onUpstream(upstream);
capConnect(upstream, name, childPort);
upstream.on('error', (err) => {
if (res.headersSent) {
res.end();
resolve(null);
return;
}
resolve(err);
});
if (body) upstream.end(body.length ? body : undefined);
else req.pipe(upstream);
});
}
// RFC 9110 §7.6.1. The client's "Connection: close" would otherwise close the pooled socket to the
// app too. Transfer-Encoding stays: it frames the body that is piped on.
function stripHopByHop(headers) {
for (const h of (headers.connection || '').split(',')) delete headers[h.trim().toLowerCase()];
for (const h of ['connection', 'keep-alive', 'proxy-connection', 'te', 'trailer', 'upgrade']) delete headers[h];
}
// Host is forwarded untouched so the child's hostGuard still sees what the browser sent. Origin is
// the one header the child cannot judge on its own: its guard compares the port to its own
// ephemeral one, so the public-port spelling is mapped to the child's; anything else passes
// through as-is and the child rejects it. Cookies on localhost are shared across ports, so the
// browser sends the hub's own token cookie to every app; it never reaches a child.
function proxyHandler(name, set) {
const { dir } = set;
return async (req, res) => {
const headers = { ...req.headers };
const cookie = stripCookie(headers.cookie, TOKEN_COOKIE);
if (cookie) headers.cookie = cookie;
else delete headers.cookie;
stripHopByHop(headers);
// req is consumed by the first attempt, so a request is re-sent only from its kept body. Waiting
// for a port is not a replay — nothing has been sent yet — so every request gets the same wait.
const body = await readReplayBody(req);
if (body === undefined) return;
// One deadline for the whole request, not one per attempt: a retry must not re-spend the wait.
const budget = { deadline: Date.now() + (isNavigation(req) ? NAV_PORT_WAIT_MS : API_PORT_WAIT_MS) };
if (isNavigation(req)) startOnDemand(dir, name);
// One listener for the request, however many attempts it takes.
let current = null;
res.once('close', () => current?.destroy());
for (let attempt = 1; !res.destroyed; attempt++) {
const childPort = await waitForPort(dir, name, budget.deadline);
if (!childPort) {
sendUnavailable(req, res, name, 503, noPortReason(dir, name));
return;
}
if (req.headers.origin) {
headers.origin = rewriteOrigin(req.headers.origin, set.ports[name], childPort);
}
const err = await forward(name, req, res, childPort, headers, body, (u) => {
current = u;
});
if (!err) return;
if (body === null || !RETRYABLE.has(err.code)) {
sendUnavailable(req, res, name, 502, { headline: 'did not respond', detail: err.message });
return;
}
const next = await afterConnectFailure(dir, name, childPort, err, attempt, budget);
if (!next.wait) {
sendUnavailable(req, res, name, 503, next);
return;
}
await delay(next.wait);
}
};
}
// WebSocket upgrades (cck's terminal) are tunnelled as raw bytes for every app. Host and Origin get
// the same treatment as proxyHandler; the child runs its own upgrade checks, and a child with no
// upgrade listener closes the socket.
function proxyUpgrade(name, set) {
const { dir } = set;
return async (req, socket, head) => {
socket.on('error', () => socket.destroy());
const childPort = await waitForPort(dir, name, Date.now() + API_PORT_WAIT_MS);
if (!childPort || socket.destroyed) {
socket.destroy();
return;
}
const lines = [`${req.method} ${req.url} HTTP/${req.httpVersion}`];
for (let i = 0; i < req.rawHeaders.length; i += 2) {
const header = req.rawHeaders[i].toLowerCase();
let value = req.rawHeaders[i + 1];
if (header === 'origin') value = rewriteOrigin(value, set.ports[name], childPort);
if (header === 'cookie' && !(value = stripCookie(value, TOKEN_COOKIE))) continue;
lines.push(`${req.rawHeaders[i]}: ${value}`);
}
const budget = { deadline: Date.now() + NAV_PORT_WAIT_MS };
tunnel(dir, name, childPort, `${lines.join('\r\n')}\r\n\r\n`, head, socket, 1, budget);
};
}
// A connect that never opened follows the same retry rule as proxyHandler.
function tunnel(dir, name, childPort, request, head, socket, attempt, budget) {
let connected = false;
const upstream = tcp.connect(childPort, '127.0.0.1', () => {
connected = true;
clearTimeout(connectTimer);
upstream.write(request);
if (head?.length) upstream.write(head);
upstream.pipe(socket);
socket.pipe(upstream);
});
const connectTimer = setTimeout(() => upstream.destroy(connectTimeoutError(name, childPort)), CONNECT_TIMEOUT_MS);
const onSocketClose = () => upstream.destroy();
socket.on('close', onSocketClose);
upstream.on('error', async (err) => {
if (connected || socket.destroyed) {
socket.destroy();
return;
}
clearTimeout(connectTimer);
socket.off('close', onSocketClose);
upstream.removeAllListeners('close');
const next = await afterConnectFailure(dir, name, childPort, err, attempt, budget);
if (!next.wait || socket.destroyed) {
socket.destroy();
return;
}
await delay(next.wait);
if (socket.destroyed) return;
tunnel(dir, name, childPort, request, head, socket, attempt + 1, budget);
});
upstream.on('close', () => socket.destroy());
}
// `servers` collects every server bound, the random-port fallback too, so a caller can close them.
// A proxy passes originPort: false, so the hub's Origin check keeps the hub port when a proxy binds
// after it.
function listenWithFallback(handler, port, onReady, label, { onUpgrade, originPort, servers = [] } = {}) {
const opts = { maxHeaderSize: HDR_BYTES, onUpgrade, originPort };
const server = net.listenLoopback(handler, port, onReady, opts);
servers.push(server);
server.on('error', (err) => {