@forwardimpact/libeval 0.1.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/LICENSE +201 -0
- package/bin/fit-eval.js +67 -0
- package/index.js +1 -0
- package/package.json +21 -0
- package/src/commands/output.js +53 -0
- package/src/commands/tee.js +99 -0
- package/src/trace-collector.js +259 -0
- package/test/fixtures/stream.ndjson +7 -0
- package/test/trace-collector.test.js +328 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Dick Olsson
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/bin/fit-eval.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { runOutputCommand } from "../src/commands/output.js";
|
|
4
|
+
import { runTeeCommand } from "../src/commands/tee.js";
|
|
5
|
+
|
|
6
|
+
const COMMANDS = {
|
|
7
|
+
output: runOutputCommand,
|
|
8
|
+
tee: runTeeCommand,
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const HELP_TEXT = `
|
|
12
|
+
Eval CLI — Process Claude Code stream-json output
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
fit-eval <command> [options]
|
|
16
|
+
|
|
17
|
+
Commands:
|
|
18
|
+
output [--format=json|text] Process trace and output formatted result
|
|
19
|
+
tee [output.ndjson] Stream text to stdout, optionally save raw NDJSON
|
|
20
|
+
|
|
21
|
+
Options:
|
|
22
|
+
--help Show this help message
|
|
23
|
+
--version Show version number
|
|
24
|
+
|
|
25
|
+
Examples:
|
|
26
|
+
fit-eval output --format=text < trace.ndjson
|
|
27
|
+
fit-eval output --format=json < trace.ndjson
|
|
28
|
+
fit-eval tee < trace.ndjson
|
|
29
|
+
fit-eval tee output.ndjson < trace.ndjson
|
|
30
|
+
`.trim();
|
|
31
|
+
|
|
32
|
+
async function main() {
|
|
33
|
+
const args = process.argv.slice(2);
|
|
34
|
+
|
|
35
|
+
if (args.includes("--help") || args.includes("-h") || args.length === 0) {
|
|
36
|
+
console.log(HELP_TEXT);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (args.includes("--version")) {
|
|
41
|
+
const { readFileSync } = await import("fs");
|
|
42
|
+
const { join, dirname } = await import("path");
|
|
43
|
+
const { fileURLToPath } = await import("url");
|
|
44
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
45
|
+
const pkg = JSON.parse(
|
|
46
|
+
readFileSync(join(__dirname, "..", "package.json"), "utf8"),
|
|
47
|
+
);
|
|
48
|
+
console.log(pkg.version);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const commandName = args[0];
|
|
53
|
+
const handler = COMMANDS[commandName];
|
|
54
|
+
|
|
55
|
+
if (!handler) {
|
|
56
|
+
console.error(`Unknown command: ${commandName}\n`);
|
|
57
|
+
console.error(HELP_TEXT);
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
await handler(args.slice(1));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
main().catch((error) => {
|
|
65
|
+
console.error(error.message);
|
|
66
|
+
process.exit(1);
|
|
67
|
+
});
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { TraceCollector, createTraceCollector } from "./src/trace-collector.js";
|
package/package.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@forwardimpact/libeval",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Process Claude Code stream-json output into structured traces",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "D. Olsson <hi@senzilla.io>",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "index.js",
|
|
9
|
+
"bin": {
|
|
10
|
+
"fit-eval": "./bin/fit-eval.js"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22.0.0"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test test/*.test.js"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createTraceCollector } from "@forwardimpact/libeval";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Output command — process a complete NDJSON trace from stdin and write
|
|
5
|
+
* formatted output to stdout.
|
|
6
|
+
*
|
|
7
|
+
* Usage: fit-eval output [--format=json|text] < trace.ndjson
|
|
8
|
+
*
|
|
9
|
+
* @param {string[]} args - Command arguments
|
|
10
|
+
*/
|
|
11
|
+
export async function runOutputCommand(args) {
|
|
12
|
+
const format = parseFormat(args);
|
|
13
|
+
const collector = createTraceCollector();
|
|
14
|
+
|
|
15
|
+
const chunks = [];
|
|
16
|
+
for await (const chunk of process.stdin) {
|
|
17
|
+
chunks.push(chunk);
|
|
18
|
+
}
|
|
19
|
+
const input = Buffer.concat(chunks).toString("utf8");
|
|
20
|
+
|
|
21
|
+
for (const line of input.split("\n")) {
|
|
22
|
+
collector.addLine(line);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (format === "text") {
|
|
26
|
+
process.stdout.write(collector.toText() + "\n");
|
|
27
|
+
} else {
|
|
28
|
+
process.stdout.write(JSON.stringify(collector.toJSON()) + "\n");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Parse --format from args. Supports --format=value and --format value.
|
|
34
|
+
* @param {string[]} args
|
|
35
|
+
* @returns {"text"|"json"}
|
|
36
|
+
*/
|
|
37
|
+
function parseFormat(args) {
|
|
38
|
+
for (let i = 0; i < args.length; i++) {
|
|
39
|
+
if (args[i].startsWith("--format=")) {
|
|
40
|
+
const value = args[i].slice("--format=".length);
|
|
41
|
+
if (value === "text" || value === "json") return value;
|
|
42
|
+
console.error(`Unknown format: ${value}. Using "json".`);
|
|
43
|
+
return "json";
|
|
44
|
+
}
|
|
45
|
+
if (args[i] === "--format" && i + 1 < args.length) {
|
|
46
|
+
const value = args[i + 1];
|
|
47
|
+
if (value === "text" || value === "json") return value;
|
|
48
|
+
console.error(`Unknown format: ${value}. Using "json".`);
|
|
49
|
+
return "json";
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return "json";
|
|
53
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { createWriteStream } from "fs";
|
|
2
|
+
import { createTraceCollector } from "@forwardimpact/libeval";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Tee command — stream text output to stdout while optionally saving the raw
|
|
6
|
+
* NDJSON to a file. Processes stdin line-by-line for streaming output.
|
|
7
|
+
*
|
|
8
|
+
* Usage: fit-eval tee [output.ndjson] < trace.ndjson
|
|
9
|
+
*
|
|
10
|
+
* @param {string[]} args - Command arguments (optional output file path)
|
|
11
|
+
*/
|
|
12
|
+
export async function runTeeCommand(args) {
|
|
13
|
+
const outputPath = args.find((a) => !a.startsWith("-")) ?? null;
|
|
14
|
+
const fileStream = outputPath ? createWriteStream(outputPath) : null;
|
|
15
|
+
const collector = createTraceCollector();
|
|
16
|
+
const turnsEmitted = { count: 0 };
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
let buffer = "";
|
|
20
|
+
|
|
21
|
+
for await (const chunk of process.stdin) {
|
|
22
|
+
buffer += chunk.toString("utf8");
|
|
23
|
+
|
|
24
|
+
let newlineIdx;
|
|
25
|
+
while ((newlineIdx = buffer.indexOf("\n")) !== -1) {
|
|
26
|
+
const line = buffer.slice(0, newlineIdx);
|
|
27
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
28
|
+
|
|
29
|
+
if (fileStream) {
|
|
30
|
+
fileStream.write(line + "\n");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
collector.addLine(line);
|
|
34
|
+
flushNewTurns(collector, turnsEmitted);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Process any remaining data without a trailing newline
|
|
39
|
+
if (buffer.trim()) {
|
|
40
|
+
if (fileStream) {
|
|
41
|
+
fileStream.write(buffer + "\n");
|
|
42
|
+
}
|
|
43
|
+
collector.addLine(buffer);
|
|
44
|
+
flushNewTurns(collector, turnsEmitted);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Emit the result summary at the end
|
|
48
|
+
if (collector.result) {
|
|
49
|
+
const text = collector.toText();
|
|
50
|
+
const lastNewline = text.lastIndexOf("\n---");
|
|
51
|
+
if (lastNewline !== -1) {
|
|
52
|
+
process.stdout.write(text.slice(lastNewline) + "\n");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
} finally {
|
|
56
|
+
if (fileStream) {
|
|
57
|
+
await new Promise((resolve, reject) => {
|
|
58
|
+
fileStream.end(() => resolve());
|
|
59
|
+
fileStream.on("error", reject);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Write text for any new turns that haven't been emitted yet.
|
|
67
|
+
* @param {import("@forwardimpact/libeval").TraceCollector} collector
|
|
68
|
+
* @param {{ count: number }} turnsEmitted
|
|
69
|
+
*/
|
|
70
|
+
function flushNewTurns(collector, turnsEmitted) {
|
|
71
|
+
const turns = collector.turns;
|
|
72
|
+
while (turnsEmitted.count < turns.length) {
|
|
73
|
+
const turn = turns[turnsEmitted.count];
|
|
74
|
+
turnsEmitted.count++;
|
|
75
|
+
|
|
76
|
+
if (turn.role === "assistant") {
|
|
77
|
+
for (const block of turn.content) {
|
|
78
|
+
if (block.type === "text") {
|
|
79
|
+
process.stdout.write(block.text + "\n");
|
|
80
|
+
} else if (block.type === "tool_use") {
|
|
81
|
+
const inputSummary = summarizeInput(block.input);
|
|
82
|
+
process.stdout.write(`> Tool: ${block.name} ${inputSummary}\n`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Summarize tool input for text display, truncated to keep logs readable.
|
|
91
|
+
* @param {object} input - Tool input object
|
|
92
|
+
* @returns {string} Truncated summary
|
|
93
|
+
*/
|
|
94
|
+
function summarizeInput(input) {
|
|
95
|
+
if (!input || typeof input !== "object") return "";
|
|
96
|
+
const json = JSON.stringify(input);
|
|
97
|
+
if (json.length <= 200) return json;
|
|
98
|
+
return json.slice(0, 197) + "...";
|
|
99
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collects Claude Code stream-json NDJSON events into structured traces.
|
|
3
|
+
*
|
|
4
|
+
* Accepts one NDJSON line at a time via addLine(), then produces either a
|
|
5
|
+
* structured JSON trace (toJSON) or human-readable text (toText).
|
|
6
|
+
*/
|
|
7
|
+
export class TraceCollector {
|
|
8
|
+
/**
|
|
9
|
+
* @param {object} [deps]
|
|
10
|
+
* @param {function} [deps.now] - Returns ISO timestamp string. Defaults to () => new Date().toISOString()
|
|
11
|
+
*/
|
|
12
|
+
constructor(deps = {}) {
|
|
13
|
+
/** @type {function} */
|
|
14
|
+
this.now = deps.now ?? (() => new Date().toISOString());
|
|
15
|
+
/** @type {object|null} */
|
|
16
|
+
this.metadata = null;
|
|
17
|
+
/** @type {Array<object>} */
|
|
18
|
+
this.turns = [];
|
|
19
|
+
/** @type {object|null} */
|
|
20
|
+
this.result = null;
|
|
21
|
+
/** @type {number} */
|
|
22
|
+
this.turnIndex = 0;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Parse one NDJSON line and accumulate state.
|
|
27
|
+
* Malformed lines are silently skipped.
|
|
28
|
+
* @param {string} line - A single JSON line from stream-json output
|
|
29
|
+
*/
|
|
30
|
+
addLine(line) {
|
|
31
|
+
const trimmed = line.trim();
|
|
32
|
+
if (!trimmed) return;
|
|
33
|
+
|
|
34
|
+
let event;
|
|
35
|
+
try {
|
|
36
|
+
event = JSON.parse(trimmed);
|
|
37
|
+
} catch {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
switch (event.type) {
|
|
42
|
+
case "system":
|
|
43
|
+
this.handleSystem(event);
|
|
44
|
+
break;
|
|
45
|
+
case "assistant":
|
|
46
|
+
this.handleAssistant(event);
|
|
47
|
+
break;
|
|
48
|
+
case "user":
|
|
49
|
+
this.handleUser(event);
|
|
50
|
+
break;
|
|
51
|
+
case "result":
|
|
52
|
+
this.handleResult(event);
|
|
53
|
+
break;
|
|
54
|
+
default:
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {object} event
|
|
61
|
+
*/
|
|
62
|
+
handleSystem(event) {
|
|
63
|
+
if (event.subtype === "init") {
|
|
64
|
+
this.metadata = {
|
|
65
|
+
timestamp: event.timestamp ?? this.now(),
|
|
66
|
+
sessionId: event.session_id ?? null,
|
|
67
|
+
model: event.model ?? null,
|
|
68
|
+
claudeCodeVersion: event.claude_code_version ?? null,
|
|
69
|
+
tools: event.tools ?? [],
|
|
70
|
+
permissionMode: event.permissionMode ?? null,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @param {object} event
|
|
77
|
+
*/
|
|
78
|
+
handleAssistant(event) {
|
|
79
|
+
const message = event.message;
|
|
80
|
+
if (!message) return;
|
|
81
|
+
|
|
82
|
+
const content = (message.content ?? []).map((block) => {
|
|
83
|
+
if (block.type === "text") {
|
|
84
|
+
return { type: "text", text: block.text };
|
|
85
|
+
}
|
|
86
|
+
if (block.type === "tool_use") {
|
|
87
|
+
return {
|
|
88
|
+
type: "tool_use",
|
|
89
|
+
toolUseId: block.id ?? null,
|
|
90
|
+
name: block.name,
|
|
91
|
+
input: block.input,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
return block;
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const usage = message.usage
|
|
98
|
+
? {
|
|
99
|
+
inputTokens: message.usage.input_tokens ?? 0,
|
|
100
|
+
outputTokens: message.usage.output_tokens ?? 0,
|
|
101
|
+
cacheReadInputTokens: message.usage.cache_read_input_tokens ?? 0,
|
|
102
|
+
cacheCreationInputTokens:
|
|
103
|
+
message.usage.cache_creation_input_tokens ?? 0,
|
|
104
|
+
}
|
|
105
|
+
: null;
|
|
106
|
+
|
|
107
|
+
this.turns.push({
|
|
108
|
+
index: this.turnIndex++,
|
|
109
|
+
role: "assistant",
|
|
110
|
+
content,
|
|
111
|
+
usage,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* @param {object} event
|
|
117
|
+
*/
|
|
118
|
+
handleUser(event) {
|
|
119
|
+
const message = event.message;
|
|
120
|
+
if (!message) return;
|
|
121
|
+
|
|
122
|
+
const contentItems = message.content;
|
|
123
|
+
if (!Array.isArray(contentItems)) return;
|
|
124
|
+
|
|
125
|
+
for (const item of contentItems) {
|
|
126
|
+
if (item.type === "tool_result") {
|
|
127
|
+
this.turns.push({
|
|
128
|
+
index: this.turnIndex++,
|
|
129
|
+
role: "tool_result",
|
|
130
|
+
toolUseId: item.tool_use_id ?? null,
|
|
131
|
+
content:
|
|
132
|
+
typeof item.content === "string"
|
|
133
|
+
? item.content
|
|
134
|
+
: JSON.stringify(item.content),
|
|
135
|
+
isError: item.is_error ?? false,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* @param {object} event
|
|
143
|
+
*/
|
|
144
|
+
handleResult(event) {
|
|
145
|
+
this.result = {
|
|
146
|
+
result: event.subtype ?? "unknown",
|
|
147
|
+
isError: event.is_error ?? false,
|
|
148
|
+
totalCostUsd: event.total_cost_usd ?? 0,
|
|
149
|
+
durationMs: event.duration_ms ?? 0,
|
|
150
|
+
numTurns: event.num_turns ?? 0,
|
|
151
|
+
tokenUsage: event.usage
|
|
152
|
+
? {
|
|
153
|
+
inputTokens: event.usage.input_tokens ?? 0,
|
|
154
|
+
outputTokens: event.usage.output_tokens ?? 0,
|
|
155
|
+
cacheReadInputTokens: event.usage.cache_read_input_tokens ?? 0,
|
|
156
|
+
cacheCreationInputTokens:
|
|
157
|
+
event.usage.cache_creation_input_tokens ?? 0,
|
|
158
|
+
}
|
|
159
|
+
: null,
|
|
160
|
+
modelUsage: event.modelUsage ?? null,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Return a structured trace object for offline analysis.
|
|
166
|
+
* @returns {object} Structured trace document
|
|
167
|
+
*/
|
|
168
|
+
toJSON() {
|
|
169
|
+
return {
|
|
170
|
+
version: "1.0.0",
|
|
171
|
+
metadata: this.metadata ?? {
|
|
172
|
+
timestamp: this.now(),
|
|
173
|
+
sessionId: null,
|
|
174
|
+
model: null,
|
|
175
|
+
claudeCodeVersion: null,
|
|
176
|
+
tools: [],
|
|
177
|
+
permissionMode: null,
|
|
178
|
+
},
|
|
179
|
+
turns: this.turns,
|
|
180
|
+
summary: this.result ?? {
|
|
181
|
+
result: "unknown",
|
|
182
|
+
isError: false,
|
|
183
|
+
totalCostUsd: 0,
|
|
184
|
+
durationMs: 0,
|
|
185
|
+
numTurns: 0,
|
|
186
|
+
tokenUsage: null,
|
|
187
|
+
modelUsage: null,
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Return human-readable text for workflow logs.
|
|
194
|
+
* @returns {string} Formatted text output
|
|
195
|
+
*/
|
|
196
|
+
toText() {
|
|
197
|
+
const lines = [];
|
|
198
|
+
|
|
199
|
+
for (const turn of this.turns) {
|
|
200
|
+
if (turn.role === "assistant") {
|
|
201
|
+
for (const block of turn.content) {
|
|
202
|
+
if (block.type === "text") {
|
|
203
|
+
lines.push(block.text);
|
|
204
|
+
} else if (block.type === "tool_use") {
|
|
205
|
+
const inputSummary = summarizeInput(block.input);
|
|
206
|
+
lines.push(`> Tool: ${block.name} ${inputSummary}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (this.result) {
|
|
213
|
+
const duration = formatDuration(this.result.durationMs);
|
|
214
|
+
const cost = Number(this.result.totalCostUsd).toFixed(4);
|
|
215
|
+
lines.push("");
|
|
216
|
+
lines.push(
|
|
217
|
+
`--- Result: ${this.result.result} | Turns: ${this.result.numTurns} | Cost: $${cost} | Duration: ${duration} ---`,
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return lines.join("\n");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Summarize tool input for text display, truncated to keep logs readable.
|
|
227
|
+
* @param {object} input - Tool input object
|
|
228
|
+
* @returns {string} Truncated summary
|
|
229
|
+
*/
|
|
230
|
+
function summarizeInput(input) {
|
|
231
|
+
if (!input || typeof input !== "object") return "";
|
|
232
|
+
const json = JSON.stringify(input);
|
|
233
|
+
if (json.length <= 200) return json;
|
|
234
|
+
return json.slice(0, 197) + "...";
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Format milliseconds into a human-readable duration.
|
|
239
|
+
* @param {number} ms - Duration in milliseconds
|
|
240
|
+
* @returns {string} Formatted duration
|
|
241
|
+
*/
|
|
242
|
+
function formatDuration(ms) {
|
|
243
|
+
if (ms < 1000) return `${ms}ms`;
|
|
244
|
+
const seconds = Math.round(ms / 1000);
|
|
245
|
+
if (seconds < 60) return `${seconds}s`;
|
|
246
|
+
const minutes = Math.floor(seconds / 60);
|
|
247
|
+
const remainingSeconds = seconds % 60;
|
|
248
|
+
return `${minutes}m ${remainingSeconds}s`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Factory function for TraceCollector.
|
|
253
|
+
* @param {object} [deps]
|
|
254
|
+
* @param {function} [deps.now] - Returns ISO timestamp string
|
|
255
|
+
* @returns {TraceCollector}
|
|
256
|
+
*/
|
|
257
|
+
export function createTraceCollector(deps) {
|
|
258
|
+
return new TraceCollector(deps);
|
|
259
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{"type":"system","subtype":"init","cwd":"/home/user/monorepo","session_id":"abc-123","tools":["Bash","Read","Glob","Grep","Write","Edit"],"mcp_servers":[],"model":"claude-opus-4-6","permissionMode":"default","claude_code_version":"2.1.87","uuid":"evt-1"}
|
|
2
|
+
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01","type":"message","role":"assistant","content":[{"type":"text","text":"I'll start by checking the repository structure."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":100,"cache_creation_input_tokens":500,"cache_read_input_tokens":200,"output_tokens":15,"service_tier":"standard"}},"session_id":"abc-123","uuid":"evt-2"}
|
|
3
|
+
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"command":"ls -la"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":100,"cache_creation_input_tokens":500,"cache_read_input_tokens":200,"output_tokens":15,"service_tier":"standard"}},"session_id":"abc-123","uuid":"evt-3"}
|
|
4
|
+
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01","type":"tool_result","content":"total 42\ndrwxr-xr-x 5 user user 4096 Mar 29 12:00 .\ndrwxr-xr-x 3 user user 4096 Mar 29 12:00 .."}]},"uuid":"evt-4","session_id":"abc-123"}
|
|
5
|
+
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_02","type":"message","role":"assistant","content":[{"type":"text","text":"The repository looks good. No security issues found."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":150,"cache_creation_input_tokens":0,"cache_read_input_tokens":700,"output_tokens":12,"service_tier":"standard"}},"session_id":"abc-123","uuid":"evt-5"}
|
|
6
|
+
{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"evt-6","session_id":"abc-123"}
|
|
7
|
+
{"type":"result","subtype":"success","is_error":false,"duration_ms":5200,"duration_api_ms":4800,"num_turns":3,"result":"The repository looks good. No security issues found.","stop_reason":"end_turn","session_id":"abc-123","total_cost_usd":0.0523,"usage":{"input_tokens":350,"cache_creation_input_tokens":500,"cache_read_input_tokens":900,"output_tokens":42,"service_tier":"standard"},"modelUsage":{"claude-opus-4-6":{"inputTokens":350,"outputTokens":42,"cacheReadInputTokens":900,"cacheCreationInputTokens":500,"costUSD":0.0523}},"uuid":"evt-7"}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { describe, test } from "node:test";
|
|
2
|
+
import assert from "node:assert";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
import { TraceCollector, createTraceCollector } from "@forwardimpact/libeval";
|
|
8
|
+
|
|
9
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const fixturePath = path.join(__dirname, "fixtures", "stream.ndjson");
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Load fixture lines from the NDJSON file.
|
|
14
|
+
* @returns {string[]}
|
|
15
|
+
*/
|
|
16
|
+
function loadFixture() {
|
|
17
|
+
return fs.readFileSync(fixturePath, "utf8").trim().split("\n");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Feed all fixture lines into a collector and return it.
|
|
22
|
+
* @returns {TraceCollector}
|
|
23
|
+
*/
|
|
24
|
+
function collectFixture() {
|
|
25
|
+
const collector = new TraceCollector();
|
|
26
|
+
for (const line of loadFixture()) {
|
|
27
|
+
collector.addLine(line);
|
|
28
|
+
}
|
|
29
|
+
return collector;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe("TraceCollector", () => {
|
|
33
|
+
describe("addLine", () => {
|
|
34
|
+
test("extracts metadata from system init event", () => {
|
|
35
|
+
const collector = new TraceCollector();
|
|
36
|
+
collector.addLine(
|
|
37
|
+
JSON.stringify({
|
|
38
|
+
type: "system",
|
|
39
|
+
subtype: "init",
|
|
40
|
+
session_id: "sess-1",
|
|
41
|
+
model: "claude-opus-4-6",
|
|
42
|
+
claude_code_version: "2.1.87",
|
|
43
|
+
tools: ["Bash", "Read"],
|
|
44
|
+
permissionMode: "default",
|
|
45
|
+
}),
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
const trace = collector.toJSON();
|
|
49
|
+
assert.strictEqual(trace.metadata.sessionId, "sess-1");
|
|
50
|
+
assert.strictEqual(trace.metadata.model, "claude-opus-4-6");
|
|
51
|
+
assert.strictEqual(trace.metadata.claudeCodeVersion, "2.1.87");
|
|
52
|
+
assert.deepStrictEqual(trace.metadata.tools, ["Bash", "Read"]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("collects assistant text turns", () => {
|
|
56
|
+
const collector = new TraceCollector();
|
|
57
|
+
collector.addLine(
|
|
58
|
+
JSON.stringify({
|
|
59
|
+
type: "assistant",
|
|
60
|
+
message: {
|
|
61
|
+
content: [{ type: "text", text: "Hello world" }],
|
|
62
|
+
usage: { input_tokens: 10, output_tokens: 5 },
|
|
63
|
+
},
|
|
64
|
+
}),
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
const trace = collector.toJSON();
|
|
68
|
+
assert.strictEqual(trace.turns.length, 1);
|
|
69
|
+
assert.strictEqual(trace.turns[0].role, "assistant");
|
|
70
|
+
assert.strictEqual(trace.turns[0].content[0].text, "Hello world");
|
|
71
|
+
assert.strictEqual(trace.turns[0].usage.inputTokens, 10);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("collects assistant tool_use turns", () => {
|
|
75
|
+
const collector = new TraceCollector();
|
|
76
|
+
collector.addLine(
|
|
77
|
+
JSON.stringify({
|
|
78
|
+
type: "assistant",
|
|
79
|
+
message: {
|
|
80
|
+
content: [
|
|
81
|
+
{
|
|
82
|
+
type: "tool_use",
|
|
83
|
+
id: "toolu_01",
|
|
84
|
+
name: "Bash",
|
|
85
|
+
input: { command: "ls" },
|
|
86
|
+
},
|
|
87
|
+
],
|
|
88
|
+
usage: { input_tokens: 20, output_tokens: 10 },
|
|
89
|
+
},
|
|
90
|
+
}),
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
const trace = collector.toJSON();
|
|
94
|
+
assert.strictEqual(trace.turns[0].content[0].type, "tool_use");
|
|
95
|
+
assert.strictEqual(trace.turns[0].content[0].name, "Bash");
|
|
96
|
+
assert.strictEqual(trace.turns[0].content[0].toolUseId, "toolu_01");
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("collects tool_result from user events", () => {
|
|
100
|
+
const collector = new TraceCollector();
|
|
101
|
+
collector.addLine(
|
|
102
|
+
JSON.stringify({
|
|
103
|
+
type: "user",
|
|
104
|
+
message: {
|
|
105
|
+
role: "user",
|
|
106
|
+
content: [
|
|
107
|
+
{
|
|
108
|
+
type: "tool_result",
|
|
109
|
+
tool_use_id: "toolu_01",
|
|
110
|
+
content: "file listing output",
|
|
111
|
+
},
|
|
112
|
+
],
|
|
113
|
+
},
|
|
114
|
+
}),
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
const trace = collector.toJSON();
|
|
118
|
+
assert.strictEqual(trace.turns.length, 1);
|
|
119
|
+
assert.strictEqual(trace.turns[0].role, "tool_result");
|
|
120
|
+
assert.strictEqual(trace.turns[0].toolUseId, "toolu_01");
|
|
121
|
+
assert.strictEqual(trace.turns[0].content, "file listing output");
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("extracts summary from result event", () => {
|
|
125
|
+
const collector = new TraceCollector();
|
|
126
|
+
collector.addLine(
|
|
127
|
+
JSON.stringify({
|
|
128
|
+
type: "result",
|
|
129
|
+
subtype: "success",
|
|
130
|
+
is_error: false,
|
|
131
|
+
total_cost_usd: 1.23,
|
|
132
|
+
duration_ms: 45000,
|
|
133
|
+
num_turns: 12,
|
|
134
|
+
usage: {
|
|
135
|
+
input_tokens: 5000,
|
|
136
|
+
output_tokens: 2000,
|
|
137
|
+
cache_read_input_tokens: 3000,
|
|
138
|
+
cache_creation_input_tokens: 1000,
|
|
139
|
+
},
|
|
140
|
+
modelUsage: { "claude-opus-4-6": { costUSD: 1.23 } },
|
|
141
|
+
}),
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
const trace = collector.toJSON();
|
|
145
|
+
assert.strictEqual(trace.summary.result, "success");
|
|
146
|
+
assert.strictEqual(trace.summary.totalCostUsd, 1.23);
|
|
147
|
+
assert.strictEqual(trace.summary.durationMs, 45000);
|
|
148
|
+
assert.strictEqual(trace.summary.numTurns, 12);
|
|
149
|
+
assert.strictEqual(trace.summary.tokenUsage.inputTokens, 5000);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("skips rate_limit_event and unknown types", () => {
|
|
153
|
+
const collector = new TraceCollector();
|
|
154
|
+
collector.addLine(
|
|
155
|
+
JSON.stringify({ type: "rate_limit_event", rate_limit_info: {} }),
|
|
156
|
+
);
|
|
157
|
+
collector.addLine(JSON.stringify({ type: "unknown_event" }));
|
|
158
|
+
|
|
159
|
+
const trace = collector.toJSON();
|
|
160
|
+
assert.strictEqual(trace.turns.length, 0);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test("skips malformed JSON lines", () => {
|
|
164
|
+
const collector = new TraceCollector();
|
|
165
|
+
collector.addLine("not valid json {{{");
|
|
166
|
+
collector.addLine("");
|
|
167
|
+
collector.addLine(" ");
|
|
168
|
+
|
|
169
|
+
const trace = collector.toJSON();
|
|
170
|
+
assert.strictEqual(trace.turns.length, 0);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("skips assistant event with missing message", () => {
|
|
174
|
+
const collector = new TraceCollector();
|
|
175
|
+
collector.addLine(JSON.stringify({ type: "assistant" }));
|
|
176
|
+
collector.addLine(JSON.stringify({ type: "assistant", message: null }));
|
|
177
|
+
|
|
178
|
+
assert.strictEqual(collector.toJSON().turns.length, 0);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test("skips user event with non-array content", () => {
|
|
182
|
+
const collector = new TraceCollector();
|
|
183
|
+
collector.addLine(
|
|
184
|
+
JSON.stringify({
|
|
185
|
+
type: "user",
|
|
186
|
+
message: { role: "user", content: "plain string" },
|
|
187
|
+
}),
|
|
188
|
+
);
|
|
189
|
+
collector.addLine(
|
|
190
|
+
JSON.stringify({ type: "user", message: { role: "user" } }),
|
|
191
|
+
);
|
|
192
|
+
collector.addLine(JSON.stringify({ type: "user" }));
|
|
193
|
+
|
|
194
|
+
assert.strictEqual(collector.toJSON().turns.length, 0);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test("uses event timestamp when present in system init", () => {
|
|
198
|
+
const collector = new TraceCollector();
|
|
199
|
+
collector.addLine(
|
|
200
|
+
JSON.stringify({
|
|
201
|
+
type: "system",
|
|
202
|
+
subtype: "init",
|
|
203
|
+
timestamp: "2026-01-15T10:00:00Z",
|
|
204
|
+
session_id: "sess-ts",
|
|
205
|
+
}),
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
assert.strictEqual(
|
|
209
|
+
collector.toJSON().metadata.timestamp,
|
|
210
|
+
"2026-01-15T10:00:00Z",
|
|
211
|
+
);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
describe("toJSON", () => {
|
|
216
|
+
test("produces complete trace from fixture", () => {
|
|
217
|
+
const collector = collectFixture();
|
|
218
|
+
const trace = collector.toJSON();
|
|
219
|
+
|
|
220
|
+
assert.strictEqual(trace.version, "1.0.0");
|
|
221
|
+
assert.strictEqual(trace.metadata.sessionId, "abc-123");
|
|
222
|
+
assert.strictEqual(trace.metadata.model, "claude-opus-4-6");
|
|
223
|
+
assert.strictEqual(trace.metadata.claudeCodeVersion, "2.1.87");
|
|
224
|
+
assert.strictEqual(trace.metadata.tools.length, 6);
|
|
225
|
+
assert.ok(trace.turns.length > 0);
|
|
226
|
+
assert.strictEqual(trace.summary.result, "success");
|
|
227
|
+
assert.strictEqual(trace.summary.totalCostUsd, 0.0523);
|
|
228
|
+
assert.strictEqual(trace.summary.numTurns, 3);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
test("assigns sequential turn indexes", () => {
|
|
232
|
+
const collector = collectFixture();
|
|
233
|
+
const trace = collector.toJSON();
|
|
234
|
+
|
|
235
|
+
trace.turns.forEach((turn, i) => {
|
|
236
|
+
assert.strictEqual(turn.index, i);
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
test("returns defaults for empty input", () => {
|
|
241
|
+
const collector = new TraceCollector();
|
|
242
|
+
const trace = collector.toJSON();
|
|
243
|
+
|
|
244
|
+
assert.strictEqual(trace.version, "1.0.0");
|
|
245
|
+
assert.strictEqual(trace.metadata.sessionId, null);
|
|
246
|
+
assert.strictEqual(trace.turns.length, 0);
|
|
247
|
+
assert.strictEqual(trace.summary.result, "unknown");
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe("toText", () => {
|
|
252
|
+
test("includes assistant text content", () => {
|
|
253
|
+
const collector = collectFixture();
|
|
254
|
+
const text = collector.toText();
|
|
255
|
+
|
|
256
|
+
assert.ok(
|
|
257
|
+
text.includes("I'll start by checking the repository structure"),
|
|
258
|
+
);
|
|
259
|
+
assert.ok(text.includes("No security issues found"));
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
test("includes tool call summaries", () => {
|
|
263
|
+
const collector = collectFixture();
|
|
264
|
+
const text = collector.toText();
|
|
265
|
+
|
|
266
|
+
assert.ok(text.includes("> Tool: Bash"));
|
|
267
|
+
assert.ok(text.includes("ls -la"));
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
test("includes result summary line", () => {
|
|
271
|
+
const collector = collectFixture();
|
|
272
|
+
const text = collector.toText();
|
|
273
|
+
|
|
274
|
+
assert.ok(text.includes("--- Result: success"));
|
|
275
|
+
assert.ok(text.includes("Turns: 3"));
|
|
276
|
+
assert.ok(text.includes("Cost: $0.0523"));
|
|
277
|
+
assert.ok(text.includes("Duration: 5s"));
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
test("truncates long tool input summaries", () => {
|
|
281
|
+
const collector = new TraceCollector();
|
|
282
|
+
const longCommand = "x".repeat(300);
|
|
283
|
+
collector.addLine(
|
|
284
|
+
JSON.stringify({
|
|
285
|
+
type: "assistant",
|
|
286
|
+
message: {
|
|
287
|
+
content: [
|
|
288
|
+
{
|
|
289
|
+
type: "tool_use",
|
|
290
|
+
name: "Bash",
|
|
291
|
+
input: { command: longCommand },
|
|
292
|
+
},
|
|
293
|
+
],
|
|
294
|
+
},
|
|
295
|
+
}),
|
|
296
|
+
);
|
|
297
|
+
|
|
298
|
+
const text = collector.toText();
|
|
299
|
+
assert.ok(text.includes("> Tool: Bash"));
|
|
300
|
+
assert.ok(text.includes("..."));
|
|
301
|
+
// Total line should be truncated, not the full 300+ chars
|
|
302
|
+
const toolLine = text.split("\n").find((l) => l.startsWith("> Tool:"));
|
|
303
|
+
assert.ok(toolLine.length < 250);
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test("returns empty string for empty input", () => {
|
|
307
|
+
const collector = new TraceCollector();
|
|
308
|
+
const text = collector.toText();
|
|
309
|
+
|
|
310
|
+
assert.strictEqual(text, "");
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
describe("createTraceCollector", () => {
|
|
315
|
+
test("returns a TraceCollector instance", () => {
|
|
316
|
+
const collector = createTraceCollector();
|
|
317
|
+
assert.ok(collector instanceof TraceCollector);
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
test("accepts injectable clock for deterministic timestamps", () => {
|
|
321
|
+
const fixedTime = "2026-01-01T00:00:00Z";
|
|
322
|
+
const collector = createTraceCollector({ now: () => fixedTime });
|
|
323
|
+
const trace = collector.toJSON();
|
|
324
|
+
|
|
325
|
+
assert.strictEqual(trace.metadata.timestamp, fixedTime);
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
});
|