-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2881 lines (2697 loc) · 113 KB
/
Copy pathserver.js
File metadata and controls
2881 lines (2697 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
'use strict';
// Claude Control Center — backend server.
//
// Part 1: security skeleton — localhost bind, Host check, per-launch token
// auth on /api/*, whitelisted static files.
// Part 2: session index — transcript scanner, live-session poller, status
// derivation, GET /api/sessions[/:id].
// Part 3: tmux controller — mapPanes (PPID walk), capturePane, sendPrompt,
// sendKeys (whitelist), launchSession, killPane. No HTTP routes yet (Part 6).
// Part 4: JSONL tailer (byte offsets + partial-line buffers), directory
// watchers with a 2s safety pump, SSE hub (GET /api/events), and the
// transcript seed route (GET /api/sessions/:id/transcript).
// Part 5: aux endpoints (GET /api/sessions/:id/tasks, /api/stats,
// /api/projects) and macOS notifications on busy -> ready|idle.
// Part 6: control endpoints — POST prompt/keys/kill/new/watch wired to the
// tmux controller (incl. resume-into-new-tmux-session for done sessions),
// the launch overlay that bridges the post-launch adoption gap, and the
// watched-pane mirror loop feeding `pane` SSE events.
//
// Stdlib only. This file never writes anything under ~/.claude.
const http = require('http');
const fs = require('fs');
const fsp = fs.promises;
const path = require('path');
const crypto = require('crypto');
const os = require('os');
const { execFile } = require('child_process');
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const DEFAULT_PORT = 7777;
const PORT = (() => {
const raw = process.env.CCC_PORT;
if (typeof raw !== 'string' || !/^\d+$/.test(raw)) return DEFAULT_PORT;
const n = Number.parseInt(raw, 10);
return n >= 1 && n <= 65535 ? n : DEFAULT_PORT;
})();
// Per-launch token; never persisted. Gates every /api/* route.
const TOKEN = crypto.randomBytes(32).toString('hex');
const TOKEN_BUF = Buffer.from(TOKEN, 'utf8');
const PUBLIC_DIR = path.join(__dirname, 'public');
// Read-only data sources under ~/.claude. CCC_CLAUDE_DIR exists ONLY so smoke
// tests can point at a throwaway fixture tree (the dead-PID path cannot be
// exercised against the real ~/.claude without writing to it, which is
// forbidden — this server never writes anything under CLAUDE_DIR).
const CLAUDE_DIR = process.env.CCC_CLAUDE_DIR || path.join(os.homedir(), '.claude');
const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
const SESSIONS_DIR = path.join(CLAUDE_DIR, 'sessions');
const TASKS_DIR = path.join(CLAUDE_DIR, 'tasks');
// ~/.claude.json holds secrets. It is read-only input and ONLY its .projects
// key set is ever consumed (see readProjectKeys). CCC_CLAUDE_JSON mirrors the
// CCC_CLAUDE_DIR fixture override for smoke tests.
const CLAUDE_JSON_PATH = process.env.CCC_CLAUDE_JSON || path.join(os.homedir(), '.claude.json');
const LIVE_SCAN_INTERVAL_MS = 2000;
// The ONLY paths ever served as static files. Lookup is an exact-string match
// on the WHATWG-normalized url.pathname, and the map values are fixed
// filenames — request input is never joined into a filesystem path, so
// traversal to non-whitelisted files is structurally impossible.
const STATIC_WHITELIST = {
'/': { file: 'index.html', type: 'text/html; charset=utf-8' },
'/app.js': { file: 'app.js', type: 'text/javascript; charset=utf-8' },
'/style.css': { file: 'style.css', type: 'text/css; charset=utf-8' },
};
// ---------------------------------------------------------------------------
// Security helpers
// ---------------------------------------------------------------------------
// Accept only `localhost` or `127.0.0.1`, optionally with a `:<digits>` port
// suffix. We bind 127.0.0.1, so `[::1]` cannot legitimately appear; anything
// else (other IPs, DNS names, IPv6 forms) is rejected.
function isAllowedHost(hostHeader) {
if (typeof hostHeader !== 'string' || hostHeader === '') return false;
const host = hostHeader.replace(/:\d+$/, '');
return host.toLowerCase() === 'localhost' || host === '127.0.0.1';
}
// Constant-time token comparison. Candidate comes from the X-CCC-Token header
// or the ?token= query param (the latter is needed for EventSource later).
function checkToken(req, url) {
let candidate = req.headers['x-ccc-token'];
if (candidate === undefined) candidate = url.searchParams.get('token');
if (typeof candidate !== 'string') return false; // array header / absent
const candidateBuf = Buffer.from(candidate, 'utf8');
if (candidateBuf.length !== TOKEN_BUF.length) return false;
return crypto.timingSafeEqual(candidateBuf, TOKEN_BUF);
}
// ---------------------------------------------------------------------------
// Response helpers
// ---------------------------------------------------------------------------
// Applied to every response, success and error alike. The launch URL carries
// the token in its query string, so suppressing referrers is cheap insurance.
function baseHeaders() {
return {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
};
}
function sendJson(res, status, obj) {
const body = JSON.stringify(obj);
res.writeHead(status, {
...baseHeaders(),
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(body),
});
res.end(body);
}
function serveStatic(req, res, pathname) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405, {
...baseHeaders(),
'Allow': 'GET, HEAD',
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
});
res.end(JSON.stringify({ error: 'method not allowed' }));
return;
}
const entry = STATIC_WHITELIST[pathname];
if (!entry) {
sendJson(res, 404, { error: 'not found' });
return;
}
fs.readFile(path.join(PUBLIC_DIR, entry.file), (err, data) => {
if (err) {
sendJson(res, 404, { error: 'not found' });
return;
}
res.writeHead(200, {
...baseHeaders(),
'Content-Type': entry.type,
'Cache-Control': 'no-store',
'Content-Length': data.length,
});
if (req.method === 'HEAD') res.end();
else res.end(data);
});
}
// ---------------------------------------------------------------------------
// Session index
// ---------------------------------------------------------------------------
//
// Sources (all read-only):
// PROJECTS_DIR/<encoded-cwd>/<sessionId>.jsonl — transcripts (depth-2 only;
// deeper paths are subagent transcripts and are excluded). Encoded dir
// names are lossy and are NEVER decoded — real cwd comes from JSONL
// content or the live session file.
// SESSIONS_DIR/<pid>.json — live session status files. Stale files for dead
// PIDs are ignored, never deleted or modified.
// TASKS_DIR/<sessionId>/<n>.json — task lists.
// Single source of truth for what a sessionId may look like. Enforced when
// ids are admitted to the index (from transcript filenames and live session
// files), re-checked in getTasks before any path.join, and reused by the
// /api/sessions/:id route pattern — so nothing path-unsafe (e.g. "..") can
// ever become an index key or reach the filesystem.
const SESSION_ID_PATTERN = '[A-Za-z0-9-]{1,128}';
const SESSION_ID_RE = new RegExp(`^${SESSION_ID_PATTERN}$`);
const transcriptCache = new Map(); // path -> { mtimeMs, size, summary }
let transcriptBySession = new Map(); // sessionId -> summary (deduped, deterministic)
const sessionIndex = new Map(); // sessionId -> record (exported; cleared in place)
let liveBySession = new Map(); // sessionId -> { pid, status, cwd, name, startedAt, updatedAt }
const warnedOnce = new Set();
function warnOnce(key, message) {
if (warnedOnce.has(key)) return;
warnedOnce.add(key);
console.warn(`ccc: ${message}`);
}
function safeJsonParse(str) {
try {
return JSON.parse(str);
} catch (err) {
return null;
}
}
// Null-safe timestamp math: non-finite/null operands are ignored; returns
// null only when both are absent. Every place timestamps merge goes through
// these so NaN can never reach a record or the sort comparator.
function maxTs(a, b) {
const av = Number.isFinite(a) ? a : null;
const bv = Number.isFinite(b) ? b : null;
if (av === null) return bv;
if (bv === null) return av;
return av > bv ? av : bv;
}
function minTs(a, b) {
const av = Number.isFinite(a) ? a : null;
const bv = Number.isFinite(b) ? b : null;
if (av === null) return bv;
if (bv === null) return av;
return av < bv ? av : bv;
}
function toTs(value) {
return Number.isFinite(value) ? value : null;
}
function toCount(value) {
return Number.isFinite(value) ? value : 0;
}
// Local-calendar-day key ("YYYY-MM-DD") for per-day stats buckets. Buckets
// are keyed by absolute day, not a "today"-relative window, so a cached
// summary parsed yesterday is still correct after midnight (a file not
// modified today cannot contain entries timestamped today).
function dayKey(tsMs) {
const d = new Date(tsMs);
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
// Get-or-create the summary's per-day bucket for a (finite) timestamp.
function dayBucket(summary, tsMs) {
const key = dayKey(tsMs);
let bucket = summary.byDay[key];
if (!bucket) {
// byModel keys come from JSONL message.model strings — null prototype
// guards against __proto__/constructor key collisions.
bucket = { msgs: 0, byModel: Object.create(null) };
summary.byDay[key] = bucket;
}
return bucket;
}
// Reduce one parsed transcript entry into the running summary. One assistant
// API message spans multiple jsonl lines sharing message.id, each carrying
// identical usage — msgCount and tokens MUST dedupe by message.id or they
// overcount up to 7x (verified). isSidechain exclusion applies to counts and
// tokens only. Per-day buckets are filled at exactly the two count sites, so
// they inherit the dedupe and sidechain/isMeta exclusions bit-for-bit;
// entries without a finite timestamp count toward cumulative totals but are
// not bucketed (excluded from per-day stats).
function reduceTranscriptEntry(summary, entry, seenAssistantIds) {
if (typeof entry.cwd === 'string' && entry.cwd !== '') summary.cwd = entry.cwd;
if (typeof entry.gitBranch === 'string' && entry.gitBranch !== '') summary.gitBranch = entry.gitBranch;
if (typeof entry.slug === 'string' && entry.slug !== '') summary.slug = entry.slug;
if (typeof entry.version === 'string' && entry.version !== '') summary.version = entry.version;
let entryTs = null;
if (typeof entry.timestamp === 'string') {
const ts = Date.parse(entry.timestamp);
if (Number.isFinite(ts)) {
entryTs = ts;
summary.firstTs = minTs(summary.firstTs, ts);
summary.lastTs = maxTs(summary.lastTs, ts);
summary.lastEntry = {
type: typeof entry.type === 'string' ? entry.type : null,
subtype: typeof entry.subtype === 'string' ? entry.subtype : null,
};
}
}
switch (entry.type) {
case 'assistant': {
const msg = entry.message && typeof entry.message === 'object' ? entry.message : null;
if (msg && typeof msg.model === 'string' && msg.model !== '') summary.model = msg.model;
if (entry.isSidechain === true) break;
const id = msg && typeof msg.id === 'string' && msg.id !== '' ? msg.id : null;
if (id !== null) {
if (seenAssistantIds.has(id)) break; // later lines of the same message
seenAssistantIds.add(id);
}
summary.msgCount += 1;
const usage = msg && msg.usage && typeof msg.usage === 'object' ? msg.usage : null;
if (usage) {
summary.tokens.input += toCount(usage.input_tokens);
summary.tokens.output += toCount(usage.output_tokens);
summary.tokens.cacheRead += toCount(usage.cache_read_input_tokens);
summary.tokens.cacheCreate += toCount(usage.cache_creation_input_tokens);
}
if (entryTs !== null) {
const bucket = dayBucket(summary, entryTs);
bucket.msgs += 1;
if (usage) {
// The message's OWN model, not summary.model — sessions switch models.
const model = msg && typeof msg.model === 'string' && msg.model !== ''
? msg.model
: 'unknown';
let m = bucket.byModel[model];
if (!m) {
m = { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 };
bucket.byModel[model] = m;
}
m.input += toCount(usage.input_tokens);
m.output += toCount(usage.output_tokens);
m.cacheRead += toCount(usage.cache_read_input_tokens);
m.cacheCreate += toCount(usage.cache_creation_input_tokens);
}
}
break;
}
case 'user':
if (entry.isSidechain !== true && entry.isMeta !== true) {
summary.msgCount += 1;
if (entryTs !== null) dayBucket(summary, entryTs).msgs += 1;
}
break;
case 'ai-title':
if (typeof entry.aiTitle === 'string' && entry.aiTitle !== '') summary.aiTitle = entry.aiTitle;
break;
case 'system':
if (entry.subtype === 'away_summary' && typeof entry.content === 'string') {
summary.awaySummary = entry.content;
}
break;
default:
break; // unknown entry types are fine — skip
}
}
// Streamed line-by-line transcript parse (manual \n splitting; the stdlib
// whitelist does not include readline). The trailing partial line — present
// when the file is mid-append — is parsed if it is valid JSON, else dropped.
// Resolves null on stream errors (ENOENT race, EACCES); caller drops the file.
function parseTranscriptFile(filePath) {
return new Promise((resolve) => {
const summary = {
path: filePath,
sessionId: null, // set by the caller from the filename
cwd: null,
gitBranch: null,
slug: null,
version: null,
model: null,
aiTitle: null,
awaySummary: null,
firstTs: null,
lastTs: null,
msgCount: 0,
tokens: { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 },
lastEntry: null, // { type, subtype } of the last entry with a timestamp
// dayKey -> { msgs, byModel } (stats only; makeRecord copies explicit
// fields, so byDay never reaches API records or SSE snapshots).
byDay: Object.create(null),
};
const seenAssistantIds = new Set();
const reduceLine = (line) => {
if (line === '' || line.trim() === '') return;
const entry = safeJsonParse(line);
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return;
reduceTranscriptEntry(summary, entry, seenAssistantIds);
};
let partial = '';
const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
stream.on('data', (chunk) => {
const pieces = (partial + chunk).split('\n');
partial = pieces.pop();
for (const piece of pieces) reduceLine(piece);
});
stream.on('end', () => {
reduceLine(partial);
resolve(summary);
});
stream.on('error', () => resolve(null));
});
}
let transcriptScans = 0;
// Scan PROJECTS_DIR/*/*.jsonl (depth-2 regular files only). Unchanged files
// (matching mtimeMs+size) reuse the cached summary, so steady-state ticks are
// stat-only. After the cache pass, transcriptBySession is rebuilt with
// deterministic duplicate resolution: later lastTs wins, ties go to the
// lexicographically smaller path — the outcome never depends on Map order.
async function scanTranscripts() {
const t0 = Date.now();
let dirents = [];
try {
dirents = await fsp.readdir(PROJECTS_DIR, { withFileTypes: true });
} catch (err) {
if (err.code === 'ENOENT') warnOnce('projects-enoent', `projects dir missing: ${PROJECTS_DIR}`);
else warnOnce('projects-readdir', `cannot read projects dir: ${err.message}`);
dirents = [];
}
const seenPaths = new Set();
for (const dirent of dirents) {
if (!dirent.isDirectory()) continue;
const dirPath = path.join(PROJECTS_DIR, dirent.name);
let files = [];
try {
files = await fsp.readdir(dirPath, { withFileTypes: true });
} catch (err) {
continue; // dir vanished mid-scan
}
for (const f of files) {
if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
if (!SESSION_ID_RE.test(path.basename(f.name, '.jsonl'))) continue;
const filePath = path.join(dirPath, f.name);
let st;
try {
st = await fsp.stat(filePath);
} catch (err) {
continue; // file vanished mid-scan
}
if (!st.isFile()) continue;
seenPaths.add(filePath);
const cached = transcriptCache.get(filePath);
if (cached && cached.mtimeMs === st.mtimeMs && cached.size === st.size) continue;
const summary = await parseTranscriptFile(filePath);
if (summary === null) {
transcriptCache.delete(filePath);
seenPaths.delete(filePath);
continue;
}
summary.sessionId = path.basename(f.name, '.jsonl');
transcriptCache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, summary });
}
}
for (const key of transcriptCache.keys()) {
if (!seenPaths.has(key)) transcriptCache.delete(key);
}
const next = new Map();
for (const { summary } of transcriptCache.values()) {
const prev = next.get(summary.sessionId);
if (!prev) {
next.set(summary.sessionId, summary);
continue;
}
warnOnce(`dup-${summary.sessionId}`, `duplicate transcripts for session ${summary.sessionId}`);
const prevTs = prev.lastTs === null ? -Infinity : prev.lastTs;
const curTs = summary.lastTs === null ? -Infinity : summary.lastTs;
if (curTs > prevTs || (curTs === prevTs && summary.path < prev.path)) {
next.set(summary.sessionId, summary);
}
}
transcriptBySession = next;
transcriptScans += 1;
if (transcriptScans === 1) {
console.log(`ccc: scanned ${transcriptCache.size} transcripts in ${Date.now() - t0}ms`);
}
}
// PID-reuse guard: one batched `ps -o pid=,lstart= -p p1,p2,...` (argv array,
// never a shell) for all kill-alive candidates. procStart strings in session
// files are `ps lstart` rendered in UTC (verified: machine TZ is PDT yet every
// file matches `TZ=UTC ps` exactly), so ps runs with TZ=UTC or every
// comparison would fail and all live sessions would be treated as dead.
// Resolves a Map<pid, lstart>, or null on total ps failure (guard skipped).
function psLstartByPid(pids) {
return new Promise((resolve) => {
execFile(
'ps',
['-o', 'pid=,lstart=', '-p', pids.join(',')],
{ timeout: 5000, env: { ...process.env, TZ: 'UTC' } },
(err, stdout) => {
// Non-zero exit just means some PIDs were gone — parse whatever stdout
// it produced. Spawn-level failure (string err.code) or a timeout kill
// means no trustworthy output: skip the guard this tick.
if (err && (typeof err.code === 'string' || err.killed)) {
warnOnce('ps-guard', `ps unavailable, PID-reuse guard skipped: ${err.message}`);
resolve(null);
return;
}
const byPid = new Map();
for (const line of String(stdout || '').split('\n')) {
const m = /^\s*(\d+)\s+(.+?)\s*$/.exec(line);
if (m) byPid.set(Number.parseInt(m[1], 10), m[2]);
}
resolve(byPid);
}
);
});
}
function normalizeWhitespace(str) {
return str.trim().replace(/\s+/g, ' ');
}
// kill(pid, 0) aliveness probe; EPERM = exists but not ours = alive.
function isPidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === 'EPERM';
}
}
// Scan SESSIONS_DIR/*.json into a fresh liveBySession map. A file survives
// only if its pid is alive (`process.kill(pid, 0)`; EPERM counts as alive)
// AND, when the file carries a procStart string, that string matches the live
// process's `ps lstart` (PID reuse by an unrelated process => treated as
// dead). Dead/stale files are ignored — NEVER deleted or modified. This
// matters because later parts type keystrokes into panes resolved from these
// PIDs.
async function scanLiveSessions() {
let dirents = [];
try {
dirents = await fsp.readdir(SESSIONS_DIR, { withFileTypes: true });
} catch (err) {
if (err.code !== 'ENOENT') warnOnce('sessions-readdir', `cannot read sessions dir: ${err.message}`);
dirents = [];
}
const candidates = [];
for (const dirent of dirents) {
// Only regular files named <pid>.json, and the embedded pid must match
// the filename — a stale or malformed file must not be able to point at
// an arbitrary alive process (later parts control sessions by PID).
if (!dirent.isFile()) continue;
const nameMatch = /^([1-9]\d*)\.json$/.exec(dirent.name);
if (!nameMatch) continue;
const filePid = Number.parseInt(nameMatch[1], 10);
let raw;
try {
raw = await fsp.readFile(path.join(SESSIONS_DIR, dirent.name), 'utf8');
} catch (err) {
continue; // vanished mid-scan
}
const data = safeJsonParse(raw); // mid-write JSON -> null -> retried next tick
if (!data || typeof data !== 'object' || Array.isArray(data)) continue;
const pid = data.pid;
if (!Number.isSafeInteger(pid) || pid <= 0) continue; // never reaches process.kill
if (pid !== filePid) continue;
if (typeof data.sessionId !== 'string' || !SESSION_ID_RE.test(data.sessionId)) continue;
if (!isPidAlive(pid)) continue; // stale file: ignore, never delete
candidates.push({ pid, sessionId: data.sessionId, data });
}
if (candidates.length > 0) {
const lstartByPid = await psLstartByPid(candidates.map((c) => c.pid));
if (lstartByPid !== null) {
for (let i = candidates.length - 1; i >= 0; i--) {
const { pid, data } = candidates[i];
if (typeof data.procStart !== 'string' || data.procStart === '') continue; // kill-only fallback
const liveLstart = lstartByPid.get(pid);
if (liveLstart === undefined ||
normalizeWhitespace(data.procStart) !== normalizeWhitespace(liveLstart)) {
candidates.splice(i, 1); // PID reused by an unrelated process
}
}
}
}
const next = new Map();
for (const { pid, sessionId, data } of candidates) {
const entry = {
pid,
status: typeof data.status === 'string' ? data.status : null,
cwd: typeof data.cwd === 'string' && data.cwd !== '' ? data.cwd : null,
name: typeof data.name === 'string' && data.name !== '' ? data.name : null,
version: typeof data.version === 'string' && data.version !== '' ? data.version : null,
startedAt: toTs(data.startedAt),
updatedAt: toTs(data.updatedAt),
// Internal only (never copied onto API records): lets the op-time
// guard (assertLiveRecordPid) re-run the PID-reuse check above.
procStart: typeof data.procStart === 'string' && data.procStart !== '' ? data.procStart : null,
};
const prev = next.get(sessionId);
if (!prev) {
next.set(sessionId, entry);
continue;
}
// Two surviving files claim the same sessionId: larger updatedAt wins.
const prevTs = prev.updatedAt === null ? -Infinity : prev.updatedAt;
const curTs = entry.updatedAt === null ? -Infinity : entry.updatedAt;
if (curTs > prevTs) next.set(sessionId, entry);
}
liveBySession = next;
}
const TASK_FILE_MAX_BYTES = 1024 * 1024; // task files are <1KB in practice
// Tasks for one session (route added in Part 5 — this feeds an HTTP
// endpoint). Defense in depth before path.join: the id must match
// SESSION_ID_RE (no "..", no separators) AND be one we discovered ourselves
// via readdir. Only regular files are read: dirents must be files (a symlink
// named 1.json must not be able to exfiltrate arbitrary JSON such as
// ~/.claude.json), and the open itself uses O_NOFOLLOW + O_NONBLOCK with an
// fstat re-check, so a swap-to-symlink/FIFO between readdir and open can
// neither follow a link nor block the event loop. Reads are size-capped.
function getTasks(sessionId) {
if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return [];
if (!sessionIndex.has(sessionId)) return [];
const dir = path.join(TASKS_DIR, sessionId);
let dirents;
try {
dirents = fs.readdirSync(dir, { withFileTypes: true });
} catch (err) {
return []; // ENOENT et al -> no tasks
}
const tasks = [];
const taskNames = dirents
.filter((d) => d.isFile() && /^\d+\.json$/.test(d.name))
.map((d) => d.name)
.sort((a, b) => Number.parseInt(a, 10) - Number.parseInt(b, 10));
const openFlags = fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK;
for (const name of taskNames) {
let raw = null;
let fd = null;
try {
fd = fs.openSync(path.join(dir, name), openFlags);
const st = fs.fstatSync(fd);
if (st.isFile() && st.size <= TASK_FILE_MAX_BYTES) {
raw = fs.readFileSync(fd, 'utf8');
}
} catch (err) {
// ELOOP (symlink), ENOENT (vanished), etc. -> skip this entry
} finally {
if (fd !== null) {
try { fs.closeSync(fd); } catch (err) { /* already closed */ }
}
}
if (raw === null) continue;
const task = safeJsonParse(raw);
// Only task-shaped values (plain objects) are exposed.
if (task && typeof task === 'object' && !Array.isArray(task)) tasks.push(task);
}
return tasks;
}
// ---------------------------------------------------------------------------
// JSONL tailer
// ---------------------------------------------------------------------------
//
// Per-file incremental transcript reader feeding the SSE hub: seeds read the
// trailing tailKb of a file, pumps read only appended bytes. Splitting is
// done on raw bytes (0x0A) and only complete lines are decoded, so a
// multi-byte UTF-8 character split across reads is never corrupted. Strictly
// read-only: stat / open('r') / read; every FileHandle closes in try/finally.
const TAIL_SKIP_THRESHOLD_BYTES = 512 * 1024; // a single pump never reads more
const TAIL_WINDOW_BYTES = 64 * 1024; // trailing window when skipping ahead
const TAIL_PARTIAL_CAP_BYTES = 1024 * 1024; // pathological line without \n
const WIRE_TEXT_CAP = 4000;
const WIRE_PREVIEW_CAP = 200;
const tailStates = new Map(); // path -> { offset, partial: Buffer, sessionId }
const tailOpTails = new Map(); // path -> never-rejecting tail promise
// Per-file op queue (same pattern as enqueuePaneOp): a seed read and a
// watcher pump on the same file can never interleave their
// stat/read/state-update sequences.
function enqueueTailOp(filePath, fn) {
const tail = tailOpTails.get(filePath) || Promise.resolve();
const run = tail.then(fn);
const guard = run.then(() => undefined, () => undefined);
tailOpTails.set(filePath, guard);
guard.then(() => {
if (tailOpTails.get(filePath) === guard) tailOpTails.delete(filePath);
});
return run;
}
// First line of a string, capped for wire previews.
function previewLine(str) {
if (typeof str !== 'string') return '';
const nl = str.indexOf('\n');
return (nl === -1 ? str : str.slice(0, nl)).slice(0, WIRE_PREVIEW_CAP);
}
function toolResultPreview(content) {
if (typeof content === 'string') return previewLine(content);
if (Array.isArray(content)) {
for (const block of content) {
if (block && typeof block === 'object' && block.type === 'text' &&
typeof block.text === 'string') {
return previewLine(block.text);
}
}
}
return '';
}
// Reduce one parsed JSONL entry to the compact wire format. Full tool
// payloads never cross the wire — tool inputs/results can carry secrets, so
// previews stay strictly capped. Returns null for non-object entries. The
// client dedupes seed/SSE overlap (and truncation replays) by uuid.
function toWireEntry(entry) {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null;
const msg = entry.message && typeof entry.message === 'object' && !Array.isArray(entry.message)
? entry.message
: null;
let text = null;
const blocks = [];
if (entry.type === 'user' || entry.type === 'assistant') {
const content = msg ? msg.content : null;
const parts = [];
if (typeof content === 'string') {
parts.push(content);
} else if (Array.isArray(content)) {
for (const block of content) {
if (!block || typeof block !== 'object') continue;
if (block.type === 'text' && typeof block.text === 'string') {
parts.push(block.text);
} else if (block.type === 'tool_use') {
let preview = '';
try {
const json = JSON.stringify(block.input); // single-line by construction
if (typeof json === 'string') preview = json.slice(0, WIRE_PREVIEW_CAP);
} catch (err) { /* unstringifiable input -> empty preview */ }
blocks.push({
kind: 'tool_use',
name: typeof block.name === 'string' ? block.name : null,
preview,
});
} else if (block.type === 'tool_result') {
blocks.push({
kind: 'tool_result',
preview: toolResultPreview(block.content),
isError: block.is_error === true,
});
}
}
}
if (parts.length > 0) text = parts.join('\n');
} else if (typeof entry.content === 'string') {
text = entry.content; // system entries (incl. away_summary)
}
let textTruncated = false;
if (typeof text === 'string' && text.length > WIRE_TEXT_CAP) {
text = text.slice(0, WIRE_TEXT_CAP);
textTruncated = true;
}
const ts = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN;
return {
uuid: typeof entry.uuid === 'string' ? entry.uuid : null,
ts: Number.isFinite(ts) ? ts : null,
type: typeof entry.type === 'string' ? entry.type : null,
subtype: typeof entry.subtype === 'string' ? entry.subtype : null,
isSidechain: entry.isSidechain === true,
role: msg && typeof msg.role === 'string' ? msg.role : null,
model: msg && typeof msg.model === 'string' ? msg.model : null,
text,
textTruncated,
blocks,
// Carried for turn_duration dividers in the UI; null on all other entries.
durationMs: Number.isFinite(entry.durationMs) ? entry.durationMs : null,
};
}
// Split a buffer on 0x0A. `lines` are complete lines (views into buf);
// `rest` is a COPY of the trailing incomplete piece so storing it as a tail
// state's `partial` does not pin a large parent buffer in memory.
function splitBufferLines(buf) {
const lines = [];
let start = 0;
let idx;
while ((idx = buf.indexOf(0x0a, start)) !== -1) {
lines.push(buf.subarray(start, idx));
start = idx + 1;
}
return { lines, rest: Buffer.from(buf.subarray(start)) };
}
function pushWireLine(lineBuf, entries) {
const line = lineBuf.toString('utf8');
if (line.trim() === '') return;
const wire = toWireEntry(safeJsonParse(line)); // malformed JSON -> null -> dropped
if (wire !== null) entries.push(wire);
}
// Read [start, end) through an open file handle. Returns however many bytes
// were actually available (the file may shrink between stat and read).
async function readByteRange(fh, start, end) {
const length = end - start;
const buf = Buffer.alloc(length);
let done = 0;
while (done < length) {
const { bytesRead } = await fh.read(buf, done, length - done, start + done);
if (bytesRead === 0) break;
done += bytesRead;
}
return done === length ? buf : buf.subarray(0, done);
}
// Seed read for the transcript route: the trailing tailKb of the file. When
// the read does not start at byte 0, everything up to and including the
// first \n is dropped (a partial first line must never be parsed); the
// trailing piece at EOF is parsed if it is complete valid JSON, dropped
// otherwise. PURE READ: tail states are never created, advanced, or rewound
// here — startup EOF seeding and pumpTail own that state. A seed that
// touched it could mark a newly discovered file "already delivered" and
// suppress its first broadcast to existing SSE clients; the overlap a
// seeding client may see instead is deduped client-side by uuid. Runs inside
// the per-file op queue so it cannot interleave with a pump's stat/read
// sequence. ENOENT resolves to []; any other error propagates to the route's
// 500 boundary.
function readTailSeed(filePath, tailKb) {
return enqueueTailOp(filePath, async () => {
let fh;
try {
fh = await fsp.open(filePath, 'r');
} catch (err) {
if (err && err.code === 'ENOENT') return [];
throw err;
}
let buf;
try {
const size = (await fh.stat()).size;
const start = Math.max(0, size - tailKb * 1024);
buf = await readByteRange(fh, start, size);
if (start > 0) {
const nl = buf.indexOf(0x0a);
buf = nl === -1 ? Buffer.alloc(0) : buf.subarray(nl + 1);
}
} finally {
await fh.close();
}
const entries = [];
const { lines, rest } = splitBufferLines(buf);
for (const lineBuf of lines) pushWireLine(lineBuf, entries);
pushWireLine(rest, entries); // EOF piece: parsed if valid, else dropped
return entries;
});
}
// Incremental pump: read appended bytes, return new wire entries (callers
// broadcast). Never rejects — watcher callbacks and the safety pump must not
// throw. State transitions:
// no state -> created at offset 0, so a file first seen via a watcher
// streams from the start (bounded by the skip-ahead cap)
// ENOENT -> state dropped (recreated at 0 if the file reappears)
// size < offset -> truncation/replacement: reset to 0 and pump the current
// contents in this same call (a coalesced truncate+append
// still delivers; uuid-dedupe absorbs replays)
// far behind -> skip-ahead: only the trailing 64 KB window is read
function pumpTail(filePath) {
return enqueueTailOp(filePath, async () => {
let state = tailStates.get(filePath);
if (!state) {
state = {
offset: 0,
partial: Buffer.alloc(0),
sessionId: path.basename(filePath, '.jsonl'),
};
tailStates.set(filePath, state);
}
let size;
try {
size = (await fsp.stat(filePath)).size;
} catch (err) {
if (err && err.code === 'ENOENT') tailStates.delete(filePath);
return [];
}
if (size < state.offset) {
state.offset = 0;
state.partial = Buffer.alloc(0);
}
if (size === state.offset) return [];
let fh;
try {
fh = await fsp.open(filePath, 'r');
} catch (err) {
if (err && err.code === 'ENOENT') tailStates.delete(filePath);
return [];
}
const entries = [];
try {
if (size - state.offset > TAIL_SKIP_THRESHOLD_BYTES) {
// Skip-ahead: discard the old partial, deliver the trailing window.
const start = size - TAIL_WINDOW_BYTES;
let buf = await readByteRange(fh, start, size);
const consumed = start + buf.length;
const nl = buf.indexOf(0x0a);
buf = nl === -1 ? Buffer.alloc(0) : buf.subarray(nl + 1);
const { lines, rest } = splitBufferLines(buf);
for (const lineBuf of lines) pushWireLine(lineBuf, entries);
state.offset = consumed;
state.partial = rest;
} else {
const chunk = await readByteRange(fh, state.offset, size);
const combined = Buffer.concat([state.partial, chunk]);
const { lines, rest } = splitBufferLines(combined);
for (const lineBuf of lines) pushWireLine(lineBuf, entries);
state.offset += chunk.length;
// Defensive cap: a giant line that never ends must not grow forever.
state.partial = rest.length > TAIL_PARTIAL_CAP_BYTES ? Buffer.alloc(0) : rest;
}
} catch (err) {
return []; // read error: keep state, retry on the next pump
} finally {
await fh.close().catch(() => {});
}
return entries;
});
}
// ---------------------------------------------------------------------------
// tmux controller
// ---------------------------------------------------------------------------
//
// All control operations target tmux pane IDs (%N from #{pane_id}): unique,
// stable for the pane's lifetime, and immune to the session-name prefix/glob
// matching and window/pane-index renumbering that make session:window.pane
// strings unsafe for scripted control. The human-readable string is kept on
// records as tmuxLabel for display only. tmux is always invoked via execFile
// with argv arrays — never a shell.
const TMUX_BIN = fs.existsSync('/opt/homebrew/bin/tmux') ? '/opt/homebrew/bin/tmux' : 'tmux';
const PANE_ID_RE = /^%\d+$/;
// Promise wrapper around execFile(tmux, ...). Rejects with the subcommand and
// trimmed stderr so callers see real causes ("can't find pane", "no server
// running"); spawn failure (ENOENT) rejects too. `input`, when given, is
// written to stdin (with an error listener so an early tmux exit surfaces as
// the callback's rejection, not an EPIPE crash).
function execTmux(args, { input } = {}) {
return new Promise((resolve, reject) => {
const child = execFile(
TMUX_BIN,
args,
{ timeout: 10000, maxBuffer: 4 * 1024 * 1024 },
(err, stdout, stderr) => {
if (err) {
const detail = String(stderr || '').trim() || err.message;
reject(new Error(`tmux ${args[0]}: ${detail}`));
return;
}
resolve(String(stdout));
}
);
if (child.stdin) {
child.stdin.on('error', () => {}); // EPIPE if tmux exits early
if (input !== undefined) child.stdin.end(input);
else child.stdin.end();
}
});
}
// The only target form this module ever stores or accepts. Targets are always
// passed as the argv element after -t, so flag/shell injection is
// structurally impossible even before this check.
function assertTarget(target) {
if (typeof target !== 'string' || !PANE_ID_RE.test(target)) {
throw new Error(`invalid tmux target: ${String(target).slice(0, 64)}`);
}
}
let tmuxTargetByPid = new Map(); // live claude pid -> { paneId, label }; swapped atomically
// Panes created by launchSession this run: paneId -> tmux SERVER pid at
// launch time. Entries are removed on a successful killPane, and mapPanes
// purges every entry recorded against a different tmux server generation —
// pane IDs are never reused within one server's lifetime, but a RESTARTED
// tmux server starts its %N counter over, so without the generation tag a
// stale id could match an unrelated new pane and pass assertControlledPane.
// Within one generation a stale id can only ever error, never reach another
// pane, and the map is bounded by the number of launches per server run.
const launchedPaneIds = new Map();
// Ownership boundary on top of the shape check: control operations are
// allowed only against panes that hold a live claude we mapped ourselves
// (tmuxTargetByPid) or panes this module launched. The Part 6 routes derive
// targets server-side from the session index, but these functions are
// client-reachable there — a token holder must not be able to capture or
// type into arbitrary tmux panes by guessing pane ids. .code lets the routes
// map this to a 409 (pane vanished between scan ticks / stale index).
function assertControlledPane(target) {
assertTarget(target);
if (launchedPaneIds.has(target)) return;
for (const pane of tmuxTargetByPid.values()) {
if (pane.paneId === target) return;
}
const err = new Error(`not a controlled pane: ${target}`);
err.code = 'UNKNOWN_TARGET';
throw err;
}
// Op-time generation re-check for panes we launched: the scan-driven purge
// in mapPanes is up to one tick (~2s) behind, and across a tmux server
// restart pane ids restart and may be reused — a stale launched id must
// never reach an unrelated pane on the new server. One display-message
// round-trip pins the pane to the server generation it was launched on; a
// mismatch drops the entry and rejects. Panes resolved via tmuxTargetByPid
// skip this: that map is rebuilt from the CURRENT server every tick, pane
// ids are never reused within one server generation, and a restart kills the
// mapped claude (the pid guards reject the op).
async function verifyLaunchedPaneGeneration(target) {
const expected = launchedPaneIds.get(target);
if (expected === undefined) return;