-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathopenclaw-trace.js
More file actions
executable file
·4245 lines (3845 loc) · 189 KB
/
openclaw-trace.js
File metadata and controls
executable file
·4245 lines (3845 loc) · 189 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
// OpenClaw Trace
// Repository: https://github.com/Tell-Me-Mo/openclaw-trace
// Usage: npx openclaw-trace (foreground)
// npx openclaw-trace --bg (background daemon)
'use strict';
// ── Stop: gracefully shut down a running instance ────────────────────────────
if (process.argv.includes('--stop')) {
const http = require('http');
const req = http.get('http://127.0.0.1:3141/api/shutdown', (res) => {
console.log('\n 🦞 OpenClaw Trace stopped\n');
process.exit(0);
});
req.on('error', () => {
console.log('\n No running instance found on port 3141\n');
process.exit(1);
});
req.setTimeout(3000, () => { req.destroy(); process.exit(1); });
} else
// ── Background mode: re-spawn as detached process ────────────────────────────
if (process.argv.includes('--bg')) {
const { spawn } = require('child_process');
const args = process.argv.slice(1).filter(a => a !== '--bg');
const child = spawn(process.execPath, args, {
detached: true,
stdio: 'ignore',
});
child.unref();
console.log(`\n 🦞 OpenClaw Trace running in background (pid ${child.pid})`);
console.log(` → http://localhost:3141`);
console.log(` Stop: npx openclaw-trace --stop\n`);
process.exit(0);
}
const http = require('http');
const fs = require('fs');
const path = require('path');
const os = require('os');
const PORT = 3141;
const OC = process.env.OPENCLAW_STATE_DIR || process.env.OPENCLAW_HOME || path.join(os.homedir(), '.openclaw');
const SHADOW_DIR = path.join(OC, '.openclaw-trace-shadow');
// ── Session file watcher (preserves heartbeats truncated by OpenClaw) ────────
try { fs.mkdirSync(SHADOW_DIR, { recursive: true }); } catch {}
// Track known file content so we can detect truncation
const fileSnapshots = {}; // filePath -> { lines: number, content: string }
function snapshotFile(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.trim() ? content.trim().split('\n').length : 0;
fileSnapshots[filePath] = { lines, content };
} catch {}
}
function onFileChanged(filePath) {
try {
const newContent = fs.readFileSync(filePath, 'utf8');
const newLines = newContent.trim() ? newContent.trim().split('\n').length : 0;
const prev = fileSnapshots[filePath];
if (prev && newLines < prev.lines) {
// File was truncated — save the removed entries
const prevArr = prev.content.trim().split('\n');
const newArr = newContent.trim() ? newContent.trim().split('\n') : [];
// The truncated entries are lines that existed before but are gone now
// OpenClaw resets to the pre-heartbeat state, so removed = prevArr[newArr.length..]
const removed = prevArr.slice(newArr.length);
if (removed.length > 0) {
const agentId = filePath.split(path.sep + 'agents' + path.sep)[1]?.split(path.sep)[0];
if (agentId) saveShadowEntries(agentId, filePath, removed);
}
}
fileSnapshots[filePath] = { lines: newLines, content: newContent };
} catch {}
}
function saveShadowEntries(agentId, sourceFile, lines) {
const shadowFile = path.join(SHADOW_DIR, agentId + '.jsonl');
try {
// Deduplicate: check if these entries already exist in shadow
const existing = new Set();
try {
const prev = fs.readFileSync(shadowFile, 'utf8').trim();
if (prev) prev.split('\n').forEach(l => existing.add(l));
} catch {}
const newLines = lines.filter(l => !existing.has(l));
if (newLines.length > 0) {
fs.appendFileSync(shadowFile, newLines.join('\n') + '\n');
}
} catch {}
}
// Watch all agent session directories for JSONL changes
const watchers = {};
const CLAUDE_HOME = path.join(os.homedir(), '.claude', 'projects');
function startWatching() {
// Watch OpenClaw agent sessions
const agentsDir = path.join(OC, 'agents');
try {
const agents = fs.readdirSync(agentsDir);
for (const agent of agents) {
const sessDir = path.join(agentsDir, agent, 'sessions');
watchSessionDir(sessDir);
}
} catch {}
try {
fs.watch(agentsDir, (ev, filename) => {
if (filename) {
const sessDir = path.join(agentsDir, filename, 'sessions');
watchSessionDir(sessDir);
}
});
} catch {}
// Watch Claude Code project sessions
try {
const projects = fs.readdirSync(CLAUDE_HOME);
for (const proj of projects) {
const projDir = path.join(CLAUDE_HOME, proj);
watchSessionDir(projDir);
}
} catch {}
try {
fs.watch(CLAUDE_HOME, (ev, filename) => {
if (filename) {
const projDir = path.join(CLAUDE_HOME, filename);
watchSessionDir(projDir);
}
});
} catch {}
}
function watchSessionDir(sessDir) {
if (watchers[sessDir]) return;
try {
// Snapshot only recent JSONL files (today + yesterday) to limit memory usage
const recentCutoff = new Date();
recentCutoff.setDate(recentCutoff.getDate() - 1);
recentCutoff.setHours(0, 0, 0, 0);
const cutoffMs = recentCutoff.getTime();
const files = fs.readdirSync(sessDir);
for (const file of files) {
if (file.endsWith('.jsonl')) {
const fp = path.join(sessDir, file);
try {
if (fs.statSync(fp).mtimeMs >= cutoffMs) snapshotFile(fp);
} catch {}
}
}
// Watch for changes
watchers[sessDir] = fs.watch(sessDir, (ev, filename) => {
if (filename && filename.endsWith('.jsonl')) {
const filePath = path.join(sessDir, filename);
if (fs.existsSync(filePath)) onFileChanged(filePath);
}
});
} catch {}
}
startWatching();
// ── Data ──────────────────────────────────────────────────────────────────────
function readJSON(p) {
try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; }
}
function readJSONL(p) {
try {
const entries = fs.readFileSync(p, 'utf8').trim().split('\n')
.map(l => { try { return JSON.parse(l); } catch { return null; } })
.filter(Boolean);
// Auto-detect Claude Code format and normalize
// Claude Code entries have sessionId + type fields like "user", "assistant", "queue-operation"
const isClaudeCode = entries.some(e => e.sessionId && e.type && (e.type === 'assistant' || e.type === 'user') && e.uuid);
if (isClaudeCode) {
return normalizeClaudeCodeEntries(entries);
}
return entries;
} catch { return []; }
}
// ── Claude Code JSONL adapter ────────────────────────────────────────────────
// Converts Claude Code JSONL entries to OpenClaw format for unified parsing
// Token pricing per model (per million tokens)
const CLAUDE_PRICING = {
'claude-opus-4-6': { input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75 },
'claude-sonnet-4-6': { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
'claude-haiku-4-5': { input: 0.8, output: 4, cacheRead: 0.08, cacheWrite: 1 },
};
function calcCost(model, usage) {
const p = CLAUDE_PRICING[model] || CLAUDE_PRICING['claude-sonnet-4-6'];
const inp = (usage.input_tokens || 0) / 1e6 * p.input;
const out = (usage.output_tokens || 0) / 1e6 * p.output;
const cr = (usage.cache_read_input_tokens || 0) / 1e6 * p.cacheRead;
const cw = ((usage.cache_creation_input_tokens || 0)) / 1e6 * p.cacheWrite;
return { input: inp, output: out, cacheRead: cr, cacheWrite: cw, total: inp + out + cr + cw };
}
function normalizeClaudeCodeEntries(entries) {
// Phase 1: Collect all assistant entries per requestId
const assistantByReq = new Map();
for (const e of entries) {
if (e.type === 'assistant' && e.message?.role === 'assistant' && e.requestId) {
if (!assistantByReq.has(e.requestId)) assistantByReq.set(e.requestId, []);
assistantByReq.get(e.requestId).push(e);
}
}
// Phase 2: Merge each requestId group into a single normalized entry
const mergedAssistants = new Map(); // requestId -> merged entry
for (const [rid, group] of assistantByReq) {
mergedAssistants.set(rid, mergeAssistantGroup(group));
}
// Phase 3: Walk entries in order, emit normalized sequence
const normalized = [];
const emittedReqs = new Set();
for (const e of entries) {
const t = e.type;
const msg = e.message;
if (!msg) continue;
if (t === 'user' && msg.role === 'user') {
const content = Array.isArray(msg.content) ? msg.content : [];
const allToolResults = content.length > 0 && content.every(c => c.type === 'tool_result');
if (allToolResults) {
for (const c of content) {
const resultText = Array.isArray(c.content)
? c.content.filter(x => x.type === 'text').map(x => x.text || '').join('')
: String(c.content || '');
normalized.push({
timestamp: e.timestamp,
message: {
role: 'toolResult',
toolName: '',
toolCallId: c.tool_use_id || '',
content: resultText,
isError: c.is_error || false,
}
});
}
} else {
normalized.push({
timestamp: e.timestamp,
message: { role: 'user', content: msg.content, timestamp: e.timestamp }
});
}
continue;
}
if (t === 'assistant' && e.requestId && !emittedReqs.has(e.requestId)) {
// Emit the merged entry on first encounter of this requestId
emittedReqs.add(e.requestId);
const merged = mergedAssistants.get(e.requestId);
if (merged) normalized.push(merged);
}
}
return normalized;
}
function mergeAssistantGroup(entries) {
// Merge multiple Claude Code assistant entries (same requestId) into one OpenClaw-format entry
const textParts = [];
const thinkingParts = [];
const toolCalls = [];
let model = '';
let timestamp = '';
let usage = null;
for (const e of entries) {
const msg = e.message || {};
if (!timestamp) timestamp = e.timestamp;
if (msg.model) model = msg.model;
// Take usage with the highest output_tokens (last entry has cumulative total)
if (msg.usage && (msg.usage.output_tokens || 0) > (usage?.output_tokens || 0)) usage = msg.usage;
const content = Array.isArray(msg.content) ? msg.content : [];
for (const c of content) {
if (c.type === 'text' && c.text) textParts.push(c.text);
if (c.type === 'thinking' && c.thinking) thinkingParts.push(c.thinking);
if (c.type === 'tool_use') {
toolCalls.push({ type: 'toolCall', id: c.id || '', name: c.name || '', arguments: c.input || {} });
}
}
}
// Use the entry with the highest output_tokens for usage (cumulative)
if (!usage) usage = {};
const input = usage.input_tokens || 0;
const cacheRead = usage.cache_read_input_tokens || 0;
const cacheWrite = usage.cache_creation_input_tokens || 0;
const output = usage.output_tokens || 0;
const cost = calcCost(model, usage);
const normContent = [];
for (const text of textParts) normContent.push({ type: 'text', text });
for (const tc of toolCalls) normContent.push(tc);
return {
timestamp,
message: {
role: 'assistant',
content: normContent,
model,
timestamp,
thinking: thinkingParts.length > 0 ? thinkingParts.join('\n') : undefined,
usage: { input, output, cacheRead, cacheWrite, totalTokens: input + output + cacheRead + cacheWrite, cost },
}
};
}
function getAgentMeta() {
const cfg = readJSON(path.join(OC, 'openclaw.json'));
const map = {};
for (const a of (cfg?.agents?.list || [])) {
map[a.id] = { id: a.id, name: a.identity?.name || a.id, emoji: a.identity?.emoji || '🤖' };
}
if (!map['main']) map['main'] = { id: 'main', name: 'main', emoji: '⚡' };
return map;
}
function extractText(msg) {
let full;
if (typeof msg.content === 'string') full = msg.content;
else if (!Array.isArray(msg.content)) return '';
else full = msg.content.filter(c => c.type === 'text').map(c => c.text || '').join('');
return full;
}
function extractToolCalls(msg) {
if (!Array.isArray(msg.content)) return [];
return msg.content
.filter(c => c.type === 'toolCall')
.map(c => ({ id: c.id || '', name: c.name || '', args: c.arguments || {} }));
}
function shortPath(p) {
return (p || '')
.replace(/.*workspace-promo-assistant-[^/]+\//, '')
.replace(/.*\.openclaw\//, '~/')
.replace(/\/Users\/[^/]+\//, '~/')
.slice(0, 45);
}
function describeCall(name, args) {
if (name === 'browser') {
const act = args.action || '';
const req = args.request || {};
if (act === 'navigate') {
const u = args.targetUrl || '';
try { const p = new URL(u).pathname; return 'nav → ' + p.slice(0, 42); } catch { return 'nav → ' + u.slice(0, 42); }
}
if (act === 'act') {
const k = req.kind || '';
if (k === 'evaluate') return `eval (fn ${(req.fn || '').length}c)`;
if (k === 'snapshot') return `snapshot${req.selector ? ' [' + req.selector.slice(0, 18) + ']' : ''}`;
if (k === 'wait') return `wait ${req.timeMs}ms`;
if (k === 'click') return `click ${req.ref || ''}`;
if (k === 'type') return `type "${(req.text || '').slice(0, 22)}"`;
if (k === 'press') return `press ${req.key || ''}`;
if (k === 'scroll') return `scroll`;
return `act:${k}`;
}
if (act === 'tabs') return 'tabs';
if (act === 'open') return 'open browser';
if (act === 'close') return 'close';
return act || 'browser';
}
if (name === 'read') return shortPath(args.file_path || args.path || '');
if (name === 'write') return shortPath(args.file_path || args.path || '');
if (name === 'edit') return shortPath(args.file_path || args.path || '');
if (name === 'glob') return args.pattern || '';
if (name === 'grep') return `/${(args.pattern || '').slice(0, 28)}/`;
if (name === 'bash') return (args.command || '').replace(/\s+/g, ' ').slice(0, 50);
if (name === 'notion_query') return 'notion query';
if (name === 'notion') return 'notion';
if (name === 'slack') return 'slack';
return name;
}
function fmtSize(n) {
if (!n) return '—';
if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
if (n >= 1000) return (n / 1000).toFixed(1) + 'k';
return n + 'c';
}
function attachToolResult(step, msg) {
const textParts = Array.isArray(msg.content)
? msg.content.filter(c => c.type === 'text').map(c => c.text || '')
: [String(msg.content || '')];
const text = textParts.join('');
const size = text.length;
step.toolResults = step.toolResults || [];
step.toolResults.push({
name: msg.toolName || '?',
callId: msg.toolCallId || '',
size,
preview: text.slice(0, 500),
full: size > 500 ? text : null,
isError: msg.isError || false,
});
step.resultTotalSize = (step.resultTotalSize || 0) + size;
}
// Sanitize numeric value: ensure it's a finite non-negative number
function safeNum(v) { return (typeof v === 'number' && isFinite(v) && v >= 0) ? v : 0; }
function parseHeartbeats(entries, sessionFile) {
const runs = [];
let cur = null;
for (let ei = 0; ei < entries.length; ei++) {
const e = entries[ei];
const msg = e.message;
if (!msg?.role) continue;
if (msg.role === 'toolResult') {
if (cur?.steps?.length) attachToolResult(cur.steps[cur.steps.length - 1], msg);
continue;
}
if (msg.role === 'user') {
const content = Array.isArray(msg.content) ? msg.content : [];
const allToolResults = content.length > 0 && content.every(c => c.type === 'toolResult');
if (allToolResults) {
if (cur?.steps?.length) {
for (const c of content) {
const text = Array.isArray(c.content)
? c.content.filter(x => x.type === 'text').map(x => x.text || '').join('')
: String(c.content || '');
cur.steps[cur.steps.length - 1].toolResults = cur.steps[cur.steps.length - 1].toolResults || [];
cur.steps[cur.steps.length - 1].toolResults.push({
name: c.toolName || '?', callId: c.toolCallId || '',
size: text.length, preview: text.slice(0, 500), full: text.length > 500 ? text : null, isError: c.isError || false,
});
cur.steps[cur.steps.length - 1].resultTotalSize =
(cur.steps[cur.steps.length - 1].resultTotalSize || 0) + text.length;
}
}
continue;
}
if (cur) {
cur.entryRange.end = ei - 1;
if (cur.steps?.length || cur.apiErrors > 0) runs.push(finalizeRun(cur));
}
cur = {
startTime: e.timestamp || msg.timestamp || null,
endTime: null,
durationMs: null,
trigger: extractText(msg),
steps: [],
totalCost: 0,
totalTokensSum: 0,
totalOutput: 0,
finalContext: 0,
summary: '',
sessionFile: sessionFile || null,
entryRange: { start: ei, end: null },
};
continue;
}
if (msg.role === 'assistant' && cur) {
const u = msg.usage;
const cost = safeNum(u?.cost?.total);
const text = extractText(msg);
const calls = extractToolCalls(msg);
const ts = e.timestamp || msg.timestamp || null;
const hasContent = text || calls.length > 0;
if (u && (u.totalTokens > 0 || u.output > 0) || hasContent) {
cur.steps.push({
time: ts,
output: safeNum(u?.output),
cacheRead: safeNum(u?.cacheRead),
cacheWrite: safeNum(u?.cacheWrite),
totalTokens: safeNum(u?.totalTokens),
cost,
costInput: safeNum(u?.cost?.input),
costOutput: safeNum(u?.cost?.output),
costCacheRead: safeNum(u?.cost?.cacheRead),
costCacheWrite: safeNum(u?.cost?.cacheWrite),
toolCalls: calls,
toolResults: [],
resultTotalSize: 0,
text,
model: msg.model || '',
thinking: msg.thinking || '',
durationMs: null,
});
cur.totalCost += cost;
cur.totalTokensSum += safeNum(u?.totalTokens);
cur.totalOutput += safeNum(u?.output);
cur.finalContext = Math.max(cur.finalContext, safeNum(u?.totalTokens));
cur.endTime = ts;
if (text && calls.length === 0) cur.summary = text;
} else if (u && u.totalTokens === 0 && u.output === 0 && !hasContent) {
// API error — empty response (rate limit, overloaded, or transient failure)
cur.apiErrors = (cur.apiErrors || 0) + 1;
cur.endTime = ts;
}
}
}
if (cur?.steps?.length) { cur.entryRange.end = entries.length - 1; runs.push(finalizeRun(cur)); }
// Also push runs with only API errors (no successful steps)
if (cur && !cur.steps.length && cur.apiErrors > 0) { cur.entryRange.end = entries.length - 1; runs.push(finalizeRun(cur)); }
return runs.reverse();
}
function finalizeRun(r) {
if (r.startTime && r.endTime)
r.durationMs = new Date(r.endTime) - new Date(r.startTime);
// Calculate step durations
for (let i = 0; i < r.steps.length - 1; i++) {
const cur = r.steps[i];
const nxt = r.steps[i + 1];
if (cur.time && nxt.time) {
cur.durationMs = new Date(nxt.time) - new Date(cur.time);
}
}
// Last step: use endTime
if (r.steps.length > 0 && r.endTime) {
const last = r.steps[r.steps.length - 1];
if (last.time && !last.durationMs) {
last.durationMs = new Date(r.endTime) - new Date(last.time);
}
}
// Error count (tool errors + API errors)
r.apiErrors = r.apiErrors || 0;
r.errorCount = r.steps.reduce((sum, s) =>
sum + (s.toolResults?.filter(tr => hasError(tr, s)).length || 0), 0) + r.apiErrors;
// Browser action breakdown
const browserBreakdown = {};
for (const s of r.steps) {
for (const tc of (s.toolCalls || [])) {
if (tc.name === 'browser') {
const act = tc.args?.action || '';
const kind = tc.args?.request?.kind || '';
const label = act === 'act' ? kind || act : act;
browserBreakdown[label] = (browserBreakdown[label] || 0) + 1;
}
}
}
r.browserBreakdown = browserBreakdown;
// Cache hit rate (cacheRead / (cacheRead + input))
let totalCacheRead = 0, totalInput = 0;
for (const s of r.steps) {
totalCacheRead += s.cacheRead || 0;
// input = totalTokens - output - cacheRead - cacheWrite, or approximate from cost
const input = Math.max(0, (s.totalTokens || 0) - (s.output || 0) - (s.cacheRead || 0) - (s.cacheWrite || 0));
totalInput += input;
}
r.cacheHitRate = (totalCacheRead + totalInput) > 0 ? totalCacheRead / (totalCacheRead + totalInput) : 0;
r.totalCacheRead = totalCacheRead;
r.totalInput = totalInput;
r.totalCacheWrite = r.steps.reduce((s,x) => s + (x.cacheWrite||0), 0);
// Waste detection flags
const wasteFlags = [];
if (r.steps.length > 30) wasteFlags.push({ type: 'runaway', msg: `${r.steps.length} steps (likely runaway loop)` });
if (r.cacheHitRate < 0.5 && r.steps.length > 5) wasteFlags.push({ type: 'cache', msg: `${Math.round(r.cacheHitRate*100)}% cache hit (cold start or drift)` });
for (const s of r.steps) {
if (s.resultTotalSize > 10000) {
wasteFlags.push({ type: 'largeResult', msg: `Step with ${fmtSize(s.resultTotalSize)} result (unscoped snapshot?)` });
break; // Only flag once per heartbeat
}
}
for (const s of r.steps) {
if (s.totalTokens > 50000) {
wasteFlags.push({ type: 'bloatedCtx', msg: `Step with ${s.totalTokens.toLocaleString()} context (bloated)` });
break;
}
}
r.wasteFlags = wasteFlags;
return r;
}
function getBudget() {
const budgetFile = path.join(OC, 'canvas', 'budget.json');
const budget = readJSON(budgetFile) || { daily: 5.00, monthly: 100.00 };
return budget;
}
// ── Gateway Log Parsing (API errors, browser timeouts) ─────────────────────────
let _gatewayErrorsCache = { ts: 0, errors: [] };
function parseGatewayErrors() {
// Cache for 10 seconds to avoid re-parsing on every request
if (Date.now() - _gatewayErrorsCache.ts < 10000) return _gatewayErrorsCache.errors;
const today = new Date();
const dateStr = today.getFullYear() + '-' +
String(today.getMonth()+1).padStart(2,'0') + '-' +
String(today.getDate()).padStart(2,'0');
const logFile = path.join('/tmp/openclaw', `openclaw-${dateStr}.log`);
const errors = [];
try {
const content = fs.readFileSync(logFile, 'utf8');
const lines = content.split('\n');
// Track active lanes: agentId → { startTime, active }
const activeLanes = {}; // agentId → lastDequeueTime
const runToAgent = {}; // runId → agentId (from tool_result_persist)
const runErrors = {}; // runId → { count, firstTime, lastTime, agentId }
for (const line of lines) {
if (!line) continue;
let parsed;
try { parsed = JSON.parse(line); } catch { continue; }
const msg = parsed['1'] || parsed['0'] || '';
const time = parsed._meta?.date || parsed.time || '';
if (typeof msg !== 'string') continue;
// Track lane activity from dequeue/done events
// "lane dequeue: lane=session:agent:AGENT_ID:..."
const dequeueMatch = msg.match(/lane dequeue: lane=session:agent:([^:]+):/);
if (dequeueMatch) {
activeLanes[dequeueMatch[1]] = time;
}
// "lane task done: lane=session:agent:AGENT_ID:..."
const doneMatch = msg.match(/lane task done: lane=session:agent:([^:]+):/);
if (doneMatch) {
delete activeLanes[doneMatch[1]];
}
// Track runId→agent from tool_result_persist (has explicit agent=XXX)
const persistMatch = msg.match(/agent=([a-z0-9-]+)\s+session=agent:/);
if (persistMatch) {
// Find the currently active runId for this agent — track last seen
runToAgent['_last_' + persistMatch[1]] = time;
}
// Detect API errors: "embedded run agent end: runId=XXX isError=true"
const apiErrMatch = msg.match(/embedded run agent end: runId=([a-f0-9-]+) isError=true/);
if (apiErrMatch) {
const runId = apiErrMatch[1];
if (!runErrors[runId]) {
runErrors[runId] = { count: 0, firstTime: time, lastTime: time, agentId: null };
// Attribute to the agent whose lane is currently active
// Find the agent that was most recently dequeued (closest to this error time)
let bestAgent = null, bestTime = '';
for (const [agId, deqTime] of Object.entries(activeLanes)) {
if (deqTime <= time && deqTime > bestTime) {
bestTime = deqTime;
bestAgent = agId;
}
}
runErrors[runId].agentId = bestAgent;
}
runErrors[runId].count++;
runErrors[runId].lastTime = time;
}
// Track runId→agent from "embedded run done: runId=XXX sessionId=YYY durationMs=NNN"
const runDoneMatch = msg.match(/embedded run done: runId=([a-f0-9-]+) sessionId=([a-f0-9-]+) durationMs=(\d+)/);
if (runDoneMatch) {
const runId = runDoneMatch[1];
const sessionId = runDoneMatch[2];
const dur = parseInt(runDoneMatch[3]);
if (runErrors[runId]) {
runErrors[runId].sessionId = sessionId;
runErrors[runId].durationMs = dur;
// If no agent mapped yet, try session file lookup
if (!runErrors[runId].agentId) {
try {
const agentsDir = path.join(OC, 'agents');
for (const dir of fs.readdirSync(agentsDir)) {
if (fs.existsSync(path.join(agentsDir, dir, 'sessions', sessionId + '.jsonl'))) {
runErrors[runId].agentId = dir;
break;
}
}
} catch {}
}
}
}
// Detect browser timeouts: "⇄ res ✗ browser.request NNNms errorCode=XXX errorMessage=YYY"
const browserErrMatch = msg.match(/res ✗ browser\.request (\d+)ms errorCode=(\w+) errorMessage=(.+?)(?:\s+conn=|$)/);
if (browserErrMatch) {
const dur = parseInt(browserErrMatch[1]);
const errorCode = browserErrMatch[2];
const errorMsg = browserErrMatch[3].trim().slice(0, 150);
errors.push({
time, type: 'browser', agentId: null,
msg: `Browser CDP: ${errorCode} — ${errorMsg}`,
detail: `${dur}ms timeout`,
});
}
}
// Build error entries from runErrors
for (const [runId, info] of Object.entries(runErrors)) {
if (info.count === 0) continue;
const agentId = info.agentId || null;
// Classify error based on retry count
let errorMsg;
if (info.count >= 3) {
errorMsg = `API: ${info.count} consecutive failures (likely rate limit or overloaded)`;
} else if (info.count === 2) {
errorMsg = `API: ${info.count} retries (transient error)`;
} else {
errorMsg = 'API: single error (transient)';
}
if (info.durationMs !== undefined) {
errorMsg += ` — session ${Math.round(info.durationMs/1000)}s`;
}
errors.push({
time: info.firstTime,
type: 'api',
agentId,
msg: errorMsg,
detail: `runId: ${runId.slice(0,8)}… (${info.count} error${info.count>1?'s':''})`,
retryCount: info.count,
});
}
errors.sort((a,b) => (b.time||'') < (a.time||'') ? -1 : 1);
} catch (e) {
// Log file doesn't exist or can't be read — that's fine
}
_gatewayErrorsCache = { ts: Date.now(), errors };
return errors;
}
function cleanStepForAPI(step) {
return {
time: step.time,
durationMs: step.durationMs,
text: step.text,
toolCalls: step.toolCalls,
toolResults: step.toolResults,
cost: step.cost,
model: step.model || undefined,
totalTokens: step.totalTokens || undefined,
output: step.output || undefined,
cacheRead: step.cacheRead || undefined,
cacheWrite: step.cacheWrite || undefined,
thinking: step.thinking || undefined,
};
}
// Benign tool_use_errors that should not be surfaced as errors in the UI
const IGNORED_TOOL_ERRORS = [
'File has not been read yet',
'File has been modified since read',
'gateway timeout after',
'unmatched "',
];
function isIgnoredToolError(text) {
if (!text) return false;
return IGNORED_TOOL_ERRORS.some(sig => text.includes(sig));
}
// grep/rg return exit code 1 when no match is found — not an actual error
function isBenignGrepExit(toolResult, step) {
const preview = (toolResult.preview || '').trim();
if (!/exit code 1\s*$/i.test(preview)) return false;
if (!step || !Array.isArray(step.toolCalls)) return false;
const call = step.toolCalls.find(tc => tc.id === toolResult.callId);
if (!call || call.name !== 'Bash') return false;
const args = call.args || call.arguments || {};
const cmd = args.command || '';
return /(^|\s|\||;|&&|\|\||\(|`)(exec\s+)?(grep|egrep|fgrep|rg|ripgrep)\b/.test(cmd);
}
function hasError(toolResult, step) {
if (isBenignGrepExit(toolResult, step)) return false;
// Check explicit error flag
if (toolResult.isError) {
if (isIgnoredToolError(toolResult.preview || toolResult.full || '')) return false;
return true;
}
// Check if result content indicates an error
const preview = toolResult.preview || '';
if (isIgnoredToolError(preview)) return false;
try {
// Try to parse JSON result
const parsed = JSON.parse(preview);
if (parsed.status === 'error' || parsed.error) return true;
} catch {
// Not JSON or parse error, check string content
if (preview.includes('"status": "error"') || preview.includes('"status":"error"')) return true;
}
// Non-zero Bash exit code — treat as error (grep/rg handled above)
const exitMatch = preview.match(/Exit code (\d+)/i);
if (exitMatch && parseInt(exitMatch[1], 10) !== 0) return true;
return false;
}
function cleanHeartbeatForAPI(hb, errorsOnly = false) {
let steps = hb.steps?.map(cleanStepForAPI) || [];
// Filter to only steps with errors if requested
if (errorsOnly) {
steps = steps.filter(step =>
step.toolResults?.some(r => hasError(r, step)) || false
);
}
const { sessionFile, entryRange, ...rest } = hb;
return {
...rest,
steps,
...(errorsOnly && { filteredToErrors: true, totalSteps: hb.steps?.length || 0 }),
};
}
function loadAll(opts = {}) {
const includeReset = opts.includeReset || false;
const meta = getAgentMeta();
const agents = [];
const dailyCosts = {}; // { "2026-02-11": cost }
const dailyTokens = {}; // { "2026-02-11": tokens }
const dailyHbs = {}; // { "2026-02-11": count }
const dailyByAgent = {}; // { "2026-02-11": { agentId: cost } }
// Only load session files modified today or yesterday to limit memory usage
const now = new Date();
const cutoff = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1).getTime();
for (const [id, info] of Object.entries(meta)) {
const sessDir = path.join(OC, 'agents', id, 'sessions');
const sessFile = path.join(sessDir, 'sessions.json');
const sessions = readJSON(sessFile) || {};
const heartbeats = [];
let totalCost = 0;
let totalTokensSum = 0;
let totalErrors = 0;
let totalCacheReadTk = 0;
let totalInputTk = 0;
let lastTime = 0;
let model = '';
let contextTokens = 200000;
let totalTokens = 0;
// Read .jsonl files modified today or yesterday to limit memory usage
const allSessionFiles = [];
try {
const files = fs.readdirSync(sessDir);
for (const file of files) {
if (file.endsWith('.jsonl') || (includeReset && file.includes('.jsonl.reset.'))) {
const fp = path.join(sessDir, file);
try {
if (fs.statSync(fp).mtimeMs >= cutoff) allSessionFiles.push(fp);
} catch {}
}
}
} catch (e) {
// Directory doesn't exist or can't be read
}
// Include shadow file with preserved (truncated) heartbeat entries
const shadowFile = path.join(SHADOW_DIR, id + '.jsonl');
try {
if (fs.existsSync(shadowFile) && fs.statSync(shadowFile).mtimeMs >= cutoff) {
allSessionFiles.push(shadowFile);
}
} catch {}
// Prefer registered sessions for metadata
for (const sess of Object.values(sessions)) {
if (!sess.sessionFile) continue;
model = sess.model || model;
contextTokens = sess.contextTokens || contextTokens;
totalTokens = Math.max(totalTokens, sess.totalTokens || 0);
lastTime = Math.max(lastTime, sess.updatedAt || 0);
}
// Parse all session files
for (const sessionFile of allSessionFiles) {
const hbs = parseHeartbeats(readJSONL(sessionFile), sessionFile);
for (const hb of hbs) heartbeats.push(hb);
}
// Deduplicate heartbeats (shadow file may overlap with live file during active runs)
const seen = new Set();
const uniqueHbs = [];
heartbeats.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
for (const hb of heartbeats) {
const key = hb.startTime || '';
if (key && seen.has(key)) continue;
if (key) seen.add(key);
uniqueHbs.push(hb);
}
// Compute totals and daily rollup from deduplicated heartbeats
for (const hb of uniqueHbs) {
totalCost += hb.totalCost;
totalTokensSum += hb.totalTokensSum || 0;
totalErrors += hb.errorCount || 0;
totalCacheReadTk += hb.totalCacheRead || 0;
totalInputTk += hb.totalInput || 0;
if (hb.startTime) {
const d = new Date(hb.startTime);
const dateKey = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
dailyCosts[dateKey] = (dailyCosts[dateKey] || 0) + hb.totalCost;
dailyTokens[dateKey] = (dailyTokens[dateKey] || 0) + (hb.totalTokensSum || 0);
dailyHbs[dateKey] = (dailyHbs[dateKey] || 0) + 1;
if (!dailyByAgent[dateKey]) dailyByAgent[dateKey] = {};
dailyByAgent[dateKey][id] = (dailyByAgent[dateKey][id] || 0) + hb.totalCost;
}
}
// Average cache hit rate
const avgCacheHit = uniqueHbs.length
? uniqueHbs.reduce((sum, hb) => sum + (hb.cacheHitRate || 0), 0) / uniqueHbs.length
: 0;
agents.push({ ...info, model, contextTokens, totalTokens, totalCost, totalTokensSum, totalErrors, lastTime, heartbeats: uniqueHbs, avgCacheHit, totalCacheReadTk, totalInputTk });
}
// ── Claude Code project sessions ───────────────────────────────────────────
const existingIds = new Set(agents.map(a => a.id));
try {
const projects = fs.readdirSync(CLAUDE_HOME);
for (const proj of projects) {
const projDir = path.join(CLAUDE_HOME, proj);
if (!fs.statSync(projDir).isDirectory()) continue;
// Derive agent id from project directory name
// e.g. "-Users-mikolakondratuk--openclaw-workspace-promo-assistant-ih" -> "claude:ih"
const wsMatch = proj.match(/workspace-promo-assistant-(\w+)$/);
const id = wsMatch ? 'claude:' + wsMatch[1] : 'claude:' + proj.replace(/^-+/, '').replace(/-/g, ':').slice(0, 30);
// Skip if this workspace already has an OpenClaw agent (avoid duplicates)
// But add it as a separate entry with "claude:" prefix for visibility
if (existingIds.has(id)) continue;
const heartbeats = [];
let totalCost = 0, totalTokensSum = 0, totalErrors = 0;
let totalCacheReadTk = 0, totalInputTk = 0, lastTime = 0;
let model = '';
const files = fs.readdirSync(projDir).filter(f => f.endsWith('.jsonl'));
for (const file of files) {
const filePath = path.join(projDir, file);
try {
if (fs.statSync(filePath).mtimeMs < cutoff) continue;
} catch { continue; }
const hbs = parseHeartbeats(readJSONL(filePath), filePath);
for (const hb of hbs) heartbeats.push(hb);
}
// Deduplicate
const seen = new Set();
const uniqueHbs = [];
heartbeats.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
for (const hb of heartbeats) {
const key = hb.startTime || '';
if (key && seen.has(key)) continue;
if (key) seen.add(key);
uniqueHbs.push(hb);
}
for (const hb of uniqueHbs) {
totalCost += hb.totalCost;
totalTokensSum += hb.totalTokensSum || 0;
totalErrors += hb.errorCount || 0;
totalCacheReadTk += hb.totalCacheRead || 0;
totalInputTk += hb.totalInput || 0;
if (hb.steps?.length) model = hb.steps[0].model || model;
if (hb.startTime) {
lastTime = Math.max(lastTime, new Date(hb.startTime).getTime());
const d = new Date(hb.startTime);
const dateKey = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
dailyCosts[dateKey] = (dailyCosts[dateKey] || 0) + hb.totalCost;
dailyTokens[dateKey] = (dailyTokens[dateKey] || 0) + (hb.totalTokensSum || 0);