@tangle-network/agent-eval 2.0.10 → 2.0.12

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.
Files changed (157) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-_JzxgLDM.d.ts → agent-profile-C0FBdYa6.d.ts} +3 -3
  4. package/dist/{agent-profile-_JzxgLDM.d.ts.map → agent-profile-C0FBdYa6.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +292 -74
  6. package/dist/analyst/index.d.ts.map +1 -1
  7. package/dist/analyst/index.js +11 -161
  8. package/dist/analyst/index.js.map +1 -1
  9. package/dist/app-grade/index.d.ts +2 -2
  10. package/dist/app-grade/index.js +3 -3
  11. package/dist/{benchmark-command-CGQXNFj7.js → benchmark-command-Be5O6A2v.js} +797 -13
  12. package/dist/benchmark-command-Be5O6A2v.js.map +1 -0
  13. package/dist/benchmarks/index.d.ts +5 -5
  14. package/dist/benchmarks/index.d.ts.map +1 -1
  15. package/dist/benchmarks/index.js +19 -10
  16. package/dist/benchmarks/index.js.map +1 -1
  17. package/dist/campaign/index.d.ts +5 -5
  18. package/dist/campaign/index.js +10 -10
  19. package/dist/{campaign-eus7YRs2.js → campaign-CE08mvQO.js} +11 -11
  20. package/dist/{campaign-eus7YRs2.js.map → campaign-CE08mvQO.js.map} +1 -1
  21. package/dist/{campaign-evidence-KM5GTsHG.js → campaign-evidence-71uzJMVY.js} +2 -2
  22. package/dist/{campaign-evidence-KM5GTsHG.js.map → campaign-evidence-71uzJMVY.js.map} +1 -1
  23. package/dist/{campaign-evidence-BOcX4w0r.d.ts → campaign-evidence-DRvr7lZU.d.ts} +2 -2
  24. package/dist/{campaign-evidence-BOcX4w0r.d.ts.map → campaign-evidence-DRvr7lZU.d.ts.map} +1 -1
  25. package/dist/{chat-client-Oyot5tyo.js → chat-client-TkNgQDLj.js} +2 -2
  26. package/dist/{chat-client-Oyot5tyo.js.map → chat-client-TkNgQDLj.js.map} +1 -1
  27. package/dist/{chat-json-call-DTmv2uNY.js → chat-json-call-gu3deRID.js} +2 -2
  28. package/dist/{chat-json-call-DTmv2uNY.js.map → chat-json-call-gu3deRID.js.map} +1 -1
  29. package/dist/cli.js +778 -10
  30. package/dist/cli.js.map +1 -1
  31. package/dist/code-agent-jsonl-aPWZG3vr.js +104 -0
  32. package/dist/code-agent-jsonl-aPWZG3vr.js.map +1 -0
  33. package/dist/{completion-verifier-CCPG2Yc0.js → completion-verifier-BvPqg9Gp.js} +4 -4
  34. package/dist/{completion-verifier-CCPG2Yc0.js.map → completion-verifier-BvPqg9Gp.js.map} +1 -1
  35. package/dist/contract/index.d.ts +8 -8
  36. package/dist/contract/index.js +16 -112
  37. package/dist/contract/index.js.map +1 -1
  38. package/dist/{cost-ledger-C5CCidPm.js → cost-ledger-ni6f77QJ.js} +106 -50
  39. package/dist/cost-ledger-ni6f77QJ.js.map +1 -0
  40. package/dist/{decision-point-CfqtnGop.js → decision-point-CjC56Enj.js} +2 -2
  41. package/dist/{decision-point-CfqtnGop.js.map → decision-point-CjC56Enj.js.map} +1 -1
  42. package/dist/{default-registry-Rs5uzlfJ.js → default-registry-C5iSuS8e.js} +5 -5
  43. package/dist/{default-registry-Rs5uzlfJ.js.map → default-registry-C5iSuS8e.js.map} +1 -1
  44. package/dist/{default-registry-X8McMoUV.d.ts → default-registry-DFRlBniE.d.ts} +2 -2
  45. package/dist/{default-registry-X8McMoUV.d.ts.map → default-registry-DFRlBniE.d.ts.map} +1 -1
  46. package/dist/{define-agent-eval-D8ntOXqV.js → define-agent-eval-BHn6t-DC.js} +4 -4
  47. package/dist/{define-agent-eval-D8ntOXqV.js.map → define-agent-eval-BHn6t-DC.js.map} +1 -1
  48. package/dist/{define-agent-eval-DH5-xi-F.d.ts → define-agent-eval-n63vmQMR.d.ts} +4 -4
  49. package/dist/{define-agent-eval-DH5-xi-F.d.ts.map → define-agent-eval-n63vmQMR.d.ts.map} +1 -1
  50. package/dist/{dspy-rlm-engine-ChE1PUM5.js → dspy-rlm-engine-CR5MSL2k.js} +6 -5
  51. package/dist/{dspy-rlm-engine-ChE1PUM5.js.map → dspy-rlm-engine-CR5MSL2k.js.map} +1 -1
  52. package/dist/{evaluation-BAisv8ZR.js → evaluation-DqfNMaKr.js} +2 -2
  53. package/dist/{evaluation-BAisv8ZR.js.map → evaluation-DqfNMaKr.js.map} +1 -1
  54. package/dist/{evaluation-CjZH6gW0.d.ts → evaluation-VbjqORBn.d.ts} +2 -2
  55. package/dist/{evaluation-CjZH6gW0.d.ts.map → evaluation-VbjqORBn.d.ts.map} +1 -1
  56. package/dist/evaluation.d.ts +1 -1
  57. package/dist/evaluation.js +1 -1
  58. package/dist/experiment/index.d.ts +1 -1
  59. package/dist/experiment/index.js +1 -1
  60. package/dist/{external-optimizer-contracts-BFV8lnhl.js → external-optimizer-contracts-vrye9kti.js} +2 -2
  61. package/dist/{external-optimizer-contracts-BFV8lnhl.js.map → external-optimizer-contracts-vrye9kti.js.map} +1 -1
  62. package/dist/{external-optimizer-process-B6emPodQ.js → external-optimizer-process-DkOMkeHW.js} +3 -3
  63. package/dist/{external-optimizer-process-B6emPodQ.js.map → external-optimizer-process-DkOMkeHW.js.map} +1 -1
  64. package/dist/{external-optimizer-subprocess-_O06eDVA.js → external-optimizer-subprocess-CFIiwHSE.js} +3 -3
  65. package/dist/{external-optimizer-subprocess-_O06eDVA.js.map → external-optimizer-subprocess-CFIiwHSE.js.map} +1 -1
  66. package/dist/{finding-scope-B_As3F_v.js → finding-scope-BVQVcjz7.js} +2 -2
  67. package/dist/{finding-scope-B_As3F_v.js.map → finding-scope-BVQVcjz7.js.map} +1 -1
  68. package/dist/{findings-store-CvYUzQBR.js → findings-store-Drnjid7m.js} +5 -5
  69. package/dist/{findings-store-CvYUzQBR.js.map → findings-store-Drnjid7m.js.map} +1 -1
  70. package/dist/fuzz.js +1 -1
  71. package/dist/hosted/index.js +1 -1
  72. package/dist/{index-BmWw8zN6.d.ts → index-BEXEYURJ.d.ts} +7 -7
  73. package/dist/{index-BmWw8zN6.d.ts.map → index-BEXEYURJ.d.ts.map} +1 -1
  74. package/dist/{index-ZffK_5sD.d.ts → index-CbzPtg7O.d.ts} +205 -29
  75. package/dist/index-CbzPtg7O.d.ts.map +1 -0
  76. package/dist/{index-CCOaNmh2.d.ts → index-Dt3zWlRa.d.ts} +3 -3
  77. package/dist/{index-CCOaNmh2.d.ts.map → index-Dt3zWlRa.d.ts.map} +1 -1
  78. package/dist/{index-aRalB_Ma.d.ts → index-rrPT3Pw0.d.ts} +2 -2
  79. package/dist/{index-aRalB_Ma.d.ts.map → index-rrPT3Pw0.d.ts.map} +1 -1
  80. package/dist/index.d.ts +13 -13
  81. package/dist/index.js +471 -22
  82. package/dist/index.js.map +1 -1
  83. package/dist/{judge-gate-CpD3wmcf.js → judge-gate-WgYqQ9LA.js} +2 -2
  84. package/dist/{judge-gate-CpD3wmcf.js.map → judge-gate-WgYqQ9LA.js.map} +1 -1
  85. package/dist/{kind-factory-B-xCxG7p.js → kind-factory-C8MJpMTV.js} +2 -2
  86. package/dist/{kind-factory-B-xCxG7p.js.map → kind-factory-C8MJpMTV.js.map} +1 -1
  87. package/dist/{llm-client-Dk8lBnMh.js → llm-client-D4B1qR_1.js} +2 -2
  88. package/dist/{llm-client-Dk8lBnMh.js.map → llm-client-D4B1qR_1.js.map} +1 -1
  89. package/dist/{llm-judge-DYmEdo3M.js → llm-judge-CgF3ZM3R.js} +4 -4
  90. package/dist/{llm-judge-DYmEdo3M.js.map → llm-judge-CgF3ZM3R.js.map} +1 -1
  91. package/dist/{matrix-BDl7hoBr.d.ts → matrix-B95YsrV7.d.ts} +2 -2
  92. package/dist/{matrix-BDl7hoBr.d.ts.map → matrix-B95YsrV7.d.ts.map} +1 -1
  93. package/dist/meta-eval/index.js +2 -2
  94. package/dist/metrics-C6pXdupw.js +9 -0
  95. package/dist/metrics-C6pXdupw.js.map +1 -0
  96. package/dist/multishot/golden/index.d.ts +1 -1
  97. package/dist/multishot/index.d.ts +6 -6
  98. package/dist/multishot/index.js +8 -7
  99. package/dist/multishot/index.js.map +1 -1
  100. package/dist/openapi.json +1 -1
  101. package/dist/{optimization-method-4JlbMxd2.js → optimization-method-1xzXK-B6.js} +9 -9
  102. package/dist/{optimization-method-4JlbMxd2.js.map → optimization-method-1xzXK-B6.js.map} +1 -1
  103. package/dist/{proposal-findings-CfRFCFXS.js → proposal-findings-BCd4KjLy.js} +2 -2
  104. package/dist/{proposal-findings-CfRFCFXS.js.map → proposal-findings-BCd4KjLy.js.map} +1 -1
  105. package/dist/rl.d.ts +1 -1
  106. package/dist/rollout/index.d.ts +2 -2
  107. package/dist/rollout/index.js +1 -1
  108. package/dist/{rollout--rSr43Pd.js → rollout-CbHMVoDr.js} +2 -2
  109. package/dist/{rollout--rSr43Pd.js.map → rollout-CbHMVoDr.js.map} +1 -1
  110. package/dist/{run-improvement-loop-BeHu5D9Z.d.ts → run-improvement-loop-BPhkYKV2.d.ts} +5 -5
  111. package/dist/{run-improvement-loop-BeHu5D9Z.d.ts.map → run-improvement-loop-BPhkYKV2.d.ts.map} +1 -1
  112. package/dist/search/index.d.ts +2 -2
  113. package/dist/search/index.js +2 -2
  114. package/dist/{search-kernel-mZc79S6N.js → search-kernel-BkkDo75N.js} +2 -2
  115. package/dist/{search-kernel-mZc79S6N.js.map → search-kernel-BkkDo75N.js.map} +1 -1
  116. package/dist/{search-kernel-CJZ-ZSV1.d.ts → search-kernel-CDSEWa2X.d.ts} +2 -2
  117. package/dist/{search-kernel-CJZ-ZSV1.d.ts.map → search-kernel-CDSEWa2X.d.ts.map} +1 -1
  118. package/dist/{search-ledger-C7t68cmy.js → search-ledger-sormHFLS.js} +17 -1
  119. package/dist/search-ledger-sormHFLS.js.map +1 -0
  120. package/dist/{search-shipper-CmDW9dU6.js → search-shipper-BJ2Bkx2q.js} +2 -2
  121. package/dist/{search-shipper-CmDW9dU6.js.map → search-shipper-BJ2Bkx2q.js.map} +1 -1
  122. package/dist/{search-summary-CCgP2qXz.js → search-summary-DMckFUNY.js} +2 -2
  123. package/dist/{search-summary-CCgP2qXz.js.map → search-summary-DMckFUNY.js.map} +1 -1
  124. package/dist/{self-improve-C_Bcdmv8.js → self-improve-CMrPmjYE.js} +5 -5
  125. package/dist/{self-improve-C_Bcdmv8.js.map → self-improve-CMrPmjYE.js.map} +1 -1
  126. package/dist/{self-improve-B1fsNejr.d.ts → self-improve-D0TtJz4e.d.ts} +5 -5
  127. package/dist/{self-improve-B1fsNejr.d.ts.map → self-improve-D0TtJz4e.d.ts.map} +1 -1
  128. package/dist/{server-aZFmRucn.js → server-B-7vXS9T.js} +4 -4
  129. package/dist/{server-aZFmRucn.js.map → server-B-7vXS9T.js.map} +1 -1
  130. package/dist/{skillopt-optimization-method-DHk1K757.js → skillopt-optimization-method-D-BPMi8J.js} +9 -9
  131. package/dist/{skillopt-optimization-method-DHk1K757.js.map → skillopt-optimization-method-D-BPMi8J.js.map} +1 -1
  132. package/dist/{store-otlp-CdeW7NWq.js → store-otlp-DL30pdXE.js} +2 -2
  133. package/dist/{store-otlp-CdeW7NWq.js.map → store-otlp-DL30pdXE.js.map} +1 -1
  134. package/dist/{store-tool-spans-CVX-jfkk.js → store-tool-spans-DRdpbrnb.js} +3 -3
  135. package/dist/{store-tool-spans-CVX-jfkk.js.map → store-tool-spans-DRdpbrnb.js.map} +1 -1
  136. package/dist/{systemone-4PadCE4C.d.ts → systemone-C26IFS-a.d.ts} +3 -3
  137. package/dist/{systemone-4PadCE4C.d.ts.map → systemone-C26IFS-a.d.ts.map} +1 -1
  138. package/dist/systemone.d.ts +2 -2
  139. package/dist/systemone.js +2 -2
  140. package/dist/traces.js +3 -3
  141. package/dist/{tree-CiIe-f3f.js → tree-BX9ykHi3.js} +3 -3
  142. package/dist/{tree-CiIe-f3f.js.map → tree-BX9ykHi3.js.map} +1 -1
  143. package/dist/{types-D5XtEH9Q.d.ts → types-CBT-XcX5.d.ts} +14 -1
  144. package/dist/types-CBT-XcX5.d.ts.map +1 -0
  145. package/dist/{types-an-CUndX.d.ts → types-CYPV2dlR.d.ts} +52 -5
  146. package/dist/types-CYPV2dlR.d.ts.map +1 -0
  147. package/dist/wire/index.js +1 -1
  148. package/docs/feature-guide.md +2 -0
  149. package/docs/public-api.md +23 -16
  150. package/docs/skill-eval.md +103 -0
  151. package/package.json +4 -2
  152. package/dist/benchmark-command-CGQXNFj7.js.map +0 -1
  153. package/dist/cost-ledger-C5CCidPm.js.map +0 -1
  154. package/dist/index-ZffK_5sD.d.ts.map +0 -1
  155. package/dist/search-ledger-C7t68cmy.js.map +0 -1
  156. package/dist/types-D5XtEH9Q.d.ts.map +0 -1
  157. package/dist/types-an-CUndX.d.ts.map +0 -1
@@ -1,21 +1,24 @@
1
1
  import { c as errorMessage, s as ValidationError, t as AgentEvalError } from "./errors-DeEEV9Vx.js";
2
2
  import { a as hashCanonical, i as compareCodeUnits, o as jsonDocument, r as canonicalString } from "./canonical-DKgL_Wby.js";
3
3
  import { _ as mean$1, m as summarizeNumberSeries, r as pairedBootstrap, v as meanOrNull } from "./paired-tests-CXcD_B80.js";
4
- import { a as CostLedgerPersistenceError, i as CostCeilingReachedError, m as resolveModelPricing, n as CostAccountingIncompleteError, o as CostReceiptCaptureError, r as CostCallConflictError, s as CostReservationExceededError, t as CostLedger } from "./cost-ledger-C5CCidPm.js";
4
+ import { n as sampleMedian } from "./statistics-AKnVFnK-.js";
5
+ import { a as CostLedgerPersistenceError, i as CostCeilingReachedError, l as costForTokenPricing, n as CostAccountingIncompleteError, o as CostReceiptCaptureError, p as resolveModelPricing, r as CostCallConflictError, s as CostReservationExceededError, t as CostLedger, u as costForUsage } from "./cost-ledger-ni6f77QJ.js";
5
6
  import { a as writeLedgerFileAtomically, i as withLedgerFileLock } from "./journal-file-AekB57Er.js";
6
7
  import "./ledger-core-auznoaD7.js";
7
- import { f as createRunCostLedger, p as fsCampaignStorage, t as AnalystFindingSchema } from "./finding-scope-B_As3F_v.js";
8
+ import { f as createRunCostLedger, p as fsCampaignStorage, t as AnalystFindingSchema } from "./finding-scope-BVQVcjz7.js";
8
9
  import { c as redactText } from "./redact-zp_ILC4l.js";
9
10
  import { i as makeFinding } from "./types-_tlhWGUq.js";
10
11
  import { a as LlmCallError, n as isRecord, o as LlmResponseError } from "./json-DtvZNAU9.js";
11
- import { f as resolveExternalOptimizerProcessLimits } from "./external-optimizer-contracts-BFV8lnhl.js";
12
+ import { f as resolveExternalOptimizerProcessLimits } from "./external-optimizer-contracts-vrye9kti.js";
12
13
  import { t as acquireSingleRunLock } from "./single-run-lock-BSKsoeQF.js";
13
- import { A as RawAnalystFindingSchema, K as usageReceiptFromCostLedger, W as assertValidAnalystUsageReceipt, j as evidenceRefsFromRawFinding, k as RAW_FINDING_SCHEMA_PROMPT, m as TRACE_ANALYSIS_LIMITS, n as runTraceAnalyst } from "./kind-factory-B-xCxG7p.js";
14
- import { n as callLlmJson } from "./llm-client-Dk8lBnMh.js";
15
- import { t as createDspyRlmTraceEngine } from "./dspy-rlm-engine-ChE1PUM5.js";
16
- import { i as startExternalOptimizerModelProxy, r as runWithCleanup } from "./external-optimizer-subprocess-_O06eDVA.js";
17
- import { i as otlpTextToTraceAnalysisStore, n as DEFAULT_MAX_TRACE_FILE_BYTES, t as BufferTraceStore } from "./store-otlp-CdeW7NWq.js";
18
- import "./external-optimizer-process-B6emPodQ.js";
14
+ import { A as RawAnalystFindingSchema, K as usageReceiptFromCostLedger, W as assertValidAnalystUsageReceipt, j as evidenceRefsFromRawFinding, k as RAW_FINDING_SCHEMA_PROMPT, m as TRACE_ANALYSIS_LIMITS, n as runTraceAnalyst } from "./kind-factory-C8MJpMTV.js";
15
+ import { n as callLlmJson } from "./llm-client-D4B1qR_1.js";
16
+ import { t as createDspyRlmTraceEngine } from "./dspy-rlm-engine-CR5MSL2k.js";
17
+ import { i as startExternalOptimizerModelProxy, r as runWithCleanup } from "./external-optimizer-subprocess-CFIiwHSE.js";
18
+ import "./metrics-C6pXdupw.js";
19
+ import { i as otlpTextToTraceAnalysisStore, n as DEFAULT_MAX_TRACE_FILE_BYTES, t as BufferTraceStore } from "./store-otlp-DL30pdXE.js";
20
+ import { a as record$1, n as parseCodeAgentJsonlFile, o as stringField } from "./code-agent-jsonl-aPWZG3vr.js";
21
+ import "./external-optimizer-process-DkOMkeHW.js";
19
22
  import { t as assertEqualDeclarativeTerms } from "./equal-terms-K11VHmR3.js";
20
23
  import { c as runPrimeExchange, l as decodeReplyRows, n as buildPrimePrompt, o as primeProtocolSha256, s as projectPrimeTrajectory, t as analystUsageReceiptFromPrimeUsage } from "./prime-protocol-CrhpXRz9.js";
21
24
  import { t as nodeHttpPrimeBridgeTransport } from "./prime-bridge-transport-Csd5SQg7.js";
@@ -23,13 +26,794 @@ import { createHash, randomUUID } from "node:crypto";
23
26
  import { z } from "zod";
24
27
  import { constants, existsSync, lstatSync, readFileSync } from "node:fs";
25
28
  import * as nodePath from "node:path";
26
- import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
29
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
27
30
  import { arch, platform } from "node:os";
28
31
  import { pathToFileURL } from "node:url";
29
32
  import { link, lstat, mkdir, open, readFile, readdir, realpath, stat, unlink } from "node:fs/promises";
33
+ import { readSessionInput } from "@tangle-network/harness-sessions";
30
34
  import { TextDecoder as TextDecoder$1 } from "node:util";
31
35
  import { performance } from "node:perf_hooks";
32
36
  import { linearSumAssignment } from "linear-sum-assignment";
37
+ // src/skill-usage/change-refs.ts
38
+ const SHELL_TOOLS = /* @__PURE__ */ new Set(["Bash"]);
39
+ /** `gh pr create`, or a wrapper named `gh-<identity>`, including its flags up to the subcommand. */
40
+ const PR_COMMAND = /\bgh(?:-[\w-]+)?\s+(?:-\S+\s+\S+\s+)*pr\s+(create|merge)\b/g;
41
+ const PULL_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/g;
42
+ const MERGE_ARGS = /\bpr\s+merge\s+(?:(?:https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/)?(\d+))/;
43
+ const REPO_FLAG = /(?:-R|--repo)[\s=]+([\w.-]+\/[\w.-]+)/;
44
+ function githubPullRequestRefs(call) {
45
+ if (!SHELL_TOOLS.has(call.name)) return [];
46
+ const command = record$1(call.input)?.command;
47
+ if (typeof command !== "string") return [];
48
+ const kinds = /* @__PURE__ */ new Set();
49
+ for (const match of command.matchAll(PR_COMMAND)) kinds.add(match[1]);
50
+ if (kinds.size === 0) return [];
51
+ const refs = /* @__PURE__ */ new Set();
52
+ if (call.result !== null && call.result.isError !== true) {
53
+ const text = call.result.text ?? "";
54
+ for (const match of text.matchAll(PULL_URL)) refs.add(`${match[1]}#${match[2]}`);
55
+ }
56
+ if (kinds.has("merge")) {
57
+ const merge = MERGE_ARGS.exec(command);
58
+ const repository = merge?.[1] ?? REPO_FLAG.exec(command)?.[1];
59
+ if (merge?.[2] !== void 0 && repository !== void 0) refs.add(`${repository}#${merge[2]}`);
60
+ }
61
+ return [...refs];
62
+ }
63
+ // src/skill-usage/skill-file.ts
64
+ /**
65
+ * A skill's version is the hash of the body an agent is given. A session
66
+ * record and the skill file both yield that body, so one invocation's version
67
+ * can be compared with the file as it is now.
68
+ */
69
+ const FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
70
+ /** The body an agent is given: the file without its frontmatter block, trimmed. */
71
+ function skillBody(text) {
72
+ return text.replace(FRONTMATTER, "").trim();
73
+ }
74
+ /** sha256 of {@link skillBody}, as lowercase hex. */
75
+ function skillBodySha256(text) {
76
+ return createHash("sha256").update(skillBody(text)).digest("hex");
77
+ }
78
+ /** Read one skill file. A missing or unreadable file is a typed failure, never an empty body. */
79
+ function readSkillFile(path) {
80
+ let bytes;
81
+ try {
82
+ bytes = readFileSync(path);
83
+ } catch (error) {
84
+ const code = error?.code;
85
+ return {
86
+ succeeded: false,
87
+ path,
88
+ error: typeof code === "string" ? code : errorMessage(error)
89
+ };
90
+ }
91
+ return {
92
+ succeeded: true,
93
+ path,
94
+ fileSha256: createHash("sha256").update(bytes).digest("hex"),
95
+ bodySha256: skillBodySha256(bytes.toString("utf8"))
96
+ };
97
+ }
98
+ // src/skill-usage/harness-session.ts
99
+ /** A response's usage as the cost ledger prices it; null unless input and output are both recorded. */
100
+ function costUsage(usage) {
101
+ if (usage === null || usage.input === null || usage.output === null) return null;
102
+ return {
103
+ inputTokens: usage.input,
104
+ outputTokens: usage.output,
105
+ ...usage.cacheRead === null ? {} : { cachedTokens: usage.cacheRead },
106
+ ...usage.cacheWrite === null ? {} : { cacheWriteTokens: usage.cacheWrite }
107
+ };
108
+ }
109
+ function invocation(fields, loaded) {
110
+ return {
111
+ kind: "skill",
112
+ ...fields,
113
+ version: loaded == null ? null : {
114
+ bodySha256: skillBodySha256(loaded.body),
115
+ source: "session"
116
+ },
117
+ skillFile: loaded?.skillFile ?? null
118
+ };
119
+ }
120
+ /**
121
+ * Project a normalized session into recorded order.
122
+ *
123
+ * Without markers the record carries tool and model calls and no invocations,
124
+ * which is the honest reading of a harness whose sessions do not mark them.
125
+ * Calls the session copied from a parent fork are left out: they are the
126
+ * parent's work. A call the session lists but no message places is appended
127
+ * after the placed ones and named in `gaps`.
128
+ */
129
+ function skillSessionFromHarnessSession(session, markers = {}) {
130
+ const toolCalls = new Map(session.toolCalls.map((call) => [call.id, call]));
131
+ const modelCalls = new Map(session.modelCalls.map((call) => [call.id, call]));
132
+ const placedModelCalls = /* @__PURE__ */ new Set();
133
+ const placedToolCalls = /* @__PURE__ */ new Set();
134
+ const events = [];
135
+ const changes = [];
136
+ const placeModelCall = (id) => {
137
+ const call = modelCalls.get(id);
138
+ if (call === void 0 || placedModelCalls.has(id)) return;
139
+ placedModelCalls.add(id);
140
+ if (call.error !== null || call.inherited === true) return;
141
+ events.push({
142
+ kind: "model",
143
+ id,
144
+ at: call.at,
145
+ model: call.servedModel,
146
+ usage: costUsage(call.usage)
147
+ });
148
+ };
149
+ const placeToolCall = (id) => {
150
+ const call = toolCalls.get(id);
151
+ if (call === void 0 || placedToolCalls.has(id)) return;
152
+ placedToolCalls.add(id);
153
+ if (call.inherited === true) return;
154
+ const failed = call.result === null ? null : call.result.isError;
155
+ for (const ref of markers.changesOfToolCall?.(call) ?? []) changes.push({
156
+ ref,
157
+ callId: id,
158
+ at: call.startedAt
159
+ });
160
+ const skill = markers.skillOfToolCall?.(call) ?? null;
161
+ if (skill === null) {
162
+ events.push({
163
+ kind: "tool",
164
+ id,
165
+ name: call.name,
166
+ at: call.startedAt,
167
+ failed
168
+ });
169
+ return;
170
+ }
171
+ events.push(invocation({
172
+ callId: id,
173
+ skill,
174
+ invoker: "agent",
175
+ at: call.startedAt,
176
+ failed
177
+ }, markers.loadedByCallId?.get(id)));
178
+ };
179
+ for (const message of session.messages) {
180
+ if (message.inherited === true) continue;
181
+ if (message.role === "assistant") {
182
+ if (message.modelCallId !== null) placeModelCall(message.modelCallId);
183
+ for (const part of message.parts) if (part.type === "tool-call") placeToolCall(part.toolCallId);
184
+ continue;
185
+ }
186
+ const marker = markers.invocationsByMessageId?.get(message.id);
187
+ if (marker !== void 0) events.push(invocation({
188
+ callId: message.id,
189
+ skill: marker.skill,
190
+ invoker: marker.invoker,
191
+ at: message.at,
192
+ failed: null
193
+ }, marker.loaded));
194
+ }
195
+ const gaps = [...session.integrity.gaps];
196
+ const unplacedModelCalls = session.modelCalls.filter((call) => !placedModelCalls.has(call.id) && call.error === null && call.inherited !== true);
197
+ const unplacedToolCalls = session.toolCalls.filter((call) => !placedToolCalls.has(call.id) && call.inherited !== true);
198
+ for (const call of unplacedModelCalls) placeModelCall(call.id);
199
+ for (const call of unplacedToolCalls) placeToolCall(call.id);
200
+ if (unplacedModelCalls.length + unplacedToolCalls.length > 0) gaps.push(`${unplacedModelCalls.length} model calls and ${unplacedToolCalls.length} tool calls are in no message, so they are ordered after the ones that are`);
201
+ return {
202
+ harness: session.harness,
203
+ sessionId: session.nativeSessionId,
204
+ parentSessionId: session.parentNativeSessionId,
205
+ endedAt: session.endedAt,
206
+ events,
207
+ ...markers.changesOfToolCall === void 0 ? {} : { changes },
208
+ gaps
209
+ };
210
+ }
211
+ // src/skill-usage/claude-code.ts
212
+ /**
213
+ * Claude Code transcripts as skill session records.
214
+ *
215
+ * The shared session reader decides what a transcript's tool calls, model calls
216
+ * and usage are. A transcript also says how each skill started, in records the
217
+ * normalized session does not keep, so this module reads those from the same
218
+ * parsed lines:
219
+ *
220
+ * | Invoker | Record |
221
+ * |---|---|
222
+ * | agent | an `assistant` record with a `tool_use` named `Skill` |
223
+ * | user | a `user` record that opens with a `command-name` tag, written by a person, whose first reply is the prompt the command expanded to |
224
+ * | harness | the same tag in a record the harness wrote (`isMeta`) or inside a subagent (`isSidechain`): a preload |
225
+ *
226
+ * A typed command the CLI answers itself (its reply is command output) is not a
227
+ * skill and is left out. The text a skill was loaded with is the `isMeta`
228
+ * record that names the call in `sourceToolUseID`; its hash is the version that
229
+ * ran, whatever the skill file holds today.
230
+ */
231
+ const SKILL_TOOL = "Skill";
232
+ const COMMAND_NAME = /<command-name>([\s\S]*?)<\/command-name>/;
233
+ const COMMAND_ARGS = /<command-args>([\s\S]*?)<\/command-args>/;
234
+ const BASE_DIRECTORY = "Base directory for this skill: ";
235
+ const COMMAND_OUTPUT = "<local-command-";
236
+ function textBlocks(content) {
237
+ if (typeof content === "string") return [content];
238
+ if (!Array.isArray(content)) return [];
239
+ const texts = [];
240
+ for (const block of content) {
241
+ const part = record$1(block);
242
+ if (part !== null && part.type === "text" && typeof part.text === "string") texts.push(part.text);
243
+ }
244
+ return texts;
245
+ }
246
+ /** A `command-name` tag that opens the text, alone or after its `command-message`. */
247
+ function commandTag(text) {
248
+ const head = text.trimStart();
249
+ if (!head.startsWith("<command-name>") && !head.startsWith("<command-message>")) return null;
250
+ const name = COMMAND_NAME.exec(head)?.[1]?.trim().replace(/^\//, "");
251
+ if (!name) return null;
252
+ const args = COMMAND_ARGS.exec(head)?.[1];
253
+ return {
254
+ name,
255
+ args: args === void 0 || args.trim() === "" ? null : args
256
+ };
257
+ }
258
+ /**
259
+ * The body a skill was loaded with. The harness frames it with the skill's
260
+ * directory on the first line and appends the caller's arguments; both are
261
+ * removed so two calls of one version hash the same.
262
+ */
263
+ function loadedSkillText(text, args) {
264
+ if (!text.startsWith(BASE_DIRECTORY)) return null;
265
+ const lineEnd = text.indexOf("\n");
266
+ const directory = (lineEnd === -1 ? text : text.slice(0, lineEnd)).slice(31).trim();
267
+ let body = lineEnd === -1 ? "" : text.slice(lineEnd + 1);
268
+ const trailer = args === null ? null : `\n\nARGUMENTS: ${args}`;
269
+ if (trailer !== null && body.endsWith(trailer)) body = body.slice(0, -trailer.length);
270
+ return {
271
+ body,
272
+ skillFile: directory === "" ? null : join(directory, "SKILL.md")
273
+ };
274
+ }
275
+ function firstLoadedSkillText(texts, args) {
276
+ for (const text of texts) {
277
+ const loaded = loadedSkillText(text, args);
278
+ if (loaded !== null) return loaded;
279
+ }
280
+ return null;
281
+ }
282
+ /** The skill a Claude Code tool call invokes, or null. */
283
+ function skillOfToolCall(call) {
284
+ if (call.name !== SKILL_TOOL) return null;
285
+ const skill = record$1(call.input)?.skill;
286
+ return typeof skill === "string" && skill !== "" ? skill : null;
287
+ }
288
+ /**
289
+ * Read how skills started from parsed transcript lines. `subagent` is true for
290
+ * a subagent's own transcript; in a top-level transcript, sidechain records
291
+ * belong to subagents and are skipped, as the shared reader skips them.
292
+ */
293
+ function skillMarkers(records, subagent) {
294
+ const loadedByCallId = /* @__PURE__ */ new Map();
295
+ const invocationsByMessageId = /* @__PURE__ */ new Map();
296
+ /** Arguments of each `Skill` call seen so far, by call id. */
297
+ const skillCallArgs = /* @__PURE__ */ new Map();
298
+ /** Typed commands whose first reply has not been read yet, by record id. */
299
+ const typedCommands = /* @__PURE__ */ new Map();
300
+ const seenRecords = /* @__PURE__ */ new Set();
301
+ for (const value of records) {
302
+ const entry = record$1(value);
303
+ if (entry === null) continue;
304
+ if (!subagent && entry.isSidechain === true) continue;
305
+ if (entry.type !== "user" && entry.type !== "assistant") continue;
306
+ const id = stringField(entry, "uuid");
307
+ if (id !== void 0) {
308
+ if (seenRecords.has(id)) continue;
309
+ seenRecords.add(id);
310
+ }
311
+ const content = record$1(entry.message)?.content;
312
+ if (entry.type === "assistant") {
313
+ for (const block of Array.isArray(content) ? content : []) {
314
+ const part = record$1(block);
315
+ if (part === null || part.type !== "tool_use" || part.name !== SKILL_TOOL) continue;
316
+ if (typeof part.id !== "string") continue;
317
+ const args = record$1(part.input)?.args;
318
+ skillCallArgs.set(part.id, typeof args === "string" && args !== "" ? args : null);
319
+ }
320
+ continue;
321
+ }
322
+ const texts = textBlocks(content);
323
+ const first = texts[0];
324
+ if (first === void 0) continue;
325
+ const answers = stringField(entry, "sourceToolUseID");
326
+ if (answers !== void 0 && skillCallArgs.has(answers)) {
327
+ if (!loadedByCallId.has(answers)) {
328
+ const loaded = firstLoadedSkillText(texts, skillCallArgs.get(answers) ?? null);
329
+ if (loaded !== null) loadedByCallId.set(answers, loaded);
330
+ }
331
+ continue;
332
+ }
333
+ const parent = stringField(entry, "parentUuid");
334
+ const typed = parent === void 0 ? void 0 : typedCommands.get(parent);
335
+ if (parent !== void 0 && typed !== void 0) {
336
+ typedCommands.delete(parent);
337
+ if (entry.isMeta === true && !first.trimStart().startsWith(COMMAND_OUTPUT)) invocationsByMessageId.set(parent, {
338
+ skill: typed.name,
339
+ invoker: "user",
340
+ loaded: firstLoadedSkillText(texts, typed.args)
341
+ });
342
+ continue;
343
+ }
344
+ const tag = commandTag(first);
345
+ if (tag === null || id === void 0) continue;
346
+ if (entry.isMeta === true || entry.isSidechain === true || subagent) invocationsByMessageId.set(id, {
347
+ skill: tag.name,
348
+ invoker: "harness",
349
+ loaded: firstLoadedSkillText(texts.slice(1), tag.args)
350
+ });
351
+ else typedCommands.set(id, tag);
352
+ }
353
+ return {
354
+ loadedByCallId,
355
+ invocationsByMessageId
356
+ };
357
+ }
358
+ /**
359
+ * Whose transcript this is, from its own records: a subagent's records are all
360
+ * sidechain and name the agent, whatever folder the file sits in.
361
+ */
362
+ function transcriptIdentity(records, fallbackId) {
363
+ for (const value of records) {
364
+ const entry = record$1(value);
365
+ if (entry === null || entry.type !== "user" && entry.type !== "assistant") continue;
366
+ const sessionId = stringField(entry, "sessionId");
367
+ if (entry.isSidechain === true) return {
368
+ sessionId: stringField(entry, "agentId") ?? fallbackId,
369
+ parentSessionId: sessionId ?? fallbackId
370
+ };
371
+ return {
372
+ sessionId: sessionId ?? fallbackId,
373
+ parentSessionId: null
374
+ };
375
+ }
376
+ return {
377
+ sessionId: fallbackId,
378
+ parentSessionId: null
379
+ };
380
+ }
381
+ /** One transcript's parsed lines as a skill session record. */
382
+ function skillSession(records, identity) {
383
+ return skillSessionFromHarnessSession(readSessionInput("claude-code", { records }, {
384
+ nativeSessionId: identity.sessionId,
385
+ parentNativeSessionId: identity.parentSessionId
386
+ }), {
387
+ skillOfToolCall,
388
+ changesOfToolCall: githubPullRequestRefs,
389
+ ...skillMarkers(records, identity.parentSessionId !== null)
390
+ });
391
+ }
392
+ async function walkTranscripts(directory, walk) {
393
+ const entries = await readdir(directory, { withFileTypes: true });
394
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
395
+ for (const entry of entries) {
396
+ const path = join(directory, entry.name);
397
+ if (entry.isDirectory()) try {
398
+ await walkTranscripts(path, walk);
399
+ } catch (error) {
400
+ walk.unreadable.push({
401
+ source: path,
402
+ error: errorMessage(error)
403
+ });
404
+ }
405
+ else if ((entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".jsonl")) walk.files.push(path);
406
+ }
407
+ }
408
+ /**
409
+ * Every transcript under a Claude Code projects directory, one read per file:
410
+ * top-level sessions and each subagent's own file. A file or folder that cannot
411
+ * be read is a failed read with its reason, so it is counted and never mistaken
412
+ * for a session with no skills. Throws when the directory itself cannot be read.
413
+ */
414
+ async function* claudeCodeSkillSessions(directory, options = {}) {
415
+ const walk = {
416
+ files: [],
417
+ unreadable: []
418
+ };
419
+ try {
420
+ await walkTranscripts(directory, walk);
421
+ } catch (error) {
422
+ throw new ValidationError(`claudeCodeSkillSessions: cannot read ${directory}: ${errorMessage(error)}`);
423
+ }
424
+ for (const failure of walk.unreadable) yield {
425
+ succeeded: false,
426
+ ...failure
427
+ };
428
+ for (const path of walk.files) try {
429
+ if (options.sinceMs !== void 0 && (await stat(path)).mtimeMs < options.sinceMs) continue;
430
+ const parsed = await parseCodeAgentJsonlFile(path);
431
+ const value = skillSession(parsed.entries, transcriptIdentity(parsed.entries, basename(path, ".jsonl").replace(/^agent-/, "")));
432
+ if (parsed.malformedLines > 0) value.gaps.push(`${parsed.malformedLines} lines are not JSON`);
433
+ yield {
434
+ succeeded: true,
435
+ source: path,
436
+ value
437
+ };
438
+ } catch (error) {
439
+ yield {
440
+ succeeded: false,
441
+ source: path,
442
+ error: errorMessage(error)
443
+ };
444
+ }
445
+ }
446
+ // src/skill-usage/report.ts
447
+ const OVERLAP_NOTE = "A session that invokes several skills counts its later work under each of them, so the after-invocation columns overlap across rows and do not add up.";
448
+ const PRICING_NOTE = "costUsd prices each model call with the cost ledger: the rates the caller gave for that model, else the ledger model table. Cache reads and writes are priced only at a rate the table names for that model; a call with cache tokens on a model without one, or a model with no row, is counted as not priced and stays out of the total.";
449
+ function emptyTokens() {
450
+ return {
451
+ input: 0,
452
+ output: 0,
453
+ cached: 0,
454
+ cacheWrite: 0,
455
+ total: 0
456
+ };
457
+ }
458
+ function addUsage(tokens, usage) {
459
+ const cached = usage.cachedTokens ?? 0;
460
+ const cacheWrite = usage.cacheWriteTokens ?? 0;
461
+ tokens.input += usage.inputTokens;
462
+ tokens.output += usage.outputTokens;
463
+ tokens.cached += cached;
464
+ tokens.cacheWrite += cacheWrite;
465
+ tokens.total += usage.inputTokens + usage.outputTokens + cached + cacheWrite;
466
+ }
467
+ function instant(value) {
468
+ if (value === null) return null;
469
+ const ms = Date.parse(value);
470
+ return Number.isFinite(ms) ? ms : null;
471
+ }
472
+ /** What one response cost, or null when neither the caller nor the cost ledger has a rate for its model. */
473
+ function modelCallCost(model, usage, pricing) {
474
+ if (model === null) return null;
475
+ const rates = pricing?.(model);
476
+ if (rates !== void 0) return costForTokenPricing(rates, usage);
477
+ const priced = costForUsage(model, usage);
478
+ return priced.costUnknown ? null : priced.costUsd;
479
+ }
480
+ /** What one session did after position `from`, to its end. */
481
+ function afterInvocation(session, from, startedAt, options) {
482
+ const after = {
483
+ toolCalls: 0,
484
+ toolErrors: 0,
485
+ toolCallsUnsettled: 0,
486
+ modelCalls: 0,
487
+ modelCallsWithoutUsage: 0,
488
+ tokens: emptyTokens(),
489
+ wallMs: null,
490
+ costUsd: 0,
491
+ pricedModelCalls: 0,
492
+ unpricedModelCalls: 0
493
+ };
494
+ for (let index = from + 1; index < session.events.length; index++) {
495
+ const event = session.events[index];
496
+ if (event.kind === "tool") {
497
+ after.toolCalls += 1;
498
+ if (event.failed === true) after.toolErrors += 1;
499
+ else if (event.failed === null) after.toolCallsUnsettled += 1;
500
+ } else if (event.kind === "model") {
501
+ after.modelCalls += 1;
502
+ if (event.usage === null) {
503
+ after.modelCallsWithoutUsage += 1;
504
+ continue;
505
+ }
506
+ addUsage(after.tokens, event.usage);
507
+ const cost = modelCallCost(event.model, event.usage, options.pricing);
508
+ if (cost === null) after.unpricedModelCalls += 1;
509
+ else {
510
+ after.costUsd += cost;
511
+ after.pricedModelCalls += 1;
512
+ }
513
+ }
514
+ }
515
+ const start = instant(startedAt);
516
+ const end = instant(session.endedAt);
517
+ if (start !== null && end !== null && end >= start) after.wallMs = end - start;
518
+ return after;
519
+ }
520
+ function median(values) {
521
+ return sampleMedian(values.filter((value) => value !== null));
522
+ }
523
+ function sum$1(values) {
524
+ return values.reduce((total, value) => total + value, 0);
525
+ }
526
+ function rowAfter(sessions) {
527
+ const tokens = emptyTokens();
528
+ for (const session of sessions) {
529
+ tokens.input += session.tokens.input;
530
+ tokens.output += session.tokens.output;
531
+ tokens.cached += session.tokens.cached;
532
+ tokens.cacheWrite += session.tokens.cacheWrite;
533
+ tokens.total += session.tokens.total;
534
+ }
535
+ const walls = sessions.flatMap((session) => session.wallMs === null ? [] : [session.wallMs]);
536
+ const pricedModelCalls = sum$1(sessions.map((session) => session.pricedModelCalls));
537
+ const priced = sessions.filter((session) => session.pricedModelCalls > 0);
538
+ return {
539
+ toolCalls: sum$1(sessions.map((session) => session.toolCalls)),
540
+ toolErrors: sum$1(sessions.map((session) => session.toolErrors)),
541
+ toolCallsUnsettled: sum$1(sessions.map((session) => session.toolCallsUnsettled)),
542
+ modelCalls: sum$1(sessions.map((session) => session.modelCalls)),
543
+ modelCallsWithoutUsage: sum$1(sessions.map((session) => session.modelCallsWithoutUsage)),
544
+ tokens,
545
+ wallMs: walls.length === 0 ? null : sum$1(walls),
546
+ sessionsWithWallTime: walls.length,
547
+ costUsd: pricedModelCalls === 0 ? null : sum$1(sessions.map((session) => session.costUsd)),
548
+ pricedModelCalls,
549
+ unpricedModelCalls: sum$1(sessions.map((session) => session.unpricedModelCalls)),
550
+ perSessionMedian: {
551
+ toolCalls: median(sessions.map((session) => session.toolCalls)),
552
+ toolErrors: median(sessions.map((session) => session.toolErrors)),
553
+ tokens: median(sessions.map((session) => session.modelCalls > session.modelCallsWithoutUsage ? session.tokens.total : null)),
554
+ wallMs: median(walls),
555
+ costUsd: median(priced.map((session) => session.costUsd))
556
+ }
557
+ };
558
+ }
559
+ function skillFileState(path, version, read) {
560
+ if (path === null) return null;
561
+ if (read === void 0) return {
562
+ path,
563
+ state: "not-read"
564
+ };
565
+ const file = read(path);
566
+ if (!file.succeeded) return {
567
+ path,
568
+ state: "unreadable",
569
+ error: file.error
570
+ };
571
+ return {
572
+ path,
573
+ state: file.bodySha256 === version?.bodySha256 ? "current" : "changed",
574
+ fileSha256: file.fileSha256
575
+ };
576
+ }
577
+ /**
578
+ * Build the usage report from any source of session reads.
579
+ *
580
+ * An invocation is counted once per call id across the whole source, so a
581
+ * resumed session that carries a copy of its history adds nothing. With
582
+ * `sinceMs`, only invocations at or after it count, and a session's "first
583
+ * invocation" is its first counted one. Rows are ordered by invocations, most
584
+ * first, then by skill name and version.
585
+ */
586
+ async function buildSkillUsageReport(source, options = {}) {
587
+ if (options.sinceMs !== void 0 && !Number.isFinite(options.sinceMs)) throw new ValidationError(`buildSkillUsageReport: sinceMs must be finite, got ${options.sinceMs}`);
588
+ const files = /* @__PURE__ */ new Map();
589
+ const readSkillFile = options.readSkillFile === void 0 ? void 0 : (path) => {
590
+ const known = files.get(path);
591
+ if (known !== void 0) return known;
592
+ const read = options.readSkillFile(path);
593
+ files.set(path, read);
594
+ return read;
595
+ };
596
+ const rows = /* @__PURE__ */ new Map();
597
+ const seenCalls = /* @__PURE__ */ new Set();
598
+ const unreadable = [];
599
+ const sessions = {
600
+ read: 0,
601
+ unreadable: 0,
602
+ subagent: 0,
603
+ withInvocation: 0,
604
+ withGaps: 0
605
+ };
606
+ const invocations = {
607
+ agent: 0,
608
+ user: 0,
609
+ harness: 0,
610
+ duplicates: 0,
611
+ beforeWindow: 0,
612
+ undated: 0
613
+ };
614
+ const modelCalls = /* @__PURE__ */ new Map();
615
+ /** The version an invocation ran: what the session recorded, else the skill file as it is now. */
616
+ const versionOf = (event) => {
617
+ if (event.version !== null) return event.version;
618
+ if (event.skillFile === null || readSkillFile === void 0) return null;
619
+ const file = readSkillFile(event.skillFile);
620
+ return file.succeeded ? {
621
+ bodySha256: file.bodySha256,
622
+ source: "file"
623
+ } : null;
624
+ };
625
+ for await (const read of source) {
626
+ if (!read.succeeded) {
627
+ sessions.unreadable += 1;
628
+ unreadable.push({
629
+ source: read.source,
630
+ error: read.error
631
+ });
632
+ continue;
633
+ }
634
+ const session = read.value;
635
+ const subagent = session.parentSessionId !== null;
636
+ sessions.read += 1;
637
+ if (subagent) sessions.subagent += 1;
638
+ if (session.gaps.length > 0) sessions.withGaps += 1;
639
+ for (const event of session.events) if (event.kind === "model") modelCalls.set(event.model, (modelCalls.get(event.model) ?? 0) + 1);
640
+ const rowsInSession = /* @__PURE__ */ new Set();
641
+ session.events.forEach((event, index) => {
642
+ if (event.kind !== "skill") return;
643
+ if (seenCalls.has(event.callId)) {
644
+ invocations.duplicates += 1;
645
+ return;
646
+ }
647
+ seenCalls.add(event.callId);
648
+ if (options.sinceMs !== void 0) {
649
+ const at = instant(event.at);
650
+ if (at === null) {
651
+ invocations.undated += 1;
652
+ return;
653
+ }
654
+ if (at < options.sinceMs) {
655
+ invocations.beforeWindow += 1;
656
+ return;
657
+ }
658
+ }
659
+ const version = versionOf(event);
660
+ const key = `${event.skill}\u0000${version?.bodySha256 ?? ""}`;
661
+ let row = rows.get(key);
662
+ if (row === void 0) {
663
+ row = {
664
+ skill: event.skill,
665
+ version,
666
+ skillFile: null,
667
+ invocations: {
668
+ agent: 0,
669
+ user: 0,
670
+ harness: 0
671
+ },
672
+ failedInvocations: 0,
673
+ subagentInvocations: 0,
674
+ subagentSessions: 0,
675
+ firstMs: null,
676
+ lastMs: null,
677
+ sessions: []
678
+ };
679
+ rows.set(key, row);
680
+ }
681
+ if (version?.source === "session" && row.version?.source === "file") row.version = version;
682
+ invocations[event.invoker] += 1;
683
+ row.invocations[event.invoker] += 1;
684
+ if (event.failed === true) row.failedInvocations += 1;
685
+ if (subagent) row.subagentInvocations += 1;
686
+ const at = instant(event.at);
687
+ if (at !== null) {
688
+ if (row.firstMs === null || at < row.firstMs) row.firstMs = at;
689
+ if (row.lastMs === null || at > row.lastMs) row.lastMs = at;
690
+ }
691
+ if (row.skillFile === null) row.skillFile = event.skillFile;
692
+ if (!rowsInSession.has(key)) {
693
+ rowsInSession.add(key);
694
+ if (subagent) row.subagentSessions += 1;
695
+ row.sessions.push(afterInvocation(session, index, event.at, options));
696
+ }
697
+ });
698
+ if (rowsInSession.size > 0) sessions.withInvocation += 1;
699
+ }
700
+ const total = invocations.agent + invocations.user + invocations.harness;
701
+ const built = [...rows.values()].map((row) => {
702
+ const rowTotal = row.invocations.agent + row.invocations.user + row.invocations.harness;
703
+ return {
704
+ skill: row.skill,
705
+ version: row.version,
706
+ skillFile: skillFileState(row.skillFile, row.version, readSkillFile),
707
+ invocations: {
708
+ ...row.invocations,
709
+ total: rowTotal
710
+ },
711
+ failedInvocations: row.failedInvocations,
712
+ sessions: row.sessions.length,
713
+ subagentSessions: row.subagentSessions,
714
+ subagentShare: row.subagentInvocations / rowTotal,
715
+ firstAt: row.firstMs === null ? null : new Date(row.firstMs).toISOString(),
716
+ lastAt: row.lastMs === null ? null : new Date(row.lastMs).toISOString(),
717
+ afterFirstInvocation: rowAfter(row.sessions)
718
+ };
719
+ });
720
+ built.sort((a, b) => {
721
+ if (a.invocations.total !== b.invocations.total) return b.invocations.total - a.invocations.total;
722
+ if (a.skill !== b.skill) return a.skill < b.skill ? -1 : 1;
723
+ const left = a.version?.bodySha256 ?? "";
724
+ const right = b.version?.bodySha256 ?? "";
725
+ return left < right ? -1 : left > right ? 1 : 0;
726
+ });
727
+ return {
728
+ since: options.sinceMs === void 0 ? null : new Date(options.sinceMs).toISOString(),
729
+ sessions,
730
+ invocations: {
731
+ ...invocations,
732
+ total
733
+ },
734
+ skills: new Set(built.map((row) => row.skill)).size,
735
+ rows: built,
736
+ models: [...modelCalls.entries()].map(([model, calls]) => ({
737
+ model,
738
+ modelCalls: calls,
739
+ priced: modelCallCost(model, {
740
+ inputTokens: 0,
741
+ outputTokens: 0
742
+ }, options.pricing) !== null
743
+ })).sort((a, b) => {
744
+ if (a.modelCalls !== b.modelCalls) return b.modelCalls - a.modelCalls;
745
+ const left = a.model ?? "";
746
+ const right = b.model ?? "";
747
+ return left < right ? -1 : left > right ? 1 : 0;
748
+ }),
749
+ unreadable,
750
+ notes: [OVERLAP_NOTE, PRICING_NOTE]
751
+ };
752
+ }
753
+ function compact(value) {
754
+ if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
755
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
756
+ return String(value);
757
+ }
758
+ function minutes(ms) {
759
+ return ms === null ? "no reading" : `${(ms / 6e4).toFixed(1)}m`;
760
+ }
761
+ function dollars(usd) {
762
+ return usd === null ? "not priced" : `$${usd.toFixed(2)}`;
763
+ }
764
+ /**
765
+ * The report as a short text table: the summary lines, then the rows with the
766
+ * most invocations. An unreadable version reads `not recorded`, a missing
767
+ * measure `no reading` or `not priced`; none of them prints as a zero.
768
+ */
769
+ function renderSkillUsageTable(report, limit = 30) {
770
+ const { sessions, invocations } = report;
771
+ const lines = [
772
+ `window: ${report.since === null ? "all recorded invocations" : `since ${report.since}`}`,
773
+ `sessions: ${sessions.read} read (${sessions.subagent} subagent), ${sessions.unreadable} unreadable, ${sessions.withInvocation} with a skill invocation`,
774
+ `invocations: ${invocations.total} across ${report.skills} skills: ${invocations.agent} agent, ${invocations.user} user, ${invocations.harness} harness`,
775
+ `not counted: ${invocations.duplicates} repeated call ids, ${invocations.beforeWindow} before the window, ${invocations.undated} without a timestamp`,
776
+ `models: ${report.models.length === 0 ? "none recorded" : report.models.map((entry) => `${entry.model ?? "not recorded"} ${entry.modelCalls} calls${entry.priced ? "" : " (no rate)"}`).join(", ")}`,
777
+ ""
778
+ ];
779
+ const header = [
780
+ "skill",
781
+ "version",
782
+ "calls",
783
+ "agent/user/harness",
784
+ "sessions",
785
+ "subagent",
786
+ "tool calls",
787
+ "tool errors",
788
+ "tokens",
789
+ "wall",
790
+ "ledger cost"
791
+ ];
792
+ const body = report.rows.slice(0, limit).map((row) => {
793
+ const after = row.afterFirstInvocation;
794
+ return [
795
+ row.skill,
796
+ row.version === null ? "not recorded" : row.version.bodySha256.slice(0, 12),
797
+ String(row.invocations.total),
798
+ `${row.invocations.agent}/${row.invocations.user}/${row.invocations.harness}`,
799
+ String(row.sessions),
800
+ `${Math.round(row.subagentShare * 100)}%`,
801
+ String(after.toolCalls),
802
+ String(after.toolErrors),
803
+ after.modelCalls === after.modelCallsWithoutUsage ? "no reading" : compact(after.tokens.total),
804
+ minutes(after.wallMs),
805
+ dollars(after.costUsd)
806
+ ];
807
+ });
808
+ const widths = header.map((title, column) => Math.max(title.length, ...body.map((cells) => cells[column].length)));
809
+ const format = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd();
810
+ lines.push(format(header), ...body.map(format));
811
+ if (report.rows.length > limit) lines.push(`... ${report.rows.length - limit} more rows`);
812
+ lines.push("", "tool calls, tool errors, tokens, wall and cost are summed over sessions, each");
813
+ lines.push("from its first counted invocation of the row to the end of that session.");
814
+ for (const note of report.notes) lines.push(note);
815
+ return `${lines.join("\n")}\n`;
816
+ }
33
817
  // src/analyst/benchmark-scoring.ts
34
818
  function scoreAnalystFindings(testCase, findings) {
35
819
  assertValidAnalystScoringCase(testCase);
@@ -2027,7 +2811,7 @@ const ANALYST_BENCHMARK_IMPLEMENTATION_FILES = Object.freeze([
2027
2811
  "src/trace/schema.ts",
2028
2812
  "src/verdict-cache.ts"
2029
2813
  ]);
2030
- const ANALYST_BENCHMARK_IMPLEMENTATION_SHA256 = "c495086da936e5a9c088c264c6bec6cf870cdee3e40d0ccf591edec6a2356cf9";
2814
+ const ANALYST_BENCHMARK_IMPLEMENTATION_SHA256 = "aa73aa8a3c022ae21720924e630907fd4ffcbb770486e77d5bff3213bfd58d55";
2031
2815
  // src/analyst/benchmark-evidence-validation.ts
2032
2816
  const MIN_ACTION_EXCERPT_CHARACTERS = 12;
2033
2817
  const MAX_LABEL_SCAN_DEPTH = 64;
@@ -6862,6 +7646,6 @@ function printSuccessSummary(artifact, paths) {
6862
7646
  function shellQuote(value) {
6863
7647
  return /^[a-zA-Z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
6864
7648
  }
6865
- export { agentRxBenchmarkCase as A, ANALYST_BENCHMARK_COST_LEDGER_FILE as C, AGENT_RX_UPSTREAM_REVISION as D, ANALYST_BENCHMARK_OBSERVATIONS_FILE as E, runAnalystBenchmark as F, traceStoreEvidenceResolver as I, normalizeAgentRxCategory as M, externalId as N, codeTraceBenchCase as O, positiveStep as P, ANALYST_BENCHMARK_IMPLEMENTATION_FILES as S, ANALYST_BENCHMARK_MANIFEST_FILE as T, readAnalystBenchmarkArtifact as _, runInlineAnalystDefinition as a, ANALYST_BENCHMARK_EVIDENCE_DEPENDENCY_LOCK_SHA256 as b, publicRlmAnalystDefinition as c, publicDirectAnalystDefinition as d, runChunkedAnalystDefinition as f, expandCodeTraceFailureBlocks as g, analystDefinitionProtocolSha256 as h, primeCodeTraceAnalystDefinition as i, agentRxPredictionsToFindings as j, codeTracerPredictionsToFindings as k, runReplVariableAnalystDefinition as l, analystDefinitionAsymmetries as m, createPrimeBenchmarkRunner as n, loadPublicBenchmarkRows as o, AnalystExpressivenessError as p, primeAnalystProtocolSha256 as r, createPublicBenchmarkRlmRunner as s, runAnalystBenchmarkCommand as t, createPublicBenchmarkDirectRunner as u, CODE_TRACE_BENCH_ANALYST_PROMPT as v, ANALYST_BENCHMARK_LOCAL_RECEIPT_FILE as w, ANALYST_BENCHMARK_EVIDENCE_IMPLEMENTATION_SHA256 as x, publicBenchmarkProtocolSha256 as y };
7649
+ export { agentRxBenchmarkCase as A, renderSkillUsageTable as B, ANALYST_BENCHMARK_COST_LEDGER_FILE as C, AGENT_RX_UPSTREAM_REVISION as D, ANALYST_BENCHMARK_OBSERVATIONS_FILE as E, runAnalystBenchmark as F, skillSessionFromHarnessSession as H, traceStoreEvidenceResolver as I, afterInvocation as L, normalizeAgentRxCategory as M, externalId as N, codeTraceBenchCase as O, positiveStep as P, buildSkillUsageReport as R, ANALYST_BENCHMARK_IMPLEMENTATION_FILES as S, ANALYST_BENCHMARK_MANIFEST_FILE as T, readSkillFile as U, claudeCodeSkillSessions as V, readAnalystBenchmarkArtifact as _, runInlineAnalystDefinition as a, ANALYST_BENCHMARK_EVIDENCE_DEPENDENCY_LOCK_SHA256 as b, publicRlmAnalystDefinition as c, publicDirectAnalystDefinition as d, runChunkedAnalystDefinition as f, expandCodeTraceFailureBlocks as g, analystDefinitionProtocolSha256 as h, primeCodeTraceAnalystDefinition as i, agentRxPredictionsToFindings as j, codeTracerPredictionsToFindings as k, runReplVariableAnalystDefinition as l, analystDefinitionAsymmetries as m, createPrimeBenchmarkRunner as n, loadPublicBenchmarkRows as o, AnalystExpressivenessError as p, primeAnalystProtocolSha256 as r, createPublicBenchmarkRlmRunner as s, runAnalystBenchmarkCommand as t, createPublicBenchmarkDirectRunner as u, CODE_TRACE_BENCH_ANALYST_PROMPT as v, ANALYST_BENCHMARK_LOCAL_RECEIPT_FILE as w, ANALYST_BENCHMARK_EVIDENCE_IMPLEMENTATION_SHA256 as x, publicBenchmarkProtocolSha256 as y, instant as z };
6866
7650
 
6867
- //# sourceMappingURL=benchmark-command-CGQXNFj7.js.map
7651
+ //# sourceMappingURL=benchmark-command-Be5O6A2v.js.map