@tangle-network/agent-eval 2.0.11 → 2.0.13

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 (164) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-_JzxgLDM.d.ts → agent-profile-8S2LfCvs.d.ts} +4 -4
  4. package/dist/{agent-profile-_JzxgLDM.d.ts.map → agent-profile-8S2LfCvs.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +324 -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-C7ObyGm9.js} +945 -13
  12. package/dist/benchmark-command-C7ObyGm9.js.map +1 -0
  13. package/dist/benchmarks/index.d.ts +4 -4
  14. package/dist/benchmarks/index.js +3 -3
  15. package/dist/campaign/index.d.ts +6 -6
  16. package/dist/campaign/index.js +10 -10
  17. package/dist/{campaign-eus7YRs2.js → campaign-CaO2k8Jb.js} +11 -11
  18. package/dist/{campaign-eus7YRs2.js.map → campaign-CaO2k8Jb.js.map} +1 -1
  19. package/dist/{campaign-evidence-KM5GTsHG.js → campaign-evidence-71uzJMVY.js} +2 -2
  20. package/dist/{campaign-evidence-KM5GTsHG.js.map → campaign-evidence-71uzJMVY.js.map} +1 -1
  21. package/dist/{campaign-evidence-BOcX4w0r.d.ts → campaign-evidence-DcTgo4ze.d.ts} +2 -2
  22. package/dist/{campaign-evidence-BOcX4w0r.d.ts.map → campaign-evidence-DcTgo4ze.d.ts.map} +1 -1
  23. package/dist/{chat-client-Oyot5tyo.js → chat-client-TkNgQDLj.js} +2 -2
  24. package/dist/{chat-client-Oyot5tyo.js.map → chat-client-TkNgQDLj.js.map} +1 -1
  25. package/dist/{chat-json-call-DTmv2uNY.js → chat-json-call-gu3deRID.js} +2 -2
  26. package/dist/{chat-json-call-DTmv2uNY.js.map → chat-json-call-gu3deRID.js.map} +1 -1
  27. package/dist/cli.js +1371 -11
  28. package/dist/cli.js.map +1 -1
  29. package/dist/{client-DUMIaMob.d.ts → client-3sR4_h5q.d.ts} +2 -2
  30. package/dist/{client-DUMIaMob.d.ts.map → client-3sR4_h5q.d.ts.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 +9 -9
  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-CVklg2e-.d.ts} +2 -2
  45. package/dist/{default-registry-X8McMoUV.d.ts.map → default-registry-CVklg2e-.d.ts.map} +1 -1
  46. package/dist/{define-agent-eval-D8ntOXqV.js → define-agent-eval-BLHr0_IP.js} +4 -4
  47. package/dist/{define-agent-eval-D8ntOXqV.js.map → define-agent-eval-BLHr0_IP.js.map} +1 -1
  48. package/dist/{define-agent-eval-DH5-xi-F.d.ts → define-agent-eval-DZ7wWMHC.d.ts} +5 -5
  49. package/dist/{define-agent-eval-DH5-xi-F.d.ts.map → define-agent-eval-DZ7wWMHC.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-CjZH6gW0.d.ts → evaluation-D50Dzyce.d.ts} +2 -2
  53. package/dist/{evaluation-CjZH6gW0.d.ts.map → evaluation-D50Dzyce.d.ts.map} +1 -1
  54. package/dist/{evaluation-BAisv8ZR.js → evaluation-DqfNMaKr.js} +2 -2
  55. package/dist/{evaluation-BAisv8ZR.js.map → evaluation-DqfNMaKr.js.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 +2 -2
  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.d.ts +2 -2
  72. package/dist/hosted/index.js +1 -1
  73. package/dist/{index-BmWw8zN6.d.ts → index-Bam453Y5.d.ts} +8 -8
  74. package/dist/{index-BmWw8zN6.d.ts.map → index-Bam453Y5.d.ts.map} +1 -1
  75. package/dist/{index-Cn9gB5Ca.d.ts → index-CYrvUGQl.d.ts} +206 -30
  76. package/dist/index-CYrvUGQl.d.ts.map +1 -0
  77. package/dist/{index-aRalB_Ma.d.ts → index-CxciVDt0.d.ts} +2 -2
  78. package/dist/{index-aRalB_Ma.d.ts.map → index-CxciVDt0.d.ts.map} +1 -1
  79. package/dist/{index-CCOaNmh2.d.ts → index-D1ghgNRI.d.ts} +3 -3
  80. package/dist/{index-CCOaNmh2.d.ts.map → index-D1ghgNRI.d.ts.map} +1 -1
  81. package/dist/index.d.ts +14 -14
  82. package/dist/index.js +471 -22
  83. package/dist/index.js.map +1 -1
  84. package/dist/{judge-gate-CpD3wmcf.js → judge-gate-WgYqQ9LA.js} +2 -2
  85. package/dist/{judge-gate-CpD3wmcf.js.map → judge-gate-WgYqQ9LA.js.map} +1 -1
  86. package/dist/{kind-factory-B-xCxG7p.js → kind-factory-C8MJpMTV.js} +2 -2
  87. package/dist/{kind-factory-B-xCxG7p.js.map → kind-factory-C8MJpMTV.js.map} +1 -1
  88. package/dist/{llm-client-Dk8lBnMh.js → llm-client-D4B1qR_1.js} +2 -2
  89. package/dist/{llm-client-Dk8lBnMh.js.map → llm-client-D4B1qR_1.js.map} +1 -1
  90. package/dist/{llm-judge-DYmEdo3M.js → llm-judge-ChGnwj4s.js} +4 -4
  91. package/dist/{llm-judge-DYmEdo3M.js.map → llm-judge-ChGnwj4s.js.map} +1 -1
  92. package/dist/{matrix-BDl7hoBr.d.ts → matrix-CAeyP9m-.d.ts} +2 -2
  93. package/dist/{matrix-BDl7hoBr.d.ts.map → matrix-CAeyP9m-.d.ts.map} +1 -1
  94. package/dist/meta-eval/index.js +2 -2
  95. package/dist/metrics-C6pXdupw.js +9 -0
  96. package/dist/metrics-C6pXdupw.js.map +1 -0
  97. package/dist/multishot/golden/index.d.ts +1 -1
  98. package/dist/multishot/index.d.ts +6 -6
  99. package/dist/multishot/index.js +8 -7
  100. package/dist/multishot/index.js.map +1 -1
  101. package/dist/openapi.json +1 -1
  102. package/dist/{optimization-method-4JlbMxd2.js → optimization-method-D2uCSc2j.js} +9 -9
  103. package/dist/{optimization-method-4JlbMxd2.js.map → optimization-method-D2uCSc2j.js.map} +1 -1
  104. package/dist/{proposal-findings-CfRFCFXS.js → proposal-findings-BCd4KjLy.js} +2 -2
  105. package/dist/{proposal-findings-CfRFCFXS.js.map → proposal-findings-BCd4KjLy.js.map} +1 -1
  106. package/dist/rl.d.ts +1 -1
  107. package/dist/rollout/index.d.ts +2 -2
  108. package/dist/rollout/index.js +1 -1
  109. package/dist/{rollout--rSr43Pd.js → rollout-CbHMVoDr.js} +2 -2
  110. package/dist/{rollout--rSr43Pd.js.map → rollout-CbHMVoDr.js.map} +1 -1
  111. package/dist/{run-improvement-loop-BeHu5D9Z.d.ts → run-improvement-loop-C9z817z_.d.ts} +7 -7
  112. package/dist/{run-improvement-loop-BeHu5D9Z.d.ts.map → run-improvement-loop-C9z817z_.d.ts.map} +1 -1
  113. package/dist/search/index.d.ts +3 -3
  114. package/dist/search/index.js +2 -2
  115. package/dist/{search-kernel-mZc79S6N.js → search-kernel-B1TEQ9pa.js} +2 -2
  116. package/dist/{search-kernel-mZc79S6N.js.map → search-kernel-B1TEQ9pa.js.map} +1 -1
  117. package/dist/{search-kernel-CJZ-ZSV1.d.ts → search-kernel-CZmj8gJW.d.ts} +3 -3
  118. package/dist/{search-kernel-CJZ-ZSV1.d.ts.map → search-kernel-CZmj8gJW.d.ts.map} +1 -1
  119. package/dist/{search-ledger-C7t68cmy.js → search-ledger-EjLGVZ4X.js} +25 -5
  120. package/dist/search-ledger-EjLGVZ4X.js.map +1 -0
  121. package/dist/{search-ledger-types-BhZE848w.d.ts → search-ledger-types-D4FsvPP9.d.ts} +8 -2
  122. package/dist/search-ledger-types-D4FsvPP9.d.ts.map +1 -0
  123. package/dist/{search-shipper-CmDW9dU6.js → search-shipper-DtSnRfOJ.js} +2 -2
  124. package/dist/{search-shipper-CmDW9dU6.js.map → search-shipper-DtSnRfOJ.js.map} +1 -1
  125. package/dist/{search-summary-CCgP2qXz.js → search-summary-C5fewoUi.js} +2 -2
  126. package/dist/{search-summary-CCgP2qXz.js.map → search-summary-C5fewoUi.js.map} +1 -1
  127. package/dist/{self-improve-C_Bcdmv8.js → self-improve-CQM7hIL_.js} +5 -5
  128. package/dist/{self-improve-C_Bcdmv8.js.map → self-improve-CQM7hIL_.js.map} +1 -1
  129. package/dist/{self-improve-B1fsNejr.d.ts → self-improve-Eo-EAWL8.d.ts} +7 -7
  130. package/dist/{self-improve-B1fsNejr.d.ts.map → self-improve-Eo-EAWL8.d.ts.map} +1 -1
  131. package/dist/{server-aZFmRucn.js → server-B-7vXS9T.js} +4 -4
  132. package/dist/{server-aZFmRucn.js.map → server-B-7vXS9T.js.map} +1 -1
  133. package/dist/{skillopt-optimization-method-DHk1K757.js → skillopt-optimization-method-DQ4urRij.js} +9 -9
  134. package/dist/{skillopt-optimization-method-DHk1K757.js.map → skillopt-optimization-method-DQ4urRij.js.map} +1 -1
  135. package/dist/{store-otlp-CdeW7NWq.js → store-otlp-DL30pdXE.js} +2 -2
  136. package/dist/{store-otlp-CdeW7NWq.js.map → store-otlp-DL30pdXE.js.map} +1 -1
  137. package/dist/{store-tool-spans-M3WxeRrG.d.ts → store-tool-spans-BD5Z304_.d.ts} +2 -2
  138. package/dist/{store-tool-spans-M3WxeRrG.d.ts.map → store-tool-spans-BD5Z304_.d.ts.map} +1 -1
  139. package/dist/{store-tool-spans-CVX-jfkk.js → store-tool-spans-DRdpbrnb.js} +3 -3
  140. package/dist/{store-tool-spans-CVX-jfkk.js.map → store-tool-spans-DRdpbrnb.js.map} +1 -1
  141. package/dist/{systemone-4PadCE4C.d.ts → systemone-D7FQ7n00.d.ts} +3 -3
  142. package/dist/{systemone-4PadCE4C.d.ts.map → systemone-D7FQ7n00.d.ts.map} +1 -1
  143. package/dist/systemone.d.ts +2 -2
  144. package/dist/systemone.js +2 -2
  145. package/dist/traces.d.ts +1 -1
  146. package/dist/traces.js +3 -3
  147. package/dist/{tree-CiIe-f3f.js → tree-CljLPWVm.js} +3 -3
  148. package/dist/{tree-CiIe-f3f.js.map → tree-CljLPWVm.js.map} +1 -1
  149. package/dist/{types-D5XtEH9Q.d.ts → types-BtWzceBY.d.ts} +17 -2
  150. package/dist/types-BtWzceBY.d.ts.map +1 -0
  151. package/dist/{types-Bte3EsFQ.d.ts → types-XxFZ2IAT.d.ts} +2 -2
  152. package/dist/{types-Bte3EsFQ.d.ts.map → types-XxFZ2IAT.d.ts.map} +1 -1
  153. package/dist/wire/index.js +1 -1
  154. package/docs/feature-guide.md +2 -0
  155. package/docs/public-api.md +16 -10
  156. package/docs/search-ledger.md +1 -1
  157. package/docs/skill-eval.md +110 -0
  158. package/package.json +4 -2
  159. package/dist/benchmark-command-CGQXNFj7.js.map +0 -1
  160. package/dist/cost-ledger-C5CCidPm.js.map +0 -1
  161. package/dist/index-Cn9gB5Ca.d.ts.map +0 -1
  162. package/dist/search-ledger-C7t68cmy.js.map +0 -1
  163. package/dist/search-ledger-types-BhZE848w.d.ts.map +0 -1
  164. package/dist/types-D5XtEH9Q.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,942 @@ 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 { codexRefForFile, 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
+ /** Claude Code's shell tool, and Codex's: `exec_command`, `shell`, and `exec`, the code-mode tool whose JavaScript runs the shell. */
39
+ const SHELL_TOOLS = /* @__PURE__ */ new Set([
40
+ "Bash",
41
+ "exec_command",
42
+ "shell",
43
+ "shell_command",
44
+ "exec"
45
+ ]);
46
+ /** `gh pr create`, or a wrapper named `gh-<identity>`, including its flags up to the subcommand. */
47
+ const PR_COMMAND = /\bgh(?:-[\w-]+)?\s+(?:-\S+\s+\S+\s+)*pr\s+(create|merge)\b/g;
48
+ const PULL_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/g;
49
+ const MERGE_ARGS = /\bpr\s+merge\s+(?:(?:https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/)?(\d+))/;
50
+ const REPO_FLAG = /(?:-R|--repo)[\s=]+([\w.-]+\/[\w.-]+)/;
51
+ /**
52
+ * The shell text of a call: the `command` or `cmd` of its input (a string, or an
53
+ * argv joined), or, for Codex's `exec`, the JavaScript, which holds the commands.
54
+ */
55
+ function shellCommandText(call) {
56
+ if (!SHELL_TOOLS.has(call.name)) return null;
57
+ if (typeof call.input === "string") return call.name === "exec" ? call.input : null;
58
+ const input = record$1(call.input);
59
+ const command = input?.command ?? input?.cmd;
60
+ if (typeof command === "string") return command;
61
+ if (Array.isArray(command) && command.every((part) => typeof part === "string")) return command.join(" ");
62
+ return null;
63
+ }
64
+ function githubPullRequestRefs(call) {
65
+ const command = shellCommandText(call);
66
+ if (command === null) return [];
67
+ const kinds = /* @__PURE__ */ new Set();
68
+ for (const match of command.matchAll(PR_COMMAND)) kinds.add(match[1]);
69
+ if (kinds.size === 0) return [];
70
+ const refs = /* @__PURE__ */ new Set();
71
+ if (call.result !== null && call.result.isError !== true) {
72
+ const text = call.result.text ?? "";
73
+ for (const match of text.matchAll(PULL_URL)) refs.add(`${match[1]}#${match[2]}`);
74
+ }
75
+ if (kinds.has("merge")) {
76
+ const merge = MERGE_ARGS.exec(command);
77
+ const repository = merge?.[1] ?? REPO_FLAG.exec(command)?.[1];
78
+ if (merge?.[2] !== void 0 && repository !== void 0) refs.add(`${repository}#${merge[2]}`);
79
+ }
80
+ return [...refs];
81
+ }
82
+ // src/skill-usage/skill-file.ts
83
+ /**
84
+ * A skill's version is the hash of the body an agent is given. A session
85
+ * record and the skill file both yield that body, so one invocation's version
86
+ * can be compared with the file as it is now.
87
+ */
88
+ const FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
89
+ /** The body an agent is given: the file without its frontmatter block, trimmed. */
90
+ function skillBody(text) {
91
+ return text.replace(FRONTMATTER, "").trim();
92
+ }
93
+ /** sha256 of {@link skillBody}, as lowercase hex. */
94
+ function skillBodySha256(text) {
95
+ return createHash("sha256").update(skillBody(text)).digest("hex");
96
+ }
97
+ /** Read one skill file. A missing or unreadable file is a typed failure, never an empty body. */
98
+ function readSkillFile(path) {
99
+ let bytes;
100
+ try {
101
+ bytes = readFileSync(path);
102
+ } catch (error) {
103
+ const code = error?.code;
104
+ return {
105
+ succeeded: false,
106
+ path,
107
+ error: typeof code === "string" ? code : errorMessage(error)
108
+ };
109
+ }
110
+ return {
111
+ succeeded: true,
112
+ path,
113
+ fileSha256: createHash("sha256").update(bytes).digest("hex"),
114
+ bodySha256: skillBodySha256(bytes.toString("utf8"))
115
+ };
116
+ }
117
+ // src/skill-usage/harness-session.ts
118
+ /** A response's usage as the cost ledger prices it; null unless input and output are both recorded. */
119
+ function costUsage(usage) {
120
+ if (usage === null || usage.input === null || usage.output === null) return null;
121
+ return {
122
+ inputTokens: usage.input,
123
+ outputTokens: usage.output,
124
+ ...usage.cacheRead === null ? {} : { cachedTokens: usage.cacheRead },
125
+ ...usage.cacheWrite === null ? {} : { cacheWriteTokens: usage.cacheWrite }
126
+ };
127
+ }
128
+ function invocation(fields, loaded, skillFile = null) {
129
+ return {
130
+ kind: "skill",
131
+ ...fields,
132
+ version: loaded == null ? null : {
133
+ bodySha256: skillBodySha256(loaded.body),
134
+ source: "session"
135
+ },
136
+ skillFile: loaded?.skillFile ?? skillFile
137
+ };
138
+ }
139
+ /**
140
+ * Project a normalized session into recorded order.
141
+ *
142
+ * Without markers the record carries tool and model calls and no invocations,
143
+ * which is the honest reading of a harness whose sessions do not mark them.
144
+ * Calls the session copied from a parent fork are left out: they are the
145
+ * parent's work. A call the session lists but no message places is appended
146
+ * after the placed ones and named in `gaps`.
147
+ */
148
+ function skillSessionFromHarnessSession(session, markers = {}) {
149
+ const toolCalls = new Map(session.toolCalls.map((call) => [call.id, call]));
150
+ const modelCalls = new Map(session.modelCalls.map((call) => [call.id, call]));
151
+ const placedModelCalls = /* @__PURE__ */ new Set();
152
+ const placedToolCalls = /* @__PURE__ */ new Set();
153
+ const events = [];
154
+ const changes = [];
155
+ const turns = [];
156
+ const placeModelCall = (id) => {
157
+ const call = modelCalls.get(id);
158
+ if (call === void 0 || placedModelCalls.has(id)) return;
159
+ placedModelCalls.add(id);
160
+ if (call.error !== null || call.inherited === true) return;
161
+ events.push({
162
+ kind: "model",
163
+ id,
164
+ at: call.at,
165
+ model: call.servedModel,
166
+ usage: costUsage(call.usage)
167
+ });
168
+ };
169
+ const placeToolCall = (id) => {
170
+ const call = toolCalls.get(id);
171
+ if (call === void 0 || placedToolCalls.has(id)) return;
172
+ placedToolCalls.add(id);
173
+ if (call.inherited === true) return;
174
+ const failed = call.result === null ? null : call.result.isError;
175
+ for (const ref of markers.changesOfToolCall?.(call) ?? []) changes.push({
176
+ ref,
177
+ callId: id,
178
+ at: call.startedAt
179
+ });
180
+ const skill = markers.skillOfToolCall?.(call) ?? null;
181
+ if (skill === null) {
182
+ events.push({
183
+ kind: "tool",
184
+ id,
185
+ name: call.name,
186
+ at: call.startedAt,
187
+ failed
188
+ });
189
+ return;
190
+ }
191
+ events.push(invocation({
192
+ callId: id,
193
+ skill,
194
+ invoker: "agent",
195
+ at: call.startedAt,
196
+ failed
197
+ }, markers.loadedByCallId?.get(id), markers.skillFileOfToolCall?.(call) ?? null));
198
+ };
199
+ for (const message of session.messages) {
200
+ if (message.inherited === true) continue;
201
+ if (message.role === "assistant") {
202
+ if (message.modelCallId !== null) placeModelCall(message.modelCallId);
203
+ for (const part of message.parts) if (part.type === "tool-call") placeToolCall(part.toolCallId);
204
+ continue;
205
+ }
206
+ if (message.role === "user" && message.actor === "human") {
207
+ const text = message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n").trim();
208
+ if (text !== "") turns.push({
209
+ id: message.id,
210
+ at: message.at,
211
+ eventIndex: events.length,
212
+ text
213
+ });
214
+ }
215
+ const marker = markers.invocationsByMessageId?.get(message.id);
216
+ if (marker !== void 0) events.push(invocation({
217
+ callId: message.id,
218
+ skill: marker.skill,
219
+ invoker: marker.invoker,
220
+ at: message.at,
221
+ failed: null
222
+ }, marker.loaded));
223
+ }
224
+ const gaps = [...session.integrity.gaps];
225
+ const unplacedModelCalls = session.modelCalls.filter((call) => !placedModelCalls.has(call.id) && call.error === null && call.inherited !== true);
226
+ const unplacedToolCalls = session.toolCalls.filter((call) => !placedToolCalls.has(call.id) && call.inherited !== true);
227
+ for (const call of unplacedModelCalls) placeModelCall(call.id);
228
+ for (const call of unplacedToolCalls) placeToolCall(call.id);
229
+ 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`);
230
+ return {
231
+ harness: session.harness,
232
+ sessionId: session.nativeSessionId,
233
+ parentSessionId: session.parentNativeSessionId,
234
+ endedAt: session.endedAt,
235
+ events,
236
+ ...markers.changesOfToolCall === void 0 ? {} : { changes },
237
+ ...markers.callAliases === void 0 || Object.keys(markers.callAliases).length === 0 ? {} : { callAliases: markers.callAliases },
238
+ turns,
239
+ gaps
240
+ };
241
+ }
242
+ // src/skill-usage/transcript-walk.ts
243
+ /** Finding the session files under a harness's store: one walk, shared by every reader. */
244
+ async function walkTranscripts(directory, walk, wanted = (name) => name.endsWith(".jsonl")) {
245
+ const entries = await readdir(directory, { withFileTypes: true });
246
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
247
+ for (const entry of entries) {
248
+ const path = join(directory, entry.name);
249
+ if (entry.isDirectory()) try {
250
+ await walkTranscripts(path, walk, wanted);
251
+ } catch (error) {
252
+ walk.unreadable.push({
253
+ source: path,
254
+ error: errorMessage(error)
255
+ });
256
+ }
257
+ else if ((entry.isFile() || entry.isSymbolicLink()) && wanted(entry.name)) walk.files.push(path);
258
+ }
259
+ }
260
+ // src/skill-usage/claude-code.ts
261
+ /**
262
+ * Claude Code transcripts as skill session records.
263
+ *
264
+ * The shared session reader decides what a transcript's tool calls, model calls
265
+ * and usage are. A transcript also says how each skill started, in records the
266
+ * normalized session does not keep, so this module reads those from the same
267
+ * parsed lines:
268
+ *
269
+ * | Invoker | Record |
270
+ * |---|---|
271
+ * | agent | an `assistant` record with a `tool_use` named `Skill` |
272
+ * | 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 |
273
+ * | harness | the same tag in a record the harness wrote (`isMeta`) or inside a subagent (`isSidechain`): a preload |
274
+ *
275
+ * A typed command the CLI answers itself (its reply is command output) is not a
276
+ * skill and is left out. The text a skill was loaded with is the `isMeta`
277
+ * record that names the call in `sourceToolUseID`; its hash is the version that
278
+ * ran, whatever the skill file holds today.
279
+ */
280
+ const SKILL_TOOL = "Skill";
281
+ const COMMAND_NAME = /<command-name>([\s\S]*?)<\/command-name>/;
282
+ const COMMAND_ARGS = /<command-args>([\s\S]*?)<\/command-args>/;
283
+ const BASE_DIRECTORY = "Base directory for this skill: ";
284
+ const COMMAND_OUTPUT = "<local-command-";
285
+ function textBlocks(content) {
286
+ if (typeof content === "string") return [content];
287
+ if (!Array.isArray(content)) return [];
288
+ const texts = [];
289
+ for (const block of content) {
290
+ const part = record$1(block);
291
+ if (part !== null && part.type === "text" && typeof part.text === "string") texts.push(part.text);
292
+ }
293
+ return texts;
294
+ }
295
+ /** A `command-name` tag that opens the text, alone or after its `command-message`. */
296
+ function commandTag(text) {
297
+ const head = text.trimStart();
298
+ if (!head.startsWith("<command-name>") && !head.startsWith("<command-message>")) return null;
299
+ const name = COMMAND_NAME.exec(head)?.[1]?.trim().replace(/^\//, "");
300
+ if (!name) return null;
301
+ const args = COMMAND_ARGS.exec(head)?.[1];
302
+ return {
303
+ name,
304
+ args: args === void 0 || args.trim() === "" ? null : args
305
+ };
306
+ }
307
+ /**
308
+ * The body a skill was loaded with. The harness frames it with the skill's
309
+ * directory on the first line and appends the caller's arguments; both are
310
+ * removed so two calls of one version hash the same.
311
+ */
312
+ function loadedSkillText(text, args) {
313
+ if (!text.startsWith(BASE_DIRECTORY)) return null;
314
+ const lineEnd = text.indexOf("\n");
315
+ const directory = (lineEnd === -1 ? text : text.slice(0, lineEnd)).slice(31).trim();
316
+ let body = lineEnd === -1 ? "" : text.slice(lineEnd + 1);
317
+ const trailer = args === null ? null : `\n\nARGUMENTS: ${args}`;
318
+ if (trailer !== null && body.endsWith(trailer)) body = body.slice(0, -trailer.length);
319
+ return {
320
+ body,
321
+ skillFile: directory === "" ? null : join(directory, "SKILL.md")
322
+ };
323
+ }
324
+ function firstLoadedSkillText(texts, args) {
325
+ for (const text of texts) {
326
+ const loaded = loadedSkillText(text, args);
327
+ if (loaded !== null) return loaded;
328
+ }
329
+ return null;
330
+ }
331
+ /** The skill a Claude Code tool call invokes, or null. */
332
+ function skillOfToolCall(call) {
333
+ if (call.name !== SKILL_TOOL) return null;
334
+ const skill = record$1(call.input)?.skill;
335
+ return typeof skill === "string" && skill !== "" ? skill : null;
336
+ }
337
+ /**
338
+ * Read how skills started from parsed transcript lines. `subagent` is true for
339
+ * a subagent's own transcript; in a top-level transcript, sidechain records
340
+ * belong to subagents and are skipped, as the shared reader skips them.
341
+ */
342
+ function skillMarkers(records, subagent) {
343
+ const loadedByCallId = /* @__PURE__ */ new Map();
344
+ const invocationsByMessageId = /* @__PURE__ */ new Map();
345
+ /** Arguments of each `Skill` call seen so far, by call id. */
346
+ const skillCallArgs = /* @__PURE__ */ new Map();
347
+ /** Typed commands whose first reply has not been read yet, by record id. */
348
+ const typedCommands = /* @__PURE__ */ new Map();
349
+ const seenRecords = /* @__PURE__ */ new Set();
350
+ for (const value of records) {
351
+ const entry = record$1(value);
352
+ if (entry === null) continue;
353
+ if (!subagent && entry.isSidechain === true) continue;
354
+ if (entry.type !== "user" && entry.type !== "assistant") continue;
355
+ const id = stringField(entry, "uuid");
356
+ if (id !== void 0) {
357
+ if (seenRecords.has(id)) continue;
358
+ seenRecords.add(id);
359
+ }
360
+ const content = record$1(entry.message)?.content;
361
+ if (entry.type === "assistant") {
362
+ for (const block of Array.isArray(content) ? content : []) {
363
+ const part = record$1(block);
364
+ if (part === null || part.type !== "tool_use" || part.name !== SKILL_TOOL) continue;
365
+ if (typeof part.id !== "string") continue;
366
+ const args = record$1(part.input)?.args;
367
+ skillCallArgs.set(part.id, typeof args === "string" && args !== "" ? args : null);
368
+ }
369
+ continue;
370
+ }
371
+ const texts = textBlocks(content);
372
+ const first = texts[0];
373
+ if (first === void 0) continue;
374
+ const answers = stringField(entry, "sourceToolUseID");
375
+ if (answers !== void 0 && skillCallArgs.has(answers)) {
376
+ if (!loadedByCallId.has(answers)) {
377
+ const loaded = firstLoadedSkillText(texts, skillCallArgs.get(answers) ?? null);
378
+ if (loaded !== null) loadedByCallId.set(answers, loaded);
379
+ }
380
+ continue;
381
+ }
382
+ const parent = stringField(entry, "parentUuid");
383
+ const typed = parent === void 0 ? void 0 : typedCommands.get(parent);
384
+ if (parent !== void 0 && typed !== void 0) {
385
+ typedCommands.delete(parent);
386
+ if (entry.isMeta === true && !first.trimStart().startsWith(COMMAND_OUTPUT)) invocationsByMessageId.set(parent, {
387
+ skill: typed.name,
388
+ invoker: "user",
389
+ loaded: firstLoadedSkillText(texts, typed.args)
390
+ });
391
+ continue;
392
+ }
393
+ const tag = commandTag(first);
394
+ if (tag === null || id === void 0) continue;
395
+ if (entry.isMeta === true || entry.isSidechain === true || subagent) invocationsByMessageId.set(id, {
396
+ skill: tag.name,
397
+ invoker: "harness",
398
+ loaded: firstLoadedSkillText(texts.slice(1), tag.args)
399
+ });
400
+ else typedCommands.set(id, tag);
401
+ }
402
+ return {
403
+ loadedByCallId,
404
+ invocationsByMessageId
405
+ };
406
+ }
407
+ /**
408
+ * Whose transcript this is, from its own records: a subagent's records are all
409
+ * sidechain and name the agent, whatever folder the file sits in.
410
+ */
411
+ function transcriptIdentity(records, fallbackId) {
412
+ for (const value of records) {
413
+ const entry = record$1(value);
414
+ if (entry === null || entry.type !== "user" && entry.type !== "assistant") continue;
415
+ const sessionId = stringField(entry, "sessionId");
416
+ if (entry.isSidechain === true) return {
417
+ sessionId: stringField(entry, "agentId") ?? fallbackId,
418
+ parentSessionId: sessionId ?? fallbackId
419
+ };
420
+ return {
421
+ sessionId: sessionId ?? fallbackId,
422
+ parentSessionId: null
423
+ };
424
+ }
425
+ return {
426
+ sessionId: fallbackId,
427
+ parentSessionId: null
428
+ };
429
+ }
430
+ /** One transcript's parsed lines as a skill session record. */
431
+ function skillSession(records, identity) {
432
+ return skillSessionFromHarnessSession(readSessionInput("claude-code", { records }, {
433
+ nativeSessionId: identity.sessionId,
434
+ parentNativeSessionId: identity.parentSessionId
435
+ }), {
436
+ skillOfToolCall,
437
+ changesOfToolCall: githubPullRequestRefs,
438
+ ...skillMarkers(records, identity.parentSessionId !== null)
439
+ });
440
+ }
441
+ /**
442
+ * Every transcript under a Claude Code projects directory, one read per file:
443
+ * top-level sessions and each subagent's own file. A file or folder that cannot
444
+ * be read is a failed read with its reason, so it is counted and never mistaken
445
+ * for a session with no skills. Throws when the directory itself cannot be read.
446
+ */
447
+ async function* claudeCodeSkillSessions(directory, options = {}) {
448
+ const walk = {
449
+ files: [],
450
+ unreadable: []
451
+ };
452
+ try {
453
+ await walkTranscripts(directory, walk);
454
+ } catch (error) {
455
+ throw new ValidationError(`claudeCodeSkillSessions: cannot read ${directory}: ${errorMessage(error)}`);
456
+ }
457
+ for (const failure of walk.unreadable) yield {
458
+ succeeded: false,
459
+ ...failure
460
+ };
461
+ for (const path of walk.files) try {
462
+ if (options.sinceMs !== void 0 && (await stat(path)).mtimeMs < options.sinceMs) continue;
463
+ const parsed = await parseCodeAgentJsonlFile(path);
464
+ const value = skillSession(parsed.entries, transcriptIdentity(parsed.entries, basename(path, ".jsonl").replace(/^agent-/, "")));
465
+ if (parsed.malformedLines > 0) value.gaps.push(`${parsed.malformedLines} lines are not JSON`);
466
+ yield {
467
+ succeeded: true,
468
+ source: path,
469
+ value
470
+ };
471
+ } catch (error) {
472
+ yield {
473
+ succeeded: false,
474
+ source: path,
475
+ error: errorMessage(error)
476
+ };
477
+ }
478
+ }
479
+ // src/skill-usage/codex.ts
480
+ /**
481
+ * Codex rollouts as skill session records.
482
+ *
483
+ * `@tangle-network/harness-sessions` owns what a rollout's tool calls, model
484
+ * calls, typed turns and usage are. This module adds what the rollout says about
485
+ * skills and changes:
486
+ *
487
+ * | Fact | Record |
488
+ * |---|---|
489
+ * | a skill invocation | a shell call that reads a `skills/<name>/SKILL.md` file with a viewer (`cat`, `sed`, `head`, `nl`...); Codex has no skill tool, so the read is the invocation |
490
+ * | the skill's version | none from the session: the read is often partial (`head -70`), so the report reads the skill file as it is now and says so |
491
+ * | a change | a pull request a shell call opened or merged, as for Claude Code; the change ledger adds commits |
492
+ *
493
+ * Inside Codex's code-mode `exec` tool a script runs shell commands, and the
494
+ * hook that wrote a change ledger row saw the command's own id (`exec-<uuid>`),
495
+ * not the id of the `exec` call. The rollout records that id on the command's
496
+ * completion event, between the call and its output, so it names the call when
497
+ * exactly one `exec` call is open. With none or several open it names none, and
498
+ * the session says how many ids it could not place.
499
+ */
500
+ /** A viewer reading a skill file: `cat path`, `sed -n '1,80p' path`, `head -70 path`. */
501
+ const SKILL_READ = /\b(?:cat|head|tail|sed|nl|bat|less|more|awk)\b[^\n;&|]*?(?:^|[\s'"=])((?:[\w~.$/-]*\/)?skills\/([\w.-]+)\/SKILL\.md)\b/;
502
+ /** The skill a shell call reads, and the file it reads it from. */
503
+ function skillRead(call) {
504
+ const command = shellCommandText(call);
505
+ if (command === null) return null;
506
+ const match = SKILL_READ.exec(command);
507
+ if (match === null) return null;
508
+ return {
509
+ skill: match[2],
510
+ file: match[1]
511
+ };
512
+ }
513
+ /** The ids hooks name nested commands by, mapped to the `exec` call that ran them. */
514
+ function execCallAliases(records) {
515
+ const aliases = {};
516
+ const open = /* @__PURE__ */ new Set();
517
+ let unplaced = 0;
518
+ for (const value of records) {
519
+ const entry = record$1(value);
520
+ const payload = record$1(entry?.payload);
521
+ if (entry === null || payload === null) continue;
522
+ if (entry.type === "response_item") {
523
+ const callId = stringField(payload, "call_id");
524
+ if (callId === void 0) continue;
525
+ if (payload.type === "custom_tool_call" && payload.name === "exec") open.add(callId);
526
+ else if (payload.type === "custom_tool_call_output") open.delete(callId);
527
+ } else if (entry.type === "event_msg" && payload.type === "item_completed") {
528
+ const item = record$1(payload.item);
529
+ if (item === null || item.type !== "CommandExecution") continue;
530
+ const id = stringField(item, "id");
531
+ if (id === void 0 || !id.startsWith("exec-")) continue;
532
+ const [only] = open;
533
+ if (open.size === 1 && only !== void 0) aliases[id] = only;
534
+ else unplaced += 1;
535
+ }
536
+ }
537
+ return {
538
+ aliases,
539
+ unplaced
540
+ };
541
+ }
542
+ /** One rollout's parsed lines as a skill session record. */
543
+ function rolloutSession(records, path) {
544
+ const session = readSessionInput("codex", { records }, codexRefForFile(path));
545
+ const { aliases, unplaced } = execCallAliases(records);
546
+ const value = skillSessionFromHarnessSession(session, {
547
+ skillOfToolCall: (call) => skillRead(call)?.skill ?? null,
548
+ skillFileOfToolCall: (call) => skillRead(call)?.file ?? null,
549
+ changesOfToolCall: githubPullRequestRefs,
550
+ callAliases: aliases
551
+ });
552
+ if (unplaced > 0) value.gaps.push(`${unplaced} commands run inside code-mode scripts name no single script, so a change ledger row for them cannot be placed`);
553
+ return value;
554
+ }
555
+ /**
556
+ * Every rollout under a Codex sessions directory (`~/.codex/sessions`, or one
557
+ * account's), one read per file: top-level threads and each subagent's own. A
558
+ * file or folder that cannot be read is a failed read with its reason. Throws
559
+ * when the directory itself cannot be read.
560
+ */
561
+ async function* codexSkillSessions(directory, options = {}) {
562
+ const walk = {
563
+ files: [],
564
+ unreadable: []
565
+ };
566
+ try {
567
+ await walkTranscripts(directory, walk, (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"));
568
+ } catch (error) {
569
+ throw new ValidationError(`codexSkillSessions: cannot read ${directory}: ${errorMessage(error)}`);
570
+ }
571
+ for (const failure of walk.unreadable) yield {
572
+ succeeded: false,
573
+ ...failure
574
+ };
575
+ for (const path of walk.files) try {
576
+ if (options.sinceMs !== void 0 && (await stat(path)).mtimeMs < options.sinceMs) continue;
577
+ const parsed = await parseCodeAgentJsonlFile(path);
578
+ const value = rolloutSession(parsed.entries, path);
579
+ if (parsed.malformedLines > 0) value.gaps.push(`${parsed.malformedLines} lines are not JSON`);
580
+ yield {
581
+ succeeded: true,
582
+ source: path,
583
+ value
584
+ };
585
+ } catch (error) {
586
+ yield {
587
+ succeeded: false,
588
+ source: path,
589
+ error: errorMessage(error)
590
+ };
591
+ }
592
+ }
593
+ // src/skill-usage/report.ts
594
+ 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.";
595
+ 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.";
596
+ function emptyTokens() {
597
+ return {
598
+ input: 0,
599
+ output: 0,
600
+ cached: 0,
601
+ cacheWrite: 0,
602
+ total: 0
603
+ };
604
+ }
605
+ function addUsage(tokens, usage) {
606
+ const cached = usage.cachedTokens ?? 0;
607
+ const cacheWrite = usage.cacheWriteTokens ?? 0;
608
+ tokens.input += usage.inputTokens;
609
+ tokens.output += usage.outputTokens;
610
+ tokens.cached += cached;
611
+ tokens.cacheWrite += cacheWrite;
612
+ tokens.total += usage.inputTokens + usage.outputTokens + cached + cacheWrite;
613
+ }
614
+ function instant(value) {
615
+ if (value === null) return null;
616
+ const ms = Date.parse(value);
617
+ return Number.isFinite(ms) ? ms : null;
618
+ }
619
+ /** What one response cost, or null when neither the caller nor the cost ledger has a rate for its model. */
620
+ function modelCallCost(model, usage, pricing) {
621
+ if (model === null) return null;
622
+ const rates = pricing?.(model);
623
+ if (rates !== void 0) return costForTokenPricing(rates, usage);
624
+ const priced = costForUsage(model, usage);
625
+ return priced.costUnknown ? null : priced.costUsd;
626
+ }
627
+ /** What one session did after position `from`, to its end. */
628
+ function afterInvocation(session, from, startedAt, options, until = null) {
629
+ const after = {
630
+ toolCalls: 0,
631
+ toolErrors: 0,
632
+ toolCallsUnsettled: 0,
633
+ modelCalls: 0,
634
+ modelCallsWithoutUsage: 0,
635
+ tokens: emptyTokens(),
636
+ wallMs: null,
637
+ costUsd: 0,
638
+ pricedModelCalls: 0,
639
+ unpricedModelCalls: 0
640
+ };
641
+ const stop = until === null ? session.events.length : Math.min(until.eventIndex, session.events.length);
642
+ for (let index = from + 1; index < stop; index++) {
643
+ const event = session.events[index];
644
+ if (event.kind === "tool") {
645
+ after.toolCalls += 1;
646
+ if (event.failed === true) after.toolErrors += 1;
647
+ else if (event.failed === null) after.toolCallsUnsettled += 1;
648
+ } else if (event.kind === "model") {
649
+ after.modelCalls += 1;
650
+ if (event.usage === null) {
651
+ after.modelCallsWithoutUsage += 1;
652
+ continue;
653
+ }
654
+ addUsage(after.tokens, event.usage);
655
+ const cost = modelCallCost(event.model, event.usage, options.pricing);
656
+ if (cost === null) after.unpricedModelCalls += 1;
657
+ else {
658
+ after.costUsd += cost;
659
+ after.pricedModelCalls += 1;
660
+ }
661
+ }
662
+ }
663
+ const start = instant(startedAt);
664
+ const end = instant(until === null ? session.endedAt : until.at);
665
+ if (start !== null && end !== null && end >= start) after.wallMs = end - start;
666
+ return after;
667
+ }
668
+ function median(values) {
669
+ return sampleMedian(values.filter((value) => value !== null));
670
+ }
671
+ function sum$1(values) {
672
+ return values.reduce((total, value) => total + value, 0);
673
+ }
674
+ function rowAfter(sessions) {
675
+ const tokens = emptyTokens();
676
+ for (const session of sessions) {
677
+ tokens.input += session.tokens.input;
678
+ tokens.output += session.tokens.output;
679
+ tokens.cached += session.tokens.cached;
680
+ tokens.cacheWrite += session.tokens.cacheWrite;
681
+ tokens.total += session.tokens.total;
682
+ }
683
+ const walls = sessions.flatMap((session) => session.wallMs === null ? [] : [session.wallMs]);
684
+ const pricedModelCalls = sum$1(sessions.map((session) => session.pricedModelCalls));
685
+ const priced = sessions.filter((session) => session.pricedModelCalls > 0);
686
+ return {
687
+ toolCalls: sum$1(sessions.map((session) => session.toolCalls)),
688
+ toolErrors: sum$1(sessions.map((session) => session.toolErrors)),
689
+ toolCallsUnsettled: sum$1(sessions.map((session) => session.toolCallsUnsettled)),
690
+ modelCalls: sum$1(sessions.map((session) => session.modelCalls)),
691
+ modelCallsWithoutUsage: sum$1(sessions.map((session) => session.modelCallsWithoutUsage)),
692
+ tokens,
693
+ wallMs: walls.length === 0 ? null : sum$1(walls),
694
+ sessionsWithWallTime: walls.length,
695
+ costUsd: pricedModelCalls === 0 ? null : sum$1(sessions.map((session) => session.costUsd)),
696
+ pricedModelCalls,
697
+ unpricedModelCalls: sum$1(sessions.map((session) => session.unpricedModelCalls)),
698
+ perSessionMedian: {
699
+ toolCalls: median(sessions.map((session) => session.toolCalls)),
700
+ toolErrors: median(sessions.map((session) => session.toolErrors)),
701
+ tokens: median(sessions.map((session) => session.modelCalls > session.modelCallsWithoutUsage ? session.tokens.total : null)),
702
+ wallMs: median(walls),
703
+ costUsd: median(priced.map((session) => session.costUsd))
704
+ }
705
+ };
706
+ }
707
+ function skillFileState(path, version, read) {
708
+ if (path === null) return null;
709
+ if (read === void 0) return {
710
+ path,
711
+ state: "not-read"
712
+ };
713
+ const file = read(path);
714
+ if (!file.succeeded) return {
715
+ path,
716
+ state: "unreadable",
717
+ error: file.error
718
+ };
719
+ return {
720
+ path,
721
+ state: file.bodySha256 === version?.bodySha256 ? "current" : "changed",
722
+ fileSha256: file.fileSha256
723
+ };
724
+ }
725
+ /**
726
+ * Build the usage report from any source of session reads.
727
+ *
728
+ * An invocation is counted once per call id across the whole source, so a
729
+ * resumed session that carries a copy of its history adds nothing. With
730
+ * `sinceMs`, only invocations at or after it count, and a session's "first
731
+ * invocation" is its first counted one. Rows are ordered by invocations, most
732
+ * first, then by skill name and version.
733
+ */
734
+ async function buildSkillUsageReport(source, options = {}) {
735
+ if (options.sinceMs !== void 0 && !Number.isFinite(options.sinceMs)) throw new ValidationError(`buildSkillUsageReport: sinceMs must be finite, got ${options.sinceMs}`);
736
+ const files = /* @__PURE__ */ new Map();
737
+ const readSkillFile = options.readSkillFile === void 0 ? void 0 : (path) => {
738
+ const known = files.get(path);
739
+ if (known !== void 0) return known;
740
+ const read = options.readSkillFile(path);
741
+ files.set(path, read);
742
+ return read;
743
+ };
744
+ const rows = /* @__PURE__ */ new Map();
745
+ const seenCalls = /* @__PURE__ */ new Set();
746
+ const unreadable = [];
747
+ const sessions = {
748
+ read: 0,
749
+ unreadable: 0,
750
+ subagent: 0,
751
+ withInvocation: 0,
752
+ withGaps: 0
753
+ };
754
+ const invocations = {
755
+ agent: 0,
756
+ user: 0,
757
+ harness: 0,
758
+ duplicates: 0,
759
+ beforeWindow: 0,
760
+ undated: 0
761
+ };
762
+ const modelCalls = /* @__PURE__ */ new Map();
763
+ /** The version an invocation ran: what the session recorded, else the skill file as it is now. */
764
+ const versionOf = (event) => {
765
+ if (event.version !== null) return event.version;
766
+ if (event.skillFile === null || readSkillFile === void 0) return null;
767
+ const file = readSkillFile(event.skillFile);
768
+ return file.succeeded ? {
769
+ bodySha256: file.bodySha256,
770
+ source: "file"
771
+ } : null;
772
+ };
773
+ for await (const read of source) {
774
+ if (!read.succeeded) {
775
+ sessions.unreadable += 1;
776
+ unreadable.push({
777
+ source: read.source,
778
+ error: read.error
779
+ });
780
+ continue;
781
+ }
782
+ const session = read.value;
783
+ const subagent = session.parentSessionId !== null;
784
+ sessions.read += 1;
785
+ if (subagent) sessions.subagent += 1;
786
+ if (session.gaps.length > 0) sessions.withGaps += 1;
787
+ for (const event of session.events) if (event.kind === "model") modelCalls.set(event.model, (modelCalls.get(event.model) ?? 0) + 1);
788
+ const rowsInSession = /* @__PURE__ */ new Set();
789
+ session.events.forEach((event, index) => {
790
+ if (event.kind !== "skill") return;
791
+ if (seenCalls.has(event.callId)) {
792
+ invocations.duplicates += 1;
793
+ return;
794
+ }
795
+ seenCalls.add(event.callId);
796
+ if (options.sinceMs !== void 0) {
797
+ const at = instant(event.at);
798
+ if (at === null) {
799
+ invocations.undated += 1;
800
+ return;
801
+ }
802
+ if (at < options.sinceMs) {
803
+ invocations.beforeWindow += 1;
804
+ return;
805
+ }
806
+ }
807
+ const version = versionOf(event);
808
+ const key = `${event.skill}\u0000${version?.bodySha256 ?? ""}`;
809
+ let row = rows.get(key);
810
+ if (row === void 0) {
811
+ row = {
812
+ skill: event.skill,
813
+ version,
814
+ skillFile: null,
815
+ invocations: {
816
+ agent: 0,
817
+ user: 0,
818
+ harness: 0
819
+ },
820
+ failedInvocations: 0,
821
+ subagentInvocations: 0,
822
+ subagentSessions: 0,
823
+ firstMs: null,
824
+ lastMs: null,
825
+ sessions: []
826
+ };
827
+ rows.set(key, row);
828
+ }
829
+ if (version?.source === "session" && row.version?.source === "file") row.version = version;
830
+ invocations[event.invoker] += 1;
831
+ row.invocations[event.invoker] += 1;
832
+ if (event.failed === true) row.failedInvocations += 1;
833
+ if (subagent) row.subagentInvocations += 1;
834
+ const at = instant(event.at);
835
+ if (at !== null) {
836
+ if (row.firstMs === null || at < row.firstMs) row.firstMs = at;
837
+ if (row.lastMs === null || at > row.lastMs) row.lastMs = at;
838
+ }
839
+ if (row.skillFile === null) row.skillFile = event.skillFile;
840
+ if (!rowsInSession.has(key)) {
841
+ rowsInSession.add(key);
842
+ if (subagent) row.subagentSessions += 1;
843
+ row.sessions.push(afterInvocation(session, index, event.at, options));
844
+ }
845
+ });
846
+ if (rowsInSession.size > 0) sessions.withInvocation += 1;
847
+ }
848
+ const total = invocations.agent + invocations.user + invocations.harness;
849
+ const built = [...rows.values()].map((row) => {
850
+ const rowTotal = row.invocations.agent + row.invocations.user + row.invocations.harness;
851
+ return {
852
+ skill: row.skill,
853
+ version: row.version,
854
+ skillFile: skillFileState(row.skillFile, row.version, readSkillFile),
855
+ invocations: {
856
+ ...row.invocations,
857
+ total: rowTotal
858
+ },
859
+ failedInvocations: row.failedInvocations,
860
+ sessions: row.sessions.length,
861
+ subagentSessions: row.subagentSessions,
862
+ subagentShare: row.subagentInvocations / rowTotal,
863
+ firstAt: row.firstMs === null ? null : new Date(row.firstMs).toISOString(),
864
+ lastAt: row.lastMs === null ? null : new Date(row.lastMs).toISOString(),
865
+ afterFirstInvocation: rowAfter(row.sessions)
866
+ };
867
+ });
868
+ built.sort((a, b) => {
869
+ if (a.invocations.total !== b.invocations.total) return b.invocations.total - a.invocations.total;
870
+ if (a.skill !== b.skill) return a.skill < b.skill ? -1 : 1;
871
+ const left = a.version?.bodySha256 ?? "";
872
+ const right = b.version?.bodySha256 ?? "";
873
+ return left < right ? -1 : left > right ? 1 : 0;
874
+ });
875
+ return {
876
+ since: options.sinceMs === void 0 ? null : new Date(options.sinceMs).toISOString(),
877
+ sessions,
878
+ invocations: {
879
+ ...invocations,
880
+ total
881
+ },
882
+ skills: new Set(built.map((row) => row.skill)).size,
883
+ rows: built,
884
+ models: [...modelCalls.entries()].map(([model, calls]) => ({
885
+ model,
886
+ modelCalls: calls,
887
+ priced: modelCallCost(model, {
888
+ inputTokens: 0,
889
+ outputTokens: 0
890
+ }, options.pricing) !== null
891
+ })).sort((a, b) => {
892
+ if (a.modelCalls !== b.modelCalls) return b.modelCalls - a.modelCalls;
893
+ const left = a.model ?? "";
894
+ const right = b.model ?? "";
895
+ return left < right ? -1 : left > right ? 1 : 0;
896
+ }),
897
+ unreadable,
898
+ notes: [OVERLAP_NOTE, PRICING_NOTE]
899
+ };
900
+ }
901
+ function compact(value) {
902
+ if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
903
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
904
+ return String(value);
905
+ }
906
+ function minutes(ms) {
907
+ return ms === null ? "no reading" : `${(ms / 6e4).toFixed(1)}m`;
908
+ }
909
+ function dollars(usd) {
910
+ return usd === null ? "not priced" : `$${usd.toFixed(2)}`;
911
+ }
912
+ /**
913
+ * The report as a short text table: the summary lines, then the rows with the
914
+ * most invocations. An unreadable version reads `not recorded`, a missing
915
+ * measure `no reading` or `not priced`; none of them prints as a zero.
916
+ */
917
+ function renderSkillUsageTable(report, limit = 30) {
918
+ const { sessions, invocations } = report;
919
+ const lines = [
920
+ `window: ${report.since === null ? "all recorded invocations" : `since ${report.since}`}`,
921
+ `sessions: ${sessions.read} read (${sessions.subagent} subagent), ${sessions.unreadable} unreadable, ${sessions.withInvocation} with a skill invocation`,
922
+ `invocations: ${invocations.total} across ${report.skills} skills: ${invocations.agent} agent, ${invocations.user} user, ${invocations.harness} harness`,
923
+ `not counted: ${invocations.duplicates} repeated call ids, ${invocations.beforeWindow} before the window, ${invocations.undated} without a timestamp`,
924
+ `models: ${report.models.length === 0 ? "none recorded" : report.models.map((entry) => `${entry.model ?? "not recorded"} ${entry.modelCalls} calls${entry.priced ? "" : " (no rate)"}`).join(", ")}`,
925
+ ""
926
+ ];
927
+ const header = [
928
+ "skill",
929
+ "version",
930
+ "calls",
931
+ "agent/user/harness",
932
+ "sessions",
933
+ "subagent",
934
+ "tool calls",
935
+ "tool errors",
936
+ "tokens",
937
+ "wall",
938
+ "ledger cost"
939
+ ];
940
+ const body = report.rows.slice(0, limit).map((row) => {
941
+ const after = row.afterFirstInvocation;
942
+ return [
943
+ row.skill,
944
+ row.version === null ? "not recorded" : row.version.bodySha256.slice(0, 12),
945
+ String(row.invocations.total),
946
+ `${row.invocations.agent}/${row.invocations.user}/${row.invocations.harness}`,
947
+ String(row.sessions),
948
+ `${Math.round(row.subagentShare * 100)}%`,
949
+ String(after.toolCalls),
950
+ String(after.toolErrors),
951
+ after.modelCalls === after.modelCallsWithoutUsage ? "no reading" : compact(after.tokens.total),
952
+ minutes(after.wallMs),
953
+ dollars(after.costUsd)
954
+ ];
955
+ });
956
+ const widths = header.map((title, column) => Math.max(title.length, ...body.map((cells) => cells[column].length)));
957
+ const format = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd();
958
+ lines.push(format(header), ...body.map(format));
959
+ if (report.rows.length > limit) lines.push(`... ${report.rows.length - limit} more rows`);
960
+ lines.push("", "tool calls, tool errors, tokens, wall and cost are summed over sessions, each");
961
+ lines.push("from its first counted invocation of the row to the end of that session.");
962
+ for (const note of report.notes) lines.push(note);
963
+ return `${lines.join("\n")}\n`;
964
+ }
33
965
  // src/analyst/benchmark-scoring.ts
34
966
  function scoreAnalystFindings(testCase, findings) {
35
967
  assertValidAnalystScoringCase(testCase);
@@ -2027,7 +2959,7 @@ const ANALYST_BENCHMARK_IMPLEMENTATION_FILES = Object.freeze([
2027
2959
  "src/trace/schema.ts",
2028
2960
  "src/verdict-cache.ts"
2029
2961
  ]);
2030
- const ANALYST_BENCHMARK_IMPLEMENTATION_SHA256 = "c495086da936e5a9c088c264c6bec6cf870cdee3e40d0ccf591edec6a2356cf9";
2962
+ const ANALYST_BENCHMARK_IMPLEMENTATION_SHA256 = "aa73aa8a3c022ae21720924e630907fd4ffcbb770486e77d5bff3213bfd58d55";
2031
2963
  // src/analyst/benchmark-evidence-validation.ts
2032
2964
  const MIN_ACTION_EXCERPT_CHARACTERS = 12;
2033
2965
  const MAX_LABEL_SCAN_DEPTH = 64;
@@ -6862,6 +7794,6 @@ function printSuccessSummary(artifact, paths) {
6862
7794
  function shellQuote(value) {
6863
7795
  return /^[a-zA-Z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
6864
7796
  }
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 };
7797
+ 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, claudeCodeSkillSessions 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, skillSessionFromHarnessSession as U, codexSkillSessions as V, readSkillFile as W, 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
7798
 
6867
- //# sourceMappingURL=benchmark-command-CGQXNFj7.js.map
7799
+ //# sourceMappingURL=benchmark-command-C7ObyGm9.js.map