-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
6423 lines (6281 loc) · 362 KB
/
Copy pathserver.js
File metadata and controls
6423 lines (6281 loc) · 362 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');
// ── X display detection (Linux clipboard / xclip) ──
// The inherited DISPLAY is unreliable: the server is often (re)started from
// shells with a stale value (e.g. :99 with no X server behind it), and under
// XWayland the display also needs the compositor's XAUTHORITY cookie — without
// it even the right display number fails. Probe candidates at startup and use
// the first {DISPLAY, XAUTHORITY} pair that actually answers; this env is used
// for the server's own xclip calls AND injected into spawned sessions (the CLI
// reads the clipboard itself on Ctrl+V).
function detectXDisplay() {
if (process.platform !== 'linux') return { DISPLAY: process.env.DISPLAY || '', XAUTHORITY: process.env.XAUTHORITY || '' };
const displays = [];
if (process.env.DISPLAY) displays.push(process.env.DISPLAY);
try {
for (const f of fs.readdirSync('/tmp/.X11-unix')) {
if (/^X\d+$/.test(f)) { const d = ':' + f.slice(1); if (!displays.includes(d)) displays.push(d); }
}
} catch {}
const xauths = [];
if (process.env.XAUTHORITY) xauths.push(process.env.XAUTHORITY);
try {
const rd = `/run/user/${process.getuid()}`;
for (const f of fs.readdirSync(rd)) {
// .mutter-Xwaylandauth.XXXXXX, Xauthority, xauth_XXXXXX (sddm), …
// NOTE: "Xwaylandauth" does NOT contain the substring "xauth" — match "auth"
if (/auth/i.test(f)) xauths.push(path.join(rd, f));
}
} catch {}
xauths.push(path.join(os.homedir(), '.Xauthority'));
const xauthCandidates = ['', ...xauths.filter((p, i, a) => p && a.indexOf(p) === i && fs.existsSync(p))];
const xsetCmd = resolveCmd('xset');
for (const d of displays) {
for (const xa of xauthCandidates) {
try {
execFileSync(xsetCmd, ['q'], {
env: { ...process.env, DISPLAY: d, ...(xa ? { XAUTHORITY: xa } : {}) },
timeout: 1500, stdio: 'ignore',
});
return stabilizeXAuth({ DISPLAY: d, XAUTHORITY: xa, probed: true });
} catch {}
}
}
return { DISPLAY: process.env.DISPLAY || '', XAUTHORITY: process.env.XAUTHORITY || '', probed: false }; // best effort
}
// Compositor restarts mint a NEW per-instance cookie file
// (.mutter-Xwaylandauth.XXXXXX) while every already-running session keeps the
// OLD path in its env — the clipboard silently dies for all of them (real
// incident 2026-07-09: an Xwayland restart at 18:42 broke image paste in 11
// live sessions at once). Stabilize: merge the working cookie into
// ~/.Xauthority and hand THAT path to sessions — processes re-open the auth
// file on every X request, so after a future rotation one refreshXEnv() merge
// heals everything, old sessions included, without respawns.
function stabilizeXAuth(found) {
if (!found.probed || !found.XAUTHORITY) return found;
const home = path.join(os.homedir(), '.Xauthority');
if (found.XAUTHORITY === home) return found;
try {
execFileSync(resolveCmd('xauth'), ['merge', found.XAUTHORITY], {
env: { ...process.env, XAUTHORITY: home }, timeout: 3000, stdio: 'ignore',
});
// switch to the stable path only if it actually answers
execFileSync(resolveCmd('xset'), ['q'], {
env: { ...process.env, DISPLAY: found.DISPLAY, XAUTHORITY: home }, timeout: 1500, stdio: 'ignore',
});
return { ...found, XAUTHORITY: home };
} catch { return found; }
}
// ONE mutable object — ws-handler and app.locals hold references to it, so a
// refresh propagates everywhere (new spawns + the paste route) without rewiring.
const X_ENV = detectXDisplay();
function refreshXEnv() { Object.assign(X_ENV, detectXDisplay()); return X_ENV; }
const CLAUDE_CMD = CLAUDE_CMD_RAW.startsWith('/') ? CLAUDE_CMD_RAW : resolveCmd(CLAUDE_CMD_RAW);
const CODEX_CMD = CODEX_CMD_RAW.startsWith('/') ? CODEX_CMD_RAW : resolveCmd(CODEX_CMD_RAW);
const CLAUDE_SUBSCRIPTION_LOGIN_HELPER = path.join(__dirname, 'data', 'bin', 'vibespace-claude-subscription-login.mjs');
const CODEX_LINUX_SANDBOX_CMD = resolveCmd('codex-linux-sandbox');
const CODEX_SANDBOX_SUPPORTED = process.platform !== 'linux'
|| (!!CODEX_LINUX_SANDBOX_CMD && CODEX_LINUX_SANDBOX_CMD !== 'codex-linux-sandbox')
|| (typeof CODEX_LINUX_SANDBOX_CMD === 'string' && fs.existsSync(CODEX_LINUX_SANDBOX_CMD));
const adapterRegistry = createAdapterRegistry({
claudeCmd: CLAUDE_CMD,
codexCmd: CODEX_CMD,
codexSandboxSupported: CODEX_SANDBOX_SUPPORTED,
chatWrapper: path.join(__dirname, 'data', 'bin', 'chat-wrapper.js'),
codexChatWrapper: path.join(__dirname, 'data', 'bin', 'codex-chat-wrapper.js'),
ptyWrapper: path.join(__dirname, 'data', 'bin', 'pty-wrapper.js'),
buffersDir: path.join(__dirname, 'data', 'session-buffers'),
});
if (!CODEX_SANDBOX_SUPPORTED) {
console.log('[codex] codex-linux-sandbox not found; default/safe-yolo sessions will run unsandboxed.');
}
// Parse available permission modes, effort levels, and supported flags from claude --help
let PERMISSION_MODES = ['default', 'acceptEdits', 'auto', 'bypassPermissions', 'dontAsk', 'plan'];
// The effortLevel enum (parsed from `claude --help` below, which lists it on a
// wrapped line: "(low, medium, high, xhigh, max)"). This is the fallback if the
// parse ever fails — keep it matching. NOTE: "ultracode" is deliberately NOT
// here — it's not an effortLevel value but a separate session mode (xhigh +
// dynamic-workflow orchestration), appended as a pseudo-level client-side.
let EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
let CLAUDE_SUPPORTS_NAME = false;
try {
const help = execFileSync(CLAUDE_CMD, ['--help'], { encoding: 'utf-8', timeout: 5000 });
const permMatch = help.match(/--permission-mode.*choices:\s*(.+)\)/);
if (permMatch) {
PERMISSION_MODES = permMatch[1].match(/"([^"]+)"/g)?.map(s => s.replace(/"/g, '')) || PERMISSION_MODES;
}
// --effort <level> Effort level ... (low, medium, high, max)
const effortMatch = help.match(/--effort\s+\S+\s+[^(]*\(([^)]+)\)/);
if (effortMatch) {
EFFORT_LEVELS = effortMatch[1].split(',').map(s => s.trim()).filter(Boolean);
}
CLAUDE_SUPPORTS_NAME = /--name\b/.test(help);
} catch {}
// Propagate capability flags to the adapter
adapterRegistry.get('claude').config.supportsName = CLAUDE_SUPPORTS_NAME;
// Discover available models per backend (cached, refreshed periodically)
const CLAUDE_MODEL_ALIASES = [
{ id: '', label: 'Default' },
{ id: 'fable', label: 'fable (latest, 200k)' },
{ id: 'fable[1m]', label: 'fable[1m] (latest, 1M context)' },
{ id: 'opus', label: 'opus (latest, 200k)' },
{ id: 'opus[1m]', label: 'opus[1m] (latest, 1M context)' },
{ id: 'sonnet', label: 'sonnet (latest)' },
{ id: 'sonnet[1m]', label: 'sonnet[1m] (latest, 1M context)' },
{ id: 'haiku', label: 'haiku (latest)' },
];
// Known GA full model ids — the BASELINE the dropdown always carries.
// The passive statusline discovery only learns models that have SERVED a
// LOCAL TERMINAL session here (real report: the list held Opus 4.8 —
// once seen — but never Opus 5), and the /v1/models fetch is §ban-safety
// opt-in. A new tier ships → add it here (same convention as the aliases).
// No context-size claims on these labels: a full id can serve the long
// context (a claude-opus-5 session was observed at 222k/1M under an old
// "(200k)" label) — the status bar derives the real window from usage.
const CLAUDE_KNOWN_MODELS = [
{ id: 'claude-fable-5', label: 'Fable 5' },
{ id: 'claude-opus-5', label: 'Opus 5' },
{ id: 'claude-sonnet-5', label: 'Sonnet 5' },
{ id: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5' },
];
// Served-model passive discovery: EVERY session's assistant records name the
// model that actually served — feed the same __models__.json the statusline
// hook writes, so chat/remote sessions teach the dropdown too (both writers
// preserve-merge; ingestPassiveModels picks it up within ~30s).
const _modelsSeenRam = new Set();
function noteModelSeen(id) {
if (!id || typeof id !== 'string' || id === '<synthetic>' || _modelsSeenRam.has(id)) return;
_modelsSeenRam.add(id);
try {
const fp = path.join(USAGE_CACHE_DIR, '__models__.json');
let list = [];
try { list = JSON.parse(fs.readFileSync(fp, 'utf-8')) || []; } catch { }
if (!list.some((m) => m && m.id === id)) {
list.push({ id, label: id.replace(/^claude-/, '').replace(/-(\d{8})$/, '').replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()) });
fs.writeFileSync(fp, JSON.stringify(list));
}
} catch { }
}
const AVAILABLE_MODELS = {
claude: [...CLAUDE_MODEL_ALIASES, ...CLAUDE_KNOWN_MODELS],
codex: [{ id: '', label: 'Default' }],
};
function refreshAvailableModels() {
// /v1/models accepts both auth schemes now (OAuth needs Bearer + the oauth
// beta header — it used to 401, fixed server-side ~2026-06). The old
// bootstrap endpoint's additional_model_options now returns null, so
// /v1/models is the single source for full model IDs; CLI aliases
// (fable/opus/sonnet/haiku) stay hardcoded since they're CLI-side names.
function fetchModels(token, useOAuth) {
const headers = { 'anthropic-version': '2023-06-01' };
if (useOAuth) {
headers['Authorization'] = 'Bearer ' + token;
headers['anthropic-beta'] = 'oauth-2025-04-20';
} else {
headers['x-api-key'] = token;
}
const req = https.request('https://api.anthropic.com/v1/models?limit=100', {
method: 'GET', headers,
}, (res) => {
let body = '';
res.on('data', (d) => { body += d; });
res.on('end', () => {
try {
const data = JSON.parse(body);
if (data.data?.length) {
const models = data.data.map(m => {
const ctx = m.max_input_tokens >= 1000000 ? '1M' : m.max_input_tokens >= 200000 ? '200k' : Math.round(m.max_input_tokens / 1000) + 'k';
return { id: m.id, label: `${m.display_name || m.id} (${ctx})` };
});
const known = CLAUDE_KNOWN_MODELS.filter((k) => !models.some((m) => m.id === k.id));
AVAILABLE_MODELS.claude = [...CLAUDE_MODEL_ALIASES, ...known, ...models];
} else if (res.statusCode !== 200) {
console.warn(`[models] /v1/models failed: HTTP ${res.statusCode}`);
}
} catch {}
});
});
req.on('error', () => {});
req.end();
}
// §ban-safety: a /v1/models fetch with the OAuth (subscription) token is the
// same off-CLI background-call pattern as the usage poll, so it's gated behind
// the SAME opt-in. Default OFF → the dropdown falls back to the hardcoded CLI
// aliases (fable/opus/sonnet/haiku[+1m]); only full model IDs are missed, and
// "Custom…" still lets you type one. An API KEY (sanctioned) is always used.
const apiKey = process.env.ANTHROPIC_API_KEY || null;
if (apiKey) {
fetchModels(apiKey, false);
} else if (usagePollingEnabled()) {
getOAuthToken((oauthToken) => { if (oauthToken) fetchModels(oauthToken, true); });
}
refreshCodexModels();
}
// ── 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 (flag agentd.remoteSessions) ──
// 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 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).
const _agentdInstalled = new Map(); // hostId → version
// ── Transport B (dial-out) server side: devices behind NAT dial US. Pairing
// mints {deviceId, dialToken}; the daemon presents the dial token at the ws
// upgrade (gates the endpoint), then the normal hello/vsht_ auth runs INSIDE
// the mux like every transport. Incoming dials land in a registry the
// device's transport waits on. ──
const agentdDials = new Map(); // deviceId → ws stream adapter (live dial)
// B-f3e8: the pairing credential lives ON the dial host record (hosts.json
// dialTokenHash) — dial-tokens.json is migrated once at boot (below, after
// HostManager construction) and there is no separate device registry anymore.
function agentdMintDialPair(deviceId) {
ensureDir(AGENTD_DIR);
const tok = 'vsdt_' + require('crypto').randomBytes(18).toString('hex');
hosts.setDialToken(deviceId, require('crypto').createHash('sha256').update(tok).digest('hex'));
// the device token (vsht_) for in-mux auth ships in the install payload
return { deviceId, dialToken: tok, hostToken: agentdHostToken('dial-' + deviceId) };
}
/** Full unpair of a dial machine (DELETE /api/hosts/:id on a dial record):
* mounts torn down, vsht_ token file gone, live stream destroyed. The token
* hash dies with the host record itself. */
async function unpairDialDevice(deviceId) {
try { await machineMounts.onMachineUnpaired(hosts.findByDeviceId(deviceId)?.id); } catch { }
try { portForwards.onMachineUnpaired(hosts.findByDeviceId(deviceId)?.id); } catch { }
try { exitProxy.onMachineUnpaired(hosts.findByDeviceId(deviceId)?.id); } catch { }
try { fs.unlinkSync(path.join(AGENTD_DIR, `host-dial-${deviceId}.token`)); } catch { }
const live = agentdDials.get(deviceId);
if (live) { try { live.destroy(); } catch { } agentdDials.delete(deviceId); }
agentdDialDevices.delete(deviceId);
}
// A DeviceManager over a DIALED-IN device (Transport B consumption): the
// device's daemon holds the mux-server end; we drive it (fs/serve-folder/
// tcp-forward) as the client over the live ws stream in agentdDials. Reused
// per device; reconnects follow the device's --dial retries (getStream picks
// up the fresh stream). Enables 'device' mounts + remote fs for NAT'd devices.
const agentdDialDevices = new Map(); // deviceId → DeviceManager
async function deviceForDial(deviceId, _retried = false) {
// FAIL FAST when the device isn't dialed in: the stream transport's connect
// loop otherwise backs off and retries FOREVER, so every operation against
// an offline device (session create, mount, test) HUNG instead of erroring
// (real report: create卡住/terminal空白/mount打不开 — Mac daemon died after
// a self-upgrade re-exec and nothing surfaced it).
const curStream = agentdDials.get(deviceId);
if (!curStream) throw new Error(`device "${deviceId}" is offline — its daemon is not dialed in (rerun the install command on it)`);
let dm = agentdDialDevices.get(deviceId);
// STALE-STREAM GUARD (real report: online=true but every fs op/session
// blank): the device re-dialed after a self-upgrade re-exec, so agentdDials
// holds a FRESH stream — but the cached DeviceManager's mux is still bound
// to the DEAD old stream, and its status().connected can lag true. Rebuild
// whenever the live stream differs from the one this dm connected over.
// A STOPPED dm must be treated exactly like a stale stream: stop() is
// terminal (_connectLoop throws 'stopped' forever), so reusing one wedges
// EVERY op against an otherwise-healthy device until the stream changes
// (real userW outage: hours of "offline"/'stopped' while the Mac was
// dialed-in and fine — a re-dial/unpair race stopped the cached dm).
if (dm && (dm._stopped || (dm._dialStream && dm._dialStream !== curStream))) {
try { dm.stop?.(); } catch { }
dm = null;
agentdDialDevices.delete(deviceId);
}
if (dm && dm.status().connected) return dm;
if (!dm) {
const { DeviceManager } = require('./src/agentd/client.js');
dm = new DeviceManager({
dataDir: path.join(__dirname, 'data'),
bundlePath: path.join(__dirname, 'data', 'bin', 'vibespace-agentd.js'),
version: require('./package.json').version,
transport: { kind: 'stream', hostToken: agentdHostToken('dial-' + deviceId), getStream: () => agentdDials.get(deviceId) || null },
log: (...a) => console.log('[device-dial]', ...a),
});
agentdDialDevices.set(deviceId, dm);
}
dm._dialStream = curStream; // remember which stream we bind the mux to
try {
await dm.connect();
} catch (e) {
// never leave a failed dm in the cache — the next op must rebuild clean
try { dm.stop?.(); } catch { }
if (agentdDialDevices.get(deviceId) === dm) agentdDialDevices.delete(deviceId);
// a dm stopped MID-CONNECT by a concurrent re-dial cleanup surfaces one
// transient 'stopped' — while the stream is live, rebuild once instead of
// failing the caller's FIRST op after a re-dial (seen live on the userW
// verification: test probe errored once, next op self-healed)
if (!_retried && String(e && e.message) === 'stopped' && agentdDials.get(deviceId)) {
return deviceForDial(deviceId, true);
}
throw e;
}
return dm;
}
async function ensureAgentdOnHost(hostId) {
const version = require('./package.json').version;
if (_agentdInstalled.get(hostId) === version) return;
const bundlePath = path.join(__dirname, 'data', 'bin', 'vibespace-agentd.js');
await hosts.installAgentd(hostId, bundlePath, version, agentdHostToken(hostId));
_agentdInstalled.set(hostId, version);
}
function daemonPtyShim(handle) {
let dataCb = null, exitCb = null;
handle.onData = (buf) => { if (dataCb) dataCb(buf.toString('utf-8')); };
handle.onExit = (code) => { if (exitCb) exitCb({ exitCode: code }); };
return {
_daemon: true,
get pid() { return handle.pid; },
onData(cb) { dataCb = cb; return { dispose() { dataCb = null; } }; },
onExit(cb) { exitCb = cb; return { dispose() { exitCb = null; } }; },
write(s) { try { handle.write(s); } catch {} },
resize(cols, rows) { try { handle.resize(cols, rows); } catch {} },
kill() { try { handle.kill(); } catch {} },
};
}
const CHAT_WRAPPER = path.join(__dirname, 'data', 'bin', 'chat-wrapper.js');
const CODEX_CHAT_WRAPPER = path.join(__dirname, 'data', 'bin', 'codex-chat-wrapper.js');
function ensureDir(dir) { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); }
// ── 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 {} }
}
}
// ── Stop-on-model-fallback belt (2.228.0, claude.disableModelFallback) ──
// The PRIMARY mechanism is the CLI's native switchModelsOnFlag=false
// (spawn --settings + mid-session apply_flag_settings) — with it armed no
// fallback ever happens and this never fires. The belt covers sessions whose
// CLI predates the toggle (spawned before it was enabled, or restored from
// before a server restart): the moment a fallback signal appears on the
// stream, interrupt the turn (same recipe as the ws 'interrupt' case) and
// tell the user why. Once per turn (_fallbackStopFired, cleared on result).
// ── Pooled pseudo-account auto-switch (B-6217 v2) ───────────────────────────
// Runs at each claude turn end for sessions billed to a pool with auto=on.
// Decisions read ONLY the passive usage cache (§ban-safety — never an API
// call); see src/account-pool-auto.js for the semantics. hot=on → just
// re-point (the running CLI re-reads the credential file on its next request);
// hot=off → also ask ONE connected client to cold-restart the affected
// conversations (headless instances degrade to hot behavior until a client
// appears — the switch itself never waits on a browser).
const { decidePoolSwitch, rankPoolMembers, SWITCH_THRESHOLD_PCT: POOL_HARD_PCT } = require('./src/account-pool-auto.js');
const _poolAutoLast = new Map(); // poolId → ts of last DECISION (eval gate)
const _poolSwitchAt = new Map(); // poolId → ts of last actual SWITCH (dwell belt)
// ── get_usage control channel + chat-mode limit banner (B-7edc/B-292b) ──────
// The get_usage control request makes the CLI (first-party client) fetch usage
// itself — strictly better ToS posture than our bare /api/oauth/usage call.
// HUMAN-TRIGGERED ONLY (the ⟳ button): auto-firing was REJECTED (2026-08-09,
// user decision) — a machine-initiated quota check is the automated-access
// pattern that got a real account banned. The passive chat-mode signal is the
// LIMIT BANNER instead (markLimitBanner below): zero calls.
const { ClaudeCodeAdapter } = require('./src/adapters/claude-code.js');
// ── usage ANCHOR recorder (dead-reckoning data foundation, 2.261.0) ─────────
// Sweeps local usage-cache snapshots for NEW ground-truth readings (any
// source: statusline / ⟳ / get_usage / limit banner) and appends them, with
// the ledger cost consumed since the previous anchor, to
// data/usage-anchors/anchors-<identity>.ndjson. Identity key = orgUuid >
// email > account id, so a sub's history SURVIVES remove + re-add (user
// requirement — a re-add mints a fresh sub-<hex> id). Zero API calls.
const { UsageAnchors, identityKeyFor, costBetweenMulti } = require('./src/usage-anchors.js');
const { UsageEstimator, overlayCache: estOverlayCache, predictCalib } = require('./src/usage-estimator.js');
const usageAnchors = new UsageAnchors({ dataDir: path.join(__dirname, 'data') });
// Which caches map to which identity (org-merge aware) — shared by the sweep
// and the estimator's per-account resolution. Reads roster + cache files only.
function usageIdentityGroups() {
const groups = new Map(); // identityKey → {accountIds:[], cache, accountId}
let files = [];
try { files = fs.readdirSync(USAGE_CACHE_DIR).filter((f) => f.endsWith('.json') && !f.startsWith('__models__') && !f.startsWith('host-') && f !== 'rates.json'); } catch { return groups; }
const roster = accounts.list().accounts || [];
for (const fn of files) {
try {
const accountId = fn === '__global__.json' ? null : fn.slice(0, -5);
const cache = JSON.parse(fs.readFileSync(path.join(USAGE_CACHE_DIR, fn), 'utf-8'));
if (!cache?.fetchedAt) continue;
const acctRec = accountId ? roster.find((x) => x.id === accountId) : null;
if (accountId && acctRec && (acctRec.type === 'pooled' || acctRec.backend === 'codex')) continue; // pools have no quota; codex economics are separate
const key = identityKeyFor({ accountId, cache, email: acctRec?.email });
const g = groups.get(key) || { accountIds: [], cache: null, accountId: null };
g.accountIds.push(accountId || '__global__');
// freshest cache is the identity's anchor source (the same real login can
// surface as BOTH __global__ and a named sub — one quota, two files)
if (!g.cache || cache.fetchedAt > g.cache.fetchedAt) { g.cache = cache; g.accountId = accountId; }
groups.set(key, g);
} catch { }
}
return groups;
}
// Dead-reckoning estimator (B-fcff v2): learned per-identity per-bucket rates
// over the anchor pairs, seeded with the measured Max-20x priors. Feeds the
// pool auto-switch an ESTIMATED bucket view and /api/usage an `estimates`
// field. Zero API calls; ledger + anchor files only.
const _identGroupsMemo = { at: 0, groups: null };
function usageIdentityGroupsCached() {
if (!_identGroupsMemo.groups || Date.now() - _identGroupsMemo.at > 30000) {
_identGroupsMemo.groups = usageIdentityGroups(); _identGroupsMemo.at = Date.now();
}
return _identGroupsMemo.groups;
}
const usageEstimator = new UsageEstimator({
anchorsDir: path.join(__dirname, 'data', 'usage-anchors'),
usageHistory: () => usageHistory, // declared far below — lazy ref (TDZ)
resolveIdentity: (accountId) => {
const want = accountId || '__global__';
for (const [identityKey, g] of usageIdentityGroupsCached()) {
if (g.accountIds.includes(want)) return { identityKey };
}
return null;
},
});
app.locals.usageEstimator = usageEstimator;
// ── OFFLINE-BIAS defense (2.297.0, design §Cross-device aggregation) ──
// A source is ACTIVE-DARK when the ledger holds RECENT events from it but its
// link is down: its spend keeps accruing invisibly, which biases estimates in
// the DANGEROUS direction (under → late pool switches). 30s memo — this runs
// inside pool decisions and the anchor sweep.
let _darkMemo = { at: 0, list: [] };
function darkSources() {
if (Date.now() - _darkMemo.at < 30000) return _darkMemo.list;
const list = [];
try {
const wm = usageHistory.sourceWatermarks();
const now = Date.now();
for (const [src, ts] of Object.entries(wm)) {
if (src === 'local') continue;
if (now - ts > 48 * 3600 * 1000) continue; // idle for 2 days — not dangerous
if (hosts.linkState(src) === 'offline') list.push({ host: src, lastEventTs: ts });
}
} catch { }
_darkMemo = { at: Date.now(), list };
return list;
}
// Which accounts a dark source taints: those with ledger events from that
// host in the last 7 days (per-account precision so an all-local pool never
// pays the pessimism tax for an unrelated machine's outage).
function darkTaintedAccounts() {
const dark = darkSources();
if (!dark.length) return {};
const taint = {};
try {
const since = Date.now() - 7 * 24 * 3600 * 1000;
const darkSet = new Set(dark.map((d) => d.host));
for (const ev of usageHistory._events(since, Date.now())) {
if (ev.host && darkSet.has(ev.host) && ev.acct && ev.atype !== 'host') taint[ev.acct] = DARK_PESSIMISM_PCT;
}
} catch { }
return taint;
}
const DARK_PESSIMISM_PCT = 8; // dock: ~1 long turn of 5h headroom / real weekly $
// Disarm a pool's device-side reflex (pool deleted / auto turned off) —
// without this the daemon kept executing a stale snapshot forever, and could
// even recreate a deleted pool's symlink during a server-down window.
async function clearSealedOrders(poolId) {
try {
_sealedOrdersSent.delete(poolId);
const dm = await hosts.device(null);
await dm.poolOrders({ clearPool: poolId });
} catch { }
}
const _sealedOrdersSent = new Map(); // poolId → last pushed JSON (skip no-ops)
let _poolOrdersWarned = false; // warn once per boot, never per tick
async function pushSealedOrders(poolId) {
const a = accounts.get(poolId);
if (!a || a.type !== 'pooled') return;
const members = accounts.poolMembers(poolId);
const ranked = rankPoolMembers({
members,
readCache: (id) => { try { return JSON.parse(fs.readFileSync(path.join(USAGE_CACHE_DIR, id + '.json'), 'utf-8')); } catch { return null; } },
nowSec: Date.now() / 1000,
}).map((m) => ({ id: m.id, dir: accounts.subDir(m.id), creds: accounts.subCredsPath(m.id) }));
const orders = { poolId, linkPath: accounts.subDir(poolId), ranked, currentId: accounts.poolCurrent(poolId) || null,
// Plan C: per-session links are additional MATCH+ACT targets — the daemon
// re-points exactly the link the banner session spawned against. Old
// daemons ignore this field and keep matching only the default link:
// reduced coverage on skew, never a wrong re-point.
linkPaths: (() => { try { return accounts.sessionPoolLinks(poolId).map((l) => l.path); } catch { return []; } })() };
const j = JSON.stringify(orders);
if (_sealedOrdersSent.get(poolId) === j) return;
const dm = await hosts.device(null); // device #0 — pools are local-only
// (the memo below is per-pool AND the daemon now stores per-pool slots, so a
// second pool's push can no longer evict the first — review finding)
await dm.poolOrders(orders, (events) => {
// fallback switches executed while this server was down: surface + let
// the by-time ledger attribution reconcile billing (it already keys on
// the symlink target's real account at scan time)
for (const ev of events) {
serverNotice('sealed-orders-' + ev.ts, `账号池 ${accounts.get(ev.poolId)?.name || ev.poolId} 在服务器离线期间因触限自动切换到 ${accounts.get(ev.to)?.name || ev.to}(sealed-orders 应急反射)`, { level: 'warn' });
try { console.log('[sealed-orders] device-executed fallback switch:', JSON.stringify(ev)); } catch { }
}
try { dm.ackPoolOrdersLog(); } catch { }
});
_sealedOrdersSent.set(poolId, j);
}
function sweepUsageAnchors() {
// GROUPED BY IDENTITY (2.263.0): recording per cache-file double-anchored
// org-merged logins (__global__ + named sub interleaved in one identity
// file, each record's costSince missing the sibling account's spend — real
// data bug caught in the ProblemFactory analysis). One identity = one
// anchor stream; cost sums across ALL its account ids.
for (const [identityKey, g] of usageIdentityGroups()) {
try {
const prev = usageAnchors.lastAnchor(identityKey);
const allIds = usageEstimator.accountIdsFor(identityKey, g.accountIds);
const costSince = prev ? costBetweenMulti(usageHistory, allIds, prev.fetchedAt, g.cache.fetchedAt) : null;
// calibration: what the CURRENT rates would have predicted for this new
// reading — recorded into the anchor for offline analysis + Diagnostics
let calib = null;
if (prev && costSince) {
try {
const newBuckets = {
fiveHour: g.cache.fiveHour ? { u: g.cache.fiveHour.utilization, resetsAt: g.cache.fiveHour.resetsAt } : null,
sevenDay: g.cache.sevenDay ? { u: g.cache.sevenDay.utilization, resetsAt: g.cache.sevenDay.resetsAt } : null,
scopedWeekly: (g.cache.scopedWeekly || []).map((s) => ({ name: s.name, u: s.utilization, resetsAt: s.resetsAt })),
};
calib = predictCalib(prev, newBuckets, usageEstimator.ratesFor(identityKey), costSince, (g.cache.fetchedAt - prev.fetchedAt) / 1000);
if (calib) for (const c of Object.values(calib)) global.__vsMetric?.('usage-est-err-pct', Math.abs(c.err) * 100);
} catch { }
}
// pairs recorded while ANY tainted source was dark must not teach rates
// (Δu real, cost missing ⇒ a falsely HOT rate) — mark the record so
// extractPairs voids pairs touching it (both sides of the gap).
const darkHosts = (() => { try { const t = darkTaintedAccounts(); return allIds.some((a) => t[a]) ? darkSources().map((d) => d.host) : []; } catch { return []; } })();
if (usageAnchors.maybeRecord({ identityKey, accountId: g.accountId, cache: g.cache, costSince, calib, accountIds: allIds, dark: darkHosts })) {
usageEstimator.invalidate(identityKey); // rates re-derive from the grown pair set
}
} catch { }
}
}
// boot-time sealed-orders push: a restarted server re-arms every pool's
// device-side fallback snapshot AND collects executions from its own down
// window (the report rides the pool-orders reply)
setTimeout(() => {
// Only AUTO pools (review finding): the runtime refresh is gated on a.auto,
// so arming a manual pool at boot let the device switch a pool the user
// explicitly set to manual — with a snapshot frozen at boot forever.
try {
for (const a of (accounts.list().accounts || [])) {
const full = accounts.get(a.id);
if (full?.type === 'pooled' && full.auto) pushSealedOrders(a.id).catch(() => { });
}
} catch { }
}, 15000);
setInterval(() => { try { sweepUsageAnchors(); } catch {} }, 60000);
setTimeout(() => { try { sweepUsageAnchors(); } catch {} }, 20000);
// ── Plan C (B-a612, 2.315.0): per-session pool placement ────────────────────
// One pool, many links: each session bills the member its OWN symlink points
// at. The chooser and the per-session switch pass both read quota through the
// SAME estimator-overlaid readCache the pool engine uses, PROJECTED to the
// session's model family (src/model-family.js): scoped caps of models this
// session is not running stop vetoing its placement; 5h/7d always count
// (nested buckets); an unknown family means NO projection — today's
// conservative semantics, never a relaxation on ignorance.
const { familyOfModel, projectCacheForFamily } = require('./src/model-family.js');
function poolReadCache(poolId) {
// the engine's readCache, extracted for reuse (identity-group freshest file
// + estimator overlay); kept here so chooser/switch/engine cannot drift
const now = Date.now();
return (id) => {
let raw = null;
try { raw = JSON.parse(fs.readFileSync(path.join(USAGE_CACHE_DIR, id + '.json'), 'utf-8')); } catch { }
try {
for (const [, g] of usageIdentityGroupsCached()) {
if (g.accountIds.includes(id) && g.cache && (g.cache.fetchedAt || 0) > (raw?.fetchedAt || 0)) { raw = g.cache; break; }
}
} catch { }
try { return estOverlayCache(raw, usageEstimator.estimateFor(id, raw, now)); } catch { return raw; }
};
}
function poolChooserForModel(poolId, { model } = {}) {
try {
const a = accounts.get(poolId);
if (!a || a.type !== 'pooled') return null;
const fam = familyOfModel(model);
const cur = accounts.poolCurrent(poolId);
if (!fam) return cur; // no identity → the pool's default target
const base = poolReadCache(poolId);
const readCache = (id) => projectCacheForFamily(base(id), fam);
// decidePoolSwitch FROM the default target under the projected view: if
// the default serves this family, stay (fewest distinct billing dirs);
// if it doesn't, the switch verdict IS the placement.
const { decidePoolSwitch } = require('./src/account-pool-auto.js');
const d = decidePoolSwitch({ currentId: cur, members: accounts.poolMembers(poolId), readCache, nowSec: Date.now() / 1000, hot: true });
return (d && d.to) || cur;
} catch (e) { console.warn('[pool] chooser failed (falling back to default target):', e.message); return null; }
}
// The session's model identity, per the user's spec: the LAST assistant
// message's served model vs the last set-model pick — newest wins — else the
// spawn model. Any unknown → null (no projection).
function sessionModelFor(s) {
const served = s._servedModel ? { m: s._servedModel, at: s._servedModelAt || 0 } : null;
const picked = s._pickedModel ? { m: s._pickedModel, at: s._pickedModelAt || 0 } : null;
const newest = served && picked ? (picked.at >= served.at ? picked : served) : (picked || served);
return (newest && newest.m) || s._spawnModel || null;
}
const _vsuPending = new Map(); // request_id → {resolve, timer}
function resolveUsageKey(session) {
let acct = session._accountId || null;
try { if (acct && accounts.get(acct)?.type === 'pooled') acct = accounts.poolCurrentFor(acct, session._webuiId || null) || acct; } catch {}
return acct || '__global__';
}
function writeUsageCacheForKey(key, parsed) {
try {
const f = path.join(USAGE_CACHE_DIR, key.replace(/[^\w.-]/g, '_') + '.json');
let prev = {}; try { prev = JSON.parse(fs.readFileSync(f, 'utf-8')) || {}; } catch {}