-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlauncher.js
More file actions
1066 lines (978 loc) · 37 KB
/
launcher.js
File metadata and controls
1066 lines (978 loc) · 37 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
// ========================================
// BLUM LAUNCHER — Local Control Panel
// 17 Feb 2026
//
// One-click management of the Blum system.
// Starts/stops room server + home processes.
// Serves a web UI for status, controls, logs.
//
// Usage: node launcher.js [port]
// Default port: 3100
// ========================================
const http = require('http');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const NODE = '/opt/homebrew/bin/node';
const LAUNCHER_PORT = parseInt(process.argv[2] || '3100');
// ── Paths ──────────────────────────────
const BLUM_DIR = __dirname;
const CODE_DIR = path.join(BLUM_DIR, 'read-the-architecture-spec-first', 'i-have-read-the-spec');
const ROOM_SERVER_JS = path.join(CODE_DIR, 'shared-room-server-that-hosts-rooms-and-dispatches-transcripts-15feb2026', 'blum-room-server-15feb2026.js');
const HOME_JS = path.join(CODE_DIR, 'home-agent-os-15feb2026', 'home.js');
const CREATE_HOME_JS = path.join(CODE_DIR, 'home-agent-os-15feb2026', 'create-home.js');
const HOMES_DIR = require('path').join(require('os').homedir(), 'blum', 'homes');
// ── State ──────────────────────────────
const ROOM_SERVER_PORT = 3141;
let roomServerProc = null;
let roomServerLog = []; // ring buffer, last 200 lines
// { name: { proc, port, homeDir, config, log[] } }
const homes = {};
const MAX_LOG_LINES = 200;
const PROBE_PORTS = Array.from({ length: 31 }, (_, i) => 4100 + i);
function pushLog(buf, line) {
buf.push(line);
if (buf.length > MAX_LOG_LINES) buf.shift();
}
function extractTs(line) {
const m = line.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)/);
return m ? m[1] : null;
}
function makeBoardroomDiagnosis(kind, label, detail, severity = 'info', ts = null) {
return { kind, label, detail, severity, ts };
}
function makeHealthDiagnosis(kind, label, detail, severity = 'info', ts = null) {
return { kind, label, detail, severity, ts };
}
function titleCaseError(code) {
return String(code || '')
.replace(/[_:]+/g, ' ')
.trim()
.replace(/\b\w/g, c => c.toUpperCase());
}
function diagnoseServiceability(liveStatus, running) {
const health = liveStatus?.health;
if (!running) {
return makeHealthDiagnosis('offline', 'Offline', 'No live home endpoint is answering right now.', 'error', null);
}
if (!health) {
return makeHealthDiagnosis('unknown', 'Unknown', 'Live home status does not expose structured health yet.', 'warn', null);
}
if (health.lastErrorType) {
return makeHealthDiagnosis(
health.lastErrorType,
titleCaseError(health.lastErrorType),
'Most recent cycle ended with an explicit runtime or provider failure.',
'error',
health.lastErrorAt || null
);
}
if (health.lastFailureNoticeAt) {
return makeHealthDiagnosis(
'failure_notice',
'Failure Notice Sent',
'The home is up, but its last visible result was a system failure notice rather than a normal reply.',
'warn',
health.lastFailureNoticeAt
);
}
if (health.lastSuccessfulRoomDeliveryAt || health.lastSuccessfulInferenceAt) {
return makeHealthDiagnosis(
'healthy',
'Serviceable',
'The home has recent successful inference/delivery activity.',
'ok',
health.lastSuccessfulRoomDeliveryAt || health.lastSuccessfulInferenceAt
);
}
return makeHealthDiagnosis('idle', 'Idle', 'The home is reachable, but there is no recent success/failure signal yet.', 'warn', null);
}
function diagnoseRoomState(roomName, agentName, roomHealthEntry) {
if (!roomHealthEntry) {
return makeHealthDiagnosis('no_room_signal', 'No Room Signal', `No recent ${roomName} dispatch or delivery signal recorded.`, 'warn', null);
}
if (roomHealthEntry.lastDispatchErrorType) {
return makeHealthDiagnosis(
roomHealthEntry.lastDispatchErrorType,
titleCaseError(roomHealthEntry.lastDispatchErrorType),
`Latest ${roomName} dispatch for this agent failed before or during delivery to the home.`,
'error',
roomHealthEntry.lastDispatchErrorAt || roomHealthEntry.lastDispatchReceivedAt || null
);
}
if (roomHealthEntry.lastSuppressedReason && (!roomHealthEntry.lastVisibleMessageAt || Date.parse(roomHealthEntry.lastSuppressedAt || 0) >= Date.parse(roomHealthEntry.lastVisibleMessageAt || 0))) {
return makeHealthDiagnosis(
roomHealthEntry.lastSuppressedReason,
titleCaseError(roomHealthEntry.lastSuppressedReason),
`Latest ${roomName} message was logged but forwarding was intentionally suppressed.`,
'warn',
roomHealthEntry.lastSuppressedAt || null
);
}
if (roomHealthEntry.lastVisibleMessageAt) {
return makeHealthDiagnosis(
'visible_reply',
'Visible Reply',
`A recent message from this agent is visible in ${roomName}.`,
'ok',
roomHealthEntry.lastVisibleMessageAt
);
}
if (roomHealthEntry.lastDispatchReceivedAt) {
return makeHealthDiagnosis(
'awaiting_reply',
'Awaiting Reply',
`A ${roomName} dispatch reached this agent, but no room-visible reply is recorded yet.`,
'warn',
roomHealthEntry.lastDispatchReceivedAt
);
}
return makeHealthDiagnosis('no_room_signal', 'No Room Signal', `No recent ${roomName} signal recorded.`, 'warn', null);
}
function analyseBoardroomStatus(log = [], running = false) {
const lines = [...log].reverse();
for (const line of lines) {
const ts = extractTs(line);
if (line.includes('[exit]')) {
if (log.some(l => l.includes('EADDRINUSE'))) {
return makeBoardroomDiagnosis('startup_port_collision', 'Port collision', 'Home failed to stay up because its configured port is already in use.', 'error', ts);
}
return makeBoardroomDiagnosis('process_stopped', 'Process stopped', 'Home process exited, so it cannot answer boardroom dispatches.', 'error', ts);
}
if (line.includes('process:error room=boardroom error=')) {
if (line.includes('insufficient_quota') || line.includes('exceeded your current quota')) {
return makeBoardroomDiagnosis('provider_quota_exhausted', 'Provider quota exhausted', 'The home process is up, but the model account has no remaining credits/quota, so replies cannot be generated.', 'error', ts);
}
if (line.includes('openrouter 429')) {
return makeBoardroomDiagnosis('provider_rate_limited', 'Provider rate limit', 'Model provider is rejecting boardroom calls with 429 rate limits.', 'error', ts);
}
if (line.includes('openai 429') || line.includes('Anthropic 529') || line.includes('Overloaded')) {
return makeBoardroomDiagnosis('provider_overloaded', 'Provider overloaded', 'Model provider is overloaded or rate limiting requests.', 'error', ts);
}
if (line.includes('openai 400') && line.includes('context length')) {
return makeBoardroomDiagnosis('context_overflow', 'Context overflow', 'Boardroom prompt is too large for this model/context window.', 'error', ts);
}
if (line.includes('fetch failed')) {
return makeBoardroomDiagnosis('upstream_fetch_failed', 'Upstream fetch failed', 'The home hit a network or upstream fetch failure while processing boardroom.', 'warn', ts);
}
return makeBoardroomDiagnosis('process_error', 'Processing error', line.split('error=')[1] || 'Boardroom processing failed.', 'error', ts);
}
if (line.includes('process:output_validator hard_fallback sent to yeshua@boardroom')) {
return makeBoardroomDiagnosis('hard_fallback_sent', 'Hard fallback sent', 'The home failed to produce a proper reply and sent a system failure notice instead.', 'warn', ts);
}
if (line.includes('process:output_validator no_output=true') && line.includes('senderAddress=yeshua@boardroom')) {
return makeBoardroomDiagnosis('output_protocol_failed', 'Output formatting failed', 'The model replied, but not in a deliverable format, so correction/fallback was required.', 'warn', ts);
}
if (line.includes('process:tool_loop_max_iterations')) {
return makeBoardroomDiagnosis('tool_loop_exhausted', 'Tool loop exhausted', 'The home hit its iteration budget before producing a reply.', 'warn', ts);
}
if (line.includes('process:start room=boardroom')) {
break;
}
}
if (!running) {
return makeBoardroomDiagnosis('offline', 'Offline', 'Home is not running, so it cannot answer boardroom dispatches.', 'error', null);
}
return makeBoardroomDiagnosis('healthy', 'No recent boardroom failure', 'No recent boardroom-specific failure signature found in launcher logs.', 'ok', null);
}
async function probeHomes() {
const found = {};
await Promise.all(PROBE_PORTS.map(async (port) => {
try {
const res = await fetch(`http://localhost:${port}/status`);
if (!res.ok) return;
const data = await res.json();
if (data?.name) found[data.name] = { port, liveStatus: data };
} catch {}
}));
return found;
}
function hasLiveProc(info) {
return !!(info && info.proc && info.proc.exitCode === null && !info.proc.killed);
}
async function probeRoomServer() {
try {
const res = await fetch(`http://localhost:${ROOM_SERVER_PORT}/api/state`);
return res.ok;
} catch {
return false;
}
}
// ── Process Management ─────────────────
function startRoomServer() {
if (roomServerProc) return { ok: false, error: 'Already running' };
const proc = spawn(NODE, [ROOM_SERVER_JS], {
cwd: path.dirname(ROOM_SERVER_JS),
env: { ...process.env, PATH: '/opt/homebrew/bin:' + (process.env.PATH || '') },
stdio: ['ignore', 'pipe', 'pipe'],
});
roomServerLog = [];
proc.stdout.on('data', d => d.toString().split('\n').filter(Boolean).forEach(l => pushLog(roomServerLog, `[out] ${l}`)));
proc.stderr.on('data', d => d.toString().split('\n').filter(Boolean).forEach(l => pushLog(roomServerLog, `[err] ${l}`)));
proc.on('exit', (code, signal) => {
pushLog(roomServerLog, `[exit] code=${code} signal=${signal}`);
roomServerProc = null;
});
roomServerProc = proc;
return { ok: true, pid: proc.pid };
}
function stopRoomServer() {
if (!roomServerProc) return { ok: false, error: 'Not running' };
roomServerProc.kill('SIGTERM');
roomServerProc = null;
return { ok: true };
}
function discoverHomes() {
// Scan HOMES_DIR for existing home directories
if (!fs.existsSync(HOMES_DIR)) return [];
const found = [];
for (const entry of fs.readdirSync(HOMES_DIR, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const configPath = path.join(HOMES_DIR, entry.name, 'config.json');
if (fs.existsSync(configPath)) {
try {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
found.push({
name: config.name || entry.name,
homeDir: path.join(HOMES_DIR, entry.name),
model: config.model || 'unknown',
hasApiKey: !!(config.apiKey || config.apiKeyEnv || fs.existsSync(path.join(HOMES_DIR, entry.name, 'config.local.json'))),
});
} catch {}
}
}
return found;
}
function startHome(name, port) {
if (homes[name]?.proc) return { ok: false, error: `${name} already running` };
const homeDir = path.join(HOMES_DIR, name);
if (!fs.existsSync(path.join(homeDir, 'config.json'))) {
return { ok: false, error: `No config.json in ${homeDir}` };
}
const config = JSON.parse(fs.readFileSync(path.join(homeDir, 'config.json'), 'utf8'));
const proc = spawn(NODE, [HOME_JS, homeDir, String(port)], {
cwd: path.dirname(HOME_JS),
env: { ...process.env, PATH: '/opt/homebrew/bin:' + (process.env.PATH || '') },
stdio: ['ignore', 'pipe', 'pipe'],
});
const log = [];
proc.stdout.on('data', d => d.toString().split('\n').filter(Boolean).forEach(l => pushLog(log, `[out] ${l}`)));
proc.stderr.on('data', d => d.toString().split('\n').filter(Boolean).forEach(l => pushLog(log, `[err] ${l}`)));
proc.on('exit', (code, signal) => {
pushLog(log, `[exit] code=${code} signal=${signal}`);
if (homes[name]) homes[name].proc = null;
});
homes[name] = { proc, port, homeDir, config, log };
return { ok: true, pid: proc.pid, port };
}
function stopHome(name) {
if (!homes[name]?.proc) return { ok: false, error: `${name} not running` };
homes[name].proc.kill('SIGTERM');
homes[name].proc = null;
return { ok: true };
}
async function registerEndpoints() {
// Tell room server where each running home lives, but only from verified
// live /status identity, not remembered launcher port state.
const results = [];
const probedHomes = await probeHomes();
for (const discovered of discoverHomes()) {
const name = discovered.name;
const info = homes[name];
const live = probedHomes[name];
if (!live) {
try {
const body = JSON.stringify({ name, endpoint: null });
const res = await fetch(`http://localhost:${ROOM_SERVER_PORT}/api/directory/update-endpoint`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
results.push({
name,
ok: false,
cleared: res.ok,
error: 'No live /status match found; stale endpoint cleared',
});
} catch (e) {
results.push({ name, ok: false, error: `No live /status match found; failed to clear stale endpoint: ${e.message}` });
}
continue;
}
try {
if (info) info.port = live.port;
const body = JSON.stringify({ name, endpoint: `http://localhost:${live.port}` });
const res = await fetch(`http://localhost:${ROOM_SERVER_PORT}/api/directory/update-endpoint`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
results.push({ name, ok: res.ok, port: live.port });
} catch (e) {
results.push({ name, ok: false, error: e.message });
}
}
return results;
}
async function getStatus() {
const discovered = discoverHomes();
const homeStatus = {};
const probedHomes = await probeHomes();
const roomServerRunning = roomServerProc ? true : await probeRoomServer();
let roomHealth = {};
if (roomServerRunning) {
try {
const res = await fetch(`http://localhost:${ROOM_SERVER_PORT}/api/room-health`);
if (res.ok) roomHealth = await res.json();
} catch {}
}
for (const h of discovered) {
const launcherInfo = homes[h.name];
const running = hasLiveProc(launcherInfo) || !!probedHomes[h.name];
const port = probedHomes[h.name]?.port || launcherInfo?.port || h.port || null;
const liveStatus = probedHomes[h.name]?.liveStatus || null;
const boardroomHealth = roomHealth.boardroom?.[h.name] || null;
const cochairsHealth = roomHealth.cochairs?.[h.name] || null;
homeStatus[h.name] = {
name: h.name,
model: h.model,
homeDir: h.homeDir,
hasApiKey: h.hasApiKey,
running,
pid: hasLiveProc(launcherInfo) ? launcherInfo.proc.pid : null,
port,
queueDepth: liveStatus?.queueDepth ?? null,
processing: liveStatus?.processing ?? null,
rooms: liveStatus?.rooms ?? null,
health: liveStatus?.health ?? null,
serviceability: diagnoseServiceability(liveStatus, running),
boardroom: analyseBoardroomStatus(launcherInfo?.log || [], running),
boardroomRoomState: diagnoseRoomState('boardroom', h.name, boardroomHealth),
cochairsRoomState: diagnoseRoomState('cochairs', h.name, cochairsHealth),
};
}
return {
roomServer: {
running: roomServerRunning,
pid: roomServerProc?.pid || null,
port: ROOM_SERVER_PORT,
},
homes: homeStatus,
roomHealth,
homesDir: HOMES_DIR,
launcherPort: LAUNCHER_PORT,
};
}
// ── Default port assignment ────────────
function assignPort(name) {
const portMap = { alpha: 4110, beta: 4111, gamma: 4112 };
if (portMap[name]) return portMap[name];
// Read from config.json if available — prevents port collisions on restart
const configPath = path.join(HOMES_DIR, name, 'config.json');
if (fs.existsSync(configPath)) {
try {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
if (config.port) return config.port;
} catch {}
}
// Fall back to auto-assign from 4113+
const usedPorts = new Set(Object.values(homes).map(h => h.port));
let p = 4113;
while (usedPorts.has(p)) p++;
return p;
}
// ── HTTP API + UI ──────────────────────
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${LAUNCHER_PORT}`);
const p = url.pathname;
// ── API routes ──
if (p === '/api/status') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(await getStatus()));
}
if (p === '/api/start-room-server' && req.method === 'POST') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(startRoomServer()));
}
if (p === '/api/stop-room-server' && req.method === 'POST') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(stopRoomServer()));
}
if (p === '/api/start-home' && req.method === 'POST') {
const body = await readBody(req);
const { name, port } = JSON.parse(body);
const actualPort = port || assignPort(name);
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(startHome(name, actualPort)));
}
if (p === '/api/stop-home' && req.method === 'POST') {
const body = await readBody(req);
const { name } = JSON.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(stopHome(name)));
}
if (p === '/api/start-all' && req.method === 'POST') {
const results = {};
// Start room server first
results.roomServer = startRoomServer();
// Wait a beat for room server to bind
await new Promise(r => setTimeout(r, 1000));
// Start all discovered homes
for (const h of discoverHomes()) {
const port = assignPort(h.name);
results[h.name] = startHome(h.name, port);
}
// Wait for homes to bind, then register endpoints
await new Promise(r => setTimeout(r, 1500));
results.endpoints = await registerEndpoints();
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(results));
}
if (p === '/api/stop-all' && req.method === 'POST') {
const results = {};
for (const name of Object.keys(homes)) {
results[name] = stopHome(name);
}
results.roomServer = stopRoomServer();
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(results));
}
if (p === '/api/register-endpoints' && req.method === 'POST') {
const results = await registerEndpoints();
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(results));
}
if (p === '/api/logs') {
const name = url.searchParams.get('name');
let lines;
if (name === 'room-server') {
lines = roomServerLog;
} else if (homes[name]) {
lines = homes[name].log || [];
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Unknown service' }));
}
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ name, lines }));
}
// ── Config API ──
if (p.startsWith('/api/config/') && req.method === 'GET') {
const name = p.slice('/api/config/'.length);
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Invalid name' }));
}
const cfgPath = path.join(HOMES_DIR, name, 'config.json');
if (!fs.existsSync(cfgPath)) {
res.writeHead(404, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Not found' }));
}
const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
// Redact API key value but preserve presence indicator
const safe = { ...cfg };
if (safe.apiKey) safe.apiKey = '***';
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(safe));
}
if (p.startsWith('/api/config/') && req.method === 'POST') {
const name = p.slice('/api/config/'.length);
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Invalid name' }));
}
const cfgPath = path.join(HOMES_DIR, name, 'config.json');
if (!fs.existsSync(cfgPath)) {
res.writeHead(404, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Not found' }));
}
const body = await readBody(req);
let updates;
try { updates = JSON.parse(body); } catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
const existing = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
// Don't let masked placeholder overwrite the real key
if (updates.apiKey === '***') delete updates.apiKey;
const merged = { ...existing, ...updates };
// Preserve immutables
merged.name = existing.name;
merged.uid = existing.uid;
fs.writeFileSync(cfgPath, JSON.stringify(merged, null, 2));
// Restart so changes take effect
stopHome(name);
await new Promise(r => setTimeout(r, 500));
startHome(name, merged.port || existing.port);
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ ok: true, restarted: true, name }));
}
// ── Cron API ──
if (p.startsWith('/api/cron/') && req.method === 'GET') {
const name = p.slice('/api/cron/'.length);
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Invalid name' }));
}
const cronPath = path.join(HOMES_DIR, name, 'cron.json');
if (!fs.existsSync(cronPath)) {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify([]));
}
const jobs = JSON.parse(fs.readFileSync(cronPath, 'utf8'));
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(jobs));
}
if (p.startsWith('/api/cron/') && req.method === 'POST') {
const name = p.slice('/api/cron/'.length);
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Invalid name' }));
}
const cronPath = path.join(HOMES_DIR, name, 'cron.json');
const body = await readBody(req);
let jobs;
try { jobs = JSON.parse(body); } catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
if (!Array.isArray(jobs)) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'Expected array of cron jobs' }));
}
fs.writeFileSync(cronPath, JSON.stringify(jobs, null, 2));
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ ok: true, jobs: jobs.length, name }));
}
// ── Serve UI ──
if (p === '/' || p === '/index.html') {
res.writeHead(200, { 'Content-Type': 'text/html' });
return res.end(DASHBOARD_HTML);
}
res.writeHead(404);
res.end('Not found');
});
function readBody(req) {
return new Promise((resolve) => {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => resolve(body));
});
}
// ── Dashboard HTML ─────────────────────
const DASHBOARD_HTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blum Launcher</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro', system-ui, sans-serif;
background: #0a0a0c;
color: #e0e0e0;
min-height: 100vh;
}
header {
padding: 24px 32px;
border-bottom: 1px solid #1a1a2e;
display: flex;
align-items: center;
justify-content: space-between;
}
header h1 {
font-size: 20px;
font-weight: 600;
color: #fff;
letter-spacing: 0.5px;
}
header h1 span { color: #6366f1; }
.header-actions { display: flex; gap: 10px; }
.btn {
padding: 8px 16px;
border: 1px solid #2a2a3e;
border-radius: 8px;
background: #12121a;
color: #ccc;
font-size: 13px;
cursor: pointer;
transition: all 0.15s;
}
.btn:hover { background: #1a1a2e; color: #fff; }
.btn-start { border-color: #22543d; color: #68d391; }
.btn-start:hover { background: #1a3a2a; }
.btn-stop { border-color: #5a2020; color: #fc8181; }
.btn-stop:hover { background: #3a1a1a; }
.btn-primary { border-color: #4338ca; color: #a5b4fc; background: #1e1b4b; }
.btn-primary:hover { background: #2e2a5b; }
main { padding: 24px 32px; }
/* ── Room Server Card ── */
.section-label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 1.5px;
color: #666;
margin-bottom: 12px;
}
.service-card {
background: #12121a;
border: 1px solid #1a1a2e;
border-radius: 12px;
padding: 20px;
margin-bottom: 24px;
}
.service-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.service-name {
display: flex;
align-items: center;
gap: 10px;
font-size: 15px;
font-weight: 500;
}
.status-dot {
width: 10px; height: 10px;
border-radius: 50%;
background: #4a4a5a;
}
.status-dot.running { background: #48bb78; box-shadow: 0 0 8px rgba(72,187,120,0.4); }
.status-dot.stopped { background: #e53e3e; }
.service-meta {
font-size: 12px;
color: #666;
display: flex;
gap: 16px;
}
.service-meta span { display: flex; align-items: center; gap: 4px; }
/* ── Homes Grid ── */
.homes-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 16px;
margin-bottom: 24px;
}
.home-card {
background: #12121a;
border: 1px solid #1a1a2e;
border-radius: 12px;
padding: 20px;
}
.home-card.boardroom-ok { border-color: #214d35; }
.home-card.boardroom-warn { border-color: #6b5318; }
.home-card.boardroom-error { border-color: #6b1d1d; }
.home-card .model-tag {
font-size: 11px;
padding: 3px 8px;
border-radius: 4px;
background: #1a1a2e;
color: #8b8ba0;
font-family: 'SF Mono', monospace;
}
.model-tag.haiku { color: #68d391; background: #1a2e1a; }
.model-tag.sonnet { color: #63b3ed; background: #1a1a2e; }
.model-tag.opus { color: #d6bcfa; background: #2a1a3e; }
.diag-row {
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid #1a1a2e;
display: grid;
gap: 8px;
}
.diag-stack {
display: grid;
gap: 12px;
}
.diag-block {
display: grid;
gap: 8px;
}
.diag-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.diag-label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 1.2px;
color: #7d8597;
}
.diag-badge {
font-size: 11px;
padding: 4px 8px;
border-radius: 999px;
font-weight: 600;
}
.diag-badge.ok { color: #7ee0a1; background: #183524; }
.diag-badge.warn { color: #f3d17a; background: #3a2c10; }
.diag-badge.error { color: #ff9b9b; background: #431919; }
.diag-detail {
font-size: 12px;
color: #b6bcc9;
line-height: 1.45;
min-height: 34px;
}
.diag-meta {
font-size: 11px;
color: #7d8597;
display: flex;
gap: 12px;
flex-wrap: wrap;
}
/* ── Log Panel ── */
.log-panel {
background: #0d0d12;
border: 1px solid #1a1a2e;
border-radius: 12px;
margin-top: 24px;
overflow: hidden;
}
.log-tabs {
display: flex;
border-bottom: 1px solid #1a1a2e;
padding: 0 12px;
overflow-x: auto;
}
.log-tab {
padding: 10px 16px;
font-size: 12px;
color: #666;
cursor: pointer;
border-bottom: 2px solid transparent;
white-space: nowrap;
}
.log-tab:hover { color: #aaa; }
.log-tab.active { color: #a5b4fc; border-bottom-color: #6366f1; }
.log-content {
height: 280px;
overflow-y: auto;
padding: 12px 16px;
font-family: 'SF Mono', 'Fira Code', monospace;
font-size: 12px;
line-height: 1.6;
color: #8b8ba0;
}
.log-content .log-err { color: #fc8181; }
.log-content .log-exit { color: #fbd38d; }
</style>
</head>
<body>
<header>
<h1><span>blum</span> launcher</h1>
<div class="header-actions">
<button class="btn btn-start" onclick="startAll()">Start All</button>
<button class="btn btn-stop" onclick="stopAll()">Stop All</button>
<button class="btn" onclick="registerEndpoints()">Register Endpoints</button>
</div>
</header>
<main>
<!-- Room Server -->
<div class="section-label">Room Server</div>
<div class="service-card" id="room-server-card">
<div class="service-header">
<div class="service-name">
<div class="status-dot" id="rs-dot"></div>
<span>Room Server</span>
</div>
<div>
<button class="btn btn-start" onclick="startRoomServer()">Start</button>
<button class="btn btn-stop" onclick="stopRoomServer()">Stop</button>
</div>
</div>
<div class="service-meta">
<span>Port: <strong>3141</strong></span>
<span id="rs-pid"></span>
</div>
</div>
<!-- Homes -->
<div class="section-label">Agent Homes</div>
<div class="homes-grid" id="homes-grid"></div>
<!-- Logs -->
<div class="section-label">Logs</div>
<div class="log-panel">
<div class="log-tabs" id="log-tabs"></div>
<div class="log-content" id="log-content"></div>
</div>
</main>
<script>
const API = '';
let currentLogTab = 'room-server';
let autoScroll = true;
function modelClass(model) {
if (!model) return '';
if (model.includes('haiku')) return 'haiku';
if (model.includes('sonnet')) return 'sonnet';
if (model.includes('opus')) return 'opus';
return '';
}
function modelShort(model) {
if (!model) return 'unknown';
// "claude-haiku-4-5" → "haiku 4.5"
const m = model.match(/(haiku|sonnet|opus)[- ]?(\\d+)?[- ]?(\\d+)?/i);
if (m) {
const ver = m[2] && m[3] ? m[2] + '.' + m[3] : (m[2] || '');
return m[1].toLowerCase() + (ver ? ' ' + ver : '');
}
return model.replace('claude-', '');
}
function severityClass(severity) {
return severity === 'error' ? 'error' : (severity === 'warn' ? 'warn' : 'ok');
}
function relativeTs(ts) {
if (!ts) return 'No recent event';
const ms = Date.now() - Date.parse(ts);
if (!Number.isFinite(ms)) return ts;
const mins = Math.round(ms / 60000);
if (mins < 1) return 'just now';
if (mins < 60) return mins + 'm ago';
const hrs = Math.round(mins / 60);
if (hrs < 48) return hrs + 'h ago';
const days = Math.round(hrs / 24);
return days + 'd ago';
}
async function fetchJSON(url, opts) {
const res = await fetch(API + url, opts);
return res.json();
}
async function refresh() {
try {
const status = await fetchJSON('/api/status');
renderRoomServer(status.roomServer);
renderHomes(status.homes);
renderLogTabs(status);
await refreshLog();
} catch (e) {
console.error('Refresh failed:', e);
}
}
function renderRoomServer(rs) {
const dot = document.getElementById('rs-dot');
dot.className = 'status-dot ' + (rs.running ? 'running' : 'stopped');
document.getElementById('rs-pid').textContent = rs.running ? 'PID: ' + rs.pid : 'Stopped';
}
function renderHomes(homesMap) {
const grid = document.getElementById('homes-grid');
const names = Object.keys(homesMap).sort();
grid.innerHTML = names.map(name => {
const h = homesMap[name];
const service = h.serviceability || { label: 'Unknown', detail: 'No serviceability diagnosis available.', severity: 'warn' };
const boardroom = h.boardroomRoomState || h.boardroom || { label: 'Unknown', detail: 'No boardroom diagnosis available.', severity: 'warn' };
const cochairs = h.cochairsRoomState || { label: 'Unknown', detail: 'No cochairs diagnosis available.', severity: 'warn' };
const cardClass = 'home-card boardroom-' + severityClass(service.severity);
return \`
<div class="\${cardClass}">
<div class="service-header">
<div class="service-name">
<div class="status-dot \${h.running ? 'running' : 'stopped'}"></div>
<span>\${h.name}</span>
<span class="model-tag \${modelClass(h.model)}">\${modelShort(h.model)}</span>
</div>
<div>
<button class="btn btn-start" onclick="startHome('\${h.name}')">Start</button>
<button class="btn btn-stop" onclick="stopHome('\${h.name}')">Stop</button>
</div>
</div>
<div class="service-meta">
<span>Port: <strong>\${h.port || '—'}</strong></span>
<span>\${h.running ? 'PID: ' + h.pid : 'Stopped'}</span>
<span>\${h.hasApiKey ? 'Key: yes' : 'Key: none'}</span>
</div>
<div class="diag-row">
<div class="diag-stack">
<div class="diag-block">
<div class="diag-head">
<div class="diag-label">Serviceability</div>
<div class="diag-badge \${severityClass(service.severity)}">\${service.label}</div>
</div>
<div class="diag-detail">\${service.detail}</div>
</div>
<div class="diag-block">
<div class="diag-head">
<div class="diag-label">Boardroom</div>
<div class="diag-badge \${severityClass(boardroom.severity)}">\${boardroom.label}</div>
</div>
<div class="diag-detail">\${boardroom.detail}</div>
</div>
<div class="diag-block">
<div class="diag-head">
<div class="diag-label">Cochairs</div>
<div class="diag-badge \${severityClass(cochairs.severity)}">\${cochairs.label}</div>
</div>
<div class="diag-detail">\${cochairs.detail}</div>
</div>
</div>
<div class="diag-meta">
<span>Queue: \${h.queueDepth == null ? '—' : h.queueDepth}</span>
<span>\${h.processing === true ? 'Processing now' : (h.processing === false ? 'Idle' : 'Processing: —')}</span>
<span>Service: \${relativeTs(service.ts)}</span>
<span>Boardroom: \${relativeTs(boardroom.ts)}</span>
<span>Cochairs: \${relativeTs(cochairs.ts)}</span>
</div>
</div>
</div>\`;