Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1717 lines (1665 loc) · 201 KB
/
Copy pathserver.js
File metadata and controls
1717 lines (1665 loc) · 201 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
require('./src/server/runtime-boot.js').boot({ rootDir: __dirname }); // lane runtime-floor: FIRST — a newer data/runtime/current node replaces this process (same pid; the unit / run.sh / a pod's entrypoint unchanged), then the [runtime] verdict line + the boot pull's check
// 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'; require('./src/server/hub-port.js').claim(); // the B2b cure, law 2: the start word VIBESPACE_START_FD leaves the environment HERE, before the boot's first child (which dtach, the CLI probes) — test-hub-port ⑧ pins the order
const bootTrace = require('./src/server/boot-trace.js').start({ dataDir: require('path').join(__dirname, 'data') }); // THE BOOT HOLDS (B-1319): the boot's own loop clock from here — GET /api/boot-trace, data/boot-trace.json
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const pty = require('node-pty');
const path = require('path');
// STORE TIMING (design 011 lane 1): every named store's sync write / big read is timed from here on (src/timed-sync.js);
// VIBESPACE_STORE_TIMING=0 turns the clock off. On before any store is constructed, so the boot reads are counted.
const storeTiming = require('./src/timed-sync.js');
storeTiming.enable(process.env.VIBESPACE_STORE_TIMING !== '0');
const fs = require('fs');
const os = require('os');
const { spawn } = require('child_process'); // no sync child here (lane hub-sync-holds: the census — scripts/loop-child-census.mjs)
const compression = require('compression');
const { MessageManager, driftLedgerRows } = require('./src/message-manager');
const { sameToken } = require('./src/pairing-token'); // B-8dda: a vsst_ compare in constant time
const { createMessageManager, feedLive, feedPeerCard } = require('./src/normalizers');
const { Telemetry } = require('./src/telemetry');
const { SyncStore } = require('./src/sync-store');
const { cwdToProjectDir, SessionMessages, findSessionJsonlPath, dedupWebuiSockets } = require('./src/session-store');
const { addressableId } = require('./src/claude-lock-capture'); // verify r5 (channel-withdraw): the roster's own-id rule — a pending fork is nobody's address
const { readChildPids } = require('./src/cli-identity'); // THE process reader — /proc first, ONE `ps` table where there is none, never a fork per item
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 || Object.values(process.env).some((v) => String(v).split(path.sep).includes('provider-homes'))) { // …or a provider conversation's shell of any harness: its plan's home is the fingerprint (lane lg-providers U2 cure)
const stripped = [], plan = require('./src/server/provider-spawn.js').inheritedPlanNames(process.env), inside = !!(process.env.CLAUDECODE || process.env.CLAUDE_CODE_CHILD_SESSION); // the plan: only what a home proves; the CLI's own names: only inside Claude Code
for (const k of Object.keys(process.env)) {
if ((inside && (k === 'CLAUDECODE' || k === 'CLAUDE_EFFORT' || k.startsWith('CLAUDE_CODE_') || k.startsWith('CLAUDE_WEBUI_'))) || plan.includes(k)) {
stripped.push(k);
delete process.env[k];
}
}
if (stripped.length) console.warn(`[env] Server was started from inside an agent conversation — 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); }
// NO UPDATE RUNS INSIDE THE BOOT (lane hub-sync-holds, rank 12a; the owner 2026-11-11: «去掉吧»): a restart of ANY cause — the
// unit's respawn, a reboot, run.sh's loop — keeps the version it has. An update has ONE road: ⚙ → Update VibeSpace…
// (scripts/update.sh: pull, install, build, then the restart). The boot pull held the owner's hub 5.5 s before its first loop
// turn, right after update.sh had pulled; it is gone with its module. NO_AUTO_UPDATE (the images) still turns off the boot's
// runtime check (src/server/runtime-boot.js, a child 20 s after listen); «a newer version exists» is GET /api/version (the gear
// menu's vX → vY), which never applies anything.
// A THROWAWAY server — B-ba47 shape H's ONE test (src/server/throwaway-root.js, decided at the boot's first act): a linked worktree, or a temp root handed a temp home
const throwawayRoot = require('./src/server/throwaway-root.js').throwaway(__dirname);
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.
// The agent CLIs are re-resolved at SPAWN time when the boot answer went stale
// (B-a18e, the installer-window restart) ⇒ src/server/cli-cmd.js
const { resolveCmd } = require('./src/server/cli-cmd.js');
const DTACH_CMD = resolveCmd('dtach');
const NODE_CMD = process.execPath; // no ENV_CMD (lane antigravity-spawn-argv): a session's names ride its spawn's env, never an `env K=V` line (src/spawn/line.js)
// ── 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, harnessAvailability, noteHarnessModels, cliCmds,
} = require('./src/server/cli-env.js').create({
rootDir: __dirname, CLAUDE_CMD_RAW, CODEX_CMD_RAW, resolveCmd, serverSetting: (k) => serverSetting(k),
getOAuthToken: (...a) => getOAuthToken(...a),
usagePollingEnabled: (...a) => usagePollingEnabled(...a),
refreshHarnessModels: (...a) => refreshHarnessModels(...a), broadcast: (m) => bcastAll(m), getTelemetry: () => { try { return telemetry; } catch { return null; } }, getPlugins: () => { try { return plugins; } catch { return null; } }, // S9: opencode serve caps verdict → 'harness-caps-updated'; runaway telemetry + the 'opencode-serve' PLUGIN is the autostart switch (lazy — both defined below)
getHeldPtyIds: () => { try { return [...activeSessions.values()].map((s) => s?._opencodePtyId).filter(Boolean); } catch { return []; } }, // S9 r4: the ONE reader of session._opencodePtyId — the serve-pty reaper's keep set (lazy like getPlugins: activeSessions is declared below)
});
// ── Harness model lists: every descriptor's models({dataDir}) — codex: its CLI's
// own model cache (src/harnesses/codex-models.js); claude's list is cli-env's
// refreshAvailableModels, ACP agents report theirs (noteHarnessModels).
function refreshHarnessModels() {
for (const h of require('./src/harnesses').list()) {
if (typeof h.models !== 'function') continue;
try { const list = h.models({ dataDir: path.join(__dirname, 'data') }); if (list) AVAILABLE_MODELS[h.id] = list; } catch { }
}
}
refreshHarnessModels();
setTimeout(refreshAvailableModels, 3000);
setInterval(refreshAvailableModels, 3600000); // refresh hourly
const HOST = process.env.HOST || '0.0.0.0';
const app = express();
const hubForm = require('./src/server/hub-port.js').decide(); hubForm.then((d) => require('./src/server/hub-port.js').endBadStart(d)); let hubPort = null; // B2b: the start decides the hub's port (the start word VIBESPACE_START_FD names a start pipe ⇒ piped; no word ⇒ plain, no descriptor looked at) — read before listen, off the loop
const server = http.createServer(app); const hub = require('./src/server/tls.js').create({ app, httpServer: server, dataDir: path.join(__dirname, 'data'), port: PORT, onCertificate: (pem) => require('./src/server/hub-port.js').certificate(pem), serverSetting: (k) => serverSetting(k), getUserTodos: () => userTodos, log: console, tailscaleBin: throwawayRoot && !process.env.VIBESPACE_TAILSCALE_BIN ? null : undefined, step: (name, fn) => bootTrace.step(name, fn) }); // lane https-tailscale: ONE port, two servers — hub.front peeks each connection's first byte (TLS → https, else http), every listener reaches both through hub.attachToServers (test-architecture §89); a throwaway root never asks the real tailscale ⇒ src/server/tls.js
// ── 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 signinWitness = require('./src/server/hub-port.js').piped() ? null : { env: process.env, throwaway: throwawayRoot ? 'throwaway' : false }; // B-dc3f (1): the PLAIN form's witness (主开发 r2341) — the piped form's hub opens no file
const auth = new (require('./src/server/hub-port.js').piped() ? require('./src/server/piped-auth.js').PipedAuth : Auth)(path.join(__dirname, 'data'), { clerk: clerkAuth, witness: signinWitness, todos: () => userTodos }); // B3b-1: piped ⇒ the interface holds the sign-in table, this hub opens no file
{
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');
}
{ const line = auth.bootLine(); if (line) console.log(line); } // B-dc3f: «ENABLED», or HELD by name while the sign-in file cannot be read
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();
});
app.use(auth.middleware()); // FIRST — the cookie gate + the same-origin rule stand before every route, the auth routes too (test-auth census)
auth.registerRoutes(app);
const cspReports = require('./src/server/csp-reports.js').create({ dataDir: path.join(__dirname, 'data'), file: process.env.VIBESPACE_CSP_REPORTS_FILE, getUserTodos: () => userTodos, log: console }); cspReports.register(app); // lane app-page-csp (q-043 D6): the app page's REPORT-ONLY policy (src/app-csp.js) + POST /api/csp-report — before the json parser (it reads its own ≤ 32 KB)
require('./src/server/frame-host.js').register(app); // lane design-frame-host (B-8679) + frame-host-preview (B-5b2c): GET /frame-host?kind=design|mail|preview|eml|docx — the ONE host document a frame the page makes navigates to, its kind's policy as a real header (a srcdoc frame would run under the app page's); the preview's folder /frame-host/f/<token>/ (a door — src/auth.js)
// 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; }
});
const launchGround = require('./src/launch-ground.js'); // PURE (B-78db, r4463 fault 2) — required INSIDE the route: test-csp-report runs this route from its own text
const launchImage = require('./src/launch-image.js'); // PURE (B-78db (B), r4481) — inside the route for the same reason
const ground = launchGround.groundOf(req.headers.cookie); // the launch ground's OWN cookie (vs_ground: a colour or nothing) — never the session's; test-auth declares this one read
html = launchImage.withLinks(html, ground); // the home-screen copy's launch image, in the colour the page itself paints first
html = launchGround.withGround(html, ground); // the launch wears the stored theme's ground from the first paint
res.set('Cache-Control', 'no-cache'); res.set(...cspReports.header()); // the app page: Content-Security-Policy-Report-Only (never the enforcing header — a later lane's switch)
res.type('html').send(html);
} catch { next(); }
});
// THE LAUNCH IMAGE (B-78db (B), 主开发 r4481): a home-screen copy's startup image — ONE solid colour of a listed size, made on request
// (src/launch-image.js; any other size is a 404, any other colour today's dark). A page behind the sign-in like every other
app.get('/launch-image/:size', (req, res) => {
require('./src/launch-image.js').imageFor(req.params.size, req.query.g).then((png) => {
if (!png) return res.status(404).end();
res.set('Cache-Control', 'private, max-age=86400'); res.type('png').send(png);
}, (e) => { console.warn('[launch-image] ' + (e && e.message)); res.status(500).end(); });
});
app.use(require('./src/server/static-public.js').create(path.join(__dirname, 'public'))); // lane vault-chip-zone-errors: public/ through express.static — every file but a source map (served to nobody; test-csp-report ⑨)
// 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 });
// Proxied requests must reach unblocker with their body UNREAD — express.json
// consuming a proxied JSON POST forwarded a body-less request that hung the
// target on Content-Length (inc-mt2bpw2f: page rendered, every button dead).
// Skip here rather than mount unblocker earlier: auth must keep covering /proxy/. lane webhook-l1-server: /hook/<slug> + the pairing read their OWN raw bytes after their refusals.
const jsonBody = express.json({ limit: '50mb' }), OWN_BODY_RE = /^\/(?:proxy\/|hook\/|api\/channels\/webhook\/[^/]+\/pair$|api\/feedback\/forward$)/; // lane feedback-forward: the hub's forward door reads ≤ 64 KB AFTER its token
app.use((req, res, next) => (OWN_BODY_RE.test(req.path) || (persistenceRouter.ownsBody && persistenceRouter.ownsBody(req.path)) ? next() : jsonBody(req, res, next))); // lane sidebar-echo-order r13 (law C): the ops door reads its own body — skipped here by its parser's OWN match (the router's), never a second expression
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 f = require('./src/sock-path.js').socketPathFits(path.join(SOCKETS_DIR, 'cw-' + 'x'.repeat(36)), process.platform); if (!f.fits) console.warn(`[boot] socket paths under data/sockets would exceed ${f.max} bytes (${f.bytes}) — dtach cannot bind them; move the checkout to a shorter path`); } // the socket-path census (src/sock-path.js, lane-pairing ④): the operator's depth, said once
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): src/server/home-rename.js — B-8033: one marker per half (the projdirs
// move's with the HOME it changes, ~/.vibespace; the recorded-path rewrite's in this data/)
require('./src/server/home-rename.js').migrateHomeRename({ dataDir: path.join(__dirname, 'data'), metaDir: META_DIR });
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: the vault's entry `host:<id>` once it is set up (LOCKED ⇒ refused `vault_locked` by name; before
// the setup the 0600 file as before) — src/server/host-tokens.js (lane vault-e2e-password-fix-r2); no attach config holds it.
const AGENTD_DIR = path.join(__dirname, 'data', 'agentd');
function ensureDir(dir) { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); }
const hostTokens = require('./src/server/host-tokens.js').create({ dataDir: path.join(__dirname, 'data'), agentdDir: AGENTD_DIR, anyHubPin: () => (hosts.held() ? true : hosts.list().filter((h) => !!h.hubPinned).map((h) => h.name || h.id)), nameOf: (k) => { const h = String(k).startsWith('dial-') ? hosts.findByDeviceId(String(k).slice(5)) : hosts.get(k); return (h && h.name) || null; } }); // nameOf: a LOCKED refusal names the machine (lane vault-locked-refusal-notice)
function agentdHostToken(hostId) { return hostTokens.tokenFor(hostId); }
// 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, gateDialUpgrade, admitDial, noteDialEvent, lockOutDialHolder, wsStream, adoptDialStream,
} = require('./src/server/dial-pairing.js').create({
rootDir: __dirname, AGENTD_DIR, bcastAll: (...a) => bcastAll(...a),
agentdHostToken: (...a) => agentdHostToken(...a), hostTokenLocked: (id) => hostTokens.lockedWhy(id), dropHostToken: (id) => hostTokens.drop(id), hubIdentity: () => hostTokens.identity(), // + lane lg-remote-hardening D3b: this hub's own key
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; } }, getDialHealth: () => { try { return dialHealthWatch; } catch { return null; } },
});
// ── Cached webuiPids (PIDs managed by webui dtach sessions) ──
// childPid from the pty-wrapper meta file + that wrapper's children from /proc
// (readChildPids) — NEVER a fork per session: this runs on every kill and 3 s
// after every create, and the `pgrep -P` it replaces cost 9.16 s of blocked
// loop at 61 sessions / 1.5 GB RSS. Fork essay: src/cli-identity.js.
// lane hub-loop-stalls, unit 1 of (g) (主开发 r6456): NO READ ON THE LOOP — the side files are read in ONE PASS by fs.promises
// (src/server/webui-pids.js), the new set swapped at the pass's end (this same Set), passes never overlapping (a call during one asks
// for one more after it). The release read every live session's side file in a row, in-band: one slow file held a start, a create's
// +3 s and a kill each for its whole read. A reader that judges on the set or a child pid awaits the pass in flight (settled()).
const webuiPids = new Set();
const webuiPidsPass = require('./src/server/webui-pids.js').create({ activeSessions, buffersDir: BUFFERS_DIR, set: webuiPids, readChildPids });
// the claude adapter's Stop fallback (a SIGINT by the child's birth, 2 s after a Stop) awaits the pass in flight when the child is not
// yet known — handed through its config, as cliCmds hands claudeCmd (the adapter is a device input: it requires no hub module)
{ const ad = adapterRegistry.get('claude'); if (ad) { ad.config.pidsPending = () => webuiPidsPass.pending(); ad.config.pidsSettled = () => webuiPidsPass.settled(); } }
// a pass of the pid set (one more after the one in flight) → its promise; callers that only ask need not await it
function refreshWebuiPids() { return webuiPidsPass.refresh(); }
// ── 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', 'control_cancel_request', 'tool_progress', 'stream_event', 'summary', // control_cancel_request: the normalizer settles the card it withdraws (a helper stopped mid-ask, lane S1) — listed so the breadcrumb stops crying 'unhandled' (the naive-study log line)
'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)
'command_lifecycle', 'queued_input', 'queue_changed', 'queue_op_result', 'queue_dropped', 'input_handover', 'queue_settle', 'frame_stamp', 'rewind_out', // command_lifecycle: handled since 2.369.112 — the turn-start carrier of a harness-delivered peer message (inc-mu6bfv1t-4drq); the four queue records are the WRAPPER's (2.369.354, data/bin/chat-wrapper.js holds a mid-turn frame) — the normalizer reads them, the put-back door reads queue_dropped at its gate; input_handover (2.369.361) = what became of a frame handed to the running turn
'set_in_progress_tool_use_ids', 'compact_progress', 'tombstone', '_stdin_ack', '_stdin_nack', '_remote_state', '_remote_exit', '_fence', // B3 §2.5/§2.10/§2.11: the run set + compaction stage have readers in claude-stream-json.js, tombstone in the normalizer — listed here or the breadcrumb cries 'unhandled' for handled records (the 2.289.0 mistake). Round 4: the first two have never been observed on our stdout (host callbacks swallow them; the live compaction lane is system/status) and tombstone is unverified — the rows stay because the READER exists, which is what this set is about
]);
const _seenStreamTypes = new Set();
// THE session broadcast choke point ⇒ src/server/session-broadcast.js (perf lane
// chunk D): stamps `seq` on the session's own `msg` frames from its op ring and
// cuts a capable client whose send queue stopped draining (ONE `lagged` frame).
const { broadcastToSession } = require('./src/server/session-broadcast.js').createSessionBroadcast();
// ── Usage + pool engine (src/server/usage-pool-engine.js, decomposition #5) ──
const {
_vsuPending, usageAnchors, usageEstimator,
armWorkflowUsageWatcher, darkSources, darkTaintedAccounts, kickPoolEval,
markLimitBanner, maybePoolAutoSwitch, maybePoolAutoSwitchForPool, notePoolAuthFailure, noteTurnStopped, memberRemoved, decideDefaultTarget, fallbackDefaultTarget, removalTargetFor, setConversationPin, gatherPlan, pinAllPlan, pinAll, clearPinsTo, answerCrossProviderAsk, purgePoolMadeMoves, fallbackMoveBack, fallbackStatus, fallbackFactOf,
maybeRepinLockedModel, maybeStopOnFallback, modelsMatch, onMemberReadingFresh, claimPressTest, onMemberLoginSuccess, autoCliReady, memberServeLapsed, lastMemberReadAt, projectionRereadFor, projectionBillingIndex, // …+ the new-member wake (2026-09-08) + its LOGIN half, handed to the account routes (2026-09-29: read there since 2026-09-08, never passed — dead until now)
apiDerivedWindow, establishedWindows, repairIdentityAnchors, oatAnswer, oatIdentityAttach, oatRebind, // B-855a: the two identity witnesses handed to setupUsage — the panel probe may only write the account it proves — + c2's STANDING identity repair (boot + POST /api/usage/repair-identity)
poolChooserForModel, poolReadCache, probeUsageForAccountKey, readRawUsageCache, spendGuard, // the ONE raw usage-cache read (overage lives there — design §1.4) + THE SPEND CEILING (§4.4c): ONE authorizer in front of every turn nobody typed, per credential slot, persisted ⇒ src/server/spend-guard.js
noteTurnRunning, noteTurnStart, noteTurnError, clearStoppedBy, sessionWallVerdict, noteSessionProduced, noteModelRequest, noteCompacted, noteTurnEnd: noteTurnEndEngine, noteWallSignal, noteStreamRecord, recordIsLate, beforeAutoResumeFire, beforeClaimFire, fireIdentityFor, noMemberOf, memberLoginState, probeUsageViaSession, recordCodexQuotaSignal, recordRateLimitEvent, resolveUsageKey, noteServedModel, noteModelFallback, servedDefinesModel, rerouteAnnouncedBy, settleTurnLane, // …+ the SERVED-MODEL pair + its FALLBACK PREDICATE (r3-r2: the parse's target-less lock latch asks it, so a classifier substitute never becomes the lock target that defines placement) + the REROUTE THIS RECORD ANNOUNCES (r4: placed BEFORE the served capture at both feeds — the incident's first announcement rides the very record the substitute answered) + the per-turn LANE settle (2026-09-13 r3): both stdout feeds destructure them from the `engine:` literals below, and neither was exported here — the whole round-1 fix was a TypeError in production
quotaVerdictFor, sessionModelFor, sweepUsageAnchors, usageCacheKeyFor, resetCreditOffer, resetCreditPreview, consumeResetCreditFor, claimColdRestarts, refreshCodexForPerson, settleResetCreditByRead, catchUpResetCreditFromBuffer, // the stored reset credits the auto-resume arm card offers (design-reset-credits §5) + the manual use's preview/POST (p2) + verify r1: the session path's read before a press over an unsettled attempt
usageIdentityAccountIds, usageIdentityGroups, usageIdentityGroupsCached, usageIdentityGroupsMemo, cacheFactsOf, flushRequestStamps, // cacheFactsOf + flushRequestStamps: each live conversation's prompt-cache facts for the session list (lane cache-warmth-tiles)
writeUsageCacheForKey, clearSealedOrders, pushSealedOrders,
estOverlayCache, predictCalib, heldWordsLifted,
} = require('./src/server/usage-pool-engine.js').create({
app, rootDir: __dirname, USAGE_CACHE_DIR, activeSessions, wss, WS_OPEN,
broadcastToSession, getAutoResume: () => { try { return autoResume; } catch { return null; } }, getRestartRoad: () => { try { return { end: wsApi && wsApi.convOps && wsApi.convOps.endConversation, line: resumeLine, reopen: typeof resumeRoad.reopen === 'function' ? (item, o) => resumeRoad.reopen(item, o) : null, personEnded: wsApi && wsApi.convOps && typeof wsApi.convOps.personEndDuring === 'function' ? (s, id, at, o) => wsApi.convOps.personEndDuring(s, id, at, o) : null }; } catch { return null; } }, getQuotaProbe: () => { try { return usage.refreshViaCliPanel; } catch { return null; } }, usageDoor: () => require('./src/usage-routes').panelDoorRefusal(serverSetting) /* B-d7c4: the lift's one ask of the door */, // both lazy: created further down (TDZ otherwise); otelIngest = B-b3cd org verification
serverNotice: (...a) => serverNotice(...a),
serverSetting: (...a) => serverSetting(...a),
harnessSetting: (...a) => harnessSetting(...a), harnessDeclares: (...a) => harnessDeclares(...a), // typed per-harness reads (limitResetCredit / disableModelFallback) — lazy: harnessConfig is built further down
getAccounts: () => { try { return accounts; } catch { return null; } },
getHosts: () => { try { return hosts; } catch { return null; } },
getUsageHistory: () => { try { return usageHistory; } catch { return null; } }, onSessionListChange: () => { try { broadcastActiveSessions(); } catch { } }, // lane auto-resume-bulk: a stop fact appeared / cleared ⇒ the card's chip + the filter's count
recordUsageAttribution: (...a) => recordUsageAttribution(...a),
adapterRegistry, readUserState: () => { try { return persistenceRouter.readUserState(); } catch { return {}; } }, getUserTodos: () => { try { return userTodos; } catch { return null; } }, // lazy: the inbox a refused spend is reported in is created further down (TDZ otherwise)
getSessionMetaStore: () => { try { return { readSessionMeta, writeSessionMeta, patchSessionMeta }; } catch { return null; } }, // lazy too (session-stdout is built below): the ONE use is persisting the classifier-reroute stamp so a RESTORED conversation still knows the CLI answers with a model we did not ask for (r3)
});
// noteTurnEnd ALSO wakes the delivery ladder's retry park (lane notify-retry, 2026-10-01): a parked notification is posted the
// moment the conversation's turn ends (claude `result` / codex `task_complete` / ACP) — the stdout consumers keep the ONE name
const noteTurnEnd = (s, m) => { noteTurnEndEngine(s, m); try { deliver.noteTurnEnd(s); } catch (e) { console.warn('[deliver] turn-end hook failed:', e && e.message); } try { consumeKeptOf(s, m).catch((x) => console.warn('[kept] turn-end consume failed:', x && x.message)); } catch (e) { console.warn('[kept] turn-end consume failed:', e && e.message); } }; // B-a5a4 (2): a resume that RAN consumes its kept copy
// ── 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, patchSessionMeta,
deleteSessionMeta, sessionMetaOwnerConflict, _metaTombstones,
applyTaskToolUpdate, emitTaskListTodos, updateSessionTodos, reattachLocalPty, ptyQuietSince, writeSessionInput,
} = 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, // EVERY name the registered consumers destructure from `engine` must be here — test-fable-cap-pool-storm §10 derives that set from their own `const {…} = engine;` and fails THIS literal (r3: two were missing and every claude chat record became raw output)
noteModelRequest, // the conversation's last model request — the claude parse's stamp writer (lane cache-warmth-tiles)
noteCompacted, // a compaction's end resets the cache fact — the claude parse's call (lane cache-warmth-compact)
maybePoolAutoSwitch, maybeRepinLockedModel, maybeStopOnFallback, notePoolAuthFailure, sessionModelFor, // sessionModelFor: the acp-events wall road's model (lane agy-wall-signal r2)
modelsMatch, noteSessionProduced, noteTurnEnd, noteTurnStopped, noteWallSignal, noteTurnRunning, noteTurnStart, noteTurnError, recordCodexQuotaSignal, catchUpResetCreditFromBuffer, recordRateLimitEvent, resolveUsageKey, usageEstimator, noteStreamRecord, recordIsLate, noteServedModel, noteModelFallback, servedDefinesModel, rerouteAnnouncedBy, settleTurnLane }, // noteTurnEnd = the hooked wrapper above (the park); catchUpResetCreditFromBuffer = lane reset-path's buffer-file catch-up (codex-events — wired at the 2.369.202 integration)
checkClaudeGoalStatus, serverNotice: (...a) => serverNotice(...a), // r3749: the owed change's one notice to the person
broadcastToSession,
broadcastActiveSessions: (...a) => broadcastActiveSessions(...a),
noteModelSeen: (...a) => noteModelSeen(...a),
noteHarnessModels: (...a) => noteHarnessModels(...a), // ACP harnesses learn their model list from the agent (S8)
recordUsageAttribution: (...a) => recordUsageAttribution(...a),
daemonPtyShim: (...a) => daemonPtyShim(...a), agentEnv: (...a) => require('./src/ws-handler').agentEnv(...a), onLocalReattach: (...a) => bridgeWatch.afterReattach(...a), // the ONE local re-attach spawns with the sanitized env; every re-attach tells the dead-bridge watch (lane-dead-bridge)
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; } }, getDeliver: () => { try { return deliver; } catch { return null; } }, getPages: () => { try { return publishedPages; } catch { return null; } }, getPermissionRules: () => { try { return permissionRules; } catch { return null; } }, // lazy getters; getPages = SendUserFile hands the user a private link (published-pages is created further down)
getExitProxy: () => { try { return exitProxy; } catch { return null; } }, // verify-r2 A3-r2 / ask-a: the exit path ends a dead conversation's pairs + asks
getBrain: () => { try { return sessionBrain; } catch { return null; } }, getSyncStore: (name) => { try { return getSyncStore(name); } catch { return null; } }, // design-unknown-records: the four record→side-effect consumers the parse shares with the device feed (session-brain is created further down); lane stop-refills-composer: Stop's put-back writes the drafts store (built further down — read at record time)
});
// ── Boot restore (src/server/boot-restore.js, decomposition #7) ──
// migrations + restoreSessions + R6 pipe re-open + keeper re-adoption.
const { migrateLegacyHomeProjects, restoreSessions, restoreAgentdPipeSessions,
readoptOrphanKeeperSessions, probeSockets, probeFacts, stoppedSessions, keepEnded, endFactsBefore, keptRecordOf, consumeKeptOf, // stoppedSessions: the kept metas read back (lane dead-socket-keeps-chat-meta); keepEnded: an end on purpose (lane end-obeys-verdict); keptRecordOf: one ended conversation's record (the resume verb reads it); consumeKeptOf: at a turn end (B-a5a4 (2))
} = require('./src/server/boot-restore.js').create({
rootDir: __dirname, PORT, BUFFERS_DIR, META_DIR, SOCKETS_DIR, DTACH_CMD,
NODE_CMD, CHAT_WRAPPER, activeSessions, sessionCounterRef,
attachToDtach, setupSessionPty, readSessionMeta, writeSessionMeta,
deleteSessionMeta, broadcastToSession,
broadcastActiveSessions: (...a) => broadcastActiveSessions(...a),
refreshWebuiPids: (...a) => refreshWebuiPids(...a),
getHosts: () => { try { return hosts; } catch { return null; } },
getDialBridge: () => { try { return dialBridge; } catch { return null; } }, getExitProxy: () => { try { return exitProxy; } catch { return null; } }, note: (line) => bootTrace.note(line), step: (name, fn) => bootTrace.step(name, fn), // B-cd4b unit 3: the later registration batches named in the boot trace · B-92a4: the re-probe un-adopts through the exit proxy's onSessionEnd; its lines ride the boot trace (⚙ Diagnostics)
agentEnv: (...a) => require('./src/ws-handler').agentEnv(...a), // lane spawn-env-debts: the remote chat re-adopt's transport env (as ws-create's r6Env)
}); bootTrace.span('restore-probes', probeSockets(), probeFacts); // B-1319: the restore's fuser questions and its pairs' side-file reads start now, the questions as children — the server listens once they answered (below); B-92a4: or at the cap, the span naming what did not answer
// ── Agent-tool generators + hook registration (src/server/agent-tool-generators.js) ──
const hooksLate = require('./src/server/hooks-late.js').create({ activeSessions, getSessionStatus: () => sessionStatus, getUserTodos: () => userTodos, sessionStatusKey: (...a) => sessionStatusKey(...a), harnesses: require('./src/harnesses'), log: (...a) => console.log(...a), warn: (...a) => console.warn(...a) }); // lane hooks-create: a hook file CREATED by the registration ('dir-exists') is told to the conversations that predate it (one free note each + ONE For-you line); held until ready() after the boot restore; owns POST /api/cli-config/apply
// lane browser-resource-care (B-afeb): memory pressure reaches the owner — ONE For-you item per episode naming who started each
// process group (fed by sysinfo.startWatch's onSample below); a conversation's own Chrome (debugging port, no keeper mark) is told
const memoryPressure = require('./src/server/memory-pressure-watch.js').create({ activeSessions, BUFFERS_DIR, getUserTodos: () => userTodos, getSessionStatus: () => sessionStatus, sessionStatusKey: (...a) => sessionStatusKey(...a), jobsWiringOf: () => { try { return jobsWiring; } catch { return null; } }, getKeeper: () => { try { return require('./src/server/browser-keeper.js').keeper(); } catch { return null; } }, log: console });
const {
AGENT_BIN_DIR, EDITOR_DIR, EDITOR_CMD, STATUS_CMD, USAGE_STATUSLINE_CMD, HOOK_CMD,
createEditorHelper, createStatusHelper, createHookHelper, userStatuslineCmd,
ensureAgentHooks, stripAgentHookEntries, removeAgentHooks, hookRegistrationSafe, ownerWriteRefusal, refuseOwnerWrite, rootRecovery, rootFactsNow, onRootLanded, // B-1425: the root facts a caller that can wait awaits
agentHooksStatus, optOutMarkNow, // B-f276 (s1126): the opt-out mark by the store-read law — 'opted-out' | 'not' | { unread } (was an existsSync)
} = require('./src/server/agent-tool-generators.js').create({ rootDir: __dirname, port: PORT, onHookFileCreated: (ev) => hooksLate.noteCreated(ev), applyThisMachine: (o) => harnessConfig.applyThisMachine(o), homeRead: (fn, ms, opts) => harnessConfig.homeRead(fn, ms, opts) }); // B-ddf3 u2 line 1: this machine's hooks through the shipped helper
// ── Harness settings (src/server/harness-config-sync.js; docs/design-harness-settings.zh.md) ──
// THE typed accessors over the descriptor-declared tables (harnessSetting /
// harnessDeclares / harnessSpawnSettings — threaded to ws-create and the pool
// engine via deps, never a literal harness id) + the CLI-config plan every
// machine applies (local: in-process below; remote: VIBESPACE_CLI_CONFIG on the
// install/prelude/dial sites in hosts.js and ws-create.js).
const harnessConfig = require('./src/server/harness-config-sync.js').create({
serverSetting: (...a) => serverSetting(...a), harnesses: require('./src/harnesses'), adapterRegistry, activeSessions, hookRegistrationSafe, ownerWriteRefusal, refuseOwnerWrite, rootRecovery,
log: (...a) => console.log(...a), warn: (...a) => console.warn(...a), helperPath: path.join(__dirname, 'data', 'bin', 'vibespace-hook-register.mjs'), hooksWanted: () => integrationEnabled() && optOutMarkNow() === 'not', // B-ddf3 u2 line 1: THIS machine served by the shipped helper through the starter (no in-process write)
}); require('./src/server/conversation-ops.js').provide({ keepEnded, endFactsBefore }); // lane end-obeys-verdict: TERMINATE SAYS WHO — the ended record, written around the kill body
const { harnessSetting, harnessDeclares, harnessSpawnSettings, cliConfigPlanB64 } = harnessConfig;
// 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. RETURNS how many clients got it (r5): a caller that latches "already said" latches on THIS — the boot probes fire into an EMPTY client set on a systemd restart.
const _sentNotices = new Map(); // key → clients it reached
function serverNotice(key, text, { level = 1, i18n = null, keep = true } = {}) { // i18n = {key, params}: the client words it with t(key, params); `text` stays the English (journal, older clients) · r5931 (g): `keep: false` — a notice whose key is its own (one a call) is never kept in the table (it would grow for the life of the process)
if (keep && _sentNotices.has(key)) return _sentNotices.get(key);
console.warn('[notice]', text);
global.__vsEvent?.('server-notice', key);
let delivered = 0;
try {
const payload = JSON.stringify({ type: 'server-notice', key, text, level, ...(i18n && i18n.key ? { i18n } : {}) });
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 && keep) _sentNotices.set(key, delivered); return delivered;
}
// 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.
async function checkAgentHookHealth() {
try {
if (!hookRootWatch.probeMayRun() || !integrationEnabled() || optOutMarkNow() !== 'not') return; // verify r2 ①: an unjudgeable root arms the backoff re-judge, never a silent return
const scriptMissing = !fs.existsSync(HOOK_CMD);
if (scriptMissing) { try { createHookHelper(); } catch {} }
const st = await agentHooksStatus(); // r2345: read off the loop, through the runner's guard — an unread file is no verdict (skipped below)
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' : ''}`);
Promise.resolve(ensureAgentHooks({ auto: true })).then((healed) => { // self-heal the registration in place, through the shipped helper (B-ddf3 u2 line 1) (B-225b r552: while the settings are held it SKIPS — nothing repaired, nothing said)
if (!(healed && healed.skipped) && !(healed && healed[key] && healed[key].ok === false) && !hookRootWatch.saidRecoveryInstead(info, scriptMissing)) serverNotice(`hook-health-${key}`, // verify r2 ①: a root never registered because it could not be read is a recovery, not "broken and repaired"
`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(`[hooks] the self-heal of ${key} could not be said: ${(e && e.message) || e}`));
}
}
} catch (e) { console.warn('[hook-health] probe failed:', e.message); }
}
// Credential expiry sweeps (B-211a): every descriptor's expirySweep({accounts, serverNotice}) — claude: the
// long-lived setup-token warning (src/harnesses/claude-oat-expiry.js). Notice-deduped per account.
function checkCredentialExpiry() {
for (const h of require('./src/harnesses').list()) {
if (typeof h.expirySweep !== 'function') continue;
try { h.expirySweep({ accounts, serverNotice }); } catch { }
}
}
setTimeout(checkCredentialExpiry, 20000);
setInterval(checkCredentialExpiry, 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 — the file routes refuse every file op by name until a restart (B-3b03: never run on the main thread):', e.message);
}
// B-dc3f (1) H1 (r3030, round wefspq2j3): the network home's sign-in witness — its OWN one-worker pool, BUILT ONLY for a hub whose home is a
// network mount (auth calls the factory then; every other hub starts no worker), its failure said by auth in its own words
if (signinWitness) auth.attachWitnessPool(() => new SafeFs({ workerPath: path.join(__dirname, 'src', 'signin-witness-worker.js'), name: 'signin-witness', poolSize: 1, hungMs: 0 }));
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/', ...require('./src/server/tailnet-door.js').agents(), // lane tailnet-names: a tailnet host by name — the plugin's table (kernel) or its HTTP proxy (userspace)
responseMiddleware: [
function stripFrameHeaders(data) {
delete data.headers['x-frame-options'];
}
],
});
app.use(require('./src/server/tailnet-door.js').embedded(unblocker)); // lane tailnet-names (LAW 2): a tailnet host's miss says why through Tailscale
// Ctrl+G editor: POST /api/editor/open (the `code` helper, vsst_ auth) + /api/editor/signal — src/routes/editor.js
require('./src/routes/editor.js').registerEditorRoutes(app, { activeSessions, wss, WS_OPEN, readSessionMeta, writeSessionMeta, getRemoteFs: () => remoteFs });
// ── 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; }
}
require('./src/server/owner-facts.js').configure({ setting: serverSetting, userState: () => persistenceRouter.readUserState() }); // lane agent-context-owner-facts (B-7960): THE owner's clock (instance.timezone) and tray words every agent-facing door says
// 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.
const hookRootWatch = require('./src/server/hook-root-watch.js').create({ dataDir: path.join(__dirname, 'data'), ensureAgentHooks, rootRecovery, ownerWriteRefusal, factsNow: rootFactsNow, integrationEnabled: () => integrationEnabled(), serverNotice: (...a) => serverNotice(...a) });
function syncHookRegistration() {
try {
if (integrationEnabled()) return hookRootWatch.sync(); // the unknown ⇒ the notice once per cause + the backoff re-judge; ok ⇒ the recovery said once // verify r1 (hook-root-guard): an UNJUDGEABLE root (a read error on .git) is said to the OWNER, not only the journal; every writer re-reads, the probe heals + notifies
else return stripAgentHookEntries();
} catch (e) { console.warn('[integration] hook registration sync failed:', e.message); return null; }
}
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); const grants = require('./src/server/grants-store.js').install(require('./src/server/grants-store.js').create({ dataDir: path.join(__dirname, 'data'), wss, log: (...a) => console.warn(...a) })); syncStores.grants = grants.sync; // THE GRANTS STORE (lane grants-unify): every grant the owner gives agents in ONE file (data/grants.json), ONE writer, judged by the ONE model (src/grant-model.js admits) — created before every door, its server-owned mirror live to every client and flushed with the other stores; each door re-judges NOW on a change (grants.onChange below)
const connections = require('./src/server/connections-store.js').create({ dataDir: path.join(__dirname, 'data'), wss, grants, log: console }); syncStores.connections = connections.sync; require('./src/routes/connections.js').registerConnectionRoutes(app, { store: connections, serverSetting }); // row B-2565 «Connections» U1 (lane bl-tests-chrome): the person's declared command-line connections — ONE store (data/connections.json, the store writer), its server-owned mirror live to every page, the owner's routes (the person's own page only; the switch connections.cliLogins, off); after the grants store: a removal drops the connection's grant rows first
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, getExitProxy: () => { try { return exitProxy; } catch { return null; } } /* lane grants-unify: a machine's exit lists ride the config bundle as grant rows */,
getHosts: () => hosts, getMounts: () => mounts, getTasks: () => tasks,
getAccounts: () => accounts, getUsageHistory: () => usageHistory, onUserStateWrite: (st) => { try { channelsWiring.groups.noteUserState(); } catch {} try { tasks.noteArchived(st && st.archivedSessions); } catch {} }, // lane pair-group-fate: the sidebar archive (THE user-state write) ends that conversation's group waits; lane task-group-fanout: …and leaves every group's members (sessions[])
// 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;
const toggled = was !== now ? rootFactsNow().then(syncHookRegistration).catch((e) => { console.warn('[integration] hook registration sync failed:', e && e.message); return null; }) : null; // B-1425: the switch's sync waits for the root facts (off the loop); B-ddf3 u2 (b): the switch's own write rides back too
// Harness settings (design-harness-settings §5): a cli-config row changed ⇒
// re-apply the plan on this machine; a spawn row with a `live` verb changed
// (claude disableModelFallback → formatSetFallbackPolicy: 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
// verb goes to every running chat session whose ADAPTER has it. Sessions
// spawned after the flip get it at spawn instead.
try { if (autoCliLoop) autoCliLoop.noteSettingsWrite(next, prev); } catch { } // B-574d (主开发 r5213): the automatic usage reads switched on or off while their pacing state is unread — the held-lists notice told once
try { settingHolds.noteSettingsWrite(next, prev); } catch { } // lane setting-doors pick 2 (law B): a hand write of a held row ends its hold HERE, the moment it lands (before the wiring exists there is no hold)
const landing = harnessConfig.onSettingsWrite(next, prev); try { plugins.onSettingsWrite(next, prev); } catch { } return (landing || toggled) ? Promise.all([toggled, landing]) : null; // B-ddf3 u2 line 1 (b): the switch's registration and the rows' landing ride back to the settings write's answer (src/server/landing-answer.js notLanded reads both) // lane plugin-settings-p0: a plugin row that re-applies (frp relay fields, Tailscale mode) moved ⇒ that plugin re-applies (before the plugin wiring exists nothing can have changed)
} });
app.use(persistenceRouter);
// B-5279 (主开发 r4942 (2)): a conversation's «the settings could not be read» word goes when the settings read again
if (typeof persistenceRouter.onSettingsLift === 'function') persistenceRouter.onSettingsLift(() => { try { heldWordsLifted(); } catch (e) { console.warn('[wall] the held words could not be cleared at the lift:', e && e.message); } });
// ── 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.
rootFactsNow().then(syncHookRegistration).catch((e) => console.warn('[integration] hook registration at boot failed:', e && e.message)); // B-1425: the boot's registration waits for the root's first read (off the loop, bounded) — never an empty cache
// CLI-CONFIG PLAN AT BOOT (design-harness-settings §5): every cli-config row of every harness (claude transcriptRetentionDays → cleanupPeriodDays, codex historyPersistence → [history] persistence) is written on THIS machine through the CAS writers — guarded by hookRegistrationSafe() inside (a /tmp worktree server never writes the real HOME) and by the smoke belt here; remote machines get the same plan as VIBESPACE_CLI_CONFIG on install / spawn (hosts.js, ws-create.js)
if (!process.env.VIBESPACE_SKIP_AGENT_HOOKS) rootFactsNow().then(() => harnessConfig.syncCliConfig({ reason: 'boot' })).catch((e) => console.warn('[cli-config] the boot sync failed:', e && e.message)); // B-1425: after the first read
// 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(() => rootFactsNow().then(checkAgentHookHealth).catch((e) => console.warn('[integration] hook health probe failed:', e && e.message)), 60000).unref(); // B-1425: the probe awaits the facts
setInterval(() => rootFactsNow().then(checkAgentHookHealth).catch((e) => console.warn('[integration] hook health probe failed:', e && e.message)), 6 * 3600 * 1000).unref();
const { tasks, taskFanout } = require('./src/server/task-groups-wiring.js').createStore({ app, wss, WS_OPEN, activeSessions, grants, persistenceRouter, serverSetting, sessionStatusKey, dataDir: path.join(__dirname, 'data'), exitProxy: () => exitProxy, channelsWiring: () => channelsWiring, sessionStatus: () => sessionStatus, mounts: () => mounts, userTodos: () => userTodos, hosts: () => hosts }); // ── Task Groups (岗位; docs/design-task-system.md): the store, its fan-out, its routes and the remote context sync live in src/server/task-groups-wiring.js, called at their three old places ──
// 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, remoteProcs, signalProc } = 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,
listLayoutHistory: () => { try { return persistenceRouter.listLayoutHistory(); } catch { return []; } },
getDesktop: () => ({ vnc, keeper: desktopKeeper, stream: desktopStream, access: desktopAccess }), // 2.369.118: the desktop scene (late-bound — created further down)
});
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'))), storeWrites: storeTiming.enabled() ? storeTiming.slowest() : undefined, serverMemory: memSampler.latest() || undefined }); // the System window's "slowest store writes (last hour)" (design 011 lane 1)
} catch (e) { res.status(500).json({ error: e.message }); }
});
// Process manager (2.354.0, btop-like): full table + user-initiated signal.
app.get('/api/sysinfo/procs', async (req, res) => {
try {
const hostId = String(req.query.host || '');
if (hostId) return res.json(await remoteProcs(hostId));
res.json({ serverPid: process.pid, ...(await sysinfo.listProcs()) });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/sysinfo/signal', async (req, res) => {
try { res.json(await signalProc(String(req.body?.host || ''), req.body?.pid, req.body?.sig, { by: require('./src/device-audit.js').byOfReq(req) })); }
catch (e) { res.status(400).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, held: sysinfo.historyHeld() }); // r4991: the panel says a held history in the chart's place
});
sysinfo.startWatch({
dataDir: path.join(__dirname, 'data'), hold: require('./src/store-read-hold.js'), /* B-f276 (r4991): the history's read held, handed in as the writer */ writer: require('./src/store-writer.js').storeWriter(), onSample: (mem) => memoryPressure.onSample(mem), // lane browser-resource-care (B-afeb): the memory-pressure episode (src/server/memory-pressure-watch.js); B-0248 unit 5 (lane bl-loop-b): the history's writer is the hub's, handed here (src/sysinfo.js is in the device agent's bundle and requires none)
broadcast: (msg) => { const json = JSON.stringify(msg); wss.clients.forEach(c => { if (c.readyState === WS_OPEN) { try { c.send(json); } catch {} } }); },
});
const { convOps } = require('./src/server/task-groups-wiring.js').mountRoutes({ app, tasks, taskFanout, activeSessions, sameToken, serverSetting, sessionStatusKey, spendGuard }); // the Task Groups' routes (/api/tasks …, the Context table's), mounted where they stood; convOps stays a server.js name (broadcastActiveSessions)
const machineProbes = require('./src/machine-probes'); machineProbes.useStarter(require('./src/server/child-starter').execFileVia(require('./src/server/child-starter').childStarter())); if (!throwawayRoot) machineProbes.armSandboxCheck(); // B-323e: the hub's --version asks ride its starter
const { parseRateLimitEvent, captureRateLimitEvent } = require('./src/rate-limit-capture.js');
const { scheduleCtxSync, remoteCtxBaseFor } = require('./src/server/task-groups-wiring.js').ctxSync({ tasks, hosts: () => hosts, activeSessions, integrationEnabled, serverNotice, sessionStatusKey }); // the remote context-folder auto-sync and its 60 s timer, started where they started
// ── 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'), safeFs: () => app.locals.safeFs, // B-360d: the list's sign-in facts read OFF the loop through the file door
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
},
onSessionLinks: () => broadcastActiveSessions(), // lane badge-stale: a per-session pool link moved ⇒ auth.poolTarget in the payload (one frame per burst — accounts.js _notifyLinks)
});
// ── 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, ackOf: usageAckOf } = 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 || ''; }
},
});
try { require('./src/store-writer.js').bootKeeper(); } catch {} // lane hub-loop-stalls commit 2 r6 (E3): THE BOOT starts the store writer's exit keeper BY NAME (loaded while the install answers, asleep until armed) · below: 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) => { if (e && e.code === 'EVSMOUNTSYNC') { console.error(`[mount-guard] a refused ${e.syscall} on ${e.path} unwound a callback — the hub keeps serving (the call never reached the mount)`); return; } // lane hub-fuse-sync-guard: the guard's refusal throws BEFORE any syscall — exiting would trade a refused call for a whole-hub restart
try { if (e && (e.code === 'EMFILE' || e.code === 'ENFILE')) console.error('[fd] ' + fdGauge.blame(e, e.path).words); } catch {} // lane-dead-bridge: NAME an EMFILE before dying — this process, the mount's FUSE daemon (12:03) or the machine
try { bridgeWatch.endAttachPtys(); } catch {} // …and end the attach clients like the clean shutdown does: a crash that left them alive left ORPHANS whose stuck socket kept the next server's attach dead for 3 h (lane-dead-bridge)
let w0 = null; try { w0 = require('./src/store-writer.js').storeWriter(); w0.beginExit({ crash: true }); w0.exitFlush({ only: 'rank0' }); } catch {} const tDebt = Date.now(); // hub-loop-stalls r3 (law 2) + r6: what cannot be re-derived FIRST — no bound of ours (the keeper gives a crash with no stop asked one full grace, then ends it)
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({ stop: true }); } catch {} // B-225b's second half: a last flush that fails is the journal's line, by name
try { sessionStatus.flush(); } catch {}
try { userTodos.flush(); } catch {}
try { require('./src/server/writes-lost.js').installed()?.stop(); } catch {} // a lost write's warning still held after a failed write (lane cli-2-1-319-records r4)
console.error(e); try { w0.exitFlush({ debtMs: Date.now() - tDebt }); } catch {} process.exit(1); // lane hub-loop-stalls commit 2: every store the writer holds, ONCE — one line names what it wrote
});
process.on('unhandledRejection', (e) => { try { telemetry.record({ kind: 'server-error', name: (e && e.message) || 'unhandledRejection', stack: e && e.stack }); } catch {} console.error('unhandledRejection:', e); });
const memSampler = require('./src/server/memory-sampler.js').create({ record: (ev) => telemetry.record(ev), log: console, caches: () => [...usageHistory.cacheCensus(), require('./src/session-store').jsonlCacheCensus(), usageEstimator.lineCacheCensus()].flat(), enforce: () => require('./src/server/memory-enforce.js').tick({ activeSessions, usageEstimator }) }); // lane server-memory-census: main heap + every worker isolate + external + native every 60 s (started at listen: ONE boot census line); GET /api/sysinfo serverMemory; B-9428: + each bounded cache by name
// 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
const now = Date.now();
const lag = now - lagProbeAt - 1000;
if (lag > maxLagMs) maxLagMs = lag;
lagProbeAt = now;
}, 1000);
setInterval(() => {
try {
const mu = process.memoryUsage();
telemetry.record({ kind: 'metric', name: 'srv-rss-mb', value: Math.round(mu.rss / 1048576) });
telemetry.record({ kind: 'metric', name: 'srv-heap-mb', value: Math.round(mu.heapUsed / 1048576) });
telemetry.record({ kind: 'metric', name: 'srv-evloop-max-lag-ms', value: Math.max(0, maxLagMs) });
telemetry.record({ kind: 'metric', name: 'srv-live-sessions', value: activeSessions.size });
telemetry.record({ kind: 'metric', name: 'srv-ws-clients', value: wss.clients.size });
// store-timing (design 011 lane 1): each named store's slowest sync write / read of these 5 min + its bucket counts
for (const [name, w] of Object.entries(storeTiming.takeWindow())) telemetry.record({ kind: 'metric', name: 'srv-store-ms:' + name, value: w.max, detail: 'n=' + w.n + ' b=' + w.buckets.join(',') });
// Leak canaries — the exact classes the 2.81-2.91 audits kept finding:
// subagent watchers that outlive their agent, normalizer message piles.
let watchers = 0, normMsgs = 0;
for (const [, sess] of activeSessions) {
watchers += sess.subagentWatchers?.size || 0;
normMsgs += sess._normalizer?.total || 0;
}
telemetry.record({ kind: 'metric', name: 'srv-subagent-watchers', value: watchers });
telemetry.record({ kind: 'metric', name: 'srv-normalizer-msgs', value: normMsgs });
try { telemetry.record({ kind: 'metric', name: 'srv-buffer-files', value: fs.readdirSync(BUFFERS_DIR).length }); } catch {}
if (_httpWin.n) {
telemetry.record({ kind: 'metric', name: 'srv-http-reqs-5min', value: _httpWin.n });
telemetry.record({ kind: 'metric', name: 'srv-http-avg-ms', value: Math.round(_httpWin.sum / _httpWin.n) });
telemetry.record({ kind: 'metric', name: 'srv-http-max-ms', value: Math.round(_httpWin.max) });
for (const sl of _httpWin.slow) telemetry.record({ kind: 'event', name: `slow-request ${sl.route}`, value: sl.ms });
_httpWin.n = 0; _httpWin.sum = 0; _httpWin.max = 0; _httpWin.slow.length = 0;
}
maxLagMs = 0;
} catch {}
}, 300000);
}
// Zero-coupling metric hook for deep modules (session-store slow-parse etc.)
global.__vsMetric = (name, value, detail) => { try { telemetry.record({ kind: 'metric', name, value, detail }); } catch {} }; // detail = short attribution (account=… bucket=…), never content (B-a5c0)
// Server-side EVENT hook (2.207.0): the debugging-pain batch — session
// lifecycle anomalies, CLI error classes, probe failures — flows into the
// same Diagnostics report/fleet forwarding as client events. NAMES + short
// enum-ish details only, never content (telemetry charter).
global.__vsEvent = (name, detail) => { try { telemetry.record({ kind: 'event', name, detail }); } catch {} };
// ── Threadpool canary (2.108.6; off the main thread since design 011 lane 1) ── src/server/fs-canary.js says why: the
// stat is timed in its own SafeFs worker and the main loop's delay is a second fact, so a blocked loop never reads as
const mountHealth = require('./src/server/mount-health-watch.js').create({ file: path.join(__dirname, 'package.json'), getUserTodos: () => userTodos, ownerIds: (procs) => memoryPressure.ownerIds(procs), log: console }); // a slow mount. Three stats past 5 s in a row still kick the mount health sweep; lane fuse-canary-notice (B-b327): every answered probe drives the mount-health EPISODE — ONE For-you item naming the mount + who presses it, the server's own scans paused on it (src/server/mount-health-watch.js)
const dataFolder = require('./src/server/data-folder-notice.js').create({ dataDir: path.join(__dirname, 'data'), rootDir: __dirname, getUserTodos: () => userTodos, app }); // B-8797 (lane hub-loop-stalls, 主开发 r5195; at MODULE scope — the witness's block below is its own): the data folder on a network or user-space drive is SAID once (For you) and readable in Settings (GET /api/data-folder) — its look is armed by the listen (below), never in the start's path
{ const syncFs = require('./src/server/sync-fs-witness.js').create().wire({ record: (ev) => telemetry.record(ev), guardOn: () => serverSetting('mounts.mainThreadSyncGuard') !== false, registry: () => mounts.storageRoots(), samplingOn: () => serverSetting(require('./src/server/sync-fs-witness.js').SAMPLING_SETTING) !== false }); try { syncFs.holds()?.register(app); } catch {} // lane hub-loop-stalls: the watchdog names what held the loop — the setting read at every beat; GET /api/loop-holds (src/server/loop-holds.js) // lane hub-fuse-sync-guard: the witness boot-trace started gets telemetry, the setting and the storage rows (mounts exists later: a ReferenceError until then = no rows)
try { require('./src/server/loop-day-report.js').wire({ witness: syncFs, sessions: () => activeSessions.entries(), socketsDir: SOCKETS_DIR, buffersDir: BUFFERS_DIR, sizes: () => ({ conversations: activeSessions.size, pageSockets: wss.clients.size, deviceLinks: (deviceMgr && deviceMgr._conn ? 1 : 0) + agentdDialWss.clients.size }) }); } catch (e) { console.warn('[loop-hour] the hourly report did not start:', (e && e.message) || e); } // lane hub-loop-stalls «loop-day-report»: ONE [loop-hour] journal line per UTC hour + ONE [loop-exit] (src/server/loop-day-report.js); ⚙ Diagnostics reads its hours
const fsCanary = require('./src/server/fs-canary.js').createFsCanary({
file: path.join(__dirname, 'package.json'),
record: (ev) => telemetry.record(ev), witness: syncFs, onHeld: (e) => mountHealth.onHeld(e), // a held loop is named by the witness's call; ≥ 5 s on a mount ⇒ the For-you item names it
onWedged: () => { try { mounts._healthSweep().catch(() => {}); } catch {} }, onProbe: (p) => mountHealth.onProbe(p),
});
setInterval(() => { fsCanary.tick().catch(() => {}); }, 10000).unref();
}
const usageHistory = new UsageHistory({
dataDir: path.join(__dirname, 'data'), firstLoadInWorker: !bootTrace.syncControl /* ledger-boot-load: the first load in the fold worker; the boot-trace control keeps the one-tick warm */, paused: (roots) => mountHealth.paused('usage-walk', roots), // lane fuse-canary-notice: a wedged mount under the walk pauses it
// THE RECORD, not list() (prod-stall-202): list() reads every account's login files and the
// walker asks this once per ledger line — seconds of synchronous NFS reads per walk step on
// production. The same three fields list()'s row carries: its type/backend defaults, and a
// NO key tail (B-ba7d: a usage row reaches every reader of /api/usage-stats; the page lays the person's read on).
resolveAccount: (id) => { if (typeof accounts.held === 'function' && accounts.held()) return { held: true, type: 'unknown', name: null }; // r3060 Q1: a list that could not be read names nobody — the walk waits, never bakes «unknown»
const a = accounts.get(id);
if (!a) { let p = null; try { p = accounts.providerRecordOf(id); } catch { } return p ? { type: 'provider', name: p.label || id } : null; } // B-d578 P1-b: a third-party provider's RECORD (no account) — its name, never «unknown» / deleted
const type = a.type || 'api', backend = a.backend || 'claude';
let ledgerType = null; try { ledgerType = require('./src/harnesses').get(backend).creds?.ledgerType || null; } catch { } // codex: every account is 'codex-subscription'
return { type: ledgerType || type, name: accounts.nameShownOf(id) };
},
});
// OTel receiver (2.361.0, B-345b; DEMOTED TO CORROBORATION 2026-09-07 — the
// observed org is the identity the CLI cached at SPAWN, not the token that
// authorized the request, so it attributes nothing now). Routes are
// cookie-exempt (auth.js); the loopback+token gate is the only door.
const otelIngest = require('./src/server/otel-ingest.js').create({
dataDir: path.join(__dirname, 'data'), PORT, serverSetting,
getUsageHistory: () => usageHistory, identityGroups: () => usageIdentityGroupsCached(),
listAccounts: () => accounts.decisionList().accounts || [], // B-360d: OTel's org→account email fallback DECIDES (per record, no wait: rows confirmed within 10 s, else no email)
});
otelIngest.registerRoutes(app); bootTrace.span('otel-replay', otelIngest.replayed); bootTrace.register(app); // B-1319: the stash replay runs off the loop; GET /api/boot-trace
const bridgeWatch = require('./src/server/bridge-watch.js').create({ activeSessions, BUFFERS_DIR, SOCKETS_DIR, reattachLocalPty, serverSetting, getOtelIngest: () => otelIngest, feedPeerCard, log: console }); // THE DEAD-BRIDGE WATCH (lane-dead-bridge): the attach-pty teardown shared by shutdown + crash, the orphan sweep, silence judged against the CLI's own witnesses (buffer file / OTel), the catch-up card
// `usageHistory.setTruthLookup(otelIngest.…)` is DELIBERATELY UNWIRED since
// 2026-09-07 — reasoning at the seam (usage-history.js) + otel-ingest's header.
const { recordUsageAttribution } = require('./src/server/usage-attribution.js').create({ activeSessions, accounts, usageHistory }); // the by-time billing attribution log (moved, lane dc-seams-server)
// Rescan the ledger periodically (incremental — only new JSONL bytes). Also
// rescanned on demand when the Usage window opens.
// The walk YIELDS every MiB (perf ⑥): warm() reads the ledger only once the
// boot walk has settled, and the metric is the walk's WALL time (settle − start).
setTimeout(() => { try { usageHistory.scan(); usageHistory.scanSettled().then(() => { try { if (bootTrace.syncControl) bootTrace.step('usage-ledger-warm', () => usageHistory.warm()); else bootTrace.span('usage-ledger-warm', usageHistory.warmStepped(), (r) => r); } catch {} }); } catch {} }, 8000); // B-1319: the warm takes a MiB per tick (warmStepped)
setInterval(() => { try {
const t0 = Date.now();
const r = usageHistory.scan();
if (!r?.skipped) Promise.resolve(r).then(() => telemetry.record({ kind: 'metric', name: 'srv-usage-scan-ms', value: Date.now() - t0 })).catch(() => {});
} catch {} }, 180000);
// Telemetry ingest (client errors + feature events) + diagnostics summary.
// telemetry.enabled=false drops ingest silently (client still posts — cheap).
app.post('/api/telemetry', (req, res) => {
try {
let enabled = true;
try { enabled = serverSetting('telemetry.enabled') !== false; } catch {}
if (enabled) {
const events = Array.isArray(req.body?.events) ? req.body.events.slice(0, 20) : [];
for (const ev of events) telemetry.record(ev);
}
res.json({ success: true });
} catch { res.json({ success: true }); }
});
app.get('/api/telemetry/summary', async (req, res) => { // B-360d unit 2: the read and the summing in the telemetry-summary worker
try {
telemetry.flush();
res.json({ ...(await telemetry.summary({ days: Math.min(parseInt(req.query.days) || 14, 90) })), ...(req.query.drift === '1' ? { driftLedger: driftLedgerRows(), attended: (() => { try { return spendGuard.snapshot().attended; } catch { return null; } })() } : {}) }); // ?drift=1 = ⚙ Diagnostics: the drift ledger (lane record-oracle-2-1-296)
} catch (e) { res.status(e && e.status === 503 ? 503 : 500).json({ error: e && e.status === 503 ? `the Diagnostics report's files did not answer in time (${e.message})` : e.message }); }
});
// ── Account + usage routes (src/server/account-usage-routes.js, decomposition #9) ──
require('./src/server/account-usage-routes.js').create({
app, rootDir: __dirname, HOST, CLAUDE_CMD, cliCmds, NODE_CMD,
CLAUDE_SUBSCRIPTION_LOGIN_HELPER, activeSessions, auth,
engine: { oatAnswer, oatIdentityAttach, oatRebind, clearSealedOrders, usageIdentityGroupsMemo, pinAllPlan, pinAll, clearPinsTo, answerCrossProviderAsk, purgePoolMadeMoves, fallbackMoveBack, fallbackStatus, fallbackFactOf, establishedWindows, resetCreditPreview, consumeResetCreditFor, claimColdRestarts, refreshCodexForPerson, settleResetCreditByRead, memberRemoved, decideDefaultTarget, fallbackDefaultTarget, removalTargetFor, maybePoolAutoSwitchForPool, setConversationPin, gatherPlan, onMemberLoginSuccess }, // + B-2083 unit B's member-row press (its plan, the press, the clear) + the login re-check (2026-09-29: a member that signs in ⇒ ONE usage read + ONE pool re-decision) + the removed-member wall (2026-09-28: the members route evicts through the engine's ONE entry point, the default re-point by decision) // + claimColdRestarts (r4: the manual routes never double a restart in flight) + the manual reset-credit use (design-reset-credits p2, src/routes/reset-credit.js)
serverSetting: (...a) => serverSetting(...a),
recordUsageAttribution: (...a) => recordUsageAttribution(...a),
liveAccountIdSet: (...a) => liveAccountIdSet(...a),
buildClaudeSubscriptionLoginCommand: (...a) => buildClaudeSubscriptionLoginCommand(...a),
getAccounts: () => { try { return accounts; } catch { return null; } }, broadcastActiveSessions: () => broadcastActiveSessions(), // + the pin route's session-facts broadcast (2026-09-28)
getHosts: () => { try { return hosts; } catch { return null; } },
getMounts: () => { try { return mounts; } catch { return null; } }, getModels: () => AVAILABLE_MODELS, refreshModels: () => refreshHarnessModels(), getIntegrations: () => { try { return integrationsWiring.store; } catch { return null; } }, // + the harness catalogs a built-in model provider lists (lane provider-record); + their mtime-guarded re-read and the Integrations store a provider's key is read from (lane models-at-session)
getTelemetry: () => { try { return telemetry; } catch { return null; } },
getUsageHistory: () => { try { return usageHistory; } catch { return null; } }, broadcastAll: (m) => bcastAll(m), getLoginExpiryWatch: () => { try { return loginExpiryWatch; } catch { return null; } }, getCliCmds: () => cliCmds, // + the CLI registry the on-demand usage reading checks (lane antigravity-card-fixes) ← constructed BELOW this stanza; lazy, like every other late singleton (拆分 P1). Sharing a line because server.js is AT the size ratchet — the wiring stanza may not grow.
harnessSetting: (...a) => harnessSetting(...a), // + the vendor's own row the on-demand usage door asks for an automatic read (lane usage-predict, one row per vendor)
});
// ── Session status (agent-set via vibespace-status CLI, user-overridable) ──
// The user's override of an agent-set status is injected as a system-reminder
// into the NEXT chat message (see ws-handler chat-input) so the agent learns
// the user disagreed with its self-assessment.
const fdGauge = require('./src/server/fd-gauge.js').create({ serverNotice: (...a) => serverNotice(...a), log: console }); // THE FD GAUGE (lane-dead-bridge): the limit node REALLY runs at, the /proc/self/fd gauge (≥ 80 % ⇒ one notice an hour, by kind) and the NAME of an EMFILE (12:03: the workspace's FUSE daemon ran out) ⇒ src/server/fd-gauge.js
const { SessionStatusManager } = require('./src/session-status');
const sessionStatus = new SessionStatusManager({
dataDir: path.join(__dirname, 'data'),
onWriteError: (e, file, o) => fdGauge.reportWriteError(e, file, o), // a failed debounced write retries + is named, never a crash (12:03:17)
onChange: (statuses, extra) => { // `extra.cleared` = a history clear's ids (a statuses map equal to every client's copy must still reach it)
const json = JSON.stringify({ type: 'session-status-updated', statuses, ...(extra && extra.sync), ...(extra && Array.isArray(extra.cleared) ? { cleared: extra.cleared } : {}) }); // lane task-group-fanout: `statuses` = the keys a write touched, `sync` = {removed, epoch, base, seq}
wss.clients.forEach(c => { if (c.readyState === WS_OPEN) { try { c.send(json); } catch {} } });
},
});
function sessionStatusKey(session, id) {
const bsid = session?.backendSessionId || session?.claudeSessionId;
return bsid ? `${session.backend || 'claude'}:${bsid}` : `webui:${id}`;
}
// ── Global user-facing TODO list (vibespace-ask) — items an agent filed that
// need the USER (decision/input/review). Merged inbox in the taskbar; each
// item belongs to one session and jumps back to it.
const { UserTodoManager } = require('./src/user-todos');
const userTodos = new UserTodoManager({
dataDir: path.join(__dirname, 'data'),
onWriteError: (e, file, o) => fdGauge.reportWriteError(e, file, o), // session-status's twin (lane-dead-bridge)
onChange: (todos) => {
const json = JSON.stringify({ type: 'user-todos-updated', todos: { ...todos, now: Date.now() } }); // lane wake-approve-card r8: the snapshot says the HUB's time (a card's countdown counts by it — src/lib/user-todos-row.js noteHubClock)
wss.clients.forEach(c => { if (c.readyState === WS_OPEN) { try { c.send(json); } catch {} } });
},
});
require('./src/server/helper-asks').install({ userTodos, sessionKeyFor: (s, id) => sessionStatusKey(s, id), activeSessions, persistAskedAt: (s, map) => { if (s && s.sockName) writeSessionMeta(s.sockName, { ...(readSessionMeta(s.sockName) || {}), helperAskedAt: map }); } }); require('./src/server/main-asks').install({ userTodos, sessionKeyFor: (s, id) => sessionStatusKey(s, id), activeSessions, readAskedAt: (s) => (s && s.sockName ? (readSessionMeta(s.sockName) || {}).mainAskedAt : null), persistAskedAt: (s, map) => { if (s && s.sockName) writeSessionMeta(s.sockName, { ...(readSessionMeta(s.sockName) || {}), mainAskedAt: map }); } }); // lane S1: a helper's ask unanswered for 60 s ⇒ ONE For-you item, resolved when it is answered; lane parked-ask-inbox: a conversation's OWN ask the same (main-asks)
require('./src/server/unexpected-exit').install({ userTodos, sessionKeyFor: (s, id) => sessionStatusKey(s, id), activeSessions, clients: () => wss.clients, buffersDir: BUFFERS_DIR, accounts }); // B-f698: an unexpected exit while working is resumed ONCE by itself (one client asked) + one For-you item
const loginExpiryWatch = require('./src/server/login-expiry-watch.js').create({ accounts, userTodos, dataDir: path.join(__dirname, 'data'), log: (...a) => console.log(...a) }); loginExpiryWatch.start(); // PASSIVE (file reads only, §ban-safety): warns the inbox at 24h/1h/expired before a subscription's LOGIN SESSION dies AND retracts those warnings once the member is re-logged in — see src/login-expiry.js. The handle is kept so the accounts login routes can sweep it IMMEDIATELY on a successful login (up to 5 min of staring at the item you just fixed is the reported defect)
try { accounts.setUserTodos(userTodos); } catch (e) { console.warn('[accounts] the For-you tray could not be wired:', e.message); } // the B-f276 family (bl-windows, r3046): an unread accounts list is told ONCE in For you
require('./src/server/ledger-shape-notice.js').wire({ usageHistory, userTodos }); // lane ledger-dedup-law F4: a shard out of shape pauses its machine's ingest — ONE named For-you notice per machine, resolved when it is back in shape
app.get('/api/user-todos', (req, res) => res.json({ todos: { ...userTodos.snapshot(), now: Date.now() } })); // r8: + the hub's clock
require('./src/routes/user-todos-reply.js').registerResolveManyRoute(app, { userTodos }); // "Mark all seen" (POST /api/user-todos/resolve-many, owner-only) — registered BEFORE the :id route below, which would otherwise read `resolve-many` as an item id
require('./src/routes/user-todos-reply.js').registerItemReadRoute(app, { userTodos }); // GET /api/user-todos/:id — ONE item whole (the snapshot previews a resolved item's detail at 300 chars; the For-you window fetches the rest here)
app.post('/api/user-todos/:id', (req, res) => { // User actions from the panel: done / dismissed / open (reopen)
// lane owner-press-attended r2 (the 15th door): the ✓ on a takeover request's item hands the browser back — an ATTENDED
// turn — so this door refuses EVERY bearer first, and the person's press rides the status to its listeners
if (require('./src/write-origin.js').pressBearer(req.headers)) return res.status(403).json({ error: 'the For-you item\'s ✓ is the user\'s — a bearer token (an agent, a job, an automation key) cannot press it', code: 'agent_forbidden' });
const press = require('./src/write-origin.js').pressOf(req);
try { const item = userTodos.setStatus(req.params.id, req.body?.status, 'user', { pressed: press, shown: req.body?.shown }); require('./src/user-todos.js').replyOnDisk(userTodos, res, () => res.json({ success: true, item }), () => res.status(503).json({ error: require('./src/user-todos.js').NOT_ON_DISK, code: 'todos-not-on-disk', item })); } // B-0248: the person's act is on disk before its answer
catch (e) { const decision = e && (e.code === 'decision_row' || e.code === 'decision_final' || e.code === 'changed_since_shown'), held = e && e.code === 'todos-unread'; res.status(held ? 503 : decision ? 409 : 400).json({ error: e.message, ...(decision || held ? { code: e.code } : {}) }); } // lane wake-approve-card r2: a decision row's two verbs only — refused by name
});
// ── Agent-facing routes ── (extracted to src/agent-routes.js in the 2.92.0 split)
const { setupAgentRoutes } = require('./src/agent-routes');
// ── Background Work (2.342.0): jobs engine — constructed here, INITIALIZED
// only after listen (failure isolated; §5 of docs/design-background-work.md).
// Shared conversation delivery ladder (2.362.0): jobs notifications AND
// agent-to-agent messages ride one implementation — local CLI inbox, then the
// owning machine's daemon (conversation-index names it), then the durable
// stash drained at that conversation's next context injection.
const deliver = require('./src/server/conversation-deliver.js').create({
dataDir: path.join(__dirname, 'data'),
peerMsg: require('./src/peer-messaging.js'),
getHosts: () => hosts,
getConvIndex: () => hosts && hosts.convIndex,
serverSetting, activeSessions, onStashChange: () => { try { stashView.changed(); } catch { } }, authorizeSpend: (req) => spendGuard.authorize(req), noteSpend: (rec) => spendGuard.note(rec), releaseSpend: (rec) => spendGuard.release(rec), reservationState: (rid) => spendGuard.reservationState(rid), waitingReservations: () => spendGuard.waitingReservations(), // THE SPEND CEILING (design §4.4c): every rung can open a BILLED turn on an idle session; a refusal is not a dropped message (the caller stashes and it rides the next injection)
// 2.363.0: render the peer card at delivery time — server-posted injections
// are body-less at the CLI, only the delivery site can show them live.
emitPeerCard: (cid, card) => {
for (const [, s] of activeSessions) {
if (addressableId(s) !== cid || !s._normalizer) continue; // verify r6 (channel-withdraw): the card is drawn in the window that OWNS the conversation, never a pending fork's (it carries the parent's id)
try { feedPeerCard(s, card); } catch { }
return true;
}
return false;
},
log: (...a) => console.log(...a), renderBatch: require('./src/agent-routes.js').renderMsgStash, // renderBatch (notify-retry verify r1): several parked notices go out as ONE frame in the hand-over's shape
});
const jobsWiring = require('./src/server/jobs-wiring.js').create({
app, dataDir: path.join(__dirname, 'data'), deliver,
broadcastAll: (msg) => { const payload = JSON.stringify(msg); for (const c of wss.clients) { try { if (c.readyState === WS_OPEN) c.send(payload); } catch {} } },
userTodos, log: (...a) => console.log(...a), getTelemetry: () => { try { return telemetry; } catch { return null; } }, // jobs-archive-write-failed rides telemetry
serverSetting, taskGroups: tasks, activeSessions, // owner auto-notify (2.344.0): toggles + channel-lane session lookup
sessionStatusKey: (...a) => sessionStatusKey(...a), // lane jobs-addressed-push r2: a subscriber's groups NOW (viewerOf — push ⊆ view)
onStash: () => { try { stashView.changed(); } catch { } }, // 2026-09-27: a job notification stashed / drained ⇒ the session's `stash` fact is re-published
onRunEnded: (job) => { try { browserKeeper?.releaseJob?.(job.id, 'the job run ended'); } catch { } try { exitProxy.onJobEnd(job.id); } catch { } }, // lane jobs-browser: a run's end releases its browser lease + window; B-36d1: and its exit pairs
});
// WHAT WAITS FOR AN AGENT (2026-09-27, the owner: "我在界面里完全看不到'有消息在 queue'这件事情"): both stashes summarized as the `stash` session fact + the user's POST /api/sessions/:id/stash/hand-over (ONE ladder turn, spend reason stash-handover) — src/server/stash-handover.js
const stashView = require('./src/server/stash-handover.js').create({ activeSessions, getSendUserInput: () => sendUserInput /* B-02a3: the group hand-over types through THE typing path (created further down — TDZ-safe) */, getSpendGuard: () => spendGuard /* B-02a3 cure: THE spend ceiling (the usage engine's, above) — the press asks it first */, getDeliver: () => deliver, getJobs: jobsWiring.getJobs, getGroups: () => { try { return channelsWiring.groups; } catch { return null; } } /* lane group-report-card: the group messages waiting for a member's next turn (created further down — TDZ-safe) */, getChannels: () => { try { return channelsWiring.channels; } catch { return null; } } /* lane owner-press-attended: a delivered held channel wake clears its row's tag */, broadcastSessions: () => broadcastActiveSessions(), renderMsgStash: require('./src/agent-routes.js').renderMsgStash, renderNotifStash: require('./src/job-model.js').renderNotifStash, dataDir: path.join(__dirname, 'data') }); stashView.register(app); // verify r4: dataDir = the delivered-hand-over memory on disk (a restart between a delivery and its echo)
deliver.registerFrameRestorer((cid, text, meta) => stashView.restoreHandedOver(cid, text, meta)); deliver.registerRedactor((match, scope) => stashView.redactDelivered(match, scope)); /* "Clear content…": the hand-over memory is a copy of held words */ // verify r2: a hand-over's frame that comes back from a wrapper is restored as its ORIGINAL entries (each store, each kind), never one blob; r4: `meta.kind` — a peer's frame never
function stashFactOf(s) { try { return stashView.summaryFor(s); } catch { return null; } } // boot-order safe: a payload built before the view exists states nothing
function poolPinFactOf(s) { return s._poolPin && s._poolPin.memberId ? { memberId: s._poolPin.memberId, name: accounts.get(s._poolPin.memberId)?.name || s._poolPin.memberId, at: s._poolPin.at || null } : null; } // THE CONVERSATION'S PIN (2026-09-28): one payload key per line (the active-sessions census reads the line's keys)
// Channels v1 (2.362.0): per-session external reach override for agent
// messaging — user-set (Session Properties), widening only; ACL reads the
// live field, meta persists it across restarts.
app.post('/api/sessions/:id/msg-reachability', (req, res) => {
const s = activeSessions.get(String(req.params.id));
if (!s) return res.status(404).json({ error: 'no such active session' });
const lv = String((req.body || {}).level || 'inherit');
if (!['inherit', 'visible', 'messageable'].includes(lv)) return res.status(400).json({ error: 'level must be inherit|visible|messageable' });
s._msgReachability = lv === 'inherit' ? null : lv;
Promise.resolve((() => { try { return writeSessionMeta(s.sockName, { ...readSessionMeta(s.sockName), msgReachability: s._msgReachability }, { durable: true }); } catch { return true; } })()).then((ok) => (ok === false ? res.status(503).json({ error: 'Saved, but not on disk yet — the storage has not written it (it is slow or failing). It stays in memory and is written when the storage can; a restart before then loses it.', code: 'not-durable', level: lv }) : res.json({ ok: true, level: lv })), () => res.json({ ok: true, level: lv })); // round 2 (law B): the person's reach level — the answer after the disk
});
require('./src/server/wait-watch.js').install({ activeSessions, getDeliver: () => deliver, getGroups: () => { try { return channelsWiring.groups; } catch { return null; } }, getUserTodos: () => userTodos, sessionKeyOf: (s, id) => sessionStatusKey(s, id), log: console }); const recordClear = require('./src/server/record-clear.js').create({ tasks, userTodos, sessionStatus, getJobs: jobsWiring.getJobs, getGroups: () => channelsWiring.groups, getChannels: () => channelsWiring.channels }); require('./src/routes/records-clear.js').registerRecordClearRoutes(app, { recordClear }); // "Clear content…" (2026-09-28): ONE entry point (PURE verdict, each store's door, the journal line); the owner's POST /api/records/clear[-many] here, an agent's own verbs through setupAgentRoutes
setupAgentRoutes({ app, activeSessions, tasks, sessionStatus, SessionStatusManager, userTodos, sessionStatusKey, serverSetting, spendGuard, scheduleCtxSync, remoteCtxBaseFor, readUserState: () => persistenceRouter.readUserState(), readUserStatePending: () => persistenceRouter.readUserStatePending(), getJobs: jobsWiring.getJobs, deliver, getPublishedPages: () => publishedPages, getChannels: () => channelsWiring.channels, getGroups: () => channelsWiring.groups, getTouches: () => channelsWiring.touches, getRecordClear: () => recordClear, getSendUserInput: () => sendUserInput, getSessionMetaStore: () => ({ readSessionMeta, writeSessionMeta }), carryDir: path.join(__dirname, 'data') }); // lane report-mark-on-ack r3: carryDir = the outstanding deliveries by conversation (a restart is said from it). B-86d3: the seen marks ride the session meta; lazy getters: all three are created further down (TDZ at boot otherwise); getChannels = the vibespace-channels routes' engine (P3); getSendUserInput = THE typing path for a dispatch's `/compact` (lane worker-dispatch — sendUserInput is declared further down)
app.get('/api/agent-hooks', async (req, res) => { try { await rootFactsNow(); res.json({ ...(await agentHooksStatus()), integrationOff: !integrationEnabled(), cliConfig: await harnessConfig.cliConfigStatus() }); } catch (e) { res.status(500).json({ error: String((e && e.message) || e) }); } }); // cliConfig = fresh per-key receipts for the managed CLI-config rows (Settings window chips + the Machines card; D2: never persisted)
app.post('/api/agent-hooks/install', async (req, res) => { try { // B-1425: an async route answers a throw (500), never hangs
// The master switch outranks the button: boot/toggle would strip the entries
// right back — refuse with guidance instead of silently contradicting.
{ const sh = typeof persistenceRouter.settingsHeld === 'function' ? persistenceRouter.settingsHeld() : null; if (sh) return res.status(503).json({ error: `the settings could not be read (${sh.kind}${sh.code ? ', ' + sh.code : ''}) — the hooks were not installed; nothing was written`, code: 'store_unread', held: sh }); } if (!integrationEnabled()) return res.status(400).json({ error: 'VibeSpace integration is disabled (Settings → Integration → master switch). Enable it first.' }); // B-225b r552: the HOLD answered by name first (its strict side reads the switch OFF)
await rootFactsNow(); createHookHelper(); // B-1425: the verdict on the root's true facts; regenerate the script too (repair path)
const results = await ensureAgentHooks({ auto: false }); // explicit → clears any opt-out (B-ddf3 u2 line 1: through the shipped helper, answered at its landing)
// A worktree / temp server refuses BY NAME (src/server-root.js) — never "installed"
if (results.refused) return res.status(409).json({ error: results.refused.line, refused: results.refused, status: await agentHooksStatus() }); if (results.skipped && results.settingsHeld) return res.status(503).json({ error: 'the settings could not be read — the hooks were not installed; nothing was written', code: 'store_unread', held: { file: 'settings.json', kind: results.settingsHeld.kind, code: results.settingsHeld.code || null, since: null, rung: 'said' } });
res.json({ ...hooksLate.installAnswer(results), results, status: await agentHooksStatus() }); // r3064 (7): one verdict — a missing CLI folder is no failure (r1518); a refused row of the same run named
} catch (e) { if (!res.headersSent) res.status(500).json({ error: String((e && e.message) || e) }); } });
hooksLate.registerApplyRoute(app, { ensureAgentHooks, agentHooksStatus, integrationEnabled, harnessConfig, hookRegistrationSafe, rootFactsNow }); // POST /api/cli-config/apply — the missing-file chip's "Apply" (human-triggered): the boot registration + CLI-config plan on demand (lane hooks-create)
app.post('/api/agent-hooks/uninstall', async (req, res) => { try {
await rootFactsNow(); const landing = await removeAgentHooks(); // B-ddf3 u2: the removal through the shipped helper, answered at its landing, a failure by name
res.json({ success: !(landing && landing.ok === false), ...(landing && landing.ok === false ? { error: `the removal did not land: ${landing.why}` } : {}), status: await agentHooksStatus() });
} catch (e) { res.status(500).json({ error: String((e && e.message) || e) }); } });
// ── Hosts (the MACHINE registry — ssh hosts AND dial-out devices, B-f3e8) ──
const { HostManager } = require('./src/hosts');
const hosts = new HostManager({ dataDir: path.join(__dirname, 'data') });
hosts.ownerWriteRefusal = refuseOwnerWrite; hosts.rootFactsNow = rootFactsNow; // the root verdict (src/server-root.js): a worktree / temp server runs no register helper on another machine either
hosts.cliConfigPlanB64 = cliConfigPlanB64; // the CLI-config plan rides every remote install + the gated --status probe as VIBESPACE_CLI_CONFIG (design-harness-settings §6)
const bcastAll = (msg) => { const j = JSON.stringify(msg); wss.clients.forEach(c => { if (c.readyState === WS_OPEN) { try { c.send(j); } catch {} } }); };
// B-f3e8 one-time migration: dial-tokens.json (deviceId → sha256) folds into
// the dial host records (dialTokenHash) — see hosts.migrateDialTokenFile.
try { hosts.migrateDialTokenFile(path.join(AGENTD_DIR, 'dial-tokens.json')); }
catch (e) { console.warn('[hosts] dial-token migration failed:', e.message); }
hosts.dialOnline = (deviceId) => agentdDials.has(deviceId);
// ── R4 push-triggered remote ledger (docs/design-three-tier.md): a connected
// daemon fs.watches its transcript dirs (.claude/sessions+projects and
// .codex/sessions) and pushes one debounced dirty per change burst; we
// harvest promptly instead of waiting for a turn-end result or the idle