@dorywoof/agentreplay 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/util.js ADDED
@@ -0,0 +1,145 @@
1
+ import fs from 'node:fs';
2
+
3
+ /** Read a JSONL file, skipping blank or malformed lines. */
4
+ export function readJsonl(file) {
5
+ const out = [];
6
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
7
+ if (!line.trim()) continue;
8
+ try {
9
+ out.push(JSON.parse(line));
10
+ } catch {
11
+ /* partial line while the agent is still writing — ignore */
12
+ }
13
+ }
14
+ return out;
15
+ }
16
+
17
+ /** Flatten the many shapes "content" can take into plain text. */
18
+ export function toText(content) {
19
+ if (content == null) return '';
20
+ if (typeof content === 'string') return content;
21
+ if (Array.isArray(content)) return content.map(toText).filter(Boolean).join('\n');
22
+ if (typeof content === 'object') {
23
+ if (typeof content.text === 'string') return content.text;
24
+ if (content.type === 'image') return '[image]';
25
+ if ('content' in content) return toText(content.content);
26
+ if ('output' in content) return toText(content.output);
27
+ }
28
+ return '';
29
+ }
30
+
31
+ /** Remove harness-injected tags that are noise for a human viewer. */
32
+ export function stripHarnessTags(text) {
33
+ return text
34
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')
35
+ .replace(/<pasted_content[^>]*>[\s\S]*?<\/pasted_content[^>]*>/g, '[pasted text]')
36
+ .trim();
37
+ }
38
+
39
+ export function truncate(text, max) {
40
+ if (!text || text.length <= max) return text;
41
+ return text.slice(0, max) + `\n… (${text.length - max} more characters)`;
42
+ }
43
+
44
+ /** Rough +/- line count between two strings (good enough for stats). */
45
+ export function lineDelta(oldStr = '', newStr = '') {
46
+ const a = oldStr ? oldStr.split('\n') : [];
47
+ const b = newStr ? newStr.split('\n') : [];
48
+ const counts = new Map();
49
+ for (const l of a) counts.set(l, (counts.get(l) || 0) + 1);
50
+ let common = 0;
51
+ for (const l of b) {
52
+ const c = counts.get(l);
53
+ if (c) {
54
+ common++;
55
+ counts.set(l, c - 1);
56
+ }
57
+ }
58
+ return { added: b.length - common, removed: a.length - common };
59
+ }
60
+
61
+ /** Read a file that may be one JSON document or JSONL. Returns { doc } or { lines }. */
62
+ export function readJsonAny(file) {
63
+ const raw = fs.readFileSync(file, 'utf8').replace(/^/, '');
64
+ const trimmed = raw.trim();
65
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
66
+ try {
67
+ return { doc: JSON.parse(trimmed) };
68
+ } catch {
69
+ /* fall through to JSONL */
70
+ }
71
+ }
72
+ return { lines: readJsonl(file) };
73
+ }
74
+
75
+ /** Accept ISO strings, epoch seconds or epoch milliseconds. */
76
+ export function toMs(v) {
77
+ if (v == null || v === '') return null;
78
+ if (typeof v === 'number') return v < 1e12 ? v * 1000 : v;
79
+ if (typeof v === 'string' && /^\d+(\.\d+)?$/.test(v)) return toMs(Number(v));
80
+ const t = Date.parse(v);
81
+ return Number.isFinite(t) ? t : null;
82
+ }
83
+
84
+ /** Empty normalized session — every parser fills one of these. */
85
+ export function newSession(agent, id) {
86
+ return {
87
+ agent,
88
+ id: String(id || 'session'),
89
+ title: null,
90
+ cwd: null,
91
+ branch: null,
92
+ models: new Set(),
93
+ events: [],
94
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 },
95
+ usageByModel: {},
96
+ reportedCost: null,
97
+ timesSynthetic: false,
98
+ };
99
+ }
100
+
101
+ /** Add token usage to the session totals and the per-model breakdown. */
102
+ export function addUsage(session, model, u) {
103
+ const key = model || 'unknown';
104
+ const per = (session.usageByModel[key] ||= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 });
105
+ for (const k of ['input', 'output', 'cacheRead', 'cacheWrite', 'cacheWrite1h']) {
106
+ const v = Number(u[k]) || 0;
107
+ session.usage[k] += v;
108
+ per[k] += v;
109
+ }
110
+ }
111
+
112
+ /** Codex / OpenAI apply_patch envelope → diff hunks. */
113
+ export function parsePatch(patch, maxLen = 4000) {
114
+ const files = [];
115
+ let cur = null;
116
+ for (const line of patch.split('\n')) {
117
+ const m = line.match(/^\*\*\* (Add|Update|Delete) File: (.+)$/);
118
+ if (m) {
119
+ cur = { file: m[2].trim(), op: m[1], old: [], new: [] };
120
+ files.push(cur);
121
+ continue;
122
+ }
123
+ if (!cur || line.startsWith('***') || line.startsWith('@@')) continue;
124
+ if (line.startsWith('+')) cur.new.push(line.slice(1));
125
+ else if (line.startsWith('-')) cur.old.push(line.slice(1));
126
+ }
127
+ const first = files[0] || { file: '(patch)', old: [], new: [] };
128
+ return {
129
+ file: first.file,
130
+ files: files.map((f) => f.file),
131
+ created: first.op === 'Add',
132
+ summary: files.map((f) => f.file).join(', '),
133
+ diff: files.map((f) => ({ old: truncate(f.old.join('\n'), maxLen), new: truncate(f.new.join('\n'), maxLen), file: f.file })),
134
+ lines: files.reduce((a, f) => ({ added: a.added + f.new.length, removed: a.removed + f.old.length }), { added: 0, removed: 0 }),
135
+ };
136
+ }
137
+
138
+ /** Cline / Roo / Aider style SEARCH/REPLACE blocks → diff hunks. */
139
+ export function parseSearchReplace(text) {
140
+ const hunks = [];
141
+ const re = /<{5,}\s*SEARCH[^\n]*\n([\s\S]*?)\n?={5,}\n([\s\S]*?)\n?>{5,}\s*REPLACE/g;
142
+ let m;
143
+ while ((m = re.exec(text))) hunks.push({ old: m[1].replace(/^:start_line:\d+\n-+\n/, ''), new: m[2] });
144
+ return hunks;
145
+ }