-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
1928 lines (1874 loc) · 107 KB
/
Copy pathserver.js
File metadata and controls
1928 lines (1874 loc) · 107 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
// libuv threadpool headroom (default 4): a few fs ops stuck on a dying fuse
// mount used to starve EVERY async fs/dns op server-wide (real outage — see
// mounts.js hung-mount defense). Must be set before the pool first spins up,
// i.e. before any require that performs async I/O.
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || '32';
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const pty = require('node-pty');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { execFileSync, spawn } = require('child_process');
const compression = require('compression');
const { MessageManager } = require('./src/message-manager');
const { createMessageManager } = require('./src/normalizers');
const { Telemetry } = require('./src/telemetry');
const { SyncStore } = require('./src/sync-store');
const { cwdToProjectDir, SessionMessages, findSessionJsonlPath, dedupWebuiSockets } = require('./src/session-store');
const { CodexSessionMessages } = require('./src/codex-session-store');
const { normalizeCodexSource, CODEX_SESSIONS_DIR } = require('./src/adapters/codex');
const { createAdapterRegistry } = require('./src/adapters');
const { buildClaudeSubscriptionLoginCommand } = require('./src/claude-subscription-login');
const fileRoutes = require('./src/routes/files');
const { SafeFs } = require('./src/safe-fs');
const { router: persistenceRouter, setup: setupPersistence } = require('./src/routes/persistence');
// ── Env sanitation: the server may have been (re)started from INSIDE a Claude
// Code session (e.g. an agent running in a WebUI terminal restarts it). The
// inherited session env then leaks into every CLI this server spawns —
// CLAUDE_CODE_CHILD_SESSION=1 alone puts a spawned claude into child-session
// mode: NO lock file, NO project transcript. Conversations look fine live but
// are silently unpersisted — terminate + resume loses everything (verified on
// CLI 2.1.199 by A/B env test). Strip the whole inherited set at startup so all
// spawn paths (dtach spawn line, wrappers, probes) run top-level.
if (process.env.CLAUDECODE || process.env.CLAUDE_CODE_CHILD_SESSION) {
const stripped = [];
for (const k of Object.keys(process.env)) {
if (k === 'CLAUDECODE' || k === 'CLAUDE_EFFORT' || k.startsWith('CLAUDE_CODE_') || k.startsWith('CLAUDE_WEBUI_')) {
stripped.push(k);
delete process.env[k];
}
}
console.warn(`[env] Server was started from inside a Claude Code session — stripped inherited session env (${stripped.join(', ')}) so spawned CLIs run top-level. Without this, spawned sessions never write transcripts and their conversations are LOST on resume.`);
}
// Optional persistent ops log (env-gated no-op without VIBESPACE_OPSLOG_DIR) —
// installed EARLY so the console tee captures the whole boot narrative.
try { require('./src/opslog').setupOpslog(require('./package.json').version); } catch (e) { console.warn('[opslog] init failed:', e.message); }
// Auto-update: pull latest + rebuild on startup (skip with NO_AUTO_UPDATE=1)
if (!process.env.NO_AUTO_UPDATE) {
try {
const repoDir = __dirname;
// Ensure Homebrew/nvm paths are in PATH for child processes (macOS non-login shells)
const nodeDir = path.dirname(process.execPath);
const envPath = [nodeDir, process.env.PATH].filter(Boolean).join(path.delimiter);
const spawnEnv = { ...process.env, PATH: envPath };
const result = execFileSync('git', ['-C', repoDir, 'pull', '--ff-only'], { encoding: 'utf-8', timeout: 15000, stdio: ['pipe', 'pipe', 'pipe'] }).trim();
if (result && !result.includes('Already up to date')) {
console.log('[auto-update] git pull:', result);
execFileSync('npm', ['install', '--no-audit', '--no-fund'], { cwd: repoDir, encoding: 'utf-8', timeout: 60000, stdio: 'inherit', env: spawnEnv });
execFileSync('npm', ['run', 'build'], { cwd: repoDir, encoding: 'utf-8', timeout: 30000, stdio: 'inherit', env: spawnEnv });
console.log('[auto-update] rebuilt successfully');
}
} catch (e) { console.log('[auto-update] skipped:', e.message?.split('\n')[0]); }
}
const PORT = process.env.PORT || 3456;
const CLAUDE_CMD_RAW = process.env.CLAUDE_CMD || 'claude';
const CODEX_CMD_RAW = process.env.CODEX_CMD || 'codex';
// Resolve full paths at startup — node-pty's posix_spawnp may not find commands
// if Homebrew/nvm paths (/opt/homebrew/bin) aren't in Node's inherited PATH
function resolveCmd(name) {
// Try 'which' first
try {
const r = execFileSync('/usr/bin/which', [name], { encoding: 'utf-8', timeout: 2000 }).trim();
if (r && r.startsWith('/')) return r;
} catch {}
// Search common paths directly
const dirs = ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin',
...(process.env.PATH || '').split(path.delimiter)];
for (const dir of dirs) {
const p = path.join(dir, name);
try { fs.accessSync(p, fs.constants.X_OK); return p; } catch {}
}
return name;
}
const DTACH_CMD = resolveCmd('dtach');
const NODE_CMD = process.execPath;
const ENV_CMD = resolveCmd('env');
// ── CLI environment (src/server/cli-env.js, decomposition #14) ──
// X display + adapter registry + CLI capability probes + model registry.
const { X_ENV, detectXDisplay, refreshXEnv, stabilizeXAuth, adapterRegistry,
CLAUDE_CMD, CODEX_CMD, CODEX_LINUX_SANDBOX_CMD, CODEX_SANDBOX_SUPPORTED,
CLAUDE_SUBSCRIPTION_LOGIN_HELPER, CLAUDE_SUPPORTS_NAME, PERMISSION_MODES,
EFFORT_LEVELS, CLAUDE_MODEL_ALIASES, CLAUDE_KNOWN_MODELS, AVAILABLE_MODELS,
noteModelSeen, refreshAvailableModels,
} = require('./src/server/cli-env.js').create({
rootDir: __dirname, CLAUDE_CMD_RAW, CODEX_CMD_RAW, resolveCmd,
getOAuthToken: (...a) => getOAuthToken(...a),
usagePollingEnabled: (...a) => usagePollingEnabled(...a),
refreshCodexModels: (...a) => refreshCodexModels(...a),
});
// ── Codex model list (from ~/.codex/models_cache.json) ──
// That cache is last-writer-wins AND version-gated server-side: a still-running
// OLD codex CLI re-fetches it and writes it back WITHOUT newer models (observed
// live TWICE: a 0.142.5 session erased the gpt-5.6 entries minutes after
// 0.144.0 fetched them — and once it happened right before a server restart,
// leaving the dropdown stale for the whole hourly re-read cycle). Two guards:
// (1) union every model ever seen, PERSISTED across restarts;
// (2) mtime-guarded re-read ON DEMAND from /api/available-models — the model/
// effort dropdowns fetch per click, so they're always current, no timers.
const CODEX_MODELS_SEEN_FILE = path.join(__dirname, 'data', 'codex-models-seen.json');
const _codexModelsSeen = new Map();
try { for (const m of JSON.parse(fs.readFileSync(CODEX_MODELS_SEEN_FILE, 'utf-8'))) if (m && m.id) _codexModelsSeen.set(m.id, m); } catch {}
if (_codexModelsSeen.size) AVAILABLE_MODELS.codex = [{ id: '', label: 'Default' }, ..._codexModelsSeen.values()];
let _codexCacheMtime = 0;
function refreshCodexModels() {
try {
const fp = path.join(os.homedir(), '.codex', 'models_cache.json');
const mt = fs.statSync(fp).mtimeMs;
if (mt === _codexCacheMtime) return;
_codexCacheMtime = mt;
const codexCache = JSON.parse(fs.readFileSync(fp, 'utf-8'));
if (!codexCache.models?.length) return;
const fresh = codexCache.models.map(m => {
const ctx = m.context_window ? (m.context_window >= 1000000 ? Math.round(m.context_window / 1000000) + 'M' : Math.round(m.context_window / 1000) + 'k') : '';
// Per-model reasoning levels ride along: GPT-5.6 made efforts
// model-specific (sol/terra add max+ultra, luna tops out at max) —
// clients derive dropdowns from this instead of a stale hardcoded list.
return { id: m.slug, label: (m.display_name || m.slug) + (ctx ? ` (${ctx})` : ''), efforts: (m.supported_reasoning_levels || []).map(l => l && l.effort).filter(Boolean) };
}).filter(m => m.id);
let changed = false;
for (const m of fresh) {
const prev = _codexModelsSeen.get(m.id);
if (!prev || JSON.stringify(prev) !== JSON.stringify(m)) { _codexModelsSeen.set(m.id, m); changed = true; }
}
AVAILABLE_MODELS.codex = [{ id: '', label: 'Default' }, ..._codexModelsSeen.values()];
if (changed) {
try {
const tmp = CODEX_MODELS_SEEN_FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify([..._codexModelsSeen.values()]));
fs.renameSync(tmp, CODEX_MODELS_SEEN_FILE);
} catch {}
}
} catch {}
}
refreshCodexModels();
setTimeout(refreshAvailableModels, 3000);
setInterval(refreshAvailableModels, 3600000); // refresh hourly
const HOST = process.env.HOST || '0.0.0.0';
const app = express();
const server = http.createServer(app);
// ── Optional password auth (VIBESPACE_PASSWORD env / data/auth.json) +
// optional Clerk SSO (VIBESPACE_CLERK_PUBLISHABLE_KEY — src/clerk-auth.js) ──
const { Auth } = require('./src/auth');
const { ClerkAuth } = require('./src/clerk-auth');
const clerkAuth = new ClerkAuth();
const auth = new Auth(path.join(__dirname, 'data'), { clerk: clerkAuth });
{
const { generated } = auth.ensurePassword({ generateIfMissing: process.env.VIBESPACE_GENERATE_PASSWORD === '1' });
if (generated) {
console.log('\n ╔════════════════════════════════════════════════╗');
console.log(` ║ Generated workspace password: ${generated.padEnd(15)} ║`);
console.log(' ║ (persisted in data/auth.json — set ║');
console.log(' ║ VIBESPACE_PASSWORD to choose your own) ║');
console.log(' ╚════════════════════════════════════════════════╝\n');
}
if (auth.passwordEnabled) console.log(' Password auth: ENABLED');
if (clerkAuth.enabled) console.log(` Clerk SSO: ENABLED (${clerkAuth.frontendApi})`);
// getter — auth can be enabled/disabled at runtime via /api/auth/set-password
Object.defineProperty(app.locals, 'authEnabled', { get: () => auth.enabled });
Object.defineProperty(app.locals, 'ssoEnabled', { get: () => auth.ssoEnabled });
}
// noServer + ONE manual upgrade dispatcher (registered at the bottom of this
// file): ws's own {server, path} listener calls handleUpgrade UNCONDITIONALLY
// and abortHandshake(400)s every non-matching path — it was killing /proxy/
// WebSockets silently and the /api/vnc bridge on arrival. Auth happens in the
// dispatcher (cookie token, same as HTTP).
const wss = new WebSocketServer({ noServer: true });
app.use(compression());
// HTTP latency observation (names-and-numbers only): rolling 5-min window
// flushed by the metrics sampler; slow requests (>1.5s) recorded as events
// with the SANITIZED route (first 3 path segments — /api/file/serve/* etc.
// carry user paths that must never enter the ledger).
const _httpWin = { n: 0, sum: 0, max: 0, slow: [] };
app.use((req, res, next) => {
const t0 = process.hrtime.bigint();
res.on('finish', () => {
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
_httpWin.n++; _httpWin.sum += ms; if (ms > _httpWin.max) _httpWin.max = ms;
if (ms > 1500 && _httpWin.slow.length < 20) {
_httpWin.slow.push({ route: req.path.split('/').slice(0, 4).join('/') || '/', ms: Math.round(ms) });
}
});
next();
});
auth.registerRoutes(app);
app.use(auth.middleware());
// Serve index.html with cache-busting query params on every local js/css asset
// (?v=<mtime>). Browsers serve unversioned <script>/<link> from memory cache on
// a soft reload without revalidating, so users were stuck on a stale bundle
// after an update until a hard refresh. Versioning the URL forces a fresh fetch
// whenever the file changes — no hard refresh ever needed.
app.get(['/', '/index.html'], (req, res, next) => {
try {
const pub = path.join(__dirname, 'public');
let html = fs.readFileSync(path.join(pub, 'index.html'), 'utf-8');
html = html.replace(/(href|src)="\/([^"?]+\.(?:js|css))"/g, (m, attr, file) => {
try { return `${attr}="/${file}?v=${Math.floor(fs.statSync(path.join(pub, file)).mtimeMs)}"`; }
catch { return m; }
});
res.set('Cache-Control', 'no-cache');
res.type('html').send(html);
} catch { next(); }
});
app.use(express.static(path.join(__dirname, 'public'), { etag: true, lastModified: true, maxAge: 0 }));
// WebDAV bridge — BEFORE the json body parser (PUT bodies stream to disk).
// Auth = scoped Bearer mount tokens; see src/webdav.js for the security model.
const { MountTokens, registerWebdav } = require('./src/webdav');
const mountTokens = new MountTokens({ dataDir: path.join(__dirname, 'data') });
registerWebdav(app, { tokens: mountTokens });
app.use(express.json({ limit: '50mb' }));
app.get('/xterm.css', (req, res) => {
res.sendFile(path.join(__dirname, 'node_modules/@xterm/xterm/css/xterm.css'));
});
// ── Active session tracking (dtach-backed for persistence across server restarts) ──
// dtach is a minimal PTY detach/attach tool — no rendering layer, no mouse interception.
// Claude processes get raw PTY I/O identical to a native terminal.
const activeSessions = new Map();
// B-3f8a: account ids that have a RUNNING session — the merge/creds-rewrite
// guard consults this so a subscription merge never rewrites/removes a creds
// dir under a live session (the CLI re-reads creds per request, mid-turn).
const liveAccountIdSet = () => {
const s = new Set();
for (const sess of activeSessions.values()) if (sess?._accountId) s.add(sess._accountId);
return s;
};
const sessionCounterRef = { value: 0 };
const SOCKETS_DIR = path.join(__dirname, 'data', 'sockets');
const META_DIR = path.join(__dirname, 'data', 'session-meta');
const BUFFERS_DIR = path.join(__dirname, 'data', 'session-buffers');
// ── HOME-RENAME MIGRATION (B-b4a2, one-shot at boot) ────────────────────────
// The 3.5.0 fleet image personalizes the container user, so $HOME moves (e.g.
// /home/vibe → /home/userL) while the PVC keeps everything recorded under
// the OLD path: ~/.claude/projects dirs encode the old cwd (claude's resume
// lookup goes by CURRENT-cwd encoding → every resume died "No conversation
// found"), and mounts/layouts/session metas hold dead /home/vibe/... paths.
// This repeats for EVERY user on EVERY such roll (userL needed manual
// surgery) — migrate automatically: rename projdirs to the new encoding and
// prefix-rewrite recorded paths. One-shot per (oldUser→newUser) marker.
function migrateHomeRename() {
try {
const home = os.homedir();
const user = path.basename(home);
const projectsDir = path.join(home, '.claude', 'projects');
let dirs = [];
try { dirs = fs.readdirSync(projectsDir); } catch { return; }
// Detect the old username from leftover projdirs: -home-<old>-… where
// <old> ≠ current user and /home/<old> no longer exists.
const oldUsers = new Set();
for (const d of dirs) {
const m = /^-home-([a-z][a-z0-9]*)-/.exec(d);
if (m && m[1] !== user && !fs.existsSync(`/home/${m[1]}`)) oldUsers.add(m[1]);
}
for (const old of oldUsers) {
const marker = path.join(__dirname, 'data', `.home-migrated-${old}-to-${user}`);
if (fs.existsSync(marker)) continue;
console.log(`[migrate] home rename detected: /home/${old} → ${home} — migrating projdirs + recorded paths`);
let moved = 0;
for (const d of fs.readdirSync(projectsDir)) {
if (!d.startsWith(`-home-${old}-`)) continue;
const nd = `-home-${user}-` + d.slice(`-home-${old}-`.length);
const src = path.join(projectsDir, d), dst = path.join(projectsDir, nd);
try {
if (!fs.existsSync(dst)) { fs.renameSync(src, dst); moved++; }
else { // merge, never overwrite (both sides may hold transcripts)
for (const f of fs.readdirSync(src)) {
if (!fs.existsSync(path.join(dst, f))) fs.renameSync(path.join(src, f), path.join(dst, f));
}
try { fs.rmdirSync(src); } catch { }
moved++;
}
} catch (e) { console.warn(`[migrate] projdir ${d}: ${e.message}`); }
}
// Prefix-rewrite every recorded string path in the small JSON stores.
const rewrite = (v) => (typeof v === 'string' && v.includes(`/home/${old}/`))
? v.split(`/home/${old}/`).join(`/home/${user}/`)
: (typeof v === 'string' && v === `/home/${old}`) ? `/home/${user}` : v;
const walk = (x) => {
if (Array.isArray(x)) return x.map(walk);
if (x && typeof x === 'object') { for (const k of Object.keys(x)) x[k] = walk(x[k]); return x; }
return rewrite(x);
};
const stores = [path.join(__dirname, 'data', 'mounts.json'), path.join(__dirname, 'data', 'layouts.json'),
path.join(__dirname, 'data', 'task-groups.json'), path.join(__dirname, 'data', 'machine-mounts.json')];
try { for (const f of fs.readdirSync(META_DIR)) stores.push(path.join(META_DIR, f)); } catch { }
let rewrote = 0;
for (const f of stores) {
try {
if (!fs.existsSync(f)) continue;
const raw = fs.readFileSync(f, 'utf-8');
if (!raw.includes(`/home/${old}`)) continue;
const fixed = JSON.stringify(walk(JSON.parse(raw)));
fs.writeFileSync(f + '.pre-home-migrate', raw); // one-shot backup beside it
const tmp = f + '.tmp'; fs.writeFileSync(tmp, fixed); fs.renameSync(tmp, f);
rewrote++;
} catch (e) { console.warn(`[migrate] ${path.basename(f)}: ${e.message}`); }
}
fs.writeFileSync(marker, JSON.stringify({ at: Date.now(), moved, rewrote }));
console.log(`[migrate] home rename done: ${moved} projdirs, ${rewrote} stores rewritten (backups *.pre-home-migrate)`);
}
} catch (e) { console.warn('[migrate] home-rename check failed:', e.message); }
}
migrateHomeRename();
const USAGE_CACHE_FILE = path.join(__dirname, 'data', 'usage-cache.json');
// Per-account PASSIVE usage capture (written by data/bin/vibespace-usage, the
// statusLine hook). Key '__global__' = the machine's own login; 'sub-…' = a
// named subscription. This is the ONLY usage source now — VibeSpace makes NO
// background /api/oauth/usage calls with subscription tokens (that off-CLI
// automated pattern is what gets Max/Pro accounts banned; see §ban-safety).
const USAGE_CACHE_DIR = path.join(__dirname, 'data', 'usage-cache');
const USAGE_SCANNER_PATH = path.join(__dirname, 'data', 'bin', 'vibespace-usage-scan');
const PTY_WRAPPER = path.join(__dirname, 'data', 'bin', 'pty-wrapper.js');
// ── CS refactor M1 (opt-in, default OFF): route LOCAL terminal sessions
// through the standing vibespace-agentd daemon. deviceMgr stays null unless
// the local device daemon is ALWAYS on since the 2.175.0 graduation —
// instantiates it, never spawns a daemon, and attachToDtach is byte-identical
// to today. daemonPtyShim presents the node-pty interface over a device
// session handle so setupSessionPty is unchanged.
let deviceMgr = null;
// ── M2 host-level agentd provisioning (always on since the 2.175.0 flag graduation) ──
// Per-host vsht_ token: plaintext in a 0600 local file (the attach bridge
// reads it at spawn; never argv), sha256 recorded alongside for audit.
const AGENTD_DIR = path.join(__dirname, 'data', 'agentd');
function ensureDir(dir) { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); }
function agentdHostToken(hostId) {
ensureDir(AGENTD_DIR);
const f = path.join(AGENTD_DIR, 'host-' + hostId + '.token');
try { return fs.readFileSync(f, 'utf-8').trim(); } catch { }
const tok = 'vsht_' + require('crypto').randomBytes(24).toString('hex');
fs.writeFileSync(f, tok, { mode: 0o600 });
return tok;
}
// Install/refresh the daemon on a host, throttled per boot+version: a marker
// records the last version shipped; matching = skip (one ssh round trip saved
// per spawn; a bundle change reinstalls because the version bumps with it).
// ── Dial pairing primitives (src/server/dial-pairing.js, decomposition #13) ──
const { CHAT_WRAPPER, agentdDialDevices, agentdDials,
agentdMintDialPair, daemonPtyShim, deviceForDial, ensureAgentdOnHost,
unpairDialDevice,
} = require('./src/server/dial-pairing.js').create({
rootDir: __dirname, AGENTD_DIR,
agentdHostToken: (...a) => agentdHostToken(...a),
getHosts: () => { try { return hosts; } catch { return null; } },
getMounts: () => { try { return mounts; } catch { return null; } },
getMachineMounts: () => { try { return machineMounts; } catch { return null; } },
getPortForwards: () => { try { return portForwards; } catch { return null; } },
getExitProxy: () => { try { return exitProxy; } catch { return null; } },
});
// ── Cached webuiPids (PIDs managed by webui dtach sessions) ──
// Built from pty-wrapper metadata files (childPid), no pgrep/process-tree traversal needed.
const webuiPids = new Set();
function refreshWebuiPids() {
webuiPids.clear();
for (const [id, s] of activeSessions) {
// Read childPid from pty-wrapper's metadata file
try {
const metaPath = path.join(BUFFERS_DIR, id + '.json');
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
if (meta.childPid) {
webuiPids.add(meta.childPid);
s._childPid = meta.childPid;
// Also add direct children of childPid (claude forks from node-pty spawn)
try {
const ch = execFileSync('pgrep', ['-P', String(meta.childPid)], { encoding: 'utf-8', timeout: 2000 }).trim();
for (const line of ch.split('\n')) { const p = parseInt(line.trim()); if (p) webuiPids.add(p); }
} catch {}
}
if (meta.pid) { webuiPids.add(meta.pid); }
} catch {}
}
}
// ── Broadcast helper (avoids duplicating per-session WebSocket iteration) ──
const WS_OPEN = 1;
// Top-level stream-json record types this server KNOWS (2.227.8 breadcrumb).
// Add a type here when you add its handling — until then it announces itself.
const CLAUDE_STREAM_TYPES = new Set([
'assistant', 'user', 'system', 'result', 'attachment', 'control_request',
'control_response', 'tool_progress', 'stream_event', 'summary',
'rate_limit_event', // handled since 2.289.0 — the set lagged the handler, so the breadcrumb cried 'unhandled' for a handled type (misled the inc-msozeyw2 read)
'_stdin_ack', '_remote_state', '_remote_exit',
]);
const _seenStreamTypes = new Set();
function broadcastToSession(session, id, msg) {
const json = JSON.stringify(msg);
for (const client of session.clients.keys()) {
if (client.readyState === WS_OPEN) { try { client.send(json); } catch {} }
}
}
// ── Usage + pool engine (src/server/usage-pool-engine.js, decomposition #5) ──
const {
_vsuPending, usageAnchors, usageEstimator,
armWorkflowUsageWatcher, darkSources, darkTaintedAccounts, kickPoolEval,
markLimitBanner, maybePoolAutoSwitch, maybePoolAutoSwitchForPool,
maybeRepinLockedModel, maybeStopOnFallback, modelsMatch,
poolChooserForModel, poolReadCache, probeUsageForAccountKey,
probeUsageViaSession, recordRateLimitEvent, resolveUsageKey,
sessionModelFor, sweepUsageAnchors, usageCacheKeyFor,
usageIdentityAccountIds, usageIdentityGroups, usageIdentityGroupsCached,
writeUsageCacheForKey, clearSealedOrders, pushSealedOrders,
estOverlayCache, predictCalib,
} = require('./src/server/usage-pool-engine.js').create({
app, rootDir: __dirname, USAGE_CACHE_DIR, activeSessions, wss, WS_OPEN,
broadcastToSession,
serverNotice: (...a) => serverNotice(...a),
serverSetting: (...a) => serverSetting(...a),
getAccounts: () => { try { return accounts; } catch { return null; } },
getHosts: () => { try { return hosts; } catch { return null; } },
getUsageHistory: () => { try { return usageHistory; } catch { return null; } },
recordUsageAttribution: (...a) => recordUsageAttribution(...a),
});
// ── Effective-size computation (min cols/rows across clients + PTY resize + broadcast) ──
// Only clients that have sent a REAL `resize` (terminal fit) drive the PTY
// size. Two classes of entries must NOT shrink it:
// - viewer:true → subagent View Log windows attach to the PARENT session's
// clients map purely to receive broadcasts; they have no terminal.
// - placeholder (no `real` flag) → the 120×30 default set at attach time,
// before the client's first fit(). A reconnecting/ghost client sitting at
// this placeholder used to win the min and shrink everyone's terminal.
function resizeSessionToMin(session, sessionId) {
if (!session.clients.size || !session.pty) return;
let minCols = Infinity, minRows = Infinity, realCount = 0;
for (const sz of session.clients.values()) {
if (sz.viewer || !sz.real) continue;
realCount++;
if (sz.cols < minCols) minCols = sz.cols;
if (sz.rows < minRows) minRows = sz.rows;
}
// No real terminal client yet (e.g. chat sessions never fit) — fall back to
// non-viewer placeholders so chat PTYs still get a sane width, but never let
// a viewer entry participate.
if (!realCount) {
for (const sz of session.clients.values()) {
if (sz.viewer) continue;
if (sz.cols < minCols) minCols = sz.cols;
if (sz.rows < minRows) minRows = sz.rows;
}
}
// Size override ("take over"): one client forces the PTY to ITS size instead
// of the min — e.g. working from a big screen while a small window at home
// stays attached. Smaller clients block their view behind a "Resume here"
// overlay. Ownership follows the owner's live resizes and evaporates when the
// owner disconnects (its clients-map entry disappears → back to min policy).
let cols = minCols, rows = minRows, override = false;
const ownerSz = session._sizeOwnerWs ? session.clients.get(session._sizeOwnerWs) : null;
if (ownerSz && ownerSz.real && !ownerSz.viewer) {
cols = ownerSz.cols; rows = ownerSz.rows; override = true;
} else if (session._sizeOwnerWs) {
session._sizeOwnerWs = null; // owner gone — min policy again
}
if (cols < Infinity && rows < Infinity) {
try { session.pty.resize(cols, rows); } catch {}
// clients: real terminal count — lets the UI say "limited by a smaller
// client" (tmux-style boundary) only when someone else is actually attached
broadcastToSession(session, sessionId, { type: 'effective-size', sessionId, cols, rows, clients: realCount, override });
}
}
// ── Native goal status sync (src/server/goal-sync.js) ──
const { checkClaudeGoalStatus } = require('./src/server/goal-sync.js').create({
hosts: { get fetchSessionJsonl() { return hosts.fetchSessionJsonl.bind(hosts); } }, // lazy — hosts is created later in boot order
broadcastToSession,
findSessionJsonlPath: (...a) => findSessionJsonlPath(...a),
});
// ── Session stdout engine (src/server/session-stdout.js, decomposition #6) ──
// setupSessionPty + attachToDtach + the session-meta store.
const { setupSessionPty, attachToDtach, readSessionMeta, writeSessionMeta,
deleteSessionMeta, sessionMetaOwnerConflict, _metaTombstones,
applyTaskToolUpdate, emitTaskListTodos, updateSessionTodos,
} = require('./src/server/session-stdout.js').create({
rootDir: __dirname, BUFFERS_DIR, META_DIR, DTACH_CMD, USAGE_SCANNER_PATH,
CLAUDE_STREAM_TYPES, _seenStreamTypes, activeSessions,
engine: { _vsuPending, armWorkflowUsageWatcher, kickPoolEval, markLimitBanner,
maybePoolAutoSwitch, maybeRepinLockedModel, maybeStopOnFallback,
modelsMatch, recordRateLimitEvent, resolveUsageKey, usageEstimator },
checkClaudeGoalStatus,
broadcastToSession,
broadcastActiveSessions: (...a) => broadcastActiveSessions(...a),
noteModelSeen: (...a) => noteModelSeen(...a),
recordUsageAttribution: (...a) => recordUsageAttribution(...a),
daemonPtyShim: (...a) => daemonPtyShim(...a),
sbSeenFirst: (...a) => sbSeenFirst(...a),
getDeviceMgr: () => deviceMgr,
getHosts: () => { try { return hosts; } catch { return null; } },
getUsageHistory: () => { try { return usageHistory; } catch { return null; } },
getTelemetry: () => { try { return telemetry; } catch { return null; } },
getNoConvoRef: () => { try { return noConvoRef; } catch { return null; } },
});
// ── Boot restore (src/server/boot-restore.js, decomposition #7) ──
// migrations + restoreSessions + R6 pipe re-open + keeper re-adoption.
const { migrateLegacyHomeProjects, restoreSessions, restoreAgentdPipeSessions,
readoptOrphanKeeperSessions,
} = require('./src/server/boot-restore.js').create({
rootDir: __dirname, PORT, BUFFERS_DIR, META_DIR, SOCKETS_DIR, DTACH_CMD,
ENV_CMD, NODE_CMD, CHAT_WRAPPER, activeSessions, sessionCounterRef,
attachToDtach, setupSessionPty, readSessionMeta, writeSessionMeta,
deleteSessionMeta, broadcastToSession,
broadcastActiveSessions: (...a) => broadcastActiveSessions(...a),
refreshWebuiPids: (...a) => refreshWebuiPids(...a),
sbNoteServerOp: (...a) => sbNoteServerOp(...a),
getHosts: () => { try { return hosts; } catch { return null; } },
getDialBridge: () => { try { return dialBridge; } catch { return null; } },
});
// ── Agent-tool generators + hook registration (src/server/agent-tool-generators.js) ──
const {
AGENT_BIN_DIR, EDITOR_DIR, EDITOR_CMD, STATUS_CMD, USAGE_STATUSLINE_CMD, HOOK_CMD,
createEditorHelper, createStatusHelper, createHookHelper, userStatuslineCmd,
ensureAgentHooks, stripAgentHookEntries, removeAgentHooks, hookRegistrationSafe,
HOOK_OPTOUT_FILE,
} = require('./src/server/agent-tool-generators.js').create({ rootDir: __dirname, port: PORT });
// Generic operator-visible notice channel (2.226.0, user directive "不要静默
// 失败"): server-side probes report through this instead of dying in the log —
// every connected client toasts it (+ it lands in toast/notification history)
// and a telemetry event carries the key to the fleet collector. Key-deduped
// per boot so a recurring probe can't spam.
const _sentNotices = new Set();
function serverNotice(key, text, { level = 1 } = {}) {
if (_sentNotices.has(key)) return;
console.warn('[notice]', text);
global.__vsEvent?.('server-notice', key);
let delivered = 0;
try {
const payload = JSON.stringify({ type: 'server-notice', key, text, level });
for (const c of wss.clients) { try { if (c.readyState === WS_OPEN) { c.send(payload); delivered++; } } catch {} }
} catch {}
// No client connected (e.g. the 60s post-boot probe right after a pod
// restart) → don't burn the key; the next probe run re-notices when
// someone is actually there to see it (review finding).
if (delivered > 0) _sentNotices.add(key);
}
// Agent-hook health probe (2.226.0; born from the 2-day silent MODULE_NOT_FOUND
// outage whose CAUSE 2.225.1 fixed): a registration that goes stale or points
// at a missing script MID-RUN now self-heals + notifies instead of silently
// dropping every Stop/SessionStart/UserPromptSubmit delivery. Boot(+60s) +
// every 6h. NOTE the heal only fixes the FILE — running CLI sessions snapshot
// hook config and pick it up after restart/compaction; the notice says so.
function checkAgentHookHealth() {
try {
if (!hookRegistrationSafe() || !integrationEnabled() || fs.existsSync(HOOK_OPTOUT_FILE)) return;
const scriptMissing = !fs.existsSync(HOOK_CMD);
if (scriptMissing) { try { createHookHelper(); } catch {} }
const st = agentHooksStatus();
for (const [key, info] of Object.entries(st)) {
if (!info || typeof info !== 'object' || !('installed' in info)) continue; // hookPath/optedOut fields
if (!info.fileExists || info.parseError) continue; // that CLI isn't set up here / unreadable
if (info.stale || !info.installed || scriptMissing) {
global.__vsEvent?.('agent-hook-broken', `${key}${info.stale ? '/stale' : ''}${!info.installed ? '/missing-entry' : ''}${scriptMissing ? '/script-missing' : ''}`);
ensureAgentHooks({ auto: true }); // self-heal the registration in place
serverNotice(`hook-health-${key}`,
`VibeSpace's ${key} agent-hook registration was broken (stale or missing path) and has been repaired — CLI sessions already running pick the fix up only after they restart or compact.`,
{ level: 2 });
}
}
} catch (e) { console.warn('[hook-health] probe failed:', e.message); }
}
// Long-lived-token expiry sweep (B-211a): setup-token tokens live exactly 1
// year and a 401 has NO self-heal — warn while there's still time to re-mint.
// Once per boot, notice-deduped per account.
function checkOatExpiry() {
try {
for (const a of accounts.list().accounts) {
if (!a.oat || typeof a.oatDaysLeft !== 'number') continue;
if (a.oatDaysLeft <= 0) {
serverNotice(`oat-expired-${a.id}`, `The long-lived token for "${a.name}" has EXPIRED — sessions using it will fail until you re-mint one (Manage agents → the account's ⋯ menu → Long-lived token).`, { level: 2 });
} else if (a.oatDaysLeft <= 21) {
serverNotice(`oat-expiring-${a.id}`, `The long-lived token for "${a.name}" expires in ${a.oatDaysLeft} days — re-mint it soon (Manage agents → ⋯ → Long-lived token).`, { level: 2 });
}
}
} catch { }
}
setTimeout(checkOatExpiry, 20000);
setInterval(checkOatExpiry, 6 * 3600e3); // stable instances stay up for weeks — a one-shot sweep would sail past the threshold (serverNotice keys dedupe per boot, so re-fires are cheap)
// Boot-time hook registration is DEFERRED until settings are readable (after
// setupPersistence below) — the Integration master switch decides whether we
// register or actively strip. See "Agent-hook boot registration".
// ── File System API (extracted to src/routes/files.js) ──
app.locals.xEnv = X_ENV;
app.locals.refreshXEnv = refreshXEnv; // paste route retries through this after an X cookie rotation
app.locals.activeSessions = activeSessions; // paste-image resolves a session's host server-side (B-65ec)
// Remote fs (Files cross-host) — resolved lazily; `hosts` is created below.
app.locals.getRemoteFs = () => remoteFs;
// ── SafeFs: dedicated worker_threads pool for LOCAL user-path fs ops ──
// STRUCTURAL isolation for the hung-mount class (complements the tactical
// canary/watchdog/circuit-breaker + UV_THREADPOOL_SIZE=32 above): every local
// file-route fs call runs on a worker's own thread with a per-op deadline and
// kill-and-respawn, so a wedged mount can never again saturate the shared libuv
// pool and freeze /login. path.resolve/permission decisions stay in-main; the
// worker only executes the already-resolved absolute path. mounts.pathBlocked
// still fails known-hung roots fast in the route middleware BEFORE dispatch.
try {
app.locals.safeFs = new SafeFs({
poolSize: parseInt(process.env.VIBESPACE_SAFEFS_POOL || '', 10) || 4,
});
console.log(`[safe-fs] worker pool up (${app.locals.safeFs.poolSize} workers)`);
} catch (e) {
console.error('[safe-fs] pool init failed, file ops fall back to in-main fs:', e.message);
}
app.use(fileRoutes);
// Browser proxy — full-rewriting web proxy via node-unblocker
// Rewrites all URLs in HTML/CSS, injects JS to rewrite XHR/WebSocket, strips security headers
const Unblocker = require('unblocker');
const unblocker = new Unblocker({
prefix: '/proxy/',
responseMiddleware: [
function stripFrameHeaders(data) {
delete data.headers['x-frame-options'];
}
],
});
app.use(unblocker);
// Editor: open request from the `code` helper script (via HTTP, not terminal
// output). The caller lives INSIDE the session shell — no cookie exists there,
// so auth.middleware exempts this path and WE validate the per-session vsst_
// token instead (same trust model as /api/agent/*). Without this, enabling
// password auth silently broke Ctrl+G: the script's POST got 401 and claude
// sat on "Save and close editor to continue…" forever.
app.post('/api/editor/open', (req, res) => {
if (app.locals.authEnabled) {
const token = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
let ok = false;
if (token && token.startsWith('vsst_')) {
for (const [, s] of activeSessions) { if (s.agentToken === token) { ok = true; break; } }
}
if (!ok) return res.status(401).json({ error: 'unauthorized (session token required)' });
}
const { file, signal, sessionId } = req.body;
// Remote Ctrl+G (B-2de8): the POST came from the fake `code` helper running
// ON THE HOST (over the reverse tunnel) — the tmpfile + signal file live
// there. Resolve the session's host server-side and ship it in the
// broadcast so the client editor reads/writes/signals the right machine.
const editorHost = (sessionId && activeSessions.get(sessionId)?.host) || null;
// Persist the pending edit on the session + its meta: the helper script
// waits FOREVER on the signal file while claude shows "Save and close
// editor to continue…" — a server restart + page reload (or pod recreation
// for remote sessions, whose helper+claude survive on the host) otherwise
// loses the only record of it and the session silently hangs mid-turn.
// Cleared by /api/editor/signal; re-broadcast on terminal attach.
if (sessionId && activeSessions.has(sessionId)) {
const s = activeSessions.get(sessionId);
s._pendingEditor = { filePath: file, signalPath: signal, host: editorHost, at: Date.now() };
try { if (s.sockName) writeSessionMeta(s.sockName, { ...(readSessionMeta(s.sockName) || {}), pendingEditor: s._pendingEditor }); } catch {}
}
// Broadcast to all WebSocket clients — include sessionId so each client opens editor on the right window
const msg = JSON.stringify({ type: 'editor-open', filePath: file, signalPath: signal, sessionId: sessionId || null, host: editorHost });
wss.clients.forEach(client => {
if (client.readyState === WS_OPEN) {
try { client.send(msg); } catch {}
}
});
res.json({ success: true });
});
// Editor: signal completion (called by client when user saves/closes editor)
app.post('/api/editor/signal', async (req, res) => {
const { signalPath, filePath, content, host } = req.body;
try {
if (host && remoteFs) {
// remote Ctrl+G: the CLI polls the signal file ON ITS machine
if (content !== undefined) await remoteFs.write(String(host), filePath, Buffer.from(content));
await remoteFs.write(String(host), signalPath, Buffer.from('done'));
} else {
if (content !== undefined) fs.writeFileSync(filePath, content);
fs.writeFileSync(signalPath, 'done');
}
// The edit is settled — drop the persisted pending-editor record so a
// later restart/attach doesn't re-open a dead pane
for (const [, s] of activeSessions) {
if (s._pendingEditor?.signalPath === signalPath) {
s._pendingEditor = null;
try { if (s.sockName) writeSessionMeta(s.sockName, { ...(readSessionMeta(s.sockName) || {}), pendingEditor: null }); } catch {}
}
}
// Broadcast editor-close to all clients so they remove the split pane
const msg = JSON.stringify({ type: 'editor-close', filePath, signalPath });
wss.clients.forEach(client => {
if (client.readyState === WS_OPEN) { try { client.send(msg); } catch {} }
});
res.json({ success: true });
} catch (err) { res.status(400).json({ error: err.message }); }
});
// ── Persistence API (extracted to src/routes/persistence.js) ──
const syncStores = {};
function getSyncStore(name) { return syncStores[name]; }
// THE server-side settings reader (data/settings.json via persistence.js's
// cached accessor). getSyncStore('settings') is NOT it — that SyncStore is an
// empty migration target; reads through it silently return undefined.
function serverSetting(key) {
try { return persistenceRouter.readSettings ? persistenceRouter.readSettings()[key] : undefined; } catch { return undefined; }
}
// Integration master switch (agents.vibespaceIntegration, default ON): OFF =
// pristine CLI — no hook registration, no VIBESPACE_API/agent-tools env in new
// spawns, no context/nudge delivery even to already-running sessions. THE one
// definition — threaded into ws-handler and agent-routes via their deps.
function integrationEnabled() {
try { return serverSetting('agents.vibespaceIntegration') !== false; } catch { return true; }
}
// ONE convergence rule for boot AND the live toggle: hook registration follows
// the master switch. ensureAgentHooks({auto:true}) still honors the manual
// data/.agent-hooks-optout marker (Manage-Agents Remove) — the switch never
// overrides that narrower explicit choice; Install there clears it.
function syncHookRegistration() {
try {
if (integrationEnabled()) ensureAgentHooks({ auto: true });
else stripAgentHookEntries();
} catch (e) { console.warn('[integration] hook registration sync failed:', e.message); }
}
syncStores.drafts = new SyncStore('drafts', path.join(__dirname, 'data', 'drafts.json'), wss);
syncStores.settings = new SyncStore('settings', path.join(__dirname, 'data', 'settings-sync.json'), wss);
syncStores.uploads = new SyncStore('uploads', path.join(__dirname, 'data', 'uploads-sync.json'), wss);
syncStores.stage = new SyncStore('stage', path.join(__dirname, 'data', 'stage-sync.json'), wss); // dynamic desktop (docs/design-dynamic-desktop.md)
setupPersistence({ dataDir: path.join(__dirname, 'data'), wss, WS_OPEN, getSyncStore, activeSessions, auth,
getHosts: () => hosts, getMounts: () => mounts, getTasks: () => tasks,
getAccounts: () => accounts, getUsageHistory: () => usageHistory,
// React server-side to the Integration master switch: register/strip the
// CLI-config hook entries the moment the setting flips (the only settings
// key with a server-side side effect — everything else reads lazily).
onSettingsWrite: (next, prev) => {
const was = (prev || {})['agents.vibespaceIntegration'] !== false;
const now = (next || {})['agents.vibespaceIntegration'] !== false;
if (was !== now) syncHookRegistration();
// claude.disableModelFallback flips LIVE sessions too ("动态对对话进行调整"):
// apply_flag_settings merges switchModelsOnFlag into the CLI's inline
// flag-settings layer, effective from the next turn. Local and remote
// chat sessions alike (the control_request rides the same stdin channel
// as set_model). Sessions spawned after the flip get it at spawn instead.
const fbWas = (prev || {})['claude.disableModelFallback'] === true;
const fbNow = (next || {})['claude.disableModelFallback'] === true;
if (fbWas !== fbNow) {
for (const [sid, sess] of activeSessions) {
if (sess.backend !== 'claude' || sess.mode !== 'chat' || !sess.pty) continue;
try {
const ad = adapterRegistry.get('claude');
if (ad?.formatSetFallbackPolicy) sess.pty.write(ad.formatSetFallbackPolicy(fbNow) + '\n');
} catch (e) { console.warn(`[fallback-policy] ${sid}: ${e.message}`); }
}
}
} });
app.use(persistenceRouter);
// ── Agent-hook boot registration (deferred from the hook-machinery block so
// the Integration master switch is readable) — a toggle flipped just before a
// restart, or an imported config bundle carrying it, converges here.
syncHookRegistration();
// Health probe: catches MID-RUN poisoning (the 2.225.1 incident class) that
// boot-time registration can't — self-heals + notifies. 60s in, then 6h.
setTimeout(checkAgentHookHealth, 60000).unref();
setInterval(checkAgentHookHealth, 6 * 3600 * 1000).unref();
// ── Task Groups (岗位; task system — docs/design-task-system.md + refactor) ──
// data/task-groups.json is AUTHORITATIVE for everything the board renders (the
// store migrates the legacy data/tasks.json forward once). The one-time legacy
// Groups migration (sessionGroups/groupFolders) runs in the constructor.
const { TaskGroupManager } = require('./src/task-groups');
const tasks = new TaskGroupManager({
dataDir: path.join(__dirname, 'data'),
readUserState: () => persistenceRouter.readUserState(),
getSetting: (k) => serverSetting(k),
onChange: (list) => {
const json = JSON.stringify({ type: 'tasks-updated', tasks: list });
wss.clients.forEach(c => { if (c.readyState === WS_OPEN) { try { c.send(json); } catch {} } });
},
});
// System info + memory-pressure watch (2.216.0, userL's 32Gi OOM kill —
// the pod-level kill takes every dtach session; warn BEFORE the kernel acts)
// ── Sysinfo wiring (src/server/sysinfo-wiring.js): remote snapshot ladder ──
const { sysinfo, remoteSysinfo } = require('./src/server/sysinfo-wiring.js').create({ getHosts: () => hosts });
// ── Incident capture (src/server/incident-wiring.js) ──
const { _srvConsoleRing } = require('./src/server/incident-wiring.js').create({
app, rootDir: __dirname,
getActiveSessions: () => activeSessions,
getHosts: () => { try { return hosts; } catch { return null; } },
getNoConvoRef: () => { try { return noConvoRef; } catch { return null; } },
readLayouts: (...a) => readLayouts(...a),
sysinfo,
});
app.get('/api/sysinfo', async (req, res) => {
try {
const hostId = String(req.query.host || '');
if (hostId) return res.json(await remoteSysinfo(hostId));
res.json(await sysinfo.read(path.join(__dirname, 'data')));
} catch (e) { res.status(500).json({ error: e.message }); }
});
// Resource HISTORY for the System rail charts (2.223.0): self-sampled CPU/
// memory rings — 24h at the 45s watch cadence, 7d at 15min. range=1h|24h|7d.
app.get('/api/sysinfo/history', (req, res) => {
const ranges = { '1h': 3600e3, '24h': 24 * 3600e3, '7d': 7 * 24 * 3600e3 };
const ms = ranges[String(req.query.range || '24h')] || ranges['24h'];
res.json({ points: sysinfo.history(ms), rangeMs: ms, cpus: require('os').cpus().length });
});
sysinfo.startWatch({
dataDir: path.join(__dirname, 'data'),
broadcast: (msg) => {
const json = JSON.stringify(msg);
wss.clients.forEach(c => { if (c.readyState === WS_OPEN) { try { c.send(json); } catch {} } });
},
});
app.get('/api/tasks', (req, res) => res.json({ tasks: tasks.list() }));
app.post('/api/tasks', (req, res) => {
try { res.json({ success: true, task: tasks.create(req.body || {}) }); }
catch (e) { res.status(400).json({ error: e.message }); }
});
app.patch('/api/tasks/:id', (req, res) => {
try { res.json({ success: true, task: tasks.update(req.params.id, req.body || {}) }); }
catch (e) { res.status(e.message === 'task not found' ? 404 : 400).json({ error: e.message }); }
});
app.delete('/api/tasks/:id', (req, res) => {
try { tasks.remove(req.params.id); res.json({ success: true }); }
catch (e) { res.status(404).json({ error: e.message }); }
});
// Granular tag ops (atomic server-side — concurrent clients can't clobber
// each other's read-modify-write of the sessions array)
app.post('/api/tasks/:id/bind', (req, res) => {
try { res.json({ success: true, task: tasks.bind(req.params.id, req.body?.sessionKey) }); }
catch (e) { res.status(e.message === 'task not found' ? 404 : 400).json({ error: e.message }); }
});
app.post('/api/tasks/:id/unbind', (req, res) => {
try { res.json({ success: true, task: tasks.unbind(req.params.id, req.body?.sessionKey) }); }
catch (e) { res.status(e.message === 'task not found' ? 404 : 400).json({ error: e.message }); }
});
app.post('/api/tasks/:id/progress', (req, res) => {
try { res.json({ success: true, task: tasks.addProgress(req.params.id, req.body || {}) }); }
catch (e) { res.status(e.message === 'task not found' ? 404 : 400).json({ error: e.message }); }
});
// P4 repo task files: export a task to a committable markdown file / import one.
app.post('/api/tasks/:id/export', (req, res) => {
try { res.json({ success: true, path: tasks.exportToFile(req.params.id, req.body?.path) }); }
catch (e) { res.status(e.message === 'task not found' ? 404 : 400).json({ error: e.message }); }
});
app.post('/api/tasks/import', (req, res) => {
try { res.json({ success: true, task: tasks.importFromFile(req.body?.path) }); }
catch (e) { res.status(400).json({ error: e.message }); }
});
// ── Remote context-folder auto-sync ("mount"): a REMOTE session's belonged
// groups with a contextDir get a live-synced copy at
// <remoteHome>/.vibespace/ctx/<groupId> (bidirectional rsync, newer-wins, no
// deletes, .vibespace excluded), and the injected file index is path-translated
// to the remote copy (remoteCtxBase). Triggers: session spawn + a 60s timer
// while any live remote session belongs to the group. Remote writes sync back
// → the local signature changes → every member re-injects next turn. ──
const { syncGroupCtx, FILE_CAP: CTX_FILE_CAP, MAX_FILES: MAX_CTX_FILES } = require('./src/ctx-sync');
const machineProbes = require('./src/machine-probes');
const { parseRateLimitEvent, captureRateLimitEvent } = require('./src/rate-limit-capture.js');
const _ctxSyncBusy = new Set(); // `${hostId}:${groupId}` in-flight guard
const _ctxSkipNoticed = new Set(); // one honest notice per host:group:file per boot
async function syncRemoteGroupCtx(h, g) {
const key = `${h.id}:${g.id}`;
if (_ctxSyncBusy.has(key)) return;
_ctxSyncBusy.add(key);
try {
const home = await hosts.homeDir(h);
if (!home) return;
const rdir = `${home}/.vibespace/ctx/${g.id}`;
// ONE implementation for every transport (src/ctx-sync.js, 2.277.0):
// hashed newer-wins sync over the device link; ssh degrades to its legacy
// rsync pair when the link is down. The old split (ssh=rsync uncapped,
// dial=hashed with a SILENT 2MB/400-file cap) meant a 3MB context file
// reached every ssh host and never reached a dial device, invisibly.
await syncGroupCtx({
hosts, host: h, group: g, remoteDir: rdir,
onSkip: (rel, why, size) => {
const k = `${key}:${rel}:${why}`;
if (_ctxSkipNoticed.has(k)) return;
_ctxSkipNoticed.add(k);
const msg = why === 'count'
? `Context folder for "${g.title || g.id}" has more than ${MAX_CTX_FILES} files — the rest won't sync to ${h.name}.`
: `Context file ${rel} (${Math.round((size || 0) / 1024 / 1024)}MB) exceeds the ${Math.round(CTX_FILE_CAP / 1024 / 1024)}MB sync cap and won't reach ${h.name}.`;
console.warn('[ctx-sync]', msg);
try { serverNotice(`ctx-skip:${k}`, msg, { level: 2 }); } catch { }
},
});
} catch (e) { console.warn('[ctx-sync]', h.name, g.id, e.message); }
finally { _ctxSyncBusy.delete(key); }
}
// Groups a session belongs to that have a syncable context folder.
function ctxGroupsOf(session, id) {
if (!session.host) return [];
return tasks.groupsForSession({ sessionKey: sessionStatusKey(session, id), cwd: session.cwd, initialGroupId: session._initialGroupId })
.filter((g) => g.contextDir && g.injectContext !== false);
}
function scheduleCtxSync(session, id) {
try {
if (!session.host || !hosts) return;
let h; try { h = hosts.get(session.host); } catch { return; }
for (const g of ctxGroupsOf(session, id)) syncRemoteGroupCtx(h, g);
} catch { }
}
setInterval(() => {
try {
if (!integrationEnabled()) return; // master switch off ⇒ no ctx-folder pushes either
const seen = new Set();
for (const [id, s] of activeSessions) {
if (!s.host) continue;
let h; try { h = hosts.get(s.host); } catch { continue; }
for (const g of ctxGroupsOf(s, id)) {
const k = s.host + ':' + g.id;
if (seen.has(k)) continue;
seen.add(k);
syncRemoteGroupCtx(h, g);
}
}
} catch { }
}, 60000);
// Absolute remote path the injection should show for a group's context folder
// (null → local session, keep local paths). Uses the cached remote home; if
// the home isn't known yet (first contact) fall back to local paths this turn.
function remoteCtxBaseFor(session) {
if (!session.host || !hosts) return null;
const home = hosts._homes?.get(session.host);
if (!home) { try { hosts.homeDir(hosts.get(session.host)); } catch { } return null; } // warm the cache async
return (gid) => `${home}/.vibespace/ctx/${gid}`;
}
// ── Anthropic accounts (subscription ↔ API/console per-session switching) ──
// Keys AES-GCM encrypted in data/accounts.json; injected as ANTHROPIC_API_KEY
// into the session's spawn env (process-env channel — never argv/proc-visible).
// The CLI's own /login is mutually exclusive; this store is what lets both
// identities coexist. Design: docs/design in CLAUDE.md "Accounts".
const { AccountManager } = require('./src/accounts');
const accounts = new AccountManager({
dataDir: path.join(__dirname, 'data'),
onChange: (list) => {
const json = JSON.stringify({ type: 'accounts-updated', ...list });
for (const client of wss.clients) if (client.readyState === WS_OPEN) client.send(json);
broadcastActiveSessions(); // account names on live session cards may change
},
});
// ── Usage history: a PERMANENT per-request token ledger mined from Claude's
// JSONL transcripts (terminal + chat), for the Usage window. resolveAccount
// bakes WHICH account + its billing TYPE into each event so subscription and
// API-key usage are never conflated. ──
const { UsageHistory } = require('./src/usage-history');
// Forward URL/token: user setting wins; the VIBESPACE_TELEMETRY_FORWARD_* env
// vars are the DEPLOYMENT defaults (helm/compose set them fleet-wide so no
// per-user settings edit is needed on managed instances).
const telemetry = new Telemetry({
dataDir: path.join(__dirname, 'data'),
version: require('./package.json').version,
getForwardUrl: () => {
try { return serverSetting('telemetry.forwardUrl') || process.env.VIBESPACE_TELEMETRY_FORWARD_URL || ''; }
catch { return process.env.VIBESPACE_TELEMETRY_FORWARD_URL || ''; }
},
getForwardToken: () => {
try { return serverSetting('telemetry.forwardToken') || process.env.VIBESPACE_TELEMETRY_FORWARD_TOKEN || ''; }
catch { return process.env.VIBESPACE_TELEMETRY_FORWARD_TOKEN || ''; }
},
});
// Server-side fatals land in the same ledger (journald has them too, but the
// diagnostics report should show one unified picture).
process.on('uncaughtException', (e) => {
try { telemetry.record({ kind: 'server-error', name: e.message || 'uncaughtException', stack: e.stack }); telemetry.flush(); } catch {}
// Same flush belt as the clean shutdown (2.219.0 audit) — a crash used to
// drop up to 2s of debounced writes (layouts, session-status, user-todos).
try { for (const store of Object.values(syncStores)) { try { store.flush(); } catch {} } } catch {}
try { flushLayouts(); } catch {}
try { sessionStatus.flush(); } catch {}
try { userTodos.flush(); } catch {}
console.error(e); process.exit(1);
});
process.on('unhandledRejection', (e) => { try { telemetry.record({ kind: 'server-error', name: (e && e.message) || 'unhandledRejection', stack: e && e.stack }); } catch {} console.error('unhandledRejection:', e); });
// Server performance metrics — RSS/heap, event-loop lag, live session count.
// Every 5 min; names-and-numbers only, same ndjson ledger as everything else.
{
let lagProbeAt = Date.now();
let maxLagMs = 0;
setInterval(() => { // 1s cadence lag probe (cheap): drift beyond the interval = loop blocked