-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.js
More file actions
3706 lines (3590 loc) · 197 KB
/
Copy pathserver.js
File metadata and controls
3706 lines (3590 loc) · 197 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// libuv threadpool headroom (default 4): a few fs ops stuck on a dying fuse
// mount used to starve EVERY async fs/dns op server-wide (real outage — see
// mounts.js hung-mount defense). Must be set before the pool first spins up,
// i.e. before any require that performs async I/O.
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || '32';
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const pty = require('node-pty');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { execFileSync, spawn } = require('child_process');
const compression = require('compression');
const { MessageManager } = require('./src/message-manager');
const { createMessageManager } = require('./src/normalizers');
const { Telemetry } = require('./src/telemetry');
const { SyncStore } = require('./src/sync-store');
const { cwdToProjectDir, SessionMessages, findSessionJsonlPath, dedupWebuiSockets } = require('./src/session-store');
const { CodexSessionMessages } = require('./src/codex-session-store');
const { normalizeCodexSource, CODEX_SESSIONS_DIR } = require('./src/adapters/codex');
const { createAdapterRegistry } = require('./src/adapters');
const fileRoutes = require('./src/routes/files');
const { SafeFs } = require('./src/safe-fs');
const { router: persistenceRouter, setup: setupPersistence } = require('./src/routes/persistence');
// ── Env sanitation: the server may have been (re)started from INSIDE a Claude
// Code session (e.g. an agent running in a WebUI terminal restarts it). The
// inherited session env then leaks into every CLI this server spawns —
// CLAUDE_CODE_CHILD_SESSION=1 alone puts a spawned claude into child-session
// mode: NO lock file, NO project transcript. Conversations look fine live but
// are silently unpersisted — terminate + resume loses everything (verified on
// CLI 2.1.199 by A/B env test). Strip the whole inherited set at startup so all
// spawn paths (dtach spawn line, wrappers, probes) run top-level.
if (process.env.CLAUDECODE || process.env.CLAUDE_CODE_CHILD_SESSION) {
const stripped = [];
for (const k of Object.keys(process.env)) {
if (k === 'CLAUDECODE' || k === 'CLAUDE_EFFORT' || k.startsWith('CLAUDE_CODE_') || k.startsWith('CLAUDE_WEBUI_')) {
stripped.push(k);
delete process.env[k];
}
}
console.warn(`[env] Server was started from inside a Claude Code session — stripped inherited session env (${stripped.join(', ')}) so spawned CLIs run top-level. Without this, spawned sessions never write transcripts and their conversations are LOST on resume.`);
}
// Optional persistent ops log (env-gated no-op without VIBESPACE_OPSLOG_DIR) —
// installed EARLY so the console tee captures the whole boot narrative.
try { require('./src/opslog').setupOpslog(require('./package.json').version); } catch (e) { console.warn('[opslog] init failed:', e.message); }
// Auto-update: pull latest + rebuild on startup (skip with NO_AUTO_UPDATE=1)
if (!process.env.NO_AUTO_UPDATE) {
try {
const repoDir = __dirname;
// Ensure Homebrew/nvm paths are in PATH for child processes (macOS non-login shells)
const nodeDir = path.dirname(process.execPath);
const envPath = [nodeDir, process.env.PATH].filter(Boolean).join(path.delimiter);
const spawnEnv = { ...process.env, PATH: envPath };
const result = execFileSync('git', ['-C', repoDir, 'pull', '--ff-only'], { encoding: 'utf-8', timeout: 15000, stdio: ['pipe', 'pipe', 'pipe'] }).trim();
if (result && !result.includes('Already up to date')) {
console.log('[auto-update] git pull:', result);
execFileSync('npm', ['install', '--no-audit', '--no-fund'], { cwd: repoDir, encoding: 'utf-8', timeout: 60000, stdio: 'inherit', env: spawnEnv });
execFileSync('npm', ['run', 'build'], { cwd: repoDir, encoding: 'utf-8', timeout: 30000, stdio: 'inherit', env: spawnEnv });
console.log('[auto-update] rebuilt successfully');
}
} catch (e) { console.log('[auto-update] skipped:', e.message?.split('\n')[0]); }
}
const PORT = process.env.PORT || 3456;
const CLAUDE_CMD_RAW = process.env.CLAUDE_CMD || 'claude';
const CODEX_CMD_RAW = process.env.CODEX_CMD || 'codex';
// Resolve full paths at startup — node-pty's posix_spawnp may not find commands
// if Homebrew/nvm paths (/opt/homebrew/bin) aren't in Node's inherited PATH
function resolveCmd(name) {
// Try 'which' first
try {
const r = execFileSync('/usr/bin/which', [name], { encoding: 'utf-8', timeout: 2000 }).trim();
if (r && r.startsWith('/')) return r;
} catch {}
// Search common paths directly
const dirs = ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin',
...(process.env.PATH || '').split(path.delimiter)];
for (const dir of dirs) {
const p = path.join(dir, name);
try { fs.accessSync(p, fs.constants.X_OK); return p; } catch {}
}
return name;
}
const DTACH_CMD = resolveCmd('dtach');
const NODE_CMD = process.execPath;
const ENV_CMD = resolveCmd('env');
// ── X display detection (Linux clipboard / xclip) ──
// The inherited DISPLAY is unreliable: the server is often (re)started from
// shells with a stale value (e.g. :99 with no X server behind it), and under
// XWayland the display also needs the compositor's XAUTHORITY cookie — without
// it even the right display number fails. Probe candidates at startup and use
// the first {DISPLAY, XAUTHORITY} pair that actually answers; this env is used
// for the server's own xclip calls AND injected into spawned sessions (the CLI
// reads the clipboard itself on Ctrl+V).
function detectXDisplay() {
if (process.platform !== 'linux') return { DISPLAY: process.env.DISPLAY || '', XAUTHORITY: process.env.XAUTHORITY || '' };
const displays = [];
if (process.env.DISPLAY) displays.push(process.env.DISPLAY);
try {
for (const f of fs.readdirSync('/tmp/.X11-unix')) {
if (/^X\d+$/.test(f)) { const d = ':' + f.slice(1); if (!displays.includes(d)) displays.push(d); }
}
} catch {}
const xauths = [];
if (process.env.XAUTHORITY) xauths.push(process.env.XAUTHORITY);
try {
const rd = `/run/user/${process.getuid()}`;
for (const f of fs.readdirSync(rd)) {
// .mutter-Xwaylandauth.XXXXXX, Xauthority, xauth_XXXXXX (sddm), …
// NOTE: "Xwaylandauth" does NOT contain the substring "xauth" — match "auth"
if (/auth/i.test(f)) xauths.push(path.join(rd, f));
}
} catch {}
xauths.push(path.join(os.homedir(), '.Xauthority'));
const xauthCandidates = ['', ...xauths.filter((p, i, a) => p && a.indexOf(p) === i && fs.existsSync(p))];
const xsetCmd = resolveCmd('xset');
for (const d of displays) {
for (const xa of xauthCandidates) {
try {
execFileSync(xsetCmd, ['q'], {
env: { ...process.env, DISPLAY: d, ...(xa ? { XAUTHORITY: xa } : {}) },
timeout: 1500, stdio: 'ignore',
});
return stabilizeXAuth({ DISPLAY: d, XAUTHORITY: xa, probed: true });
} catch {}
}
}
return { DISPLAY: process.env.DISPLAY || '', XAUTHORITY: process.env.XAUTHORITY || '', probed: false }; // best effort
}
// Compositor restarts mint a NEW per-instance cookie file
// (.mutter-Xwaylandauth.XXXXXX) while every already-running session keeps the
// OLD path in its env — the clipboard silently dies for all of them (real
// incident 2026-07-09: an Xwayland restart at 18:42 broke image paste in 11
// live sessions at once). Stabilize: merge the working cookie into
// ~/.Xauthority and hand THAT path to sessions — processes re-open the auth
// file on every X request, so after a future rotation one refreshXEnv() merge
// heals everything, old sessions included, without respawns.
function stabilizeXAuth(found) {
if (!found.probed || !found.XAUTHORITY) return found;
const home = path.join(os.homedir(), '.Xauthority');
if (found.XAUTHORITY === home) return found;
try {
execFileSync(resolveCmd('xauth'), ['merge', found.XAUTHORITY], {
env: { ...process.env, XAUTHORITY: home }, timeout: 3000, stdio: 'ignore',
});
// switch to the stable path only if it actually answers
execFileSync(resolveCmd('xset'), ['q'], {
env: { ...process.env, DISPLAY: found.DISPLAY, XAUTHORITY: home }, timeout: 1500, stdio: 'ignore',
});
return { ...found, XAUTHORITY: home };
} catch { return found; }
}
// ONE mutable object — ws-handler and app.locals hold references to it, so a
// refresh propagates everywhere (new spawns + the paste route) without rewiring.
const X_ENV = detectXDisplay();
function refreshXEnv() { Object.assign(X_ENV, detectXDisplay()); return X_ENV; }
const CLAUDE_CMD = CLAUDE_CMD_RAW.startsWith('/') ? CLAUDE_CMD_RAW : resolveCmd(CLAUDE_CMD_RAW);
const CODEX_CMD = CODEX_CMD_RAW.startsWith('/') ? CODEX_CMD_RAW : resolveCmd(CODEX_CMD_RAW);
const CODEX_LINUX_SANDBOX_CMD = resolveCmd('codex-linux-sandbox');
const CODEX_SANDBOX_SUPPORTED = process.platform !== 'linux'
|| (!!CODEX_LINUX_SANDBOX_CMD && CODEX_LINUX_SANDBOX_CMD !== 'codex-linux-sandbox')
|| (typeof CODEX_LINUX_SANDBOX_CMD === 'string' && fs.existsSync(CODEX_LINUX_SANDBOX_CMD));
const adapterRegistry = createAdapterRegistry({
claudeCmd: CLAUDE_CMD,
codexCmd: CODEX_CMD,
codexSandboxSupported: CODEX_SANDBOX_SUPPORTED,
chatWrapper: path.join(__dirname, 'data', 'bin', 'chat-wrapper.js'),
codexChatWrapper: path.join(__dirname, 'data', 'bin', 'codex-chat-wrapper.js'),
ptyWrapper: path.join(__dirname, 'data', 'bin', 'pty-wrapper.js'),
buffersDir: path.join(__dirname, 'data', 'session-buffers'),
});
if (!CODEX_SANDBOX_SUPPORTED) {
console.log('[codex] codex-linux-sandbox not found; default/safe-yolo sessions will run unsandboxed.');
}
// Parse available permission modes, effort levels, and supported flags from claude --help
let PERMISSION_MODES = ['default', 'acceptEdits', 'auto', 'bypassPermissions', 'dontAsk', 'plan'];
// The effortLevel enum (parsed from `claude --help` below, which lists it on a
// wrapped line: "(low, medium, high, xhigh, max)"). This is the fallback if the
// parse ever fails — keep it matching. NOTE: "ultracode" is deliberately NOT
// here — it's not an effortLevel value but a separate session mode (xhigh +
// dynamic-workflow orchestration), appended as a pseudo-level client-side.
let EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
let CLAUDE_SUPPORTS_NAME = false;
try {
const help = execFileSync(CLAUDE_CMD, ['--help'], { encoding: 'utf-8', timeout: 5000 });
const permMatch = help.match(/--permission-mode.*choices:\s*(.+)\)/);
if (permMatch) {
PERMISSION_MODES = permMatch[1].match(/"([^"]+)"/g)?.map(s => s.replace(/"/g, '')) || PERMISSION_MODES;
}
// --effort <level> Effort level ... (low, medium, high, max)
const effortMatch = help.match(/--effort\s+\S+\s+[^(]*\(([^)]+)\)/);
if (effortMatch) {
EFFORT_LEVELS = effortMatch[1].split(',').map(s => s.trim()).filter(Boolean);
}
CLAUDE_SUPPORTS_NAME = /--name\b/.test(help);
} catch {}
// Propagate capability flags to the adapter
adapterRegistry.get('claude').config.supportsName = CLAUDE_SUPPORTS_NAME;
// Discover available models per backend (cached, refreshed periodically)
const CLAUDE_MODEL_ALIASES = [
{ id: '', label: 'Default' },
{ id: 'fable', label: 'fable (latest, 200k)' },
{ id: 'fable[1m]', label: 'fable[1m] (latest, 1M context)' },
{ id: 'opus', label: 'opus (latest, 200k)' },
{ id: 'opus[1m]', label: 'opus[1m] (latest, 1M context)' },
{ id: 'sonnet', label: 'sonnet (latest)' },
{ id: 'sonnet[1m]', label: 'sonnet[1m] (latest, 1M context)' },
{ id: 'haiku', label: 'haiku (latest)' },
];
const AVAILABLE_MODELS = {
claude: [...CLAUDE_MODEL_ALIASES],
codex: [{ id: '', label: 'Default' }],
};
function refreshAvailableModels() {
// /v1/models accepts both auth schemes now (OAuth needs Bearer + the oauth
// beta header — it used to 401, fixed server-side ~2026-06). The old
// bootstrap endpoint's additional_model_options now returns null, so
// /v1/models is the single source for full model IDs; CLI aliases
// (fable/opus/sonnet/haiku) stay hardcoded since they're CLI-side names.
function fetchModels(token, useOAuth) {
const headers = { 'anthropic-version': '2023-06-01' };
if (useOAuth) {
headers['Authorization'] = 'Bearer ' + token;
headers['anthropic-beta'] = 'oauth-2025-04-20';
} else {
headers['x-api-key'] = token;
}
const req = https.request('https://api.anthropic.com/v1/models?limit=100', {
method: 'GET', headers,
}, (res) => {
let body = '';
res.on('data', (d) => { body += d; });
res.on('end', () => {
try {
const data = JSON.parse(body);
if (data.data?.length) {
const models = data.data.map(m => {
const ctx = m.max_input_tokens >= 1000000 ? '1M' : m.max_input_tokens >= 200000 ? '200k' : Math.round(m.max_input_tokens / 1000) + 'k';
return { id: m.id, label: `${m.display_name || m.id} (${ctx})` };
});
AVAILABLE_MODELS.claude = [...CLAUDE_MODEL_ALIASES, ...models];
} else if (res.statusCode !== 200) {
console.warn(`[models] /v1/models failed: HTTP ${res.statusCode}`);
}
} catch {}
});
});
req.on('error', () => {});
req.end();
}
// §ban-safety: a /v1/models fetch with the OAuth (subscription) token is the
// same off-CLI background-call pattern as the usage poll, so it's gated behind
// the SAME opt-in. Default OFF → the dropdown falls back to the hardcoded CLI
// aliases (fable/opus/sonnet/haiku[+1m]); only full model IDs are missed, and
// "Custom…" still lets you type one. An API KEY (sanctioned) is always used.
const apiKey = process.env.ANTHROPIC_API_KEY || null;
if (apiKey) {
fetchModels(apiKey, false);
} else if (usagePollingEnabled()) {
getOAuthToken((oauthToken) => { if (oauthToken) fetchModels(oauthToken, true); });
}
refreshCodexModels();
}
// ── Codex model list (from ~/.codex/models_cache.json) ──
// That cache is last-writer-wins AND version-gated server-side: a still-running
// OLD codex CLI re-fetches it and writes it back WITHOUT newer models (observed
// live TWICE: a 0.142.5 session erased the gpt-5.6 entries minutes after
// 0.144.0 fetched them — and once it happened right before a server restart,
// leaving the dropdown stale for the whole hourly re-read cycle). Two guards:
// (1) union every model ever seen, PERSISTED across restarts;
// (2) mtime-guarded re-read ON DEMAND from /api/available-models — the model/
// effort dropdowns fetch per click, so they're always current, no timers.
const CODEX_MODELS_SEEN_FILE = path.join(__dirname, 'data', 'codex-models-seen.json');
const _codexModelsSeen = new Map();
try { for (const m of JSON.parse(fs.readFileSync(CODEX_MODELS_SEEN_FILE, 'utf-8'))) if (m && m.id) _codexModelsSeen.set(m.id, m); } catch {}
if (_codexModelsSeen.size) AVAILABLE_MODELS.codex = [{ id: '', label: 'Default' }, ..._codexModelsSeen.values()];
let _codexCacheMtime = 0;
function refreshCodexModels() {
try {
const fp = path.join(os.homedir(), '.codex', 'models_cache.json');
const mt = fs.statSync(fp).mtimeMs;
if (mt === _codexCacheMtime) return;
_codexCacheMtime = mt;
const codexCache = JSON.parse(fs.readFileSync(fp, 'utf-8'));
if (!codexCache.models?.length) return;
const fresh = codexCache.models.map(m => {
const ctx = m.context_window ? (m.context_window >= 1000000 ? Math.round(m.context_window / 1000000) + 'M' : Math.round(m.context_window / 1000) + 'k') : '';
// Per-model reasoning levels ride along: GPT-5.6 made efforts
// model-specific (sol/terra add max+ultra, luna tops out at max) —
// clients derive dropdowns from this instead of a stale hardcoded list.
return { id: m.slug, label: (m.display_name || m.slug) + (ctx ? ` (${ctx})` : ''), efforts: (m.supported_reasoning_levels || []).map(l => l && l.effort).filter(Boolean) };
}).filter(m => m.id);
let changed = false;
for (const m of fresh) {
const prev = _codexModelsSeen.get(m.id);
if (!prev || JSON.stringify(prev) !== JSON.stringify(m)) { _codexModelsSeen.set(m.id, m); changed = true; }
}
AVAILABLE_MODELS.codex = [{ id: '', label: 'Default' }, ..._codexModelsSeen.values()];
if (changed) {
try {
const tmp = CODEX_MODELS_SEEN_FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify([..._codexModelsSeen.values()]));
fs.renameSync(tmp, CODEX_MODELS_SEEN_FILE);
} catch {}
}
} catch {}
}
refreshCodexModels();
setTimeout(refreshAvailableModels, 3000);
setInterval(refreshAvailableModels, 3600000); // refresh hourly
const HOST = process.env.HOST || '0.0.0.0';
const app = express();
const server = http.createServer(app);
// ── Optional password auth (VIBESPACE_PASSWORD env / data/auth.json) +
// optional Clerk SSO (VIBESPACE_CLERK_PUBLISHABLE_KEY — src/clerk-auth.js) ──
const { Auth } = require('./src/auth');
const { ClerkAuth } = require('./src/clerk-auth');
const clerkAuth = new ClerkAuth();
const auth = new Auth(path.join(__dirname, 'data'), { clerk: clerkAuth });
{
const { generated } = auth.ensurePassword({ generateIfMissing: process.env.VIBESPACE_GENERATE_PASSWORD === '1' });
if (generated) {
console.log('\n ╔════════════════════════════════════════════════╗');
console.log(` ║ Generated workspace password: ${generated.padEnd(15)} ║`);
console.log(' ║ (persisted in data/auth.json — set ║');
console.log(' ║ VIBESPACE_PASSWORD to choose your own) ║');
console.log(' ╚════════════════════════════════════════════════╝\n');
}
if (auth.passwordEnabled) console.log(' Password auth: ENABLED');
if (clerkAuth.enabled) console.log(` Clerk SSO: ENABLED (${clerkAuth.frontendApi})`);
// getter — auth can be enabled/disabled at runtime via /api/auth/set-password
Object.defineProperty(app.locals, 'authEnabled', { get: () => auth.enabled });
Object.defineProperty(app.locals, 'ssoEnabled', { get: () => auth.ssoEnabled });
}
// noServer + ONE manual upgrade dispatcher (registered at the bottom of this
// file): ws's own {server, path} listener calls handleUpgrade UNCONDITIONALLY
// and abortHandshake(400)s every non-matching path — it was killing /proxy/
// WebSockets silently and the /api/vnc bridge on arrival. Auth happens in the
// dispatcher (cookie token, same as HTTP).
const wss = new WebSocketServer({ noServer: true });
app.use(compression());
// HTTP latency observation (names-and-numbers only): rolling 5-min window
// flushed by the metrics sampler; slow requests (>1.5s) recorded as events
// with the SANITIZED route (first 3 path segments — /api/file/serve/* etc.
// carry user paths that must never enter the ledger).
const _httpWin = { n: 0, sum: 0, max: 0, slow: [] };
app.use((req, res, next) => {
const t0 = process.hrtime.bigint();
res.on('finish', () => {
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
_httpWin.n++; _httpWin.sum += ms; if (ms > _httpWin.max) _httpWin.max = ms;
if (ms > 1500 && _httpWin.slow.length < 20) {
_httpWin.slow.push({ route: req.path.split('/').slice(0, 4).join('/') || '/', ms: Math.round(ms) });
}
});
next();
});
auth.registerRoutes(app);
app.use(auth.middleware());
// Serve index.html with cache-busting query params on every local js/css asset
// (?v=<mtime>). Browsers serve unversioned <script>/<link> from memory cache on
// a soft reload without revalidating, so users were stuck on a stale bundle
// after an update until a hard refresh. Versioning the URL forces a fresh fetch
// whenever the file changes — no hard refresh ever needed.
app.get(['/', '/index.html'], (req, res, next) => {
try {
const pub = path.join(__dirname, 'public');
let html = fs.readFileSync(path.join(pub, 'index.html'), 'utf-8');
html = html.replace(/(href|src)="\/([^"?]+\.(?:js|css))"/g, (m, attr, file) => {
try { return `${attr}="/${file}?v=${Math.floor(fs.statSync(path.join(pub, file)).mtimeMs)}"`; }
catch { return m; }
});
res.set('Cache-Control', 'no-cache');
res.type('html').send(html);
} catch { next(); }
});
app.use(express.static(path.join(__dirname, 'public'), { etag: true, lastModified: true, maxAge: 0 }));
// WebDAV bridge — BEFORE the json body parser (PUT bodies stream to disk).
// Auth = scoped Bearer mount tokens; see src/webdav.js for the security model.
const { MountTokens, registerWebdav } = require('./src/webdav');
const mountTokens = new MountTokens({ dataDir: path.join(__dirname, 'data') });
registerWebdav(app, { tokens: mountTokens });
app.use(express.json({ limit: '50mb' }));
app.get('/xterm.css', (req, res) => {
res.sendFile(path.join(__dirname, 'node_modules/@xterm/xterm/css/xterm.css'));
});
// ── Active session tracking (dtach-backed for persistence across server restarts) ──
// dtach is a minimal PTY detach/attach tool — no rendering layer, no mouse interception.
// Claude processes get raw PTY I/O identical to a native terminal.
const activeSessions = new Map();
const sessionCounterRef = { value: 0 };
const SOCKETS_DIR = path.join(__dirname, 'data', 'sockets');
const META_DIR = path.join(__dirname, 'data', 'session-meta');
const BUFFERS_DIR = path.join(__dirname, 'data', 'session-buffers');
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 PTY_WRAPPER = path.join(__dirname, 'data', 'bin', 'pty-wrapper.js');
// ── CS refactor M1 (opt-in, default OFF): route LOCAL terminal sessions
// through the standing vibespace-agentd daemon. deviceMgr stays null unless
// the local device daemon is ALWAYS on since the 2.175.0 graduation —
// instantiates it, never spawns a daemon, and attachToDtach is byte-identical
// to today. daemonPtyShim presents the node-pty interface over a device
// session handle so setupSessionPty is unchanged.
let deviceMgr = null;
// ── M2 host-level agentd provisioning (flag agentd.remoteSessions) ──
// Per-host vsht_ token: plaintext in a 0600 local file (the attach bridge
// reads it at spawn; never argv), sha256 recorded alongside for audit.
const AGENTD_DIR = path.join(__dirname, 'data', 'agentd');
function agentdHostToken(hostId) {
ensureDir(AGENTD_DIR);
const f = path.join(AGENTD_DIR, 'host-' + hostId + '.token');
try { return fs.readFileSync(f, 'utf-8').trim(); } catch { }
const tok = 'vsht_' + require('crypto').randomBytes(24).toString('hex');
fs.writeFileSync(f, tok, { mode: 0o600 });
return tok;
}
// Install/refresh the daemon on a host, throttled per boot+version: a marker
// records the last version shipped; matching = skip (one ssh round trip saved
// per spawn; a bundle change reinstalls because the version bumps with it).
const _agentdInstalled = new Map(); // hostId → version
// ── Transport B (dial-out) server side: devices behind NAT dial US. Pairing
// mints {deviceId, dialToken}; the daemon presents the dial token at the ws
// upgrade (gates the endpoint), then the normal hello/vsht_ auth runs INSIDE
// the mux like every transport. Incoming dials land in a registry the
// device's transport waits on. ──
const agentdDials = new Map(); // deviceId → ws stream adapter (live dial)
// B-f3e8: the pairing credential lives ON the dial host record (hosts.json
// dialTokenHash) — dial-tokens.json is migrated once at boot (below, after
// HostManager construction) and there is no separate device registry anymore.
function agentdMintDialPair(deviceId) {
ensureDir(AGENTD_DIR);
const tok = 'vsdt_' + require('crypto').randomBytes(18).toString('hex');
hosts.setDialToken(deviceId, require('crypto').createHash('sha256').update(tok).digest('hex'));
// the device token (vsht_) for in-mux auth ships in the install payload
return { deviceId, dialToken: tok, hostToken: agentdHostToken('dial-' + deviceId) };
}
/** Full unpair of a dial machine (DELETE /api/hosts/:id on a dial record):
* mounts torn down, vsht_ token file gone, live stream destroyed. The token
* hash dies with the host record itself. */
async function unpairDialDevice(deviceId) {
try { await machineMounts.onMachineUnpaired(hosts.findByDeviceId(deviceId)?.id); } catch { }
try { portForwards.onMachineUnpaired(hosts.findByDeviceId(deviceId)?.id); } catch { }
try { exitProxy.onMachineUnpaired(hosts.findByDeviceId(deviceId)?.id); } catch { }
try { fs.unlinkSync(path.join(AGENTD_DIR, `host-dial-${deviceId}.token`)); } catch { }
const live = agentdDials.get(deviceId);
if (live) { try { live.destroy(); } catch { } agentdDials.delete(deviceId); }
agentdDialDevices.delete(deviceId);
}
// A DeviceManager over a DIALED-IN device (Transport B consumption): the
// device's daemon holds the mux-server end; we drive it (fs/serve-folder/
// tcp-forward) as the client over the live ws stream in agentdDials. Reused
// per device; reconnects follow the device's --dial retries (getStream picks
// up the fresh stream). Enables 'device' mounts + remote fs for NAT'd devices.
const agentdDialDevices = new Map(); // deviceId → DeviceManager
async function deviceForDial(deviceId, _retried = false) {
// FAIL FAST when the device isn't dialed in: the stream transport's connect
// loop otherwise backs off and retries FOREVER, so every operation against
// an offline device (session create, mount, test) HUNG instead of erroring
// (real report: create卡住/terminal空白/mount打不开 — Mac daemon died after
// a self-upgrade re-exec and nothing surfaced it).
const curStream = agentdDials.get(deviceId);
if (!curStream) throw new Error(`device "${deviceId}" is offline — its daemon is not dialed in (rerun the install command on it)`);
let dm = agentdDialDevices.get(deviceId);
// STALE-STREAM GUARD (real report: online=true but every fs op/session
// blank): the device re-dialed after a self-upgrade re-exec, so agentdDials
// holds a FRESH stream — but the cached DeviceManager's mux is still bound
// to the DEAD old stream, and its status().connected can lag true. Rebuild
// whenever the live stream differs from the one this dm connected over.
// A STOPPED dm must be treated exactly like a stale stream: stop() is
// terminal (_connectLoop throws 'stopped' forever), so reusing one wedges
// EVERY op against an otherwise-healthy device until the stream changes
// (real walter outage: hours of "offline"/'stopped' while the Mac was
// dialed-in and fine — a re-dial/unpair race stopped the cached dm).
if (dm && (dm._stopped || (dm._dialStream && dm._dialStream !== curStream))) {
try { dm.stop?.(); } catch { }
dm = null;
agentdDialDevices.delete(deviceId);
}
if (dm && dm.status().connected) return dm;
if (!dm) {
const { DeviceManager } = require('./src/agentd/client.js');
dm = new DeviceManager({
dataDir: path.join(__dirname, 'data'),
bundlePath: path.join(__dirname, 'data', 'bin', 'vibespace-agentd.js'),
version: require('./package.json').version,
transport: { kind: 'stream', hostToken: agentdHostToken('dial-' + deviceId), getStream: () => agentdDials.get(deviceId) || null },
log: (...a) => console.log('[device-dial]', ...a),
});
agentdDialDevices.set(deviceId, dm);
}
dm._dialStream = curStream; // remember which stream we bind the mux to
try {
await dm.connect();
} catch (e) {
// never leave a failed dm in the cache — the next op must rebuild clean
try { dm.stop?.(); } catch { }
if (agentdDialDevices.get(deviceId) === dm) agentdDialDevices.delete(deviceId);
// a dm stopped MID-CONNECT by a concurrent re-dial cleanup surfaces one
// transient 'stopped' — while the stream is live, rebuild once instead of
// failing the caller's FIRST op after a re-dial (seen live on the walter
// verification: test probe errored once, next op self-healed)
if (!_retried && String(e && e.message) === 'stopped' && agentdDials.get(deviceId)) {
return deviceForDial(deviceId, true);
}
throw e;
}
return dm;
}
async function ensureAgentdOnHost(hostId) {
const version = require('./package.json').version;
if (_agentdInstalled.get(hostId) === version) return;
const bundlePath = path.join(__dirname, 'data', 'bin', 'vibespace-agentd.js');
await hosts.installAgentd(hostId, bundlePath, version, agentdHostToken(hostId));
_agentdInstalled.set(hostId, version);
}
function daemonPtyShim(handle) {
let dataCb = null, exitCb = null;
handle.onData = (buf) => { if (dataCb) dataCb(buf.toString('utf-8')); };
handle.onExit = (code) => { if (exitCb) exitCb({ exitCode: code }); };
return {
_daemon: true,
get pid() { return handle.pid; },
onData(cb) { dataCb = cb; return { dispose() { dataCb = null; } }; },
onExit(cb) { exitCb = cb; return { dispose() { exitCb = null; } }; },
write(s) { try { handle.write(s); } catch {} },
resize(cols, rows) { try { handle.resize(cols, rows); } catch {} },
kill() { try { handle.kill(); } catch {} },
};
}
const CHAT_WRAPPER = path.join(__dirname, 'data', 'bin', 'chat-wrapper.js');
const CODEX_CHAT_WRAPPER = path.join(__dirname, 'data', 'bin', 'codex-chat-wrapper.js');
function ensureDir(dir) { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); }
// ── Cached webuiPids (PIDs managed by webui dtach sessions) ──
// Built from pty-wrapper metadata files (childPid), no pgrep/process-tree traversal needed.
const webuiPids = new Set();
function refreshWebuiPids() {
webuiPids.clear();
for (const [id, s] of activeSessions) {
// Read childPid from pty-wrapper's metadata file
try {
const metaPath = path.join(BUFFERS_DIR, id + '.json');
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
if (meta.childPid) {
webuiPids.add(meta.childPid);
s._childPid = meta.childPid;
// Also add direct children of childPid (claude forks from node-pty spawn)
try {
const ch = execFileSync('pgrep', ['-P', String(meta.childPid)], { encoding: 'utf-8', timeout: 2000 }).trim();
for (const line of ch.split('\n')) { const p = parseInt(line.trim()); if (p) webuiPids.add(p); }
} catch {}
}
if (meta.pid) { webuiPids.add(meta.pid); }
} catch {}
}
}
// ── Broadcast helper (avoids duplicating per-session WebSocket iteration) ──
const WS_OPEN = 1;
function broadcastToSession(session, id, msg) {
const json = JSON.stringify(msg);
for (const client of session.clients.keys()) {
if (client.readyState === WS_OPEN) { try { client.send(json); } catch {} }
}
}
// SyncStore imported from ./src/sync-store.js
// ── 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 (Claude) ──
// /goal runs natively in the CLI (Stop hook drives continuation + met
// detection), but goal_status attachments are JSONL-only — they are NOT
// emitted on stream-json stdout (same gap class as subagent messages,
// anthropics/claude-code#8262). After each turn we tail the session JSONL for
// the newest goal_status and sync session state from it.
function checkClaudeGoalStatus(session, id) {
if (!session.claudeSessionId) return;
try {
const fp = findSessionJsonlPath(session.claudeSessionId, session.cwd || '');
if (!fp) return;
const stat = fs.statSync(fp);
const TAIL = 65536;
let content;
if (stat.size > TAIL) {
const fd = fs.openSync(fp, 'r');
try {
const buf = Buffer.alloc(TAIL);
const n = fs.readSync(fd, buf, 0, TAIL, stat.size - TAIL);
content = buf.toString('utf-8', 0, n);
content = content.slice(content.indexOf('\n') + 1);
} finally { fs.closeSync(fd); }
} else {
content = fs.readFileSync(fp, 'utf-8');
}
// Newest goal_status record wins
let latest = null;
for (const line of content.split('\n')) {
if (!line.includes('"goal_status"')) continue;
try {
const rec = JSON.parse(line);
if (rec.type === 'attachment' && rec.attachment?.type === 'goal_status') latest = rec;
} catch {}
}
if (!latest || latest.uuid === session._lastGoalStatusUuid) return;
session._lastGoalStatusUuid = latest.uuid;
const a = latest.attachment;
const prevGoal = session._goal;
if (a.durationMs) session._goalElapsed = a.durationMs;
if (a.tokens) session._goalTokensUsed = a.tokens;
if (a.met) {
if (prevGoal) session._prevGoal = prevGoal;
session._goal = null;
session._goalStatus = 'complete';
const reason = (a.reason || '').slice(0, 300);
broadcastToSession(session, id, {
type: 'goal-updated', sessionId: id, goal: null, goalStatus: 'complete',
goalElapsed: session._goalElapsed || 0,
statusMsg: `Goal met: ${a.condition}${reason ? `\n${reason}` : ''}`,
});
// Sync the wrapper meta too — the CLI already cleared its goal natively,
// but the wrapper can't see that (attachments are JSONL-only). Without
// this, a server restart would restore a stale "active" goal from meta.
// (/goal clear on an already-cleared goal is a synthetic no-op.)
if (session.pty) { try { session.pty.write(JSON.stringify({ type: 'set-goal', goal: null }) + '\n'); } catch {} }
} else if (a.condition) {
const changed = session._goal !== a.condition;
session._goal = a.condition;
session._goalStatus = 'active';
if (changed || a.durationMs) {
broadcastToSession(session, id, {
type: 'goal-updated', sessionId: id, goal: a.condition, goalStatus: 'active',
goalElapsed: session._goalElapsed || 0,
statusMsg: a.sentinel && changed ? `Goal set: ${a.condition}` : null,
});
}
}
} catch {}
}
// ── PTY setup helper (onData + onExit wiring) ──
// Live TODO capture — the agent's own TodoWrite (claude) / plan tool (codex)
// IS the session's (活儿's) checklist; VibeSpace only OBSERVES it (never a
// parallel store the agent must be taught). Summary rides active-sessions for
// the board's progress pill; the full list is fetched on demand (expanded card
// → /api/session-todos, which reads taskState() from the transcript).
// New task-tool family (CLI ≥2.1.2xx: TaskCreate/TaskUpdate — CRUD by id, not
// full-list snapshots like TodoWrite). The created task's id only arrives in
// the paired TOOL RESULT text ("Task #N created…"), so creates are stashed by
// tool_use_id until the result lands. Replayed into a list for the same pill.
function applyTaskToolUpdate(session, input) {
const list = (session._taskList ||= new Map());
const key = String(input.taskId);
if (input.status === 'deleted') list.delete(key);
else {
const cur = list.get(key) || { content: '', status: 'pending' };
if (input.subject) cur.content = input.subject;
if (input.activeForm) cur.activeForm = input.activeForm;
if (input.status) cur.status = input.status;
list.set(key, cur);
}
emitTaskListTodos(session);
}
function emitTaskListTodos(session) {
if (!session._taskList?.size) return;
const todos = [...session._taskList.entries()]
.sort((a, b) => Number(a[0]) - Number(b[0]))
.map(([, v]) => v);
updateSessionTodos(session, todos);
}
let _todoBroadcastTimer = null;
function updateSessionTodos(session, todos) {
try {
if (!Array.isArray(todos) || !todos.length) return;
const done = todos.filter((t) => t?.status === 'completed').length;
const cur = todos.find((t) => t?.status === 'in_progress');
session._todos = { done, total: todos.length, current: cur ? String(cur.content || cur.activeForm || cur.step || '').slice(0, 140) : null };
if (!_todoBroadcastTimer) { // coalesce: TodoWrite can fire several times per turn
_todoBroadcastTimer = setTimeout(() => { _todoBroadcastTimer = null; broadcastActiveSessions(); }, 500);
}
} catch { }
}
function setupSessionPty(session, id, ptyProcess, { cleanupOnExit = true } = {}) {
session.pty = ptyProcess;
if (session.mode === 'chat') {
let lineBuf = '';
if (session.backend === 'codex') {
const stripAnsi = (value) => String(value || '').replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '');
ptyProcess.onData((output) => {
if (session._reattachAttempts) session._reattachAttempts = 0;
// Append, trim only past 1.5x cap — slicing a fresh 800KB string per
// delta chunk was hundreds of MB/s of string churn while streaming
session.buffer += output;
if (session.buffer.length > 1200000) session.buffer = session.buffer.slice(-800000);
lineBuf += output;
let nlIdx;
while ((nlIdx = lineBuf.indexOf('\n')) !== -1) {
const line = lineBuf.substring(0, nlIdx).replace(/\r/g, '').trim();
lineBuf = lineBuf.substring(nlIdx + 1);
if (!line) continue;
try {
const msg = JSON.parse(stripAnsi(line).trim());
if (msg.type === '_stdin_ack') { session._stdinAckReceived = true; continue; }
const payload = msg.payload || {};
// remote transport state (2.139.0 codex remote chat, B-0588) —
// rides as an event_msg record from the wrapper; mirror the
// claude branch's broadcast so the status-bar chip works
if (msg.type === 'event_msg' && payload.type === '_remote_state') {
session._remoteState = payload.state === 'connected' ? null : { state: payload.state, attempts: payload.attempts || 0, at: Date.now() };
broadcastToSession(session, id, { type: 'remote-state', sessionId: id, state: payload.state, attempts: payload.attempts || 0 });
continue;
}
const nextThreadId = msg.type === 'session_meta'
? payload.id
: msg.type === 'wrapper_meta'
? payload.threadId
: null;
// Name ONLY from meta records: every codex function_call carries
// payload.name = the TOOL name ('shell'…) — ungated, each tool call
// renamed the session + 2 sync meta writes + 2 broadcasts, forever
// (audit round-2, high). Real thread names arrive via
// session_meta/wrapper_meta only.
const nextThreadName = (msg.type === 'session_meta' || msg.type === 'wrapper_meta')
? (payload.session_name || payload.sessionName || payload.threadName || payload.name || payload.thread?.name || null)
: null;
const sourceMeta = payload.source ? normalizeCodexSource(payload.source) : null;
let changed = false;
if (nextThreadId && session.backendSessionId !== nextThreadId) {
if (session.backendSessionId) {
const prev = session.forkedFrom || [];
if (!prev.includes(session.backendSessionId)) prev.push(session.backendSessionId);
session.forkedFrom = prev;
}
session.backendSessionId = nextThreadId;
session.claudeSessionId = null;
changed = true;
}
if (nextThreadName && session.name !== nextThreadName) {
session.name = nextThreadName;
changed = true;
}
if (payload.cwd && session.cwd !== payload.cwd) {
session.cwd = payload.cwd;
changed = true;
}
if (sourceMeta) {
const nextFields = {
sourceKind: sourceMeta.sourceKind || null,
agentKind: sourceMeta.agentKind || 'primary',
agentRole: sourceMeta.agentRole || '',
agentNickname: sourceMeta.agentNickname || '',
parentThreadId: sourceMeta.parentThreadId || null,
};
for (const [key, value] of Object.entries(nextFields)) {
if ((session[key] || null) !== (value || null)) {
session[key] = value;
changed = true;
}
}
}
if (changed && session.sockName) {
writeSessionMeta(session.sockName, {
...(readSessionMeta(session.sockName) || {}), // preserve keys not re-listed (agentToken/taskId/accountId)
name: session.name,
cwd: session.cwd,
backend: session.backend,
backendSessionId: session.backendSessionId,
claudeSessionId: null,
sourceKind: session.sourceKind || null,
agentKind: session.agentKind || 'primary',
agentRole: session.agentRole || '',
agentNickname: session.agentNickname || '',
parentThreadId: session.parentThreadId || null,
forkedFrom: session.forkedFrom || null,
permissionMode: session._permissionMode || null,
effort: session._effort || null,
createdAt: session.createdAt,
webuiSessionId: id,
mode: session.mode,
});
broadcastActiveSessions();
}
// Track turn lifecycle: streaming state + activity label
{
let newLabel = null;
if (msg.type === 'event_msg') {
const evType = payload.type;
if (evType === 'task_started' && payload.turn_id) { session._isStreaming = true; newLabel = 'thinking...'; }
else if (evType === 'task_complete' || evType === 'turn_aborted' || evType === 'task_failed') { session._isStreaming = false; newLabel = ''; }
else if (evType === 'goal_updated' && payload.goal) {
session._goal = payload.goal.objective || null;
session._goalElapsed = (payload.goal.timeUsedSeconds || payload.goal.time_used_seconds || 0) * 1000;
session._goalStatus = payload.goal.status || null;
broadcastToSession(session, id, { type: 'goal-updated', sessionId: id, goal: session._goal, goalElapsed: session._goalElapsed, goalStatus: session._goalStatus });
} else if (evType === 'goal_cleared') {
if (session._goal) session._prevGoal = session._goal;
session._goal = null; session._goalElapsed = 0; session._goalStatus = null;
broadcastToSession(session, id, { type: 'goal-updated', sessionId: id, goal: null, statusMsg: 'Goal cleared' });
}
} else if (msg.type === 'response_item') {
const itemType = payload.type;
if (itemType === 'message' && payload.role === 'assistant') newLabel = 'responding';
else if (itemType === 'function_call') newLabel = `running ${payload.name || 'tool'}`;
else if (itemType === 'reasoning') newLabel = 'thinking...';
}
if (newLabel !== null && session._streamingLabel !== newLabel) {
session._streamingLabel = newLabel;
broadcastToSession(session, id, { type: 'streaming-label', sessionId: id, label: newLabel });
}
}
// Codex plan tool → the session's live TODO summary (board pill)
if (msg.type === 'event_msg' && msg.payload?.type === 'plan_updated' && Array.isArray(msg.payload.plan)) {
updateSessionTodos(session, msg.payload.plan.map((p) => ({
content: p.step || '',
status: (p.status === 'inProgress' || p.status === 'in_progress') ? 'in_progress' : (p.status === 'completed' ? 'completed' : 'pending'),
})));
}
if (session._normalizer) session._normalizer.processLive(msg);
} catch {
broadcastToSession(session, id, { type: 'output', sessionId: id, data: line + '\n' });
}
}
});
} else {
if (!session.subagentBuffers) session.subagentBuffers = new Map();
if (!session.subagentEmittedUuids) session.subagentEmittedUuids = new Map(); // toolUseId → Set<uuid>
if (!session.subagentWatchers) session.subagentWatchers = new Map(); // toolUseId → {watcher, offset}
// Watch a subagent JSONL file for new messages (fills gap: text/thinking not in stream-json)
const startSubagentWatcher = (toolUseId, agentId, attempt = 0) => {
if (session.subagentWatchers.has(toolUseId)) return;
// Find JSONL path
const projectsDir = path.join(os.homedir(), '.claude', 'projects');
const projDir = cwdToProjectDir(session.cwd || '');
const candidates = [];
if (session.claudeSessionId) {
candidates.push(path.join(projectsDir, projDir, session.claudeSessionId, 'subagents', `agent-${agentId}.jsonl`));
try { for (const dir of fs.readdirSync(projectsDir)) { const fp = path.join(projectsDir, dir, session.claudeSessionId, 'subagents', `agent-${agentId}.jsonl`); if (!candidates.includes(fp)) candidates.push(fp); } } catch {}
}
const watchFile = candidates.find(f => { try { return fs.existsSync(f); } catch { return false; } });
if (!watchFile) {
// File doesn't exist yet — retry with backoff, capped: an agent that
// failed before writing its JSONL never gets a task_notification, so
// an uncapped 1s retry (each with a full projects-dir scan) would
// spin for the session's lifetime
if (attempt >= 30) { session.subagentWatchers.delete(toolUseId); return; }
const delay = Math.min(10000, 1000 * Math.pow(1.3, attempt));
// Belt-and-braces liveness: a killed session must not keep re-scanning
// the projects dir through this retry chain (audit round-2)
const retry = setTimeout(() => { session.subagentWatchers.delete(toolUseId); if (!activeSessions.has(id)) return; startSubagentWatcher(toolUseId, agentId, attempt + 1); }, delay);
session.subagentWatchers.set(toolUseId, { watcher: null, retry, lastActivity: Date.now() });
return;
}
if (!session.subagentEmittedUuids.has(toolUseId)) session.subagentEmittedUuids.set(toolUseId, new Set());
const emitted = session.subagentEmittedUuids.get(toolUseId);
let offset = 0;
// Read existing content first
const readNewLines = () => {
try {
const stat = fs.statSync(watchFile);
if (stat.size <= offset) return;
const buf = Buffer.alloc(stat.size - offset);
const fd = fs.openSync(watchFile, 'r');
fs.readSync(fd, buf, 0, buf.length, offset);
fs.closeSync(fd);
offset = stat.size;
for (const line of buf.toString('utf-8').split('\n')) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
const msg = JSON.parse(trimmed);
if (msg.uuid && emitted.has(msg.uuid)) continue; // already sent via stream-json
if (msg.uuid) emitted.add(msg.uuid);
if (msg.type !== 'user' && msg.type !== 'assistant' && msg.type !== 'result') continue;
// Buffer + broadcast
if (!session.subagentBuffers.has(toolUseId)) session.subagentBuffers.set(toolUseId, []);
session.subagentBuffers.get(toolUseId).push(msg);
broadcastToSession(session, id, { type: 'subagent-message', sessionId: id, parentToolUseId: toolUseId, message: msg });
// Normalize for subagent viewers
if (!session._subNormalizers) session._subNormalizers = new Map();
if (!session._subNormalizers.has(toolUseId)) {
const subMM = new MessageManager(`sub-${toolUseId}`);
subMM.onOp((op) => broadcastToSession(session, id, { type: 'msg', sessionId: `sub-${toolUseId}`, ...op }));
session._subNormalizers.set(toolUseId, subMM);
}
session._subNormalizers.get(toolUseId).processLive(msg);
} catch {}
}
} catch {}
};
readNewLines(); // read any existing content
const watcher = fs.watch(watchFile, () => { const e = session.subagentWatchers.get(toolUseId); if (e) e.lastActivity = Date.now(); readNewLines(); });
session.subagentWatchers.set(toolUseId, { watcher, lastActivity: Date.now() });
};
const stopSubagentWatcher = (toolUseId) => {
const entry = session.subagentWatchers.get(toolUseId);
if (entry) {
if (entry.watcher) entry.watcher.close();
if (entry.retry) clearTimeout(entry.retry);
session.subagentWatchers.delete(toolUseId);
}
};
ptyProcess.onData((output) => {
if (session._reattachAttempts) session._reattachAttempts = 0;
session.buffer += output;
if (session.buffer.length > 750000) session.buffer = session.buffer.slice(-500000);
lineBuf += output;
let nlIdx;
while ((nlIdx = lineBuf.indexOf('\n')) !== -1) {
const line = lineBuf.substring(0, nlIdx).replace(/\r/g, '').trim();
lineBuf = lineBuf.substring(nlIdx + 1);
if (!line) continue;
try {
const msg = JSON.parse(line);
if (msg.type === '_stdin_ack') { session._stdinAckReceived = true; continue; }
// Remote transport state from the chat-wrapper (2.125.0): the ssh
// pipe died and the wrapper is reconnecting to the host-side keeper
// (the REMOTE session is fine). Surfaced as a status-bar chip; the
// attach payload carries the current value for refreshes.
if (msg.type === '_remote_state') {
session._remoteState = { state: msg.state, attempts: msg.attempts || 0, at: Date.now() };
broadcastToSession(session, id, { type: 'remote-state', sessionId: id, ...session._remoteState });
continue;
}
// Claude fork: adopt the new session id. --fork-session makes claude
// mint a fresh id at startup — the very first system/hook_started