-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3728 lines (3294 loc) · 115 KB
/
server.js
File metadata and controls
3728 lines (3294 loc) · 115 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
import http from 'node:http';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { createReadStream, existsSync } from 'node:fs';
import readline from 'node:readline';
import { fileURLToPath } from 'node:url';
import { randomUUID } from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { getInteractionCapabilities, handleInteractionRequest } from './interaction.js';
import { loadRuntimeConfig } from './config.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const execFileAsync = promisify(execFile);
const SOURCE_META = {
claude: { label: 'Claude', shortLabel: 'CC' },
codex: { label: 'Codex', shortLabel: 'CX' },
copilot: { label: 'Copilot', shortLabel: 'CP' },
};
const CLAUDE_SYNTHETIC_WARMUP_PROMPT = 'Warmup';
const CLAUDE_SYNTHETIC_SUMMARY_PREFIX = 'Context: This summary will be shown in a list to help users and Claude choose which conversations are relevant.';
const CLAUDE_SYNTHETIC_JUDGE_PREFIX = 'Analyze this conversation and determine: Does the assistant have more autonomous work to do RIGHT NOW?';
const config = loadRuntimeConfig();
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
};
const TRASH_ROOT = '/tmp/session-dashboard-trash';
const SESSION_TITLE_OVERRIDES_FILE = path.join(__dirname, 'data', 'session-title-overrides.json');
const CLAUDE_PROVENANCE_FILE = path.join(__dirname, 'data', 'claude-session-provenance.json');
const SESSION_METADATA_CACHE_FILE = path.join(__dirname, 'data', 'session-metadata-cache.json');
const SESSION_SNAPSHOT_TTL_MS = 10000;
const MESSAGE_CACHE_LIMIT = 32;
const LARGE_SESSION_FAST_PATH_BYTES = 2 * 1024 * 1024;
const RECENT_TAIL_LINES_INITIAL = 2000;
const RECENT_TAIL_LINES_MAX = 16000;
let sessionTitleOverridesLoaded = false;
let sessionTitleOverrides = {};
let claudeProvenanceLoaded = false;
let claudeSessionProvenance = {};
let claudeProfilesCache = null;
let claudeProfilesFilePath = '';
let claudeProfilesFingerprint = '';
let sessionMetadataCacheLoaded = false;
let sessionMetadataCacheDirty = false;
const sessionMetadataCache = new Map();
let sessionsSnapshotCache = null;
let sessionsSnapshotRefreshPromise = null;
const messageParseCache = new Map();
const recentMessageCache = new Map();
let resolvedCodexStateDbPath = '';
let codexStateDbPathResolved = false;
function sendJSON(res, data, status = 200) {
const body = JSON.stringify(data);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
'Cache-Control': 'no-store, max-age=0',
Pragma: 'no-cache',
});
res.end(body);
}
function sendError(res, message, status = 500) {
sendJSON(res, { error: message }, status);
}
function isAllowedLoopbackOrigin(origin) {
if (typeof origin !== 'string' || !origin) return false;
try {
const parsed = new URL(origin);
return parsed.protocol === 'http:' && (
parsed.hostname === 'localhost' ||
parsed.hostname === '127.0.0.1'
);
} catch {
return false;
}
}
function buildCorsHeaders(req) {
const origin = req.headers.origin;
if (!isAllowedLoopbackOrigin(origin)) return null;
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '600',
Vary: 'Origin',
};
}
function buildHealthPayload() {
return {
ok: true,
pid: process.pid,
uptimeSec: Math.round(process.uptime()),
timestamp: new Date().toISOString(),
};
}
async function ensureSessionTitleOverridesLoaded() {
if (sessionTitleOverridesLoaded) return;
sessionTitleOverridesLoaded = true;
try {
const raw = await fsp.readFile(SESSION_TITLE_OVERRIDES_FILE, 'utf-8');
const parsed = JSON.parse(raw);
sessionTitleOverrides = parsed && typeof parsed === 'object' ? parsed : {};
} catch {
sessionTitleOverrides = {};
}
}
async function persistSessionTitleOverrides() {
await fsp.mkdir(path.dirname(SESSION_TITLE_OVERRIDES_FILE), { recursive: true });
await fsp.writeFile(
SESSION_TITLE_OVERRIDES_FILE,
JSON.stringify(sessionTitleOverrides, null, 2) + '\n',
'utf-8',
);
}
async function ensureSessionMetadataCacheLoaded() {
if (sessionMetadataCacheLoaded) return;
sessionMetadataCacheLoaded = true;
try {
const raw = await fsp.readFile(SESSION_METADATA_CACHE_FILE, 'utf-8');
const parsed = JSON.parse(raw);
const entries = parsed?.entries && typeof parsed.entries === 'object' ? parsed.entries : {};
for (const [key, value] of Object.entries(entries)) {
if (!value || typeof value !== 'object') continue;
sessionMetadataCache.set(key, value);
}
} catch {
sessionMetadataCache.clear();
}
}
async function persistSessionMetadataCache() {
if (!sessionMetadataCacheDirty) return;
sessionMetadataCacheDirty = false;
const payload = {
savedAt: new Date().toISOString(),
entries: Object.fromEntries(sessionMetadataCache.entries()),
};
await fsp.mkdir(path.dirname(SESSION_METADATA_CACHE_FILE), { recursive: true });
await fsp.writeFile(
SESSION_METADATA_CACHE_FILE,
JSON.stringify(payload, null, 2) + '\n',
'utf-8',
);
}
function invalidateSessionsSnapshotCache() {
sessionsSnapshotCache = null;
sessionsSnapshotRefreshPromise = null;
}
function buildSessionMetadataCacheKey(source, filePath) {
return `${source}:${filePath}`;
}
function buildFileFingerprint(stat, extra = '') {
const extraPart = extra ? `:${extra}` : '';
return `${Math.floor(stat.mtimeMs)}:${stat.size}${extraPart}`;
}
function emptyClaudeProfilesCache() {
return { byName: {}, byModel: new Map() };
}
function getCachedSessionMetadata(cacheKey, fingerprint) {
const cached = sessionMetadataCache.get(cacheKey);
if (!cached || cached.fingerprint !== fingerprint) return null;
return cached.data || null;
}
function setCachedSessionMetadata(cacheKey, fingerprint, data) {
sessionMetadataCache.set(cacheKey, {
fingerprint,
data,
});
sessionMetadataCacheDirty = true;
}
function getMessageCache(cacheKey, fingerprint) {
const cached = messageParseCache.get(cacheKey);
if (!cached || cached.fingerprint !== fingerprint) return null;
messageParseCache.delete(cacheKey);
messageParseCache.set(cacheKey, cached);
return cached.messages;
}
function setMessageCache(cacheKey, fingerprint, messages) {
if (messageParseCache.has(cacheKey)) {
messageParseCache.delete(cacheKey);
}
messageParseCache.set(cacheKey, { fingerprint, messages });
while (messageParseCache.size > MESSAGE_CACHE_LIMIT) {
const firstKey = messageParseCache.keys().next().value;
if (!firstKey) break;
messageParseCache.delete(firstKey);
}
}
function invalidateMessageCache(cacheKey) {
if (!cacheKey) return;
messageParseCache.delete(cacheKey);
}
function getRecentMessageCache(cacheKey, fingerprint) {
const cached = recentMessageCache.get(cacheKey);
if (!cached || cached.fingerprint !== fingerprint) return null;
recentMessageCache.delete(cacheKey);
recentMessageCache.set(cacheKey, cached);
return cached.result;
}
function setRecentMessageCache(cacheKey, fingerprint, result) {
if (recentMessageCache.has(cacheKey)) {
recentMessageCache.delete(cacheKey);
}
recentMessageCache.set(cacheKey, { fingerprint, result });
while (recentMessageCache.size > MESSAGE_CACHE_LIMIT) {
const firstKey = recentMessageCache.keys().next().value;
if (!firstKey) break;
recentMessageCache.delete(firstKey);
}
}
function invalidateRecentMessageCache(cacheKey) {
if (!cacheKey) return;
recentMessageCache.delete(cacheKey);
}
function buildProjectDigest(projects) {
return projects.map((project) => ({
dirName: project.dirName,
sessionCount: project.sessionCount,
archivedSessionCount: project.archivedSessionCount || 0,
totalSessionCount: project.totalSessionCount || project.sessionCount || 0,
latestModified: project.latestModified || 0,
latestVisibleModified: project.latestVisibleModified || 0,
sourceCounts: project.sourceCounts || {},
}));
}
function buildSessionDigest(sessions) {
return sessions.map((session) => ({
sessionId: session.sessionId,
source: session.source,
rawSessionId: session.rawSessionId || '',
forkedFromId: session.forkedFromId || '',
modified: session.modified || '',
messageCount: session.messageCount || 0,
model: session.model || '',
title: session.customTitle || session.firstPrompt || '',
archived: !!session.archived,
archivedAt: session.archivedAt || '',
}));
}
function buildCodexSubagentParentKey(projectPath, parentThreadId) {
return JSON.stringify({
projectPath: normalizeProjectPath(projectPath || ''),
parentThreadId: parentThreadId || '',
});
}
function compareTimestampedItems(left, right) {
const leftTime = left?.timestamp ? new Date(left.timestamp).getTime() : Number.NaN;
const rightTime = right?.timestamp ? new Date(right.timestamp).getTime() : Number.NaN;
const leftHasTime = Number.isFinite(leftTime);
const rightHasTime = Number.isFinite(rightTime);
if (leftHasTime && rightHasTime && leftTime !== rightTime) {
return leftTime - rightTime;
}
if (leftHasTime !== rightHasTime) {
return leftHasTime ? -1 : 1;
}
const leftOrder = Number.isFinite(left?._mergeOrder) ? left._mergeOrder : 0;
const rightOrder = Number.isFinite(right?._mergeOrder) ? right._mergeOrder : 0;
return leftOrder - rightOrder;
}
function compactStructuredValue(value, depth = 0) {
if (value == null) return value;
if (typeof value === 'string') return truncateText(value, 400);
if (typeof value === 'number' || typeof value === 'boolean') return value;
if (depth >= 3) return truncateText(normalizeText(value), 400);
if (Array.isArray(value)) {
return value.slice(0, 8).map((item) => compactStructuredValue(item, depth + 1));
}
if (typeof value === 'object') {
const result = {};
for (const [key, entry] of Object.entries(value).slice(0, 12)) {
result[key] = compactStructuredValue(entry, depth + 1);
}
return result;
}
return truncateText(normalizeText(value), 400);
}
function maybeParseJsonString(value) {
if (typeof value !== 'string') return value;
const trimmed = value.trim();
if (!trimmed) return value;
if (!/^[{\[]/.test(trimmed)) return value;
const parsed = safeJsonParse(trimmed);
return parsed == null ? value : parsed;
}
function normalizeToolPayload(value) {
if (typeof value === 'string') {
return maybeParseJsonString(value);
}
return value;
}
function summarizeToolPayload(toolName, value) {
const normalized = normalizeToolPayload(value);
if (typeof normalized === 'string') {
return truncateText(normalized.split('\n').find(Boolean) || normalized, 160);
}
if (Array.isArray(normalized)) {
return `${normalized.length} item${normalized.length === 1 ? '' : 's'}`;
}
if (normalized && typeof normalized === 'object') {
const candidates = [
normalized.command,
normalized.cmd,
normalized.query,
normalized.pattern,
normalized.path,
normalized.file_path,
normalized.filePath,
normalized.description,
normalized.prompt,
normalized.subject,
normalized.taskId ? `task ${normalized.taskId}` : '',
normalized.owner ? `owner ${normalized.owner}` : '',
normalized.status ? `status ${normalized.status}` : '',
].filter(Boolean);
if (candidates.length > 0) {
return truncateText(String(candidates[0]), 160);
}
const keys = Object.keys(normalized);
if (keys.length) {
return truncateText(`${toolName || 'tool'} · ${keys.slice(0, 4).join(', ')}`, 160);
}
}
return truncateText(normalizeText(normalized), 160);
}
function summarizeStructuredToolResult(value) {
if (!value || typeof value !== 'object') return '';
if (value.status === 'teammate_spawned' && (value.name || value.agent_id || value.teammate_id)) {
return `Spawned ${value.name || value.agent_id || value.teammate_id}`;
}
if (value.task?.id && value.task?.subject) {
return `Task #${value.task.id}: ${value.task.subject}`;
}
if (value.taskId && value.updatedFields) {
const fields = Array.isArray(value.updatedFields) ? value.updatedFields.join(', ') : 'updated';
return `Task #${value.taskId}: ${fields}`;
}
if (typeof value.success === 'boolean') {
return value.success ? 'Operation succeeded' : 'Operation failed';
}
if (value.agent_id || value.teammate_id) {
return String(value.agent_id || value.teammate_id);
}
const keys = Object.keys(value);
if (keys.length === 0) return '';
const preview = keys
.slice(0, 3)
.map((key) => `${key}=${truncateText(normalizeText(value[key]), 60)}`)
.join(' · ');
return truncateText(preview, 180);
}
function buildCodexTokenUsageSummary(info) {
const usage = info?.last_token_usage || info?.lastTokenUsage || null;
if (!usage) return '';
const inputTokens = Number(usage.input_tokens ?? usage.inputTokens ?? 0);
const cachedInputTokens = Number(usage.cached_input_tokens ?? usage.cachedInputTokens ?? 0);
const outputTokens = Number(usage.output_tokens ?? usage.outputTokens ?? 0);
const usedTokens = Number(usage.total_tokens ?? usage.totalTokens ?? (inputTokens + outputTokens));
const contextWindow = Number(info?.model_context_window ?? info?.modelContextWindow ?? 0);
const parts = [];
if (contextWindow > 0 && usedTokens > 0) {
parts.push(`Context ${usedTokens}/${contextWindow}`);
}
if (inputTokens > 0) {
parts.push(`Input ${inputTokens}`);
}
if (cachedInputTokens > 0) {
parts.push(`Cached ${cachedInputTokens}`);
}
if (outputTokens > 0) {
parts.push(`Output ${outputTokens}`);
}
return parts.join(' · ');
}
function nextMessageOrder(state) {
state._messageOrder = (state._messageOrder || 0) + 1;
return state._messageOrder;
}
function parseTimestampMs(value) {
if (!value) return Number.NaN;
const date = new Date(value);
const ms = date.getTime();
return Number.isFinite(ms) ? ms : Number.NaN;
}
function normalizeEpochTimestamp(value) {
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return '';
const millis = numeric < 1e12 ? numeric * 1000 : numeric;
const date = new Date(millis);
return Number.isNaN(date.getTime()) ? '' : date.toISOString();
}
async function resolveCodexStateDbPath() {
if (codexStateDbPathResolved) return resolvedCodexStateDbPath;
codexStateDbPathResolved = true;
if (config.codexStateDbPath && existsSync(config.codexStateDbPath)) {
resolvedCodexStateDbPath = config.codexStateDbPath;
return resolvedCodexStateDbPath;
}
const codexHomeDir = path.dirname(config.codexSessionsDir);
try {
const entries = await fsp.readdir(codexHomeDir, { withFileTypes: true });
const candidates = entries
.filter((entry) => entry.isFile())
.map((entry) => {
const match = entry.name.match(/^state_(\d+)\.sqlite$/);
if (!match) return null;
return {
version: Number(match[1]),
filePath: path.join(codexHomeDir, entry.name),
};
})
.filter(Boolean)
.sort((a, b) => b.version - a.version);
resolvedCodexStateDbPath = candidates[0]?.filePath || '';
} catch {
resolvedCodexStateDbPath = '';
}
return resolvedCodexStateDbPath;
}
async function readCodexThreadStateMap() {
const dbPath = await resolveCodexStateDbPath();
if (!dbPath) return new Map();
try {
const { stdout } = await execFileAsync(
'sqlite3',
[
'-readonly',
'-tabs',
dbPath,
"SELECT id, archived, COALESCE(archived_at, '') FROM threads;",
],
{
maxBuffer: 1024 * 1024 * 8,
},
);
const result = new Map();
for (const rawLine of stdout.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
const [id, archivedValue, archivedAtValue] = line.split('\t');
if (!id) continue;
result.set(id, {
archived: archivedValue === '1',
archivedAt: normalizeEpochTimestamp(archivedAtValue),
});
}
return result;
} catch {
return new Map();
}
}
function applyCodexThreadState(session, threadStateMap) {
if (!session) return session;
const threadState = threadStateMap.get(session.rawSessionId || '');
return {
...session,
archived: !!threadState?.archived,
archivedAt: threadState?.archivedAt || '',
};
}
async function ensureClaudeProvenanceLoaded() {
if (claudeProvenanceLoaded) return;
claudeProvenanceLoaded = true;
try {
const raw = await fsp.readFile(CLAUDE_PROVENANCE_FILE, 'utf-8');
const parsed = JSON.parse(raw);
claudeSessionProvenance = parsed && typeof parsed === 'object' ? parsed : {};
} catch {
claudeSessionProvenance = {};
}
}
function parseClaudeModelsJson(raw) {
const parsed = safeJsonParse(raw);
const models = parsed?.models && typeof parsed.models === 'object' ? parsed.models : {};
const byName = {};
const byModel = new Map();
for (const [name, entry] of Object.entries(models)) {
const env = entry?.env && typeof entry.env === 'object' ? entry.env : {};
const anthropicModel = env.ANTHROPIC_MODEL || '';
const baseUrl = env.ANTHROPIC_BASE_URL || '';
const label = name.toUpperCase();
byName[name] = {
name,
label,
anthropicModel,
baseUrl,
description: entry?.description || '',
};
if (anthropicModel) {
if (!byModel.has(anthropicModel)) byModel.set(anthropicModel, []);
byModel.get(anthropicModel).push(byName[name]);
}
}
return { byName, byModel };
}
function preferredClaudeProfileForModel(model) {
return '';
}
async function ensureClaudeProfilesLoaded() {
try {
const realProjectsDir = await fsp.realpath(config.claudeProjectsDir);
const modelsFile = path.join(path.dirname(path.dirname(realProjectsDir)), '.models.json');
const stat = await fsp.stat(modelsFile);
const fingerprint = buildFileFingerprint(stat);
if (
claudeProfilesCache &&
claudeProfilesFilePath === modelsFile &&
claudeProfilesFingerprint === fingerprint
) {
return;
}
const raw = await fsp.readFile(modelsFile, 'utf-8');
claudeProfilesCache = parseClaudeModelsJson(raw);
claudeProfilesFilePath = modelsFile;
claudeProfilesFingerprint = fingerprint;
} catch {
claudeProfilesCache = emptyClaudeProfilesCache();
claudeProfilesFilePath = '';
claudeProfilesFingerprint = '';
}
}
async function serveStatic(req, res) {
const requestPath = req.url === '/' ? '/index.html' : req.url.split('?')[0];
const publicRoot = path.join(__dirname, 'public');
const filePath = path.join(publicRoot, requestPath);
if (!filePath.startsWith(publicRoot)) {
sendError(res, 'Forbidden', 403);
return;
}
try {
const stat = await fsp.stat(filePath);
if (!stat.isFile()) {
sendError(res, 'Not Found', 404);
return;
}
const ext = path.extname(filePath).toLowerCase();
const mime = MIME_TYPES[ext] || 'application/octet-stream';
res.writeHead(200, {
'Content-Type': mime,
'Content-Length': stat.size,
'Cache-Control': 'no-store, max-age=0',
Pragma: 'no-cache',
});
createReadStream(filePath).pipe(res);
} catch {
sendError(res, 'Not Found', 404);
}
}
function safeJsonParse(text) {
try {
return JSON.parse(text);
} catch {
return null;
}
}
function encodeToken(payload) {
return Buffer.from(JSON.stringify(payload)).toString('base64url');
}
function decodeToken(token) {
try {
return JSON.parse(Buffer.from(token, 'base64url').toString('utf-8'));
} catch {
return null;
}
}
function buildSessionTitleOverrideKey({ source, projectPath, rawSessionId }) {
if (!source || !projectPath || !rawSessionId) return '';
return JSON.stringify({ source, projectPath, rawSessionId });
}
function applySessionTitleOverride(session) {
const defaultFirstPrompt = session.firstPrompt || '(no prompt)';
const key = buildSessionTitleOverrideKey(session);
const customTitle = key ? sessionTitleOverrides[key] || '' : '';
return {
...session,
defaultFirstPrompt,
customTitle,
firstPrompt: customTitle || defaultFirstPrompt,
};
}
function decorateClaudeSessionConfig(session) {
const key = buildSessionTitleOverrideKey(session);
const saved = key ? claudeSessionProvenance[key] || null : null;
if (saved) {
return {
...session,
claudeProfile: saved.profile || '',
claudeProfileLabel: saved.profileLabel || (saved.profile ? saved.profile.toUpperCase() : ''),
claudeProfileHint: saved.profile || '',
claudeProfileExact: true,
claudeBaseUrl: saved.baseUrl || '',
claudeModel: saved.anthropicModel || session.model || '',
claudeConfigSource: saved.source || 'recorded',
};
}
const model = session.model || '';
const candidates = model ? (claudeProfilesCache?.byModel.get(model) || []) : [];
if (candidates.length === 1) {
const candidate = candidates[0];
return {
...session,
claudeProfile: candidate.name,
claudeProfileLabel: candidate.label,
claudeProfileHint: candidate.name,
claudeProfileExact: false,
claudeBaseUrl: candidate.baseUrl,
claudeModel: candidate.anthropicModel || model,
claudeConfigSource: 'inferred-model',
};
}
if (candidates.length > 1) {
const preferred = preferredClaudeProfileForModel(model);
const preferredCandidate = preferred ? candidates.find((candidate) => candidate.name === preferred) : null;
if (preferredCandidate) {
return {
...session,
claudeProfile: preferredCandidate.name,
claudeProfileLabel: preferredCandidate.label,
claudeProfileHint: preferredCandidate.name,
claudeProfileExact: false,
claudeBaseUrl: preferredCandidate.baseUrl,
claudeModel: preferredCandidate.anthropicModel || model,
claudeConfigSource: 'default-model-family',
};
}
return {
...session,
claudeProfile: '',
claudeProfileLabel: 'MULTI',
claudeProfileHint: candidates.map((c) => c.label).join('/'),
claudeProfileExact: false,
claudeBaseUrl: '',
claudeModel: model,
claudeConfigSource: 'ambiguous-model',
};
}
const preferred = preferredClaudeProfileForModel(model);
const preferredByName = preferred ? claudeProfilesCache?.byName?.[preferred] : null;
if (preferredByName) {
return {
...session,
claudeProfile: preferredByName.name,
claudeProfileLabel: preferredByName.label,
claudeProfileHint: preferredByName.name,
claudeProfileExact: false,
claudeBaseUrl: preferredByName.baseUrl,
claudeModel: preferredByName.anthropicModel || model,
claudeConfigSource: 'default-model-family',
};
}
return {
...session,
claudeProfile: '',
claudeProfileLabel: model ? 'MODEL' : '',
claudeProfileHint: model || '',
claudeProfileExact: false,
claudeBaseUrl: '',
claudeModel: model,
claudeConfigSource: model ? 'model-only' : 'unknown',
};
}
function truncateText(text, limit = 500) {
const str = typeof text === 'string' ? text : JSON.stringify(text || '');
if (str.length <= limit) return str;
return str.slice(0, limit) + '...';
}
function normalizeText(value) {
if (typeof value === 'string') return value;
if (value == null) return '';
return JSON.stringify(value);
}
function hasNonEmptyText(value) {
return normalizeText(value).trim().length > 0;
}
function extractClaudePlainText(content) {
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
return content
.filter((block) => block && typeof block === 'object' && block.type === 'text')
.map((block) => block.text || '')
.join('\n');
}
return normalizeText(content);
}
function extractTaggedBlock(text, tag) {
if (typeof text !== 'string' || typeof tag !== 'string' || !tag) return '';
const lowerText = text.toLowerCase();
const openTag = `<${tag}>`;
const closeTag = `</${tag}>`;
const lowerOpenTag = openTag.toLowerCase();
const lowerCloseTag = closeTag.toLowerCase();
const startIndex = lowerText.indexOf(lowerOpenTag);
if (startIndex === -1) return '';
const contentStart = startIndex + openTag.length;
const endIndex = lowerText.indexOf(lowerCloseTag, contentStart);
if (endIndex === -1) return '';
return text.slice(contentStart, endIndex).trim();
}
function isClaudeSyntheticPrompt(text) {
const prompt = typeof text === 'string' ? text.trim() : '';
if (!prompt) return false;
return prompt === CLAUDE_SYNTHETIC_WARMUP_PROMPT
|| prompt.startsWith(CLAUDE_SYNTHETIC_SUMMARY_PREFIX)
|| prompt.startsWith(CLAUDE_SYNTHETIC_JUDGE_PREFIX);
}
function parseClaudeWrapper(text) {
if (typeof text !== 'string' || !text.includes('<')) return null;
const commandName = extractTaggedBlock(text, 'command-name');
const commandMessage = extractTaggedBlock(text, 'command-message');
const commandArgs = extractTaggedBlock(text, 'command-args');
const localCaveat = extractTaggedBlock(text, 'local-command-caveat');
const localStdout = extractTaggedBlock(text, 'local-command-stdout');
const localStderr = extractTaggedBlock(text, 'local-command-stderr');
const localStatus = extractTaggedBlock(text, 'local-command-status');
if (commandName || commandMessage || commandArgs) {
const parts = [];
if (commandName) {
parts.push(commandName);
} else if (commandMessage) {
parts.push(commandMessage);
}
if (commandArgs) parts.push(commandArgs);
return {
kind: 'command',
text: parts.filter(Boolean).join(' ').trim() || commandMessage || commandName || 'Command',
commandName,
commandMessage,
commandArgs,
};
}
if (localStdout) {
return { kind: 'local_stdout', text: localStdout };
}
if (localStderr) {
return { kind: 'local_stderr', text: localStderr };
}
if (localStatus) {
return { kind: 'local_status', text: localStatus };
}
if (localCaveat) {
return { kind: 'local_caveat', text: localCaveat };
}
return null;
}
function cleanClaudePromptText(text) {
if (typeof text !== 'string') return '';
if (parseClaudeSkillContext(text)) return '';
const wrapper = parseClaudeWrapper(text);
if (!wrapper) return truncateText(text.trim(), 200);
if (wrapper.kind === 'command') {
return truncateText(wrapper.text, 200);
}
if (wrapper.kind === 'local_caveat') {
return '';
}
if (wrapper.kind === 'local_stdout' || wrapper.kind === 'local_stderr' || wrapper.kind === 'local_status') {
return '';
}
return truncateText(wrapper.text || '', 200);
}
function parseClaudeSkillContext(content) {
const text = extractClaudePlainText(content).trim();
if (!text.startsWith('Base directory for this skill:')) return null;
const skillPathMatch = text.match(/Base directory for this skill:\s*(.+)/);
const skillPath = skillPathMatch ? skillPathMatch[1].split(/\r?\n/)[0].trim() : '';
const pathName = skillPath ? path.basename(skillPath) : '';
let skillName = pathName;
const headingMatch = text.match(/^#\s+(.+)$/m);
if (!skillName && headingMatch) {
skillName = headingMatch[1].trim();
}
return {
kind: 'skill_context',
skillName: skillName || 'skill',
text: `Loaded skill context: ${skillName || 'skill'}`,
};
}
function displayNameFromPath(projectPath) {
if (!projectPath) return '(unknown)';
const trimmed = projectPath.replace(/\/+$/, '');
if (!trimmed) return projectPath;
const base = path.basename(trimmed);
return base || trimmed;
}
function normalizeProjectPath(projectPath) {
if (typeof projectPath !== 'string' || !projectPath.trim()) {
return '(unknown)';
}
const trimmed = projectPath.trim().replace(/\/+$/, '');
if (!trimmed) return '(unknown)';
return resolveProjectPathAlias(trimmed);
}
function resolveProjectPathAlias(projectPath) {
if (!projectPath || projectPath === '(unknown)') return '(unknown)';
if (existsSync(projectPath)) return projectPath;
const parts = projectPath.split('/').filter(Boolean);
if (!parts.length) return projectPath;
const queue = [parts];
const seen = new Set([parts.join('/')]);
let steps = 0;
const maxStates = 256;
while (queue.length && steps < maxStates) {
const current = queue.shift();
steps++;
const candidatePath = '/' + current.join('/');
if (existsSync(candidatePath)) {
return candidatePath;
}
if (current.length < 2) continue;
for (let i = 0; i < current.length - 1; i++) {
for (const joiner of ['_', '-']) {
const merged = [
...current.slice(0, i),
`${current[i]}${joiner}${current[i + 1]}`,
...current.slice(i + 2),
];
const key = merged.join('/');
if (seen.has(key)) continue;
seen.add(key);
queue.push(merged);
}
}
}
return projectPath;
}
async function pathExists(filePath) {
try {
await fsp.access(filePath);
return true;
} catch {
return false;
}
}
async function movePathToTrash(sourcePath, bucket) {
await fsp.mkdir(path.join(TRASH_ROOT, bucket), { recursive: true });
const targetPath = path.join(
TRASH_ROOT,
bucket,
`${Date.now()}-${path.basename(sourcePath)}`
);
try {
await fsp.rename(sourcePath, targetPath);
} catch (err) {
if (err && err.code === 'EXDEV') {
await fsp.cp(sourcePath, targetPath, { recursive: true });
await fsp.rm(sourcePath, { recursive: true, force: true });
} else {
throw err;
}
}
return targetPath;
}
async function walkFiles(rootDir, predicate, acc = []) {
let entries = [];
try {
entries = await fsp.readdir(rootDir, { withFileTypes: true });
} catch {
return acc;
}
for (const entry of entries) {
const fullPath = path.join(rootDir, entry.name);
if (entry.isDirectory()) {
await walkFiles(fullPath, predicate, acc);
} else if (!predicate || predicate(fullPath, entry)) {
acc.push(fullPath);
}
}