-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2741 lines (2469 loc) · 91.3 KB
/
Copy pathserver.js
File metadata and controls
2741 lines (2469 loc) · 91.3 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
const express = require('express');
const fs = require('fs');
const fsp = require('fs/promises');
const path = require('path');
const readline = require('readline');
const Database = require('better-sqlite3');
const app = express();
const PORT = process.env.PORT || 3800;
const HOME = process.env.HOME || '/root';
const DATA_DIR = process.env.OPENCLAW_DIR || path.join(HOME, '.openclaw', 'agents');
// ========= Session Metadata Cache =========
// Key: absolute file path → { mtime: number, data: sessionMetadataObject }
const sessionMetaCache = new Map();
const CODEX_DIR = process.env.CODEX_DIR || path.join(HOME, '.codex', 'sessions');
const CLAUDE_CODE_DIR = process.env.CLAUDE_CODE_DIR || path.join(HOME, '.claude', 'projects');
const HERMES_DIR = process.env.HERMES_DIR || path.join(HOME, '.hermes');
const PUBLIC_DIR = path.join(__dirname, 'public');
const SESSION_ID_RE = /^[0-9a-zA-Z._:-]+$/;
const AGENT_NAME_RE = /^[A-Za-z0-9._-]+$/;
function resolveDir(queryDir, defaultDir) {
if (!queryDir || typeof queryDir !== 'string') return defaultDir;
if (!path.isAbsolute(queryDir)) return defaultDir;
if (queryDir.includes('..')) return defaultDir;
return queryDir;
}
function isArchivedFile(fileName) {
return fileName.includes('.jsonl.reset.') || fileName.includes('.jsonl.deleted.');
}
function isSessionLogFile(fileName) {
return fileName.endsWith('.jsonl') || isArchivedFile(fileName);
}
function sanitizeAgentName(name) {
return AGENT_NAME_RE.test(name) ? name : null;
}
function sanitizeSessionId(id) {
return SESSION_ID_RE.test(id) ? id : null;
}
async function ensureDirectory(dirPath) {
const stat = await fsp.stat(dirPath);
if (!stat.isDirectory()) {
throw new Error(`Not a directory: ${dirPath}`);
}
}
async function readAgents(baseDir) {
const dir = baseDir || DATA_DIR;
await ensureDirectory(dir);
const entries = await fsp.readdir(dir, { withFileTypes: true });
return entries
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort((a, b) => a.localeCompare(b));
}
async function parseSessionMetadata(filePath, fileName) {
// Check mtime cache first
try {
const stat = await fsp.stat(filePath);
const mtime = stat.mtimeMs;
const cached = sessionMetaCache.get(filePath);
if (cached && cached.mtime === mtime) {
return cached.data;
}
} catch {
// If stat fails, fall through to parse
}
const data = await _parseSessionMetadataRaw(filePath, fileName);
// Update cache
try {
const stat = await fsp.stat(filePath);
sessionMetaCache.set(filePath, { mtime: stat.mtimeMs, data });
} catch {
// Non-critical — just skip caching
}
return data;
}
async function _parseSessionMetadataRaw(filePath, fileName) {
const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
let session = null;
let messageCount = 0;
let userCount = 0;
let assistantCount = 0;
let toolCallCount = 0;
let toolResultCount = 0;
let spawnCount = 0;
let lastTimestamp = null;
let firstUserMessage = null;
const toolNames = {};
const modelCounts = {};
try {
for await (const line of rl) {
if (!line.trim()) {
continue;
}
let record;
try {
record = JSON.parse(line);
} catch (error) {
continue;
}
if (!session && record.type === 'session') {
session = {
id: record.id || fileName.split('.jsonl')[0],
timestamp: record.timestamp || null
};
}
if (record.type === 'message') {
messageCount += 1;
const msg = record.message || {};
const role = msg.role;
const content = Array.isArray(msg.content) ? msg.content : [];
if (role === 'user') {
userCount++;
if (!firstUserMessage) {
let texts = content.filter(c => c.type === 'text').map(c => c.text || '').join(' ').trim();
// Strip all System: lines
texts = texts.replace(/^System:.*\n?/gm, '');
// Strip metadata blocks: any block ending with ```json...```
texts = texts.replace(/^[A-Za-z ]+\([^)]*\):\n```[\s\S]*?```\n?/gm, '');
// Strip [message_id: ...] lines
texts = texts.replace(/^\[message_id:[^\]]*\].*\n?/gm, '');
// Strip ou_xxx: sender prefix from quoted message lines
texts = texts.replace(/^ou_[a-z0-9]+:\s*/gm, '');
// Strip subagent context injection
texts = texts.replace(/^\[.*?\] \[Subagent Context\][\s\S]*/m, '');
// Strip bare timestamp+channel prefix lines
texts = texts.replace(/^\[\w{3} \d{4}-\d{2}-\d{2}[^\]]*\][^\n]*\n?/gm, '');
// Strip heartbeat lines
texts = texts.replace(/^HEARTBEAT_OK.*\n?/gm, '');
texts = texts.trim();
if (texts) firstUserMessage = texts.slice(0, 120);
}
}
if (role === 'assistant') assistantCount++;
if (role === 'toolResult') toolResultCount++;
// Count tool calls and spawn calls within assistant messages
for (const c of content) {
if (c.type === 'toolCall') {
toolCallCount++;
const name = c.name || 'unknown';
toolNames[name] = (toolNames[name] || 0) + 1;
// Detect spawn
if (name === 'sessions_spawn') {
spawnCount++;
} else if (name === 'exec') {
const cmd = ((c.arguments || {}).command || '').toLowerCase();
if (cmd.includes('codex ') || cmd.includes('claude ')) {
spawnCount++;
}
}
}
}
if (record.timestamp) lastTimestamp = record.timestamp;
// Track model usage
const msgModel = msg.model;
if (msgModel && msgModel !== 'delivery-mirror') {
modelCounts[msgModel] = (modelCounts[msgModel] || 0) + 1;
}
}
}
} finally {
rl.close();
stream.destroy();
}
// Top 5 most used tools
const topTools = Object.entries(toolNames)
.sort((a, b) => b[1] - a[1])
.slice(0, 5)
.map(([name, count]) => ({ name, count }));
// Most common model (skip delivery-mirror)
const model = Object.entries(modelCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || null;
return {
id: session?.id || fileName.split('.jsonl')[0],
timestamp: session?.timestamp || null,
lastActivity: lastTimestamp,
messageCount,
userCount,
assistantCount,
toolCallCount,
toolResultCount,
spawnCount,
topTools,
model,
firstUserMessage: firstUserMessage || null,
status: isArchivedFile(fileName) ? 'archived' : 'active',
file: fileName
};
}
async function listSessionsForAgent(baseDir, agentName, includeArchived) {
const dir = baseDir || DATA_DIR;
const agentDir = path.join(dir, agentName, 'sessions');
await ensureDirectory(agentDir);
const entries = await fsp.readdir(agentDir, { withFileTypes: true });
const sessionFiles = entries
.filter((entry) => entry.isFile() && isSessionLogFile(entry.name))
.filter((entry) => includeArchived || !isArchivedFile(entry.name))
.map((entry) => entry.name);
const sessions = await Promise.all(
sessionFiles.map((fileName) => parseSessionMetadata(path.join(agentDir, fileName), fileName))
);
sessions.sort((a, b) => {
const aTime = a.timestamp ? Date.parse(a.timestamp) : 0;
const bTime = b.timestamp ? Date.parse(b.timestamp) : 0;
return bTime - aTime;
});
return sessions;
}
async function resolveSessionFile(baseDir, agentName, sessionId) {
const dir = baseDir || DATA_DIR;
const agentDir = path.join(dir, agentName, 'sessions');
await ensureDirectory(agentDir);
const entries = await fsp.readdir(agentDir, { withFileTypes: true });
const candidates = entries
.filter((entry) => entry.isFile() && isSessionLogFile(entry.name))
.map((entry) => entry.name)
.filter((fileName) => fileName === `${sessionId}.jsonl` || fileName.startsWith(`${sessionId}.jsonl.`))
.sort((a, b) => {
if (a === `${sessionId}.jsonl`) {
return -1;
}
if (b === `${sessionId}.jsonl`) {
return 1;
}
return b.localeCompare(a);
});
if (candidates.length === 0) {
return null;
}
return path.join(agentDir, candidates[0]);
}
function normalizeMessage(record) {
const message = record.message || {};
return {
id: record.id || null,
timestamp: record.timestamp || message.timestamp || null,
role: message.role || null,
content: Array.isArray(message.content) ? message.content : [],
usage: message.usage || null,
model: message.model || null,
provider: message.provider || null,
toolCallId: message.toolCallId || null,
toolName: message.toolName || null,
details: message.details || null,
isError: Boolean(message.isError)
};
}
async function parseSessionFile(filePath) {
const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
let session = null;
const messages = [];
try {
for await (const line of rl) {
if (!line.trim()) {
continue;
}
let record;
try {
record = JSON.parse(line);
} catch (error) {
continue;
}
if (record.type === 'session') {
session = {
id: record.id || null,
cwd: record.cwd || null,
timestamp: record.timestamp || null,
version: record.version || null
};
} else if (record.type === 'message') {
messages.push(normalizeMessage(record));
}
}
} finally {
rl.close();
stream.destroy();
}
return { session, messages };
}
// ========= Insights: aggregate analytics across sessions =========
const insightsCache = new Map(); // key → { expires: number, data: object }
const INSIGHTS_TTL_MS = 60_000;
function getInsightsCacheKey(platform, agent, dir) {
return `${platform}|${agent || ''}|${dir || ''}`;
}
// Collect all JSONL session file paths for a given platform
async function collectSessionFiles(platform, agentName, dirOverride) {
const files = []; // { path, sessionId }
if (platform === 'openclaw') {
const dir = resolveDir(dirOverride, DATA_DIR);
const agents = agentName ? [agentName] : await readAgents(dir).catch(() => []);
for (const agent of agents) {
const agentDir = path.join(dir, agent, 'sessions');
let entries;
try { entries = await fsp.readdir(agentDir, { withFileTypes: true }); } catch { continue; }
for (const e of entries) {
if (e.isFile() && e.name.endsWith('.jsonl') && !isArchivedFile(e.name)) {
files.push({ path: path.join(agentDir, e.name), sessionId: e.name.replace(/\.jsonl$/, '') });
}
}
}
} else if (platform === 'codex') {
const dir = resolveDir(dirOverride, CODEX_DIR);
const years = await fsp.readdir(dir, { withFileTypes: true }).catch(() => []);
for (const y of years) {
if (!y.isDirectory()) continue;
const months = await fsp.readdir(path.join(dir, y.name), { withFileTypes: true }).catch(() => []);
for (const m of months) {
if (!m.isDirectory()) continue;
const days = await fsp.readdir(path.join(dir, y.name, m.name), { withFileTypes: true }).catch(() => []);
for (const d of days) {
if (!d.isDirectory()) continue;
const dirPath = path.join(dir, y.name, m.name, d.name);
const entries = await fsp.readdir(dirPath, { withFileTypes: true }).catch(() => []);
for (const f of entries) {
if (f.isFile() && f.name.endsWith('.jsonl')) {
files.push({ path: path.join(dirPath, f.name), sessionId: f.name.replace(/\.jsonl$/, '') });
}
}
}
}
}
} else if (platform === 'claude-code') {
const dir = resolveDir(dirOverride, CLAUDE_CODE_DIR);
const projects = await fsp.readdir(dir, { withFileTypes: true }).catch(() => []);
for (const p of projects) {
if (!p.isDirectory()) continue;
const projDir = path.join(dir, p.name);
const entries = await fsp.readdir(projDir, { withFileTypes: true }).catch(() => []);
for (const f of entries) {
if (f.isFile() && f.name.endsWith('.jsonl')) {
files.push({ path: path.join(projDir, f.name), sessionId: f.name.replace(/\.jsonl$/, '') });
}
}
// Also check subagents/
const subDir = path.join(projDir, 'subagents');
const subEntries = await fsp.readdir(subDir, { withFileTypes: true }).catch(() => []);
for (const f of subEntries) {
if (f.isFile() && f.name.endsWith('.jsonl')) {
files.push({ path: path.join(subDir, f.name), sessionId: f.name.replace(/\.jsonl$/, '') });
}
}
}
}
return files;
}
// Extract first non-empty text line from content array
function extractErrorSnippet(content) {
if (!Array.isArray(content)) return '';
for (const c of content) {
if (c.type === 'text' && c.text) {
const line = c.text.trim().split('\n')[0].trim();
if (line) return line.slice(0, 200);
}
if (typeof c === 'string') {
const line = c.trim().split('\n')[0].trim();
if (line) return line.slice(0, 200);
}
}
return '';
}
// Normalize error pattern: take first line, lowercase, strip variable parts
function normalizeErrorPattern(snippet) {
if (!snippet) return '(empty)';
const line = snippet.split('\n')[0].trim().toLowerCase();
// Strip file paths
const stripped = line.replace(/\/[^\s]+/g, '/…');
// Strip hex ids
return stripped.replace(/[0-9a-f]{8,}/g, '…').slice(0, 120);
}
// Scan a single JSONL file for insights data
// Supports both standard format (type:'message' with toolCall/toolResult roles)
// and Claude Code format (type:'assistant'/'user' with tool_use/tool_result content blocks)
async function scanFileForInsights(filePath, sessionId) {
const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
let messageCount = 0;
let toolCallCount = 0;
let toolResultCount = 0;
let errorCount = 0;
let totalInputTokens = 0;
let totalOutputTokens = 0;
let totalCacheRead = 0;
let sessionDate = null;
const toolStats = {}; // name → { calls, errors, totalDurationMs }
const errorExamples = []; // { toolName, snippet, pattern }
try {
for await (const line of rl) {
if (!line.trim()) continue;
let rec;
try { rec = JSON.parse(line); } catch { continue; }
// Session timestamp
if (rec.type === 'session' && rec.timestamp) {
sessionDate = rec.timestamp.slice(0, 10);
}
// Claude Code: timestamp at top level on type:'user'/'assistant'
if ((rec.type === 'user' || rec.type === 'assistant') && !sessionDate && rec.timestamp) {
sessionDate = rec.timestamp.slice(0, 10);
}
// --- Standard format: type === 'message' ---
if (rec.type === 'message') {
messageCount++;
const msg = rec.message || {};
const content = Array.isArray(msg.content) ? msg.content : [];
if (msg.usage) {
totalInputTokens += msg.usage.input || 0;
totalOutputTokens += msg.usage.output || 0;
totalCacheRead += msg.usage.cacheRead || msg.usage.cache_read || 0;
}
for (const c of content) {
if (c.type === 'toolCall') {
toolCallCount++;
const name = c.name || 'unknown';
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
toolStats[name].calls++;
}
}
if (msg.role === 'toolResult') {
toolResultCount++;
const name = msg.toolName || '?';
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
if (msg.isError) {
errorCount++;
toolStats[name].errors++;
const snippet = extractErrorSnippet(msg.content);
const pattern = normalizeErrorPattern(snippet);
errorExamples.push({ toolName: name, snippet, pattern, sessionId, timestamp: rec.timestamp || null });
}
if (msg.details && typeof msg.details.durationMs === 'number') {
toolStats[name].totalDurationMs += msg.details.durationMs;
}
}
}
// --- Claude Code format: type === 'assistant' with tool_use blocks ---
if (rec.type === 'assistant') {
messageCount++;
const msg = rec.message || {};
const content = Array.isArray(msg.content) ? msg.content : [];
// Token usage
if (msg.usage) {
totalInputTokens += msg.usage.input_tokens || msg.usage.input || 0;
totalOutputTokens += msg.usage.output_tokens || msg.usage.output || 0;
totalCacheRead += msg.usage.cache_creation_input_tokens || msg.usage.cache_read_input_tokens || 0;
}
for (const c of content) {
if (c.type === 'tool_use') {
toolCallCount++;
const name = c.name || 'unknown';
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
toolStats[name].calls++;
}
}
}
// --- Claude Code format: type === 'user' with tool_result blocks ---
if (rec.type === 'user') {
messageCount++;
const msg = rec.message || {};
const content = Array.isArray(msg.content) ? msg.content : [];
for (const c of content) {
if (c.type === 'tool_result') {
toolResultCount++;
// tool_result blocks don't carry the tool name directly;
// we use a generic label since we can't easily correlate tool_use id
const name = 'tool';
if (c.is_error) {
errorCount++;
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
toolStats[name].errors++;
// Extract error text from tool_result content
let errorText = '';
if (typeof c.content === 'string') {
errorText = c.content;
} else if (Array.isArray(c.content)) {
errorText = c.content.filter(b => b.type === 'text').map(b => b.text || '').join(' ');
}
const snippet = errorText.trim().split('\n')[0].trim().slice(0, 200);
const pattern = normalizeErrorPattern(snippet);
errorExamples.push({ toolName: name, snippet, pattern, sessionId, timestamp: rec.timestamp || null });
}
}
}
}
// --- Codex format: type === 'response_item' with payload.type === 'function_call'/'function_call_output' ---
if (rec.type === 'response_item') {
const payload = rec.payload || {};
if (payload.type === 'message') {
messageCount++;
}
if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
toolCallCount++;
const name = payload.name || 'unknown';
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
toolStats[name].calls++;
}
if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output') {
toolResultCount++;
const name = 'tool';
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
const output = payload.output;
let outputText = '';
let isErr = false;
if (typeof output === 'string') {
outputText = output;
isErr = outputText.includes('Process exited with code') && !outputText.includes('exited with code 0');
} else if (output && typeof output === 'object') {
outputText = output.output || JSON.stringify(output);
if (output.metadata && output.metadata.exit_code !== undefined) {
isErr = output.metadata.exit_code !== 0;
}
}
if (isErr) {
errorCount++;
toolStats[name].errors++;
const snippet = outputText.trim().split('\n')[0].trim().slice(0, 200);
const pattern = normalizeErrorPattern(snippet);
errorExamples.push({ toolName: name, snippet, pattern, sessionId, timestamp: rec.timestamp || null });
}
if (output && typeof output === 'object' && output.metadata && output.metadata.duration_seconds) {
toolStats[name].totalDurationMs += Math.round(output.metadata.duration_seconds * 1000);
}
}
}
}
} finally {
rl.close();
stream.destroy();
}
return { messageCount, toolCallCount, toolResultCount, errorCount, totalInputTokens, totalOutputTokens, totalCacheRead, sessionDate, toolStats, errorExamples };
}
// Scan a single Hermes session for insights (from SQLite)
function scanHermesSessionForInsights(db, sessionId) {
let messageCount = 0;
let toolCallCount = 0;
let toolResultCount = 0;
let errorCount = 0;
let totalInputTokens = 0;
let totalOutputTokens = 0;
let sessionDate = null;
const toolStats = {};
const errorExamples = [];
const rows = db.prepare(`
SELECT role, content, tool_calls, tool_name, token_count, timestamp
FROM messages WHERE session_id = ?
ORDER BY rowid
`).all(sessionId);
for (const row of rows) {
messageCount++;
totalInputTokens += row.token_count || 0;
if (!sessionDate && row.timestamp) {
sessionDate = new Date(row.timestamp * 1000).toISOString().slice(0, 10);
}
// Parse tool calls from assistant messages
if (row.role === 'assistant' && row.tool_calls) {
let calls;
try { calls = JSON.parse(row.tool_calls); } catch { continue; }
if (Array.isArray(calls)) {
for (const tc of calls) {
const name = tc?.function?.name || tc?.name || 'unknown';
toolCallCount++;
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
toolStats[name].calls++;
}
}
}
// Tool results
if (row.role === 'tool') {
toolResultCount++;
const name = row.tool_name || 'tool';
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
// Detect errors from content (no is_error column in Hermes)
const content = row.content || '';
const isErr = content.includes('"isError":true') || content.includes('"isError": true') ||
content.toLowerCase().includes('error') && content.includes('exit code') && !content.includes('exit code 0');
if (isErr) {
errorCount++;
toolStats[name].errors++;
const snippet = content.trim().split('\n')[0].trim().slice(0, 200);
const pattern = normalizeErrorPattern(snippet);
errorExamples.push({ toolName: name, snippet, pattern, sessionId, timestamp: row.timestamp ? new Date(row.timestamp * 1000).toISOString() : null });
}
}
}
return { messageCount, toolCallCount, toolResultCount, errorCount, totalInputTokens, totalOutputTokens, totalCacheRead: 0, sessionDate, toolStats, errorExamples };
}
async function computeInsights(platform, agentName, dirOverride) {
// Hermes uses SQLite
if (platform === 'hermes') {
const dir = resolveDir(dirOverride, HERMES_DIR);
const db = openHermesDb(dir);
if (!db) return null;
try {
const sessions = db.prepare('SELECT id FROM sessions').all();
let totalSessions = sessions.length;
let totalMessages = 0, totalToolCalls = 0, totalToolResultCount = 0, totalErrors = 0;
let totalInput = 0, totalOutput = 0;
const toolStats = {};
const allErrors = [];
const dailyTrend = {};
for (const s of sessions) {
const data = scanHermesSessionForInsights(db, s.id);
totalMessages += data.messageCount;
totalToolCalls += data.toolCallCount;
totalToolResultCount += data.toolResultCount;
totalErrors += data.errorCount;
totalInput += data.totalInputTokens;
totalOutput += data.totalOutputTokens;
for (const [name, st] of Object.entries(data.toolStats)) {
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
toolStats[name].calls += st.calls;
toolStats[name].errors += st.errors;
toolStats[name].totalDurationMs += st.totalDurationMs;
}
allErrors.push(...data.errorExamples);
if (data.sessionDate) {
if (!dailyTrend[data.sessionDate]) dailyTrend[data.sessionDate] = { sessions: 0, errors: 0, toolCalls: 0 };
dailyTrend[data.sessionDate].sessions++;
dailyTrend[data.sessionDate].errors += data.errorCount;
dailyTrend[data.sessionDate].toolCalls += data.toolCallCount;
}
}
return buildInsightsResponse(totalSessions, totalMessages, totalToolCalls, totalToolResultCount, totalErrors, totalInput, totalOutput, 0, toolStats, allErrors, dailyTrend);
} finally {
db.close();
}
}
// JSONL-based platforms: openclaw, codex, claude-code
const files = await collectSessionFiles(platform, agentName, dirOverride);
if (files.length === 0) return null;
let totalSessions = files.length;
let totalMessages = 0, totalToolCalls = 0, totalToolResultCount = 0, totalErrors = 0;
let totalInput = 0, totalOutput = 0, totalCacheRead = 0;
const toolStats = {};
const allErrors = [];
const dailyTrend = {};
for (const f of files) {
const data = await scanFileForInsights(f.path, f.sessionId).catch(() => null);
if (!data) continue;
totalMessages += data.messageCount;
totalToolCalls += data.toolCallCount;
totalToolResultCount += data.toolResultCount;
totalErrors += data.errorCount;
totalInput += data.totalInputTokens;
totalOutput += data.totalOutputTokens;
totalCacheRead += data.totalCacheRead;
for (const [name, st] of Object.entries(data.toolStats)) {
if (!toolStats[name]) toolStats[name] = { calls: 0, errors: 0, totalDurationMs: 0 };
toolStats[name].calls += st.calls;
toolStats[name].errors += st.errors;
toolStats[name].totalDurationMs += st.totalDurationMs;
}
allErrors.push(...data.errorExamples);
if (data.sessionDate) {
if (!dailyTrend[data.sessionDate]) dailyTrend[data.sessionDate] = { sessions: 0, errors: 0, toolCalls: 0 };
dailyTrend[data.sessionDate].sessions++;
dailyTrend[data.sessionDate].errors += data.errorCount;
dailyTrend[data.sessionDate].toolCalls += data.toolCallCount;
}
}
return buildInsightsResponse(totalSessions, totalMessages, totalToolCalls, totalToolResultCount, totalErrors, totalInput, totalOutput, totalCacheRead, toolStats, allErrors, dailyTrend);
}
function buildInsightsResponse(totalSessions, totalMessages, totalToolCalls, totalToolResultCount, totalErrors, totalInput, totalOutput, totalCacheRead, toolStats, allErrors, dailyTrend) {
const errorRate = totalToolResultCount > 0 ? totalErrors / totalToolResultCount : 0;
// Tool stats array
const toolStatsArray = Object.entries(toolStats)
.map(([name, st]) => ({
name,
calls: st.calls,
errors: st.errors,
errorRate: st.calls > 0 ? st.errors / st.calls : 0,
avgDurationMs: st.calls > 0 ? Math.round(st.totalDurationMs / st.calls) : null
}))
.sort((a, b) => b.calls - a.calls);
// Error clusters: group by normalized pattern
const clusters = {};
for (const err of allErrors) {
const key = err.pattern;
if (!clusters[key]) clusters[key] = { pattern: err.snippet, count: 0, examples: [] };
clusters[key].count++;
if (clusters[key].examples.length < 5) {
clusters[key].examples.push({ sessionId: err.sessionId, toolName: err.toolName, snippet: err.snippet, timestamp: err.timestamp });
}
}
const errorClusters = Object.values(clusters).sort((a, b) => b.count - a.count).slice(0, 20);
// Daily trend sorted by date
const trend = Object.entries(dailyTrend)
.map(([date, d]) => ({ date, sessions: d.sessions, errors: d.errors, toolCalls: d.toolCalls }))
.sort((a, b) => a.date.localeCompare(b.date));
return {
totalSessions,
totalMessages,
totalToolCalls,
errorRate: Math.round(errorRate * 10000) / 10000,
tokenUsage: { input: totalInput, output: totalOutput, cacheRead: totalCacheRead },
toolStats: toolStatsArray,
errorClusters,
trend
};
}
app.use(express.static(PUBLIC_DIR, { maxAge: 0, etag: false, lastModified: false }));
// Disable all caching
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
res.set('Surrogate-Control', 'no-store');
next();
});
app.get('/api/agents', async (req, res) => {
try {
const dir = resolveDir(req.query.dir, DATA_DIR);
const agents = await readAgents(dir);
res.json(agents);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Insights: aggregate analytics across sessions
app.get('/api/insights', async (req, res) => {
try {
const platform = req.query.platform || 'openclaw';
const agent = req.query.agent || '';
const dir = req.query.dir || '';
const cacheKey = getInsightsCacheKey(platform, agent, dir);
const cached = insightsCache.get(cacheKey);
if (cached && cached.expires > Date.now()) {
return res.json(cached.data);
}
const data = await computeInsights(platform, agent, dir);
if (!data) {
return res.json({ totalSessions: 0, totalMessages: 0, totalToolCalls: 0, errorRate: 0, tokenUsage: { input: 0, output: 0, cacheRead: 0 }, toolStats: [], errorClusters: [], trend: [] });
}
insightsCache.set(cacheKey, { data, expires: Date.now() + INSIGHTS_TTL_MS });
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Full-text search across sessions
app.get('/api/search', async (req, res) => {
try {
const q = (req.query.q || '').trim().toLowerCase();
const platform = req.query.platform || 'openclaw';
const agent = req.query.agent || '';
const maxResults = Math.min(parseInt(req.query.limit) || 50, 100);
if (!q) return res.json([]);
let sessionFiles = [];
if (platform === 'openclaw' && agent) {
const dir = resolveDir(req.query.dir, DATA_DIR);
const agentDir = path.join(dir, agent, 'sessions');
try {
const entries = await fsp.readdir(agentDir);
sessionFiles = entries
.filter(f => f.endsWith('.jsonl') && !isArchivedFile(f))
.map(f => ({ path: path.join(agentDir, f), file: f, platform: 'openclaw' }));
} catch { /* no sessions */ }
} else if (platform === 'codex') {
const dir = resolveDir(req.query.dir, CODEX_DIR);
try {
const entries = await fsp.readdir(dir, { withFileTypes: true });
for (const e of entries) {
if (!e.isDirectory()) continue;
const jsonlPath = path.join(dir, e.name, 'conversation.jsonl');
try { await fsp.access(jsonlPath); sessionFiles.push({ path: jsonlPath, file: e.name, platform: 'codex' }); } catch {}
}
} catch {}
} else if (platform === 'hermes') {
const dir = resolveDir(req.query.dir, HERMES_DIR);
const hermesResults = searchHermesSessions(dir, q, maxResults);
return res.json(hermesResults);
} else if (platform === 'claude-code') {
const dir = resolveDir(req.query.dir, CLAUDE_CODE_DIR);
try {
const entries = await fsp.readdir(dir);
sessionFiles = entries
.filter(f => f.endsWith('.jsonl'))
.map(f => ({ path: path.join(dir, f), file: f, platform: 'claude-code' }));
} catch {}
}
const results = [];
for (const sf of sessionFiles) {
if (results.length >= maxResults) break;
const matches = [];
const stream = fs.createReadStream(sf.path, { encoding: 'utf8' });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
let sessionId = sf.file.split('.jsonl')[0];
try {
for await (const line of rl) {
if (matches.length >= 3) break; // max 3 matches per session
if (!line.includes(q) && !line.toLowerCase().includes(q)) continue;
let rec;
try { rec = JSON.parse(line); } catch { continue; }
// Extract session id
if (rec.type === 'session' && rec.id) sessionId = rec.id;
if (rec.payload?.id && !sessionId) sessionId = rec.payload.id;
if (rec.sessionId) sessionId = rec.sessionId;
// Extract text content for matching
let text = '';
let role = '';
const msg = rec.message || rec.payload || {};
role = msg.role || rec.type || '';
const content = Array.isArray(msg.content) ? msg.content : (typeof msg.content === 'string' ? [{ type: 'text', text: msg.content }] : []);
text = content
.filter(c => c.type === 'text' || c.type === 'input_text')
.map(c => c.text || '')
.join(' ');
if (text.toLowerCase().includes(q)) {
// Extract snippet around match
const idx = text.toLowerCase().indexOf(q);
const start = Math.max(0, idx - 40);
const end = Math.min(text.length, idx + q.length + 60);
const snippet = (start > 0 ? '\u2026' : '') + text.slice(start, end) + (end < text.length ? '\u2026' : '');
matches.push({ role, snippet, timestamp: rec.timestamp || null });
}
}
} finally {
rl.close();
stream.destroy();
}
if (matches.length > 0) {
results.push({ sessionId, file: sf.file, platform: sf.platform, matches });
}
}
res.json(results);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/agents/:name/sessions', async (req, res) => {
const agentName = sanitizeAgentName(req.params.name);
if (!agentName) {
return res.status(400).json({ error: 'Invalid agent name' });
}
try {
const dir = resolveDir(req.query.dir, DATA_DIR);
const sessions = await listSessionsForAgent(dir, agentName, req.query.include_archived === 'true');
res.json(sessions);
} catch (error) {
if (error.code === 'ENOENT') {
return res.status(404).json({ error: 'Agent not found' });
}
res.status(500).json({ error: error.message });
}
});
app.get('/api/agents/:name/sessions/:sessionId', async (req, res) => {
const agentName = sanitizeAgentName(req.params.name);
const sessionId = sanitizeSessionId(req.params.sessionId);
if (!agentName || !sessionId) {
return res.status(400).json({ error: 'Invalid parameters' });
}
try {
const dir = resolveDir(req.query.dir, DATA_DIR);
const filePath = await resolveSessionFile(dir, agentName, sessionId);
if (!filePath) {
return res.status(404).json({ error: 'Session not found' });
}
const payload = await parseSessionFile(filePath);
res.json(payload);
} catch (error) {
if (error.code === 'ENOENT') {
return res.status(404).json({ error: 'Session not found' });
}
res.status(500).json({ error: error.message });
}
});
// Build a map of spawn relationships: which agent/session spawned which sub-agent sessions
// Detects: sessions_spawn tool calls, exec calls containing codex/claude commands
async function buildSpawnMap(baseDir) {
const dir = baseDir || DATA_DIR;
const spawnLinks = [];
const agents = await readAgents(dir);
for (const agentName of agents) {
const agentDir = path.join(dir, agentName, 'sessions');
let entries;
try {
entries = await fsp.readdir(agentDir, { withFileTypes: true });
} catch { continue; }
const sessionFiles = entries
.filter((e) => e.isFile() && e.name.endsWith('.jsonl') && !isArchivedFile(e.name))
.map((e) => e.name);
for (const fileName of sessionFiles) {
const sessionId = fileName.split('.jsonl')[0];
const filePath = path.join(agentDir, fileName);
const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
try {
for await (const line of rl) {
if (!line.includes('toolCall') && !line.includes('sessions_spawn')) continue;
let record;
try { record = JSON.parse(line); } catch { continue; }
if (record.type !== 'message') continue;
const msg = record.message || {};