@forwardimpact/libeval 0.1.62 → 0.1.64

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 CHANGED
@@ -1,201 +1,21 @@
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Zachary Rice
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/bin/fit-trace.js CHANGED
@@ -9,6 +9,7 @@ import { createLogger } from "@forwardimpact/libtelemetry";
9
9
 
10
10
  import {
11
11
  runRunsCommand,
12
+ runFindCommand,
12
13
  runDownloadCommand,
13
14
  runOverviewCommand,
14
15
  runCountCommand,
@@ -22,6 +23,7 @@ import {
22
23
  runReasoningCommand,
23
24
  runTimelineCommand,
24
25
  runStatsCommand,
26
+ runCostCommand,
25
27
  runInitCommand,
26
28
  runTurnCommand,
27
29
  runFilterCommand,
@@ -47,6 +49,30 @@ const definition = {
47
49
  type: "string",
48
50
  description: "How far back to search (default: 7d)",
49
51
  },
52
+ participant: {
53
+ type: "string",
54
+ description:
55
+ "Filter to runs carrying this participant's trace lane; in-progress candidates are labeled, not dropped",
56
+ },
57
+ repo: {
58
+ type: "string",
59
+ description:
60
+ "GitHub repo override (default: $GITHUB_REPOSITORY or 'origin' git remote)",
61
+ },
62
+ },
63
+ },
64
+ {
65
+ name: "find",
66
+ args: ["run-id", "participant"],
67
+ argsUsage: "<run-id> <participant>",
68
+ handler: runFindCommand,
69
+ description:
70
+ "Resolve a participant's lane trace for a known run id in one keyed lookup (no run enumeration, no content inspection)",
71
+ options: {
72
+ dir: {
73
+ type: "string",
74
+ description: "Output directory for a downloaded dispatch artifact",
75
+ },
50
76
  repo: {
51
77
  type: "string",
52
78
  description:
@@ -173,6 +199,21 @@ const definition = {
173
199
  handler: runStatsCommand,
174
200
  description: "Token usage and cost breakdown",
175
201
  },
202
+ {
203
+ name: "cost",
204
+ args: ["file"],
205
+ argsUsage: "<file>",
206
+ handler: runCostCommand,
207
+ description:
208
+ "Total run cost across every participant (agent, supervisor, judge, named profiles), with a per-source breakdown",
209
+ options: {
210
+ markdown: {
211
+ type: "boolean",
212
+ description:
213
+ "Emit a GitHub-flavored markdown block (redirect into $GITHUB_STEP_SUMMARY)",
214
+ },
215
+ },
216
+ },
176
217
  {
177
218
  name: "init",
178
219
  args: ["file"],
@@ -294,11 +335,15 @@ const definition = {
294
335
  },
295
336
  examples: [
296
337
  "fit-trace runs --lookback 7d",
338
+ "fit-trace runs --participant release-engineer",
339
+ "fit-trace find 27401632821 release-engineer",
297
340
  "fit-trace download 24497273755",
298
341
  "fit-trace split structured.json --mode=facilitate",
299
342
  "fit-trace overview structured.json",
300
343
  "fit-trace timeline structured.json",
301
344
  "fit-trace stats structured.json",
345
+ "fit-trace cost trace.ndjson",
346
+ "fit-trace cost trace.ndjson --markdown",
302
347
  "fit-trace tool structured.json Conclude",
303
348
  "fit-trace search structured.json 'error|fail' --context 1",
304
349
  "fit-trace filter structured.json --tool Bash --error",
@@ -336,7 +381,7 @@ const logger = createLogger("trace", runtime);
336
381
 
337
382
  // Commands that talk to the GitHub API need a config-backed token resolver;
338
383
  // the rest only read local trace files through the runtime.
339
- const NEEDS_CONFIG = new Set(["runs", "download"]);
384
+ const NEEDS_CONFIG = new Set(["runs", "find", "download"]);
340
385
 
341
386
  async function main() {
342
387
  const cli = createCli(definition, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forwardimpact/libeval",
3
- "version": "0.1.62",
3
+ "version": "0.1.64",
4
4
  "description": "Agent evaluation framework — prove whether agent changes improved outcomes with reproducible evidence.",
5
5
  "keywords": [
6
6
  "eval",
@@ -10,6 +10,32 @@ import { AGENT_MODEL } from "@forwardimpact/libutil/models";
10
10
 
11
11
  const DEFAULT_ALLOWED_TOOLS = ["Bash", "Read", "Glob", "Grep", "Write", "Edit"];
12
12
 
13
+ /**
14
+ * Did the session actually invoke the model? A genuine run always bills
15
+ * tokens (the system prompt alone is thousands of input tokens) and costs
16
+ * more than zero. A `result` message with `subtype: "success"` but zero
17
+ * token usage and zero cost means the model was never reached — the
18
+ * canonical signature of a Claude Code init/auth failure (e.g. an invalid
19
+ * `ANTHROPIC_API_KEY`), which the SDK otherwise reports as a clean success.
20
+ *
21
+ * If the SDK gave us neither a `usage` object nor `total_cost_usd`, don't
22
+ * second-guess the subtype — trust the reported success.
23
+ * @param {object|null} result - The SDK `result` message, or null.
24
+ * @returns {boolean}
25
+ */
26
+ function modelDidWork(result) {
27
+ if (!result) return false;
28
+ const { usage, total_cost_usd: cost } = result;
29
+ if (usage == null && cost == null) return true;
30
+ const tokens = usage
31
+ ? (usage.input_tokens ?? 0) +
32
+ (usage.output_tokens ?? 0) +
33
+ (usage.cache_creation_input_tokens ?? 0) +
34
+ (usage.cache_read_input_tokens ?? 0)
35
+ : 0;
36
+ return tokens > 0 || (cost ?? 0) > 0;
37
+ }
38
+
13
39
  // fit-eval and kata-action run headless in CI/CD with no human to answer
14
40
  // permission prompts. The SDK is always launched in bypass mode — not
15
41
  // overridable — so a future caller can't accidentally reduce permissions.
@@ -148,6 +174,7 @@ export class AgentRunner {
148
174
  async #consumeQuery(iterator) {
149
175
  let text = "";
150
176
  let stopReason = null;
177
+ let resultMessage = null;
151
178
  let error = null;
152
179
  let aborted = false;
153
180
 
@@ -157,6 +184,7 @@ export class AgentRunner {
157
184
  if (message.type === "result") {
158
185
  text = message.result ?? "";
159
186
  stopReason = message.subtype;
187
+ resultMessage = message;
160
188
  }
161
189
  }
162
190
  } catch (err) {
@@ -167,8 +195,23 @@ export class AgentRunner {
167
195
  }
168
196
  }
169
197
 
198
+ // A "success" subtype is necessary but not sufficient: the SDK reports a
199
+ // failed init (e.g. an invalid API key) as success with zero model work.
200
+ // Require evidence the model actually ran, and surface a clear error when
201
+ // it didn't, so the masked failure can't be reported as a green run.
202
+ const reportedSuccess = stopReason === "success";
203
+ const success =
204
+ reportedSuccess &&
205
+ resultMessage?.is_error !== true &&
206
+ modelDidWork(resultMessage);
207
+ if (reportedSuccess && !success && !error) {
208
+ error = new Error(
209
+ "agent reported success but performed no model work (zero token usage) — likely a Claude Code init or authentication failure",
210
+ );
211
+ }
212
+
170
213
  return {
171
- success: stopReason === "success",
214
+ success,
172
215
  text,
173
216
  sessionId: this.sessionId,
174
217
  error,
@@ -23,11 +23,13 @@
23
23
 
24
24
  import { createJudge } from "../judge.js";
25
25
  import { createRedactor } from "../redaction.js";
26
+ import { sumTraceCost } from "../cost.js";
26
27
 
27
28
  /**
28
29
  * @typedef {object} JudgeVerdict
29
30
  * @property {"pass" | "fail"} verdict
30
31
  * @property {string} summary
32
+ * @property {number} costUsd - Cost of the judge's own SDK session.
31
33
  */
32
34
 
33
35
  /**
@@ -81,12 +83,25 @@ export async function runJudge(task, workdir, invariants, deps, context) {
81
83
  await new Promise((r) => output.end(r));
82
84
  }
83
85
 
86
+ // The judge is its own SDK session; its spend lands in the judge trace we
87
+ // just wrote, not in the supervisor's combined trace. Read it back so the
88
+ // benchmark record's cost includes the judge.
89
+ const judgeTrace = await fs
90
+ .readFile(workdir.judgeTracePath, "utf8")
91
+ .catch(() => "");
92
+ const { totalCostUsd } = sumTraceCost(judgeTrace.split("\n"));
93
+
84
94
  if (outcome.verdict === null) {
85
- return { verdict: "fail", summary: "judge did not conclude" };
95
+ return {
96
+ verdict: "fail",
97
+ summary: "judge did not conclude",
98
+ costUsd: totalCostUsd,
99
+ };
86
100
  }
87
101
  return {
88
102
  verdict: outcome.verdict === "success" ? "pass" : "fail",
89
103
  summary: outcome.summary ?? "",
104
+ costUsd: totalCostUsd,
90
105
  };
91
106
  }
92
107
 
@@ -27,6 +27,17 @@ const JUDGE_VERDICT_SHAPE = z.object({
27
27
  summary: z.string(),
28
28
  });
29
29
 
30
+ /**
31
+ * Per-participant cost attribution. `costUsd` is the sum of these; the
32
+ * breakdown lets reports show where the spend went. The judge runs as its
33
+ * own SDK session, so its cost is tracked separately from agent/supervisor.
34
+ */
35
+ const COST_BREAKDOWN_SHAPE = z.object({
36
+ agent: z.number(),
37
+ supervisor: z.number(),
38
+ judge: z.number(),
39
+ });
40
+
30
41
  const PROFILES_SHAPE = z.object({
31
42
  agent: z.union([z.string(), z.null()]),
32
43
  supervisor: z.union([z.string(), z.null()]),
@@ -44,6 +55,7 @@ const COMMON_FIELDS = {
44
55
  runIndex: z.number().int().min(0),
45
56
  verdict: VERDICT_ENUM,
46
57
  costUsd: z.number(),
58
+ costBreakdown: COST_BREAKDOWN_SHAPE.optional(),
47
59
  turns: z.number().int().min(0),
48
60
  profiles: PROFILES_SHAPE,
49
61
  model: z.object({
@@ -18,6 +18,7 @@ import { createInterface } from "node:readline";
18
18
  import { join, resolve as resolvePath } from "node:path";
19
19
 
20
20
  import { DEFAULT_ENV_ALLOWLIST, createRedactor } from "../redaction.js";
21
+ import { sumTraceCost } from "../cost.js";
21
22
  import { createSupervisor } from "../supervisor.js";
22
23
  import { installApm as defaultInstallApm } from "./apm-installer.js";
23
24
  import { installNpm as defaultInstallNpm } from "./npm-installer.js";
@@ -193,8 +194,9 @@ export class BenchmarkRunner {
193
194
  resultsRecordKey(task, runIndex),
194
195
  );
195
196
  }
196
- const { costUsd, turns, submission, agentError } =
197
- await this.#runAgentSafe(task, workdir);
197
+ const agentRun = await this.#runAgentSafe(task, workdir);
198
+ const { costUsd, turns, submission, agentError } = agentRun;
199
+ const breakdown = agentRun.costBreakdown ?? { agent: 0, supervisor: 0 };
198
200
  const invariants = await this._runInvariantsHook(
199
201
  task,
200
202
  {
@@ -206,13 +208,14 @@ export class BenchmarkRunner {
206
208
  this.runtime,
207
209
  );
208
210
  let judgeVerdict = null;
211
+ let judgeCost = 0;
209
212
  if (task.paths.judge) {
210
213
  const judgeContext = await this.#buildJudgeContext(
211
214
  task,
212
215
  workdir,
213
216
  skillSetHash,
214
217
  );
215
- judgeVerdict = await this._runJudgeHook(
218
+ const judgeResult = await this._runJudgeHook(
216
219
  task,
217
220
  workdir,
218
221
  invariants,
@@ -225,6 +228,13 @@ export class BenchmarkRunner {
225
228
  },
226
229
  judgeContext,
227
230
  );
231
+ judgeCost = judgeResult.costUsd ?? 0;
232
+ // The record's judgeVerdict carries only the verdict + summary; the
233
+ // judge's cost is folded into costUsd / costBreakdown instead.
234
+ judgeVerdict = {
235
+ verdict: judgeResult.verdict,
236
+ summary: judgeResult.summary,
237
+ };
228
238
  }
229
239
  const verdict =
230
240
  invariants.verdict === "pass" &&
@@ -238,7 +248,12 @@ export class BenchmarkRunner {
238
248
  invariants,
239
249
  submission,
240
250
  ...(judgeVerdict && { judgeVerdict }),
241
- costUsd,
251
+ costUsd: costUsd + judgeCost,
252
+ costBreakdown: {
253
+ agent: breakdown.agent ?? 0,
254
+ supervisor: breakdown.supervisor ?? 0,
255
+ judge: judgeCost,
256
+ },
242
257
  turns,
243
258
  agentTracePath: workdir.agentTracePath,
244
259
  supervisorTracePath: workdir.supervisorTracePath,
@@ -280,6 +295,7 @@ export class BenchmarkRunner {
280
295
  } catch (e) {
281
296
  return {
282
297
  costUsd: 0,
298
+ costBreakdown: { agent: 0, supervisor: 0 },
283
299
  turns: 0,
284
300
  submission: "",
285
301
  agentError: { message: e.message ?? String(e), aborted: false },
@@ -334,8 +350,20 @@ export class BenchmarkRunner {
334
350
  workdir.agentTracePath,
335
351
  workdir.supervisorTracePath,
336
352
  );
353
+ // Cost is summed across every participant's result events from the one
354
+ // combined trace, attributed per source. Read before unlinking.
355
+ const combined = await fs.readFile(combinedPath, "utf8");
356
+ const { totalCostUsd, bySource } = sumTraceCost(combined.split("\n"));
337
357
  await fs.unlink(combinedPath).catch(() => {});
338
- return { ...summary, agentError };
358
+ return {
359
+ ...summary,
360
+ costUsd: totalCostUsd,
361
+ costBreakdown: {
362
+ agent: bySource.agent ?? 0,
363
+ supervisor: bySource.supervisor ?? 0,
364
+ },
365
+ agentError,
366
+ };
339
367
  }
340
368
 
341
369
  async #buildJudgeContext(task, workdir, skillSetHash) {
@@ -441,10 +469,13 @@ async function writeRecord(stream, record) {
441
469
  }
442
470
 
443
471
  /**
444
- * Split the combined supervisor trace into agent and supervisor files, and
445
- * extract cost, turn count, and submission in a single pass. Agent-source
446
- * events go to `agentPath`; supervisor and orchestrator events go to
447
- * `supervisorPath`.
472
+ * Split the combined supervisor trace into agent and supervisor files and
473
+ * extract turn count and submission in a single pass. Agent-source events go
474
+ * to `agentPath`; supervisor and orchestrator events go to `supervisorPath`.
475
+ *
476
+ * Cost is deliberately not summed here — the caller derives it from the same
477
+ * combined trace via `sumTraceCost`, so there is one cost path across the
478
+ * benchmark, callback, and `fit-trace cost` consumers.
448
479
  */
449
480
  // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stream-splitting state machine
450
481
  async function splitAndSummarize(
@@ -460,8 +491,6 @@ async function splitAndSummarize(
460
491
  input: fs.createReadStream(combinedPath),
461
492
  crlfDelay: Infinity,
462
493
  });
463
- let agentCost = 0;
464
- let supervisorCost = 0;
465
494
  let turns = 0;
466
495
  let submission = "";
467
496
  for await (const line of rl) {
@@ -476,19 +505,9 @@ async function splitAndSummarize(
476
505
  target.write(line + "\n");
477
506
  const inner = event.event;
478
507
  if (!inner) continue;
479
- if (event.source === "agent") {
480
- if (inner.type === "result" && typeof inner.total_cost_usd === "number") {
481
- agentCost = inner.total_cost_usd;
482
- }
483
- if (inner.type === "assistant") {
484
- const text = extractText(inner);
485
- if (text) submission = text;
486
- }
487
- }
488
- if (event.source === "supervisor") {
489
- if (inner.type === "result" && typeof inner.total_cost_usd === "number") {
490
- supervisorCost = inner.total_cost_usd;
491
- }
508
+ if (event.source === "agent" && inner.type === "assistant") {
509
+ const text = extractText(inner);
510
+ if (text) submission = text;
492
511
  }
493
512
  if (event.source === "orchestrator" && inner.type === "summary") {
494
513
  turns = inner.turns ?? 0;
@@ -498,7 +517,7 @@ async function splitAndSummarize(
498
517
  new Promise((r) => agentStream.end(r)),
499
518
  new Promise((r) => supStream.end(r)),
500
519
  ]);
501
- return { costUsd: agentCost + supervisorCost, turns, submission };
520
+ return { turns, submission };
502
521
  }
503
522
 
504
523
  function extractText(inner) {
@@ -1,3 +1,5 @@
1
+ import { sumTraceCost } from "../cost.js";
2
+
1
3
  /**
2
4
  * Scan an NDJSON trace and return the last orchestrator summary event,
3
5
  * the first `meta` event's `discussion_id`, and any structured replies
@@ -8,15 +10,14 @@
8
10
  * "adjourned"/"recessed"/"failed" from discuss). The bridge layer maps to
9
11
  * its channel semantics.
10
12
  *
11
- * @param {string} traceFile
12
- * @param {object} fsSync - Sync filesystem surface (`runtime.fsSync`).
13
+ * @param {string} content - Raw NDJSON trace content.
13
14
  * @returns {{verdict: string, summary: string, replies: object[], trigger?: object, discussionId?: string} | null}
14
15
  */
15
16
  // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: NDJSON scan with malformed-line tolerance + meta/summary dual extraction
16
- function readTraceSummary(traceFile, fsSync) {
17
+ function readTraceSummary(content) {
17
18
  let summary = null;
18
19
  let metaDiscussionId = null;
19
- for (const line of fsSync.readFileSync(traceFile, "utf8").split("\n")) {
20
+ for (const line of content.split("\n")) {
20
21
  if (!line.trim()) continue;
21
22
  let record;
22
23
  try {
@@ -83,11 +84,15 @@ export async function runCallbackCommand(ctx) {
83
84
  if (!callbackUrl)
84
85
  return { ok: false, code: 1, error: "--callback-url is required" };
85
86
 
86
- const found = readTraceSummary(traceFile, runtime.fsSync) ?? {
87
+ const content = runtime.fsSync.readFileSync(traceFile, "utf8");
88
+ const found = readTraceSummary(content) ?? {
87
89
  verdict: "failed",
88
90
  summary: "Run ended without producing a summary.",
89
91
  replies: [],
90
92
  };
93
+ // Total spend across every participant in the trace — the bridge surfaces
94
+ // it alongside the verdict so a dispatched run reports what it cost.
95
+ const { totalCostUsd } = sumTraceCost(content.split("\n"));
91
96
 
92
97
  const discussionId = found.discussionId ?? discussionIdOverride ?? null;
93
98
  const payload = {
@@ -96,6 +101,7 @@ export async function runCallbackCommand(ctx) {
96
101
  verdict: found.verdict,
97
102
  summary: found.summary,
98
103
  run_url: runUrl,
104
+ cost_usd: totalCostUsd,
99
105
  replies: found.replies,
100
106
  last_acted_seq: found.lastActedSeq ?? -1,
101
107
  ...(discussionId && { discussion_id: discussionId }),