@tangle-network/agent-eval 2.0.15 → 2.0.17

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 (112) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-8S2LfCvs.d.ts → agent-profile-_A7aMA4F.d.ts} +4 -4
  4. package/dist/{agent-profile-8S2LfCvs.d.ts.map → agent-profile-_A7aMA4F.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +23 -5
  6. package/dist/analyst/index.d.ts.map +1 -1
  7. package/dist/analyst/index.js +3 -3
  8. package/dist/app-grade/index.d.ts +2 -2
  9. package/dist/{benchmark-command-DgR1i30h.js → benchmark-command-CZbrh9bS.js} +27 -8
  10. package/dist/benchmark-command-CZbrh9bS.js.map +1 -0
  11. package/dist/benchmarks/index.d.ts +4 -4
  12. package/dist/benchmarks/index.js +2 -2
  13. package/dist/campaign/index.d.ts +7 -7
  14. package/dist/campaign/index.js +7 -7
  15. package/dist/{campaign-CaO2k8Jb.js → campaign-CJRlis5N.js} +7 -7
  16. package/dist/{campaign-CaO2k8Jb.js.map → campaign-CJRlis5N.js.map} +1 -1
  17. package/dist/{campaign-evidence-DcTgo4ze.d.ts → campaign-evidence-Biq06MQ9.d.ts} +2 -2
  18. package/dist/{campaign-evidence-DcTgo4ze.d.ts.map → campaign-evidence-Biq06MQ9.d.ts.map} +1 -1
  19. package/dist/cli.js +11 -7
  20. package/dist/cli.js.map +1 -1
  21. package/dist/{client-3sR4_h5q.d.ts → client-B_9qUZi5.d.ts} +2 -2
  22. package/dist/{client-3sR4_h5q.d.ts.map → client-B_9qUZi5.d.ts.map} +1 -1
  23. package/dist/contract/index.d.ts +9 -9
  24. package/dist/contract/index.js +5 -5
  25. package/dist/{default-registry-CVklg2e-.d.ts → default-registry-BKHpiYiW.d.ts} +2 -2
  26. package/dist/{default-registry-CVklg2e-.d.ts.map → default-registry-BKHpiYiW.d.ts.map} +1 -1
  27. package/dist/{define-agent-eval-DZ7wWMHC.d.ts → define-agent-eval-Bh8tJHZI.d.ts} +5 -5
  28. package/dist/{define-agent-eval-DZ7wWMHC.d.ts.map → define-agent-eval-Bh8tJHZI.d.ts.map} +1 -1
  29. package/dist/{define-agent-eval-BLHr0_IP.js → define-agent-eval-Dd6hFx0-.js} +3 -3
  30. package/dist/{define-agent-eval-BLHr0_IP.js.map → define-agent-eval-Dd6hFx0-.js.map} +1 -1
  31. package/dist/dspy-rlm-engine-DFgGrKzg.js +1613 -0
  32. package/dist/dspy-rlm-engine-DFgGrKzg.js.map +1 -0
  33. package/dist/{evaluation-D50Dzyce.d.ts → evaluation-f-UIDwbL.d.ts} +2 -2
  34. package/dist/{evaluation-D50Dzyce.d.ts.map → evaluation-f-UIDwbL.d.ts.map} +1 -1
  35. package/dist/evaluation.d.ts +1 -1
  36. package/dist/experiment/index.d.ts +76 -7
  37. package/dist/experiment/index.d.ts.map +1 -1
  38. package/dist/experiment/index.js +196 -13
  39. package/dist/experiment/index.js.map +1 -1
  40. package/dist/{findings-store-Drnjid7m.js → findings-store-DcBkRLDk.js} +2 -2
  41. package/dist/{findings-store-Drnjid7m.js.map → findings-store-DcBkRLDk.js.map} +1 -1
  42. package/dist/hosted/index.d.ts +2 -2
  43. package/dist/hosted/index.js +1 -1
  44. package/dist/{index-D1ghgNRI.d.ts → index-4khf0Q7g.d.ts} +238 -4
  45. package/dist/index-4khf0Q7g.d.ts.map +1 -0
  46. package/dist/{index-Bam453Y5.d.ts → index-C1jQ7qqy.d.ts} +8 -8
  47. package/dist/{index-Bam453Y5.d.ts.map → index-C1jQ7qqy.d.ts.map} +1 -1
  48. package/dist/{index-CYrvUGQl.d.ts → index-Cq_5SLfF.d.ts} +17 -247
  49. package/dist/index-Cq_5SLfF.d.ts.map +1 -0
  50. package/dist/{index-CxciVDt0.d.ts → index-DH_Jxu9p.d.ts} +2 -2
  51. package/dist/{index-CxciVDt0.d.ts.map → index-DH_Jxu9p.d.ts.map} +1 -1
  52. package/dist/index.d.ts +14 -14
  53. package/dist/index.js +9 -1091
  54. package/dist/index.js.map +1 -1
  55. package/dist/{llm-judge-ChGnwj4s.js → llm-judge-Bf3p1WNA.js} +2 -2
  56. package/dist/{llm-judge-ChGnwj4s.js.map → llm-judge-Bf3p1WNA.js.map} +1 -1
  57. package/dist/{matrix-CAeyP9m-.d.ts → matrix-BtyN7jpb.d.ts} +2 -2
  58. package/dist/{matrix-CAeyP9m-.d.ts.map → matrix-BtyN7jpb.d.ts.map} +1 -1
  59. package/dist/multishot/golden/index.d.ts +1 -1
  60. package/dist/multishot/index.d.ts +6 -6
  61. package/dist/multishot/index.js +2 -2
  62. package/dist/openapi.json +1 -1
  63. package/dist/{optimization-method-D2uCSc2j.js → optimization-method-BO2sb1m4.js} +4 -4
  64. package/dist/{optimization-method-D2uCSc2j.js.map → optimization-method-BO2sb1m4.js.map} +1 -1
  65. package/dist/rl.d.ts +1 -1
  66. package/dist/rollout/index.d.ts +2 -2
  67. package/dist/{run-improvement-loop-C9z817z_.d.ts → run-improvement-loop-D9IAZviC.d.ts} +7 -7
  68. package/dist/{run-improvement-loop-C9z817z_.d.ts.map → run-improvement-loop-D9IAZviC.d.ts.map} +1 -1
  69. package/dist/search/index.d.ts +3 -3
  70. package/dist/search/index.js +2 -2
  71. package/dist/{search-kernel-CZmj8gJW.d.ts → search-kernel-C2XOJHvk.d.ts} +3 -3
  72. package/dist/{search-kernel-CZmj8gJW.d.ts.map → search-kernel-C2XOJHvk.d.ts.map} +1 -1
  73. package/dist/{search-kernel-B1TEQ9pa.js → search-kernel-D96Eibc_.js} +2 -2
  74. package/dist/{search-kernel-B1TEQ9pa.js.map → search-kernel-D96Eibc_.js.map} +1 -1
  75. package/dist/{search-ledger-EjLGVZ4X.js → search-ledger-C7DywY8N.js} +40 -4
  76. package/dist/search-ledger-C7DywY8N.js.map +1 -0
  77. package/dist/{search-ledger-types-D4FsvPP9.d.ts → search-ledger-types-DF-f031V.d.ts} +19 -5
  78. package/dist/search-ledger-types-DF-f031V.d.ts.map +1 -0
  79. package/dist/{search-shipper-DtSnRfOJ.js → search-shipper-l6wUUWtc.js} +2 -2
  80. package/dist/{search-shipper-DtSnRfOJ.js.map → search-shipper-l6wUUWtc.js.map} +1 -1
  81. package/dist/{search-summary-C5fewoUi.js → search-summary-DjgKz7B1.js} +2 -2
  82. package/dist/{search-summary-C5fewoUi.js.map → search-summary-DjgKz7B1.js.map} +1 -1
  83. package/dist/{self-improve-CQM7hIL_.js → self-improve-BiTuylQQ.js} +3 -3
  84. package/dist/{self-improve-CQM7hIL_.js.map → self-improve-BiTuylQQ.js.map} +1 -1
  85. package/dist/{self-improve-Eo-EAWL8.d.ts → self-improve-DZ8W-QY-.d.ts} +7 -7
  86. package/dist/{self-improve-Eo-EAWL8.d.ts.map → self-improve-DZ8W-QY-.d.ts.map} +1 -1
  87. package/dist/{skillopt-optimization-method-DQ4urRij.js → skillopt-optimization-method-CJkejuSP.js} +3 -3
  88. package/dist/{skillopt-optimization-method-DQ4urRij.js.map → skillopt-optimization-method-CJkejuSP.js.map} +1 -1
  89. package/dist/{store-tool-spans-BD5Z304_.d.ts → store-tool-spans-wH8y7InB.d.ts} +2 -2
  90. package/dist/{store-tool-spans-BD5Z304_.d.ts.map → store-tool-spans-wH8y7InB.d.ts.map} +1 -1
  91. package/dist/{systemone-D7FQ7n00.d.ts → systemone-CpW1U2Uy.d.ts} +3 -3
  92. package/dist/{systemone-D7FQ7n00.d.ts.map → systemone-CpW1U2Uy.d.ts.map} +1 -1
  93. package/dist/systemone.d.ts +2 -2
  94. package/dist/traces.d.ts +1 -1
  95. package/dist/{tree-CljLPWVm.js → tree-lU9KWuxr.js} +3 -3
  96. package/dist/{tree-CljLPWVm.js.map → tree-lU9KWuxr.js.map} +1 -1
  97. package/dist/{types-BtWzceBY.d.ts → types-BpIAnRCe.d.ts} +12 -2
  98. package/dist/types-BpIAnRCe.d.ts.map +1 -0
  99. package/dist/{types-XxFZ2IAT.d.ts → types-DSU3qb_o.d.ts} +2 -2
  100. package/dist/{types-XxFZ2IAT.d.ts.map → types-DSU3qb_o.d.ts.map} +1 -1
  101. package/docs/experiment.md +31 -1
  102. package/docs/search-ledger.md +1 -0
  103. package/docs/trace-contracts.md +23 -0
  104. package/package.json +1 -1
  105. package/dist/benchmark-command-DgR1i30h.js.map +0 -1
  106. package/dist/dspy-rlm-engine-CR5MSL2k.js +0 -463
  107. package/dist/dspy-rlm-engine-CR5MSL2k.js.map +0 -1
  108. package/dist/index-CYrvUGQl.d.ts.map +0 -1
  109. package/dist/index-D1ghgNRI.d.ts.map +0 -1
  110. package/dist/search-ledger-EjLGVZ4X.js.map +0 -1
  111. package/dist/search-ledger-types-D4FsvPP9.d.ts.map +0 -1
  112. package/dist/types-BtWzceBY.d.ts.map +0 -1
@@ -0,0 +1,1613 @@
1
+ import { n as CaptureIntegrityError, s as ValidationError } from "./errors-DeEEV9Vx.js";
2
+ import { r as canonicalString } from "./canonical-DKgL_Wby.js";
3
+ import { p as resolveModelPricing } from "./cost-ledger-ni6f77QJ.js";
4
+ import { n as isRecord } from "./json-DtvZNAU9.js";
5
+ import { d as resolveExternalOptimizerCallbackLimits, f as resolveExternalOptimizerProcessLimits, i as assertExternalOptimizerModelBudget, u as removeCredentialEnvironment } from "./external-optimizer-contracts-vrye9kti.js";
6
+ import { t as certificationEvidenceDigest } from "./verdict-5PVtsWT_.js";
7
+ import { A as RawAnalystFindingSchema, B as parseFindingSubject, P as coerceJson } from "./kind-factory-C8MJpMTV.js";
8
+ import "./trace-attributes.js";
9
+ import { t as packageVersion } from "./package-version-CJl_pY9W.js";
10
+ import { a as closeServer, c as waitForActiveHandlers, i as startExternalOptimizerModelProxy, o as listenLocal, r as runWithCleanup, s as sendJsonIfOpen, t as runExternalOptimizerProcess } from "./external-optimizer-subprocess-CFIiwHSE.js";
11
+ import "./metrics-C6pXdupw.js";
12
+ import { randomBytes } from "node:crypto";
13
+ import { ATTR, INPUT_TOKEN_ATTR_KEYS, MODEL_ATTR_KEYS, OUTPUT_TOKEN_ATTR_KEYS, SPAN_KINDS, TOOL_NAME_ATTR_KEYS, firstNumberAttr, firstStringAttr, resolveSpanKind } from "@tangle-network/agent-trace-contract";
14
+ import { createServer } from "node:http";
15
+ // src/trace-contracts/spans.ts
16
+ const EVAL_KIND_TO_CONTRACT_KIND = /* @__PURE__ */ new Map([["judge", "EVALUATOR"], ["retrieval", "RETRIEVER"]]);
17
+ /**
18
+ * The span's contract kind: a declared kind when recognised, else inferred.
19
+ * A top-level `kind` counts as a declaration only when it names a contract
20
+ * kind; OTLP words such as `SPAN_KIND_INTERNAL` and the eval kinds `sandbox`
21
+ * and `custom` fall through to the span-kind attribute and name signals.
22
+ */
23
+ function contractSpanKind(span) {
24
+ const raw = typeof span.kind === "string" ? span.kind : void 0;
25
+ const mapped = raw === void 0 ? void 0 : EVAL_KIND_TO_CONTRACT_KIND.get(raw) ?? raw.toUpperCase();
26
+ const declared = mapped !== void 0 && SPAN_KINDS.includes(mapped) ? mapped : void 0;
27
+ return resolveSpanKind({
28
+ ...declared === void 0 ? {} : { kind: declared },
29
+ name: span.name,
30
+ attributes: span.attributes ?? {}
31
+ });
32
+ }
33
+ /**
34
+ * Tool name: `span.toolName` (typed ToolSpan) → the tool-name attributes
35
+ * (`gen_ai.tool.name`, `tool.name`, ..., `toolName`) → `span.name` when the
36
+ * span is a TOOL span.
37
+ */
38
+ function contractSpanToolName(span) {
39
+ if (typeof span.toolName === "string") return span.toolName;
40
+ const attributes = span.attributes ?? {};
41
+ const fromAttr = firstStringAttr(attributes, TOOL_NAME_ATTR_KEYS) ?? firstStringAttr(attributes, ["toolName"]);
42
+ if (fromAttr !== void 0) return fromAttr;
43
+ if (typeof span.name === "string" && contractSpanKind(span) === "TOOL") return span.name;
44
+ }
45
+ function spanModel(span) {
46
+ if (typeof span.model === "string" && span.model.length > 0) return span.model;
47
+ return firstStringAttr(span.attributes ?? {}, MODEL_ATTR_KEYS);
48
+ }
49
+ /**
50
+ * Input plus output tokens, or `undefined` when either side is unrecorded.
51
+ * Input follows the OTel GenAI definition — prompt tokens plus any cache
52
+ * read and cache write tokens the span records — because a cached call's
53
+ * `INPUT_TOKEN_ATTR_KEYS` value (`llm.token_count.prompt` and its aliases)
54
+ * carries only the uncached remainder, and a cache-heavy call can spend far
55
+ * more on cache reads and writes than on that remainder. `llm.maxTotalTokens`
56
+ * would otherwise pass runs at a small fraction of what they actually cost.
57
+ */
58
+ function spanTotalTokens(span) {
59
+ const attributes = span.attributes ?? {};
60
+ const input = finite(span.inputTokens) ?? firstNumberAttr(attributes, INPUT_TOKEN_ATTR_KEYS);
61
+ const output = finite(span.outputTokens) ?? firstNumberAttr(attributes, OUTPUT_TOKEN_ATTR_KEYS);
62
+ if (input === void 0 || output === void 0) return void 0;
63
+ const cacheRead = firstNumberAttr(attributes, ["llm.token_count.prompt_cache_hit"]) ?? 0;
64
+ const cacheWrite = firstNumberAttr(attributes, ["llm.token_count.prompt_cache_write"]) ?? 0;
65
+ return input + output + cacheRead + cacheWrite;
66
+ }
67
+ const ARGUMENT_ATTR_KEYS = [
68
+ "gen_ai.tool.call.arguments",
69
+ "tool.arguments",
70
+ "input.value"
71
+ ];
72
+ /** The call's arguments: the typed `args` field, else the argument attributes.
73
+ * JSON strings are parsed; an unparseable string is kept as a string. */
74
+ function spanArguments(span) {
75
+ if (span.argsCaptured === false || span.attributes?.["tool.args_captured"] === false) return {
76
+ known: false,
77
+ reason: "arguments were not captured"
78
+ };
79
+ if (span.args !== void 0) return {
80
+ known: true,
81
+ value: parseJsonString(span.args)
82
+ };
83
+ for (const key of ARGUMENT_ATTR_KEYS) {
84
+ const value = span.attributes?.[key];
85
+ if (value !== void 0 && value !== null) return {
86
+ known: true,
87
+ value: parseJsonString(value)
88
+ };
89
+ }
90
+ return {
91
+ known: false,
92
+ reason: "the span carries no argument evidence"
93
+ };
94
+ }
95
+ /** The tool names a span records as offered to the model. */
96
+ function spanOfferedTools(span) {
97
+ const raw = span.attributes?.[ATTR.toolDefinitions];
98
+ if (raw === void 0 || raw === null) return { recorded: false };
99
+ const value = parseJsonString(raw);
100
+ if (!Array.isArray(value)) return {
101
+ recorded: true,
102
+ unreadable: `${ATTR.toolDefinitions} is not a list`
103
+ };
104
+ const names = [];
105
+ for (const entry of value) {
106
+ const name = typeof entry === "string" ? entry : definitionName(entry);
107
+ if (name === void 0) return {
108
+ recorded: true,
109
+ unreadable: `${ATTR.toolDefinitions} has an entry without a tool name`
110
+ };
111
+ names.push(name);
112
+ }
113
+ return {
114
+ recorded: true,
115
+ names
116
+ };
117
+ }
118
+ function definitionName(entry) {
119
+ if (entry === null || typeof entry !== "object") return void 0;
120
+ const record = entry;
121
+ if (typeof record.name === "string" && record.name.length > 0) return record.name;
122
+ const fn = record.function;
123
+ return fn !== null && typeof fn === "object" && typeof fn.name === "string" && fn.name.length > 0 ? fn.name : void 0;
124
+ }
125
+ function parseJsonString(value) {
126
+ if (typeof value !== "string") return value;
127
+ try {
128
+ return JSON.parse(value);
129
+ } catch {
130
+ return value;
131
+ }
132
+ }
133
+ function finite(value) {
134
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
135
+ }
136
+ function isSpanError(span) {
137
+ return typeof span.status === "string" && /^(?:error|status_code_error)$/i.test(span.status);
138
+ }
139
+ // src/trace-contracts/predicates.ts
140
+ function isSerializedRegex(v) {
141
+ return typeof v === "object" && v !== null && typeof v.$regex === "string" && typeof v.flags === "string";
142
+ }
143
+ function isOneOfMatcher(v) {
144
+ return typeof v === "object" && v !== null && Array.isArray(v.oneOf);
145
+ }
146
+ function isRegexValue(v) {
147
+ return v instanceof RegExp || isSerializedRegex(v);
148
+ }
149
+ function matchText(actual, matcher) {
150
+ if (typeof actual !== "string") return false;
151
+ if (typeof matcher === "string") return actual === matcher;
152
+ if (matcher instanceof RegExp) return matcher.test(actual);
153
+ if (isOneOfMatcher(matcher)) return matcher.oneOf.includes(actual);
154
+ return new RegExp(matcher.$regex, matcher.flags).test(actual);
155
+ }
156
+ function assertMatcher(m, where) {
157
+ if (typeof m === "string" || m instanceof RegExp) return;
158
+ if (isSerializedRegex(m)) {
159
+ try {
160
+ new RegExp(m.$regex, m.flags);
161
+ } catch (error) {
162
+ throw new ValidationError(`${where}: invalid regex /${m.$regex}/${m.flags}: ${String(error)}`);
163
+ }
164
+ return;
165
+ }
166
+ if (isOneOfMatcher(m)) {
167
+ if (m.oneOf.length === 0 || !m.oneOf.every((x) => typeof x === "string")) throw new ValidationError(`${where}: "oneOf" must be a non-empty array of strings`);
168
+ return;
169
+ }
170
+ throw new ValidationError(`${where}: matcher must be string | RegExp | SerializedRegex | { oneOf }`);
171
+ }
172
+ function assertPredicate(value, where) {
173
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new ValidationError(`${where}: predicate must be an object, got ${typeof value}`);
174
+ const p = value;
175
+ for (const field of [
176
+ "name",
177
+ "tool",
178
+ "model"
179
+ ]) if (p[field] !== void 0) assertMatcher(p[field], `${where} "${field}"`);
180
+ if (p.kind !== void 0 && !SPAN_KINDS.includes(p.kind)) throw new ValidationError(`${where}: "kind" must be one of ${SPAN_KINDS.join(", ")}`);
181
+ if (p.attr !== void 0 && (p.attr === null || typeof p.attr !== "object" || Array.isArray(p.attr))) throw new ValidationError(`${where}: "attr" must be a plain object`);
182
+ for (const [key, expected] of Object.entries(p.attr ?? {})) if (expected !== null && typeof expected === "object") assertMatcher(expected, `${where} attr "${key}"`);
183
+ if (p.not !== void 0) assertPredicate(p.not, `${where} "not"`);
184
+ if (p.requiresCustom && typeof p.custom !== "function") throw new ValidationError(`${where}: rule was built with a custom predicate function, which does not survive JSON serialization — re-attach \`custom\` after deserializing or drop the rule`);
185
+ const hasAttr = p.attr !== void 0 && Object.keys(p.attr).length > 0;
186
+ if (p.name === void 0 && p.tool === void 0 && p.model === void 0 && p.kind === void 0 && p.not === void 0 && !hasAttr && typeof p.custom !== "function") throw new ValidationError(`${where}: empty predicate would match every span — specify name, tool, model, kind, attr, not, or custom`);
187
+ }
188
+ function predicateMatches(span, p) {
189
+ if (p.kind !== void 0 && contractSpanKind(span) !== p.kind) return false;
190
+ if (p.name !== void 0 && !matchText(span.name, p.name)) return false;
191
+ if (p.tool !== void 0 && !matchText(contractSpanToolName(span), p.tool)) return false;
192
+ if (p.model !== void 0 && !matchText(spanModel(span), p.model)) return false;
193
+ if (p.attr !== void 0) for (const [key, expected] of Object.entries(p.attr)) {
194
+ const actual = span.attributes?.[key];
195
+ if (isRegexValue(expected) || isOneOfMatcher(expected)) {
196
+ if (!matchText(typeof actual === "string" ? actual : void 0, expected)) return false;
197
+ } else if (actual !== expected) return false;
198
+ }
199
+ if (p.not !== void 0 && predicateMatches(span, p.not)) return false;
200
+ if (p.custom !== void 0 && !p.custom(span)) return false;
201
+ return true;
202
+ }
203
+ function normalizeMatcher(m) {
204
+ if (m instanceof RegExp) return {
205
+ $regex: m.source,
206
+ flags: m.flags
207
+ };
208
+ if (isOneOfMatcher(m)) return { oneOf: [...m.oneOf] };
209
+ return m;
210
+ }
211
+ function normalizePredicate(p, where) {
212
+ const kind = typeof p?.kind === "string" ? p.kind.toUpperCase() : p?.kind;
213
+ const withKind = kind === void 0 ? p : {
214
+ ...p,
215
+ kind
216
+ };
217
+ assertPredicate(withKind, where);
218
+ const out = {};
219
+ if (withKind.kind !== void 0) out.kind = withKind.kind;
220
+ if (withKind.name !== void 0) out.name = normalizeMatcher(withKind.name);
221
+ if (withKind.tool !== void 0) out.tool = normalizeMatcher(withKind.tool);
222
+ if (withKind.model !== void 0) out.model = normalizeMatcher(withKind.model);
223
+ if (withKind.attr !== void 0) out.attr = Object.fromEntries(Object.entries(withKind.attr).map(([k, v]) => [k, v instanceof RegExp ? normalizeMatcher(v) : v]));
224
+ if (withKind.not !== void 0) out.not = normalizePredicate(withKind.not, `${where} "not"`);
225
+ if (typeof withKind.custom === "function") {
226
+ out.custom = withKind.custom;
227
+ out.requiresCustom = true;
228
+ }
229
+ return out;
230
+ }
231
+ // src/trace-contracts/types.ts
232
+ const ORDER_MODES = [
233
+ "start-order",
234
+ "finish-before-start",
235
+ "all-occurrences"
236
+ ];
237
+ const RUN_STATUSES = [
238
+ "running",
239
+ "completed",
240
+ "failed",
241
+ "aborted"
242
+ ];
243
+ const ARGUMENT_OCCURRENCES = [
244
+ "first",
245
+ "last",
246
+ "any",
247
+ "all"
248
+ ];
249
+ const ARGUMENT_TYPES = [
250
+ "string",
251
+ "number",
252
+ "boolean",
253
+ "object",
254
+ "array",
255
+ "null"
256
+ ];
257
+ // src/trace-contracts/validate.ts
258
+ function assertOrder(order, where) {
259
+ if (order === void 0) return void 0;
260
+ if (!ORDER_MODES.includes(order)) throw new ValidationError(`${where}: order must be one of ${ORDER_MODES.join(", ")}`);
261
+ return order;
262
+ }
263
+ function assertCount(max, where) {
264
+ if (typeof max !== "number" || !Number.isInteger(max) || max < 0) throw new ValidationError(`${where}: max must be a non-negative integer`);
265
+ }
266
+ function assertJsonPointer(pointer, where) {
267
+ if (typeof pointer !== "string" || pointer !== "" && !pointer.startsWith("/")) throw new ValidationError(`${where}: pointer must be an RFC 6901 JSON Pointer ('' or '/a/b')`);
268
+ if (/~(?![01])/.test(pointer)) throw new ValidationError(`${where}: pointer has an invalid escape; use ~0 for ~ and ~1 for /`);
269
+ }
270
+ /** A non-empty list of distinct, non-empty tool names. */
271
+ function assertNames(names, where) {
272
+ if (!Array.isArray(names) || names.length === 0) throw new ValidationError(`${where} must be a non-empty array of tool names`);
273
+ for (const name of names) if (typeof name !== "string" || name.length === 0) throw new ValidationError(`${where} must hold non-empty tool names`);
274
+ const dup = names.find((n, i) => names.indexOf(n) !== i);
275
+ if (dup !== void 0) throw new ValidationError(`${where} lists "${dup}" twice`);
276
+ return names;
277
+ }
278
+ function assertArgumentCheck(check, where) {
279
+ const c = check;
280
+ if (c === null || typeof c !== "object") throw new ValidationError(`${where}: check must be an object`);
281
+ switch (c.op) {
282
+ case "exists": return;
283
+ case "equals":
284
+ if (!("value" in c)) throw new ValidationError(`${where}: equals needs a value`);
285
+ return;
286
+ case "oneOf":
287
+ if (!Array.isArray(c.values) || c.values.length === 0) throw new ValidationError(`${where}: oneOf needs a non-empty values array`);
288
+ return;
289
+ case "type":
290
+ if (!ARGUMENT_TYPES.includes(c.type)) throw new ValidationError(`${where}: type must be one of ${ARGUMENT_TYPES.join(", ")}`);
291
+ return;
292
+ default: throw new ValidationError(`${where}: check.op must be exists, equals, oneOf, or type`);
293
+ }
294
+ }
295
+ function assertRule(rule, where) {
296
+ switch (rule.kind) {
297
+ case "always":
298
+ case "never":
299
+ case "eventually":
300
+ assertPredicate(rule.p, `${where} (p)`);
301
+ return;
302
+ case "precedes":
303
+ assertPredicate(rule.a, `${where} (a)`);
304
+ assertPredicate(rule.b, `${where} (b)`);
305
+ assertOrder(rule.order, where);
306
+ return;
307
+ case "neverUnless":
308
+ assertPredicate(rule.p, `${where} (p)`);
309
+ assertPredicate(rule.prior, `${where} (prior)`);
310
+ assertOrder(rule.order, where);
311
+ return;
312
+ case "atMost":
313
+ case "tokensAtMost":
314
+ assertPredicate(rule.p, `${where} (p)`);
315
+ assertCount(rule.max, where);
316
+ return;
317
+ case "run":
318
+ if (!rule.requireCompleted && rule.allowedStatuses === void 0 && rule.maxDurationMs === void 0) throw new ValidationError(`${where}: run rule checks nothing`);
319
+ if (rule.requireCompleted !== void 0 && typeof rule.requireCompleted !== "boolean") throw new ValidationError(`${where}: requireCompleted must be a boolean`);
320
+ if (rule.allowedStatuses !== void 0) {
321
+ if (!Array.isArray(rule.allowedStatuses) || rule.allowedStatuses.length === 0) throw new ValidationError(`${where}: allowedStatuses must be a non-empty array`);
322
+ for (const status of rule.allowedStatuses) if (!RUN_STATUSES.includes(status)) throw new ValidationError(`${where}: unknown run status "${String(status)}" — expected one of ${RUN_STATUSES.join(", ")}`);
323
+ }
324
+ if (rule.maxDurationMs !== void 0 && (typeof rule.maxDurationMs !== "number" || !Number.isFinite(rule.maxDurationMs) || rule.maxDurationMs <= 0)) throw new ValidationError(`${where}: maxDurationMs must be a positive number`);
325
+ return;
326
+ case "argument":
327
+ assertPredicate(rule.p, `${where} (p)`);
328
+ assertJsonPointer(rule.pointer, where);
329
+ assertArgumentCheck(rule.check, where);
330
+ if (rule.occurrence !== void 0 && !ARGUMENT_OCCURRENCES.includes(rule.occurrence)) throw new ValidationError(`${where}: occurrence must be one of ${ARGUMENT_OCCURRENCES.join(", ")}`);
331
+ return;
332
+ case "toolsOffered":
333
+ if (rule.declared !== void 0) assertNames(rule.declared, `${where}: declared`);
334
+ return;
335
+ case "retrySafe": {
336
+ const reads = rule.reads === void 0 ? [] : assertNames(rule.reads, `${where}: reads`);
337
+ if (rule.writes === void 0 && rule.reads === void 0) throw new ValidationError(`${where}: retrySafe needs reads or writes`);
338
+ if (rule.writes !== void 0) {
339
+ if (!Array.isArray(rule.writes) || rule.writes.length === 0) throw new ValidationError(`${where}: writes must be a non-empty array`);
340
+ const writes = assertNames(rule.writes.map((w) => w?.tool), `${where}: writes[].tool`);
341
+ for (const [i, w] of rule.writes.entries()) {
342
+ if (w.idempotencyKey === void 0) continue;
343
+ assertJsonPointer(w.idempotencyKey, `${where}: writes[${i}].idempotencyKey`);
344
+ if (w.idempotencyKey === "") throw new ValidationError(`${where}: writes[${i}].idempotencyKey must name a member, not the whole arguments`);
345
+ }
346
+ const both = writes.find((t) => reads.includes(t));
347
+ if (both !== void 0) throw new ValidationError(`${where}: "${both}" is both a read and a write`);
348
+ }
349
+ return;
350
+ }
351
+ default: throw new ValidationError(`${where}: unknown rule kind "${String(rule.kind)}"`);
352
+ }
353
+ }
354
+ function assertRules(rules, where, allowEmpty = false) {
355
+ if (!Array.isArray(rules) || rules.length === 0 && !allowEmpty) throw new ValidationError(`${where}: no rules — an empty contract would vacuously pass`);
356
+ const seen = /* @__PURE__ */ new Set();
357
+ for (const rule of rules) {
358
+ const ruleWhere = `${where} rule "${rule?.label ?? "<unlabeled>"}"`;
359
+ if (typeof rule?.label !== "string" || rule.label.length === 0) throw new ValidationError(`${ruleWhere}: label must be a non-empty string`);
360
+ if (seen.has(rule.label)) throw new ValidationError(`${ruleWhere}: duplicate label would collapse per-rule scores`);
361
+ seen.add(rule.label);
362
+ assertRule(rule, ruleWhere);
363
+ }
364
+ }
365
+ function assertContract(contract, where) {
366
+ if (typeof contract?.name !== "string" || contract.name.length === 0) throw new ValidationError(`${where}: contract.name must be a non-empty string`);
367
+ const at = `${where} "${contract.name}"`;
368
+ assertRules(contract.rules, at, Array.isArray(contract.alternatives) && contract.alternatives.length > 0);
369
+ if (contract.scope !== void 0) assertPredicate(contract.scope?.root, `${at} scope.root`);
370
+ if (contract.alternatives !== void 0) {
371
+ if (!Array.isArray(contract.alternatives) || contract.alternatives.length === 0) throw new ValidationError(`${at}: alternatives must be a non-empty array`);
372
+ const ids = /* @__PURE__ */ new Set();
373
+ for (const alternative of contract.alternatives) {
374
+ if (typeof alternative?.id !== "string" || alternative.id.length === 0) throw new ValidationError(`${at}: every alternative needs a non-empty id`);
375
+ if (ids.has(alternative.id)) throw new ValidationError(`${at}: duplicate alternative id "${alternative.id}"`);
376
+ ids.add(alternative.id);
377
+ assertRules(alternative.rules, `${at} alternative "${alternative.id}"`);
378
+ }
379
+ }
380
+ }
381
+ // src/trace-contracts/explain.ts
382
+ function describeMatcher(m) {
383
+ if (typeof m === "string") return m;
384
+ if (m instanceof RegExp) return `/${m.source}/${m.flags}`;
385
+ if (isOneOfMatcher(m)) return `oneOf(${m.oneOf.join("|")})`;
386
+ return `/${m.$regex}/${m.flags}`;
387
+ }
388
+ function describePredicate(p) {
389
+ const parts = [];
390
+ if (p.kind !== void 0) parts.push(`kind=${p.kind}`);
391
+ if (p.name !== void 0) parts.push(`name=${describeMatcher(p.name)}`);
392
+ if (p.tool !== void 0) parts.push(`tool=${describeMatcher(p.tool)}`);
393
+ if (p.model !== void 0) parts.push(`model=${describeMatcher(p.model)}`);
394
+ if (p.attr !== void 0) for (const [k, v] of Object.entries(p.attr)) parts.push(`attr.${k}=${isRegexValue(v) ? describeMatcher(v) : JSON.stringify(v)}`);
395
+ if (p.not !== void 0) parts.push(`not(${describePredicate(p.not)})`);
396
+ if (typeof p.custom === "function") parts.push(`custom=${p.custom.name || "fn"}`);
397
+ return parts.join(",");
398
+ }
399
+ function describeCheck(check) {
400
+ switch (check.op) {
401
+ case "exists": return "exists";
402
+ case "equals": return `equals ${JSON.stringify(check.value)}`;
403
+ case "oneOf": return `oneOf ${JSON.stringify(check.values)}`;
404
+ case "type": return `type ${check.type}`;
405
+ }
406
+ }
407
+ /** One line per rule, stating what it requires. */
408
+ function describeRule(rule) {
409
+ switch (rule.kind) {
410
+ case "always": return `every span matches ${describePredicate(rule.p)}`;
411
+ case "never": return `no span matches ${describePredicate(rule.p)}`;
412
+ case "eventually": return `some span matches ${describePredicate(rule.p)}`;
413
+ case "precedes": return `${describePredicate(rule.a)} and ${describePredicate(rule.b)} both occur, and the first comes before the second (${rule.order ?? "start-order"})`;
414
+ case "neverUnless": return `every ${describePredicate(rule.p)} has an earlier ${describePredicate(rule.prior)} (${rule.order ?? "start-order"})`;
415
+ case "atMost": return `at most ${rule.max} span(s) match ${describePredicate(rule.p)}`;
416
+ case "tokensAtMost": return `spans matching ${describePredicate(rule.p)} use at most ${rule.max} tokens in total`;
417
+ case "run": {
418
+ const parts = [];
419
+ if (rule.requireCompleted) parts.push("the run completed and recorded its end");
420
+ if (rule.allowedStatuses) parts.push(`its status is one of ${rule.allowedStatuses.join(", ")}`);
421
+ if (rule.maxDurationMs !== void 0) parts.push(`it took at most ${rule.maxDurationMs} ms`);
422
+ return parts.join("; ");
423
+ }
424
+ case "argument": return `${rule.occurrence ?? "all"} call(s) matching ${describePredicate(rule.p)} have argument ${rule.pointer || "(whole value)"} that ${describeCheck(rule.check)}`;
425
+ case "toolsOffered": return `the trace records the tools offered to the model, every tool call is one of them${rule.declared ? `, and every offered tool is one of ${rule.declared.join(", ")}` : ""}`;
426
+ case "retrySafe": {
427
+ const parts = ["no tool is called twice with the same arguments"];
428
+ if (rule.reads) parts.push(`except the reads ${rule.reads.join(", ")}`);
429
+ for (const w of rule.writes ?? []) parts.push(w.idempotencyKey === void 0 ? `write ${w.tool} may never repeat` : `write ${w.tool} may repeat only with one idempotency key at ${w.idempotencyKey}`);
430
+ return parts.join("; ");
431
+ }
432
+ }
433
+ }
434
+ /** Plain-language statement of everything a contract checks, one rule per line. */
435
+ function explainTraceContract(contract) {
436
+ assertContract(contract, "explainTraceContract");
437
+ const lines = [`Contract "${contract.name}"${contract.description ? ` — ${contract.description}` : ""}`];
438
+ if (contract.scope) lines.push(`Scope: only the span matching ${describePredicate(contract.scope.root)} and its descendants; exactly one span must match.`);
439
+ lines.push("Every rule must pass:");
440
+ for (const rule of contract.rules) lines.push(` - ${rule.label}: ${describeRule(rule)}`);
441
+ if (contract.alternatives) {
442
+ lines.push("And at least one alternative must pass completely:");
443
+ for (const alternative of contract.alternatives) {
444
+ lines.push(` ${alternative.id}:`);
445
+ for (const rule of alternative.rules) lines.push(` - ${rule.label}: ${describeRule(rule)}`);
446
+ }
447
+ }
448
+ return lines.join("\n");
449
+ }
450
+ // src/trace-contracts/rules.ts
451
+ function spanRef(span, index) {
452
+ return span.spanId ?? `#${index}`;
453
+ }
454
+ /**
455
+ * Whether this trace shows any sign that spans of `kind` are actually
456
+ * captured, independent of whether any span happens to match a given rule's
457
+ * predicate. A `never`, `atMost`, `tokensAtMost` or `retrySafe` rule that
458
+ * targets TOOL or LLM spans and finds zero matches cannot otherwise tell "no
459
+ * calls happened" from "calls were not recorded": an exporter that silently
460
+ * drops a span kind makes `forbidden`, `allowed`, `maxCalls` and `retries`
461
+ * checks on that kind pass vacuously. Evidence is: a span of that kind
462
+ * anywhere in the trace, or — for TOOL — a recorded offered-tool set
463
+ * (`gen_ai.tool.definitions`), which proves the capture pipeline ran even on
464
+ * a turn that called no tool.
465
+ */
466
+ function hasCaptureEvidence(spans, kind) {
467
+ if (spans.some((span) => contractSpanKind(span) === kind)) return true;
468
+ if (kind === "TOOL") return spans.some((span) => spanOfferedTools(span).recorded);
469
+ return false;
470
+ }
471
+ /** Only `TOOL`/`LLM`-scoped predicates have capture evidence to check. */
472
+ function capturedKindOf(p) {
473
+ return p.kind === "TOOL" || p.kind === "LLM" ? p.kind : void 0;
474
+ }
475
+ function requireCaptureEvidence(spans, p, rule, situation) {
476
+ const kind = capturedKindOf(p);
477
+ if (kind === void 0) return;
478
+ if (hasCaptureEvidence(spans, kind)) return;
479
+ throw new CaptureIntegrityError(`rule '${rule}': ${situation} and the trace has no ${kind} capture evidence (no ${kind} span` + (kind === "TOOL" ? `, no ${ATTR.toolDefinitions}` : "") + `) — cannot tell whether ${describePredicate(p)} never happened or was never recorded`);
480
+ }
481
+ function indexed(spans, p) {
482
+ const out = [];
483
+ spans.forEach((span, i) => {
484
+ if (predicateMatches(span, p)) out.push({
485
+ span,
486
+ ref: spanRef(span, i)
487
+ });
488
+ });
489
+ return out;
490
+ }
491
+ /**
492
+ * Is guarded span `b` preceded by the guard spans under `order`? A span never
493
+ * witnesses itself. Missing timestamps fail: the checker cannot prove an
494
+ * order it cannot see.
495
+ */
496
+ function witnessed(b, guards, order) {
497
+ const bStart = finite(b.span.startedAt);
498
+ if (bStart === void 0) return {
499
+ ok: false,
500
+ detail: `span ${b.ref} has no startedAt, so its order cannot be proven`
501
+ };
502
+ const candidates = guards.filter((a) => a.span !== b.span);
503
+ if (candidates.length === 0) return {
504
+ ok: false,
505
+ detail: `span ${b.ref} has no earlier match`
506
+ };
507
+ const boundary = order === "start-order" ? "startedAt" : "endedAt";
508
+ const untimed = candidates.find((a) => finite(a.span[boundary]) === void 0);
509
+ if (order === "all-occurrences") {
510
+ if (untimed) return {
511
+ ok: false,
512
+ detail: `span ${untimed.ref} has no endedAt, so its order cannot be proven`
513
+ };
514
+ const late = candidates.find((a) => a.span.endedAt > bStart);
515
+ return late ? {
516
+ ok: false,
517
+ detail: `span ${late.ref} ends after span ${b.ref} starts`
518
+ } : { ok: true };
519
+ }
520
+ if (candidates.some((a) => {
521
+ const t = finite(a.span[boundary]);
522
+ return t !== void 0 && (order === "start-order" ? t < bStart : t <= bStart);
523
+ })) return { ok: true };
524
+ if (untimed) return {
525
+ ok: false,
526
+ detail: `span ${untimed.ref} has no ${boundary}, so its order cannot be proven`
527
+ };
528
+ return {
529
+ ok: false,
530
+ detail: order === "start-order" ? `span ${b.ref} has no match that started before it` : `span ${b.ref} has no match that finished before it started`
531
+ };
532
+ }
533
+ function orderViolations(label, guards, guarded, order, describe) {
534
+ const out = [];
535
+ for (const b of guarded) {
536
+ const w = witnessed(b, guards, order);
537
+ if (!w.ok) out.push({
538
+ rule: label,
539
+ spanId: b.span.spanId,
540
+ detail: `${describe}: ${w.detail}`
541
+ });
542
+ }
543
+ return out;
544
+ }
545
+ /** RFC 6901 resolution. `found: false` when any reference token is absent. */
546
+ function resolveJsonPointer(value, pointer) {
547
+ if (pointer === "") return {
548
+ found: true,
549
+ value
550
+ };
551
+ let current = value;
552
+ for (const raw of pointer.slice(1).split("/")) {
553
+ const token = raw.replace(/~1/g, "/").replace(/~0/g, "~");
554
+ if (Array.isArray(current)) {
555
+ if (!/^(?:0|[1-9]\d*)$/.test(token) || Number(token) >= current.length) return { found: false };
556
+ current = current[Number(token)];
557
+ } else if (current !== null && typeof current === "object" && Object.hasOwn(current, token)) current = current[token];
558
+ else return { found: false };
559
+ }
560
+ return {
561
+ found: true,
562
+ value: current
563
+ };
564
+ }
565
+ function jsonType(value) {
566
+ if (value === null) return "null";
567
+ if (Array.isArray(value)) return "array";
568
+ const t = typeof value;
569
+ return t === "string" || t === "number" || t === "boolean" || t === "object" ? t : "undefined";
570
+ }
571
+ function jsonEqual(a, b) {
572
+ if (a === b) return true;
573
+ const ta = jsonType(a);
574
+ if (ta !== jsonType(b)) return false;
575
+ if (ta === "array") {
576
+ const x = a;
577
+ const y = b;
578
+ return x.length === y.length && x.every((v, i) => jsonEqual(v, y[i]));
579
+ }
580
+ if (ta === "object") {
581
+ const x = a;
582
+ const y = b;
583
+ const keys = Object.keys(x);
584
+ return keys.length === Object.keys(y).length && keys.every((k) => Object.hasOwn(y, k) && jsonEqual(x[k], y[k]));
585
+ }
586
+ return false;
587
+ }
588
+ /** Why `value` fails `check`, or `undefined` when it passes. Never echoes the
589
+ * actual argument value: arguments can carry customer data. */
590
+ function argumentFailure(evidence, pointer, check) {
591
+ if (!evidence.known) return evidence.reason;
592
+ const resolved = resolveJsonPointer(evidence.value, pointer);
593
+ if (!resolved.found) return `argument ${pointer || "(whole value)"} is absent`;
594
+ switch (check.op) {
595
+ case "exists": return;
596
+ case "equals": return jsonEqual(resolved.value, check.value) ? void 0 : `argument ${pointer || "(whole value)"} (a ${jsonType(resolved.value)}) does not equal the expected value`;
597
+ case "oneOf": return check.values.some((v) => jsonEqual(resolved.value, v)) ? void 0 : `argument ${pointer || "(whole value)"} (a ${jsonType(resolved.value)}) is not one of the expected values`;
598
+ case "type": return jsonType(resolved.value) === check.type ? void 0 : `argument ${pointer || "(whole value)"} is a ${jsonType(resolved.value)}, not a ${check.type}`;
599
+ }
600
+ }
601
+ function checkArgument(rule, spans) {
602
+ const matches = indexed(spans, rule.p);
603
+ if (matches.length === 0) return [{
604
+ rule: rule.label,
605
+ detail: `no span matches ${describePredicate(rule.p)}, so there is no argument evidence to check`
606
+ }];
607
+ const occurrence = rule.occurrence ?? "all";
608
+ let selected = matches;
609
+ if ((occurrence === "first" || occurrence === "last") && matches.length > 1) {
610
+ const untimed = matches.find((m) => finite(m.span.startedAt) === void 0);
611
+ if (untimed) return [{
612
+ rule: rule.label,
613
+ spanId: untimed.span.spanId,
614
+ detail: `span ${untimed.ref} has no startedAt, so the ${occurrence} call cannot be chosen`
615
+ }];
616
+ const sorted = [...matches].sort((x, y) => x.span.startedAt - y.span.startedAt);
617
+ selected = [occurrence === "first" ? sorted[0] : sorted[sorted.length - 1]];
618
+ }
619
+ const failures = selected.map((m) => ({
620
+ m,
621
+ why: argumentFailure(spanArguments(m.span), rule.pointer, rule.check)
622
+ }));
623
+ const failed = failures.filter((f) => f.why !== void 0);
624
+ if (occurrence === "any" ? failed.length < failures.length : failed.length === 0) return [];
625
+ return failed.map((f) => ({
626
+ rule: rule.label,
627
+ spanId: f.m.span.spanId,
628
+ detail: `span ${f.m.ref}: ${f.why}`
629
+ }));
630
+ }
631
+ function checkRun(rule, context) {
632
+ if ("unknown" in context) return [{
633
+ rule: rule.label,
634
+ detail: `run record unavailable: ${context.unknown}`
635
+ }];
636
+ const run = context.run;
637
+ const out = [];
638
+ if (rule.requireCompleted && (run.status !== "completed" || finite(run.endedAt) === void 0)) out.push({
639
+ rule: rule.label,
640
+ detail: run.status === "completed" ? "run status is completed but no end time was recorded" : `run status is ${run.status ?? "unknown"}, not completed`
641
+ });
642
+ if (rule.allowedStatuses && !rule.allowedStatuses.includes(run.status ?? "")) out.push({
643
+ rule: rule.label,
644
+ detail: `run status ${run.status ?? "unknown"} is not one of ${rule.allowedStatuses.join(", ")}`
645
+ });
646
+ if (rule.maxDurationMs !== void 0) {
647
+ const start = finite(run.startedAt);
648
+ const end = finite(run.endedAt);
649
+ if (start === void 0 || end === void 0) out.push({
650
+ rule: rule.label,
651
+ detail: "run duration is unknown: start or end time is missing"
652
+ });
653
+ else if (end - start > rule.maxDurationMs) out.push({
654
+ rule: rule.label,
655
+ detail: `run took ${end - start} ms, over ${rule.maxDurationMs} ms`
656
+ });
657
+ }
658
+ return out;
659
+ }
660
+ const listed = (names, max = 6) => names.length <= max ? names.join(", ") : `${names.slice(0, max).join(", ")} and ${names.length - max} more`;
661
+ function toolSpans(spans) {
662
+ const out = [];
663
+ spans.forEach((span, i) => {
664
+ if (contractSpanKind(span) === "TOOL") out.push({
665
+ span,
666
+ ref: spanRef(span, i)
667
+ });
668
+ });
669
+ return out;
670
+ }
671
+ /** Declared, offered and called tools agree. */
672
+ function checkToolsOffered(rule, spans) {
673
+ const out = [];
674
+ const offered = /* @__PURE__ */ new Set();
675
+ let recorded = 0;
676
+ const declared = rule.declared ? new Set(rule.declared) : void 0;
677
+ spans.forEach((span, i) => {
678
+ const tools = spanOfferedTools(span);
679
+ if (!tools.recorded) return;
680
+ recorded += 1;
681
+ const ref = spanRef(span, i);
682
+ if ("unreadable" in tools) {
683
+ out.push({
684
+ rule: rule.label,
685
+ spanId: span.spanId,
686
+ detail: `span ${ref}: ${tools.unreadable}`
687
+ });
688
+ return;
689
+ }
690
+ for (const name of tools.names) offered.add(name);
691
+ const undeclared = declared ? [...new Set(tools.names)].filter((n) => !declared.has(n)) : [];
692
+ if (undeclared.length > 0) out.push({
693
+ rule: rule.label,
694
+ spanId: span.spanId,
695
+ detail: `span ${ref} offered the model ${undeclared.length} undeclared tool(s): ${listed(undeclared)}`
696
+ });
697
+ });
698
+ if (recorded === 0) return [{
699
+ rule: rule.label,
700
+ detail: `no span records the tools offered to the model (${ATTR.toolDefinitions}), so what the harness enforced is unknown`
701
+ }];
702
+ for (const { span, ref } of toolSpans(spans)) {
703
+ const name = contractSpanToolName(span);
704
+ if (name === void 0) out.push({
705
+ rule: rule.label,
706
+ spanId: span.spanId,
707
+ detail: `span ${ref} has no tool name, so it cannot be matched to an offered tool`
708
+ });
709
+ else if (!offered.has(name)) out.push({
710
+ rule: rule.label,
711
+ spanId: span.spanId,
712
+ detail: `span ${ref} called ${name}, which was never offered: the harness did not enforce its tool set`
713
+ });
714
+ }
715
+ return out;
716
+ }
717
+ /** The call's idempotency key, or why it has none. */
718
+ function idempotencyKey(span, pointer) {
719
+ const evidence = spanArguments(span);
720
+ if (!evidence.known) return { missing: evidence.reason };
721
+ const resolved = resolveJsonPointer(evidence.value, pointer);
722
+ const value = resolved.value;
723
+ if (resolved.found && typeof value === "string" && value.length > 0) return { key: value };
724
+ if (resolved.found && typeof value === "number" && Number.isFinite(value)) return { key: String(value) };
725
+ return { missing: `no idempotency key at ${pointer}` };
726
+ }
727
+ /** No call repeats a side effect that is not proven safe to repeat. */
728
+ function checkRetrySafe(rule, spans) {
729
+ const reads = new Set(rule.reads ?? []);
730
+ const writes = new Map((rule.writes ?? []).map((w) => [w.tool, w]));
731
+ const out = [];
732
+ const groups = /* @__PURE__ */ new Map();
733
+ const unseen = /* @__PURE__ */ new Map();
734
+ const calls = toolSpans(spans);
735
+ if (calls.length === 0 && !hasCaptureEvidence(spans, "TOOL")) throw new CaptureIntegrityError(`rule '${rule.label}': retrySafe found 0 TOOL spans and the trace has no TOOL capture evidence (no TOOL span, no ${ATTR.toolDefinitions}) — cannot tell whether no reads or writes happened or the trace lost its TOOL spans`);
736
+ for (const call of calls) {
737
+ const name = contractSpanToolName(call.span);
738
+ if (name === void 0) {
739
+ out.push({
740
+ rule: rule.label,
741
+ spanId: call.span.spanId,
742
+ detail: `span ${call.ref} has no tool name, so whether it repeats a call is unknown`
743
+ });
744
+ continue;
745
+ }
746
+ if (reads.has(name)) continue;
747
+ const args = spanArguments(call.span);
748
+ if (!args.known) {
749
+ const list = unseen.get(name) ?? [];
750
+ list.push(call);
751
+ unseen.set(name, list);
752
+ continue;
753
+ }
754
+ const pointer = writes.get(name)?.idempotencyKey;
755
+ const identity = pointer === void 0 ? args.value : withoutMember(args.value, pointer);
756
+ const key = `${name}\u0000${canonicalString(identity)}`;
757
+ const list = groups.get(key) ?? [];
758
+ list.push(call);
759
+ groups.set(key, list);
760
+ }
761
+ for (const [name, calls] of unseen) {
762
+ const total = calls.length + [...groups].reduce((n, [k, list]) => k.startsWith(`${name}\u0000`) ? n + list.length : n, 0);
763
+ if (total > 1) out.push({
764
+ rule: rule.label,
765
+ spanId: calls[0].span.spanId,
766
+ detail: `${name} was called ${total} times and span ${calls[0].ref} has no captured arguments, so whether a call repeats another is unknown`
767
+ });
768
+ }
769
+ for (const [key, calls] of groups) {
770
+ if (calls.length < 2) continue;
771
+ const name = key.slice(0, key.indexOf("\0"));
772
+ const refs = listed(calls.map((c) => c.ref));
773
+ const write = writes.get(name);
774
+ if (!write) {
775
+ out.push({
776
+ rule: rule.label,
777
+ spanId: calls[1].span.spanId,
778
+ detail: `${name} was called ${calls.length} times with the same arguments (spans ${refs}) and its side effect is not declared, so the repeat is not proven safe`
779
+ });
780
+ continue;
781
+ }
782
+ const pointer = write.idempotencyKey;
783
+ if (pointer === void 0) {
784
+ out.push({
785
+ rule: rule.label,
786
+ spanId: calls[1].span.spanId,
787
+ detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}) and declares no idempotency key, so it may have applied more than once`
788
+ });
789
+ continue;
790
+ }
791
+ const keyed = calls.map((c) => ({
792
+ c,
793
+ k: idempotencyKey(c.span, pointer)
794
+ }));
795
+ const missing = keyed.find((x) => "missing" in x.k);
796
+ const keys = new Set(keyed.flatMap((x) => "key" in x.k ? [x.k.key] : []));
797
+ if (missing) out.push({
798
+ rule: rule.label,
799
+ spanId: missing.c.span.spanId,
800
+ detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}); span ${missing.c.ref} has ${missing.k.missing}, so it may have applied more than once`
801
+ });
802
+ else if (keys.size > 1) out.push({
803
+ rule: rule.label,
804
+ spanId: calls[1].span.spanId,
805
+ detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}) under ${keys.size} different idempotency keys, so the target cannot tell they are one operation`
806
+ });
807
+ }
808
+ const flagged = new Set(out.map((v) => v.spanId));
809
+ for (const call of toolSpans(spans)) {
810
+ const name = contractSpanToolName(call.span);
811
+ if (name === void 0 || flagged.has(call.span.spanId)) continue;
812
+ const write = writes.get(name);
813
+ if (!write || !isSpanError(call.span)) continue;
814
+ const pointer = write.idempotencyKey;
815
+ if (!(pointer !== void 0 && "key" in idempotencyKey(call.span, pointer))) {
816
+ out.push({
817
+ rule: rule.label,
818
+ spanId: call.span.spanId,
819
+ detail: `write ${name} (span ${call.ref}) errored and ${pointer === void 0 ? "declares no idempotency key" : `has ${idempotencyKey(call.span, pointer).missing}`}; its outcome is unknown, so a retry cannot be proven safe`
820
+ });
821
+ flagged.add(call.span.spanId);
822
+ }
823
+ }
824
+ return out;
825
+ }
826
+ /** A copy of `value` without the member `pointer` names (RFC 6901). */
827
+ function withoutMember(value, pointer) {
828
+ const tokens = pointer.slice(1).split("/").map((t) => t.replace(/~1/g, "/").replace(/~0/g, "~"));
829
+ const strip = (node, depth) => {
830
+ const token = tokens[depth];
831
+ const last = depth === tokens.length - 1;
832
+ if (Array.isArray(node)) {
833
+ const index = /^(?:0|[1-9]\d*)$/.test(token) ? Number(token) : -1;
834
+ if (index < 0 || index >= node.length) return node;
835
+ return last ? node.filter((_, i) => i !== index) : node.map((v, i) => i === index ? strip(v, depth + 1) : v);
836
+ }
837
+ if (node === null || typeof node !== "object" || !Object.hasOwn(node, token)) return node;
838
+ const copy = { ...node };
839
+ if (last) delete copy[token];
840
+ else copy[token] = strip(copy[token], depth + 1);
841
+ return copy;
842
+ };
843
+ return strip(value, 0);
844
+ }
845
+ function checkRule(rule, ctx) {
846
+ const { spans } = ctx;
847
+ switch (rule.kind) {
848
+ case "always": return spans.flatMap((span, i) => predicateMatches(span, rule.p) ? [] : [{
849
+ rule: rule.label,
850
+ spanId: span.spanId,
851
+ detail: `span ${spanRef(span, i)} ("${span.name ?? ""}") fails always(${describePredicate(rule.p)})`
852
+ }]);
853
+ case "never": {
854
+ const matches = indexed(spans, rule.p);
855
+ if (matches.length === 0) requireCaptureEvidence(spans, rule.p, rule.label, `never(${describePredicate(rule.p)}) matched 0 spans`);
856
+ return matches.map(({ span, ref }) => ({
857
+ rule: rule.label,
858
+ spanId: span.spanId,
859
+ detail: `span ${ref} ("${span.name ?? ""}") matches never(${describePredicate(rule.p)})`
860
+ }));
861
+ }
862
+ case "eventually": return spans.some((span) => predicateMatches(span, rule.p)) ? [] : [{
863
+ rule: rule.label,
864
+ detail: `no span matches eventually(${describePredicate(rule.p)}) over ${spans.length} span(s)`
865
+ }];
866
+ case "precedes": {
867
+ const as = indexed(spans, rule.a);
868
+ const bs = indexed(spans, rule.b);
869
+ const out = [];
870
+ if (as.length === 0) out.push({
871
+ rule: rule.label,
872
+ detail: `required predecessor ${describePredicate(rule.a)} never occurred`
873
+ });
874
+ if (bs.length === 0) out.push({
875
+ rule: rule.label,
876
+ detail: `required successor ${describePredicate(rule.b)} never occurred`
877
+ });
878
+ if (out.length > 0) return out;
879
+ return orderViolations(rule.label, as, bs, rule.order ?? "start-order", `${describePredicate(rule.b)} is not preceded by ${describePredicate(rule.a)}`);
880
+ }
881
+ case "neverUnless": return orderViolations(rule.label, indexed(spans, rule.prior), indexed(spans, rule.p), rule.order ?? "start-order", `${describePredicate(rule.p)} without an earlier ${describePredicate(rule.prior)}`);
882
+ case "atMost": {
883
+ const matches = indexed(spans, rule.p);
884
+ if (matches.length === 0) requireCaptureEvidence(spans, rule.p, rule.label, `atMost(${describePredicate(rule.p)}) matched 0 spans`);
885
+ return matches.length <= rule.max ? [] : [{
886
+ rule: rule.label,
887
+ spanId: matches[rule.max]?.span.spanId,
888
+ detail: `${matches.length} span(s) match ${describePredicate(rule.p)}, over the limit of ${rule.max}`
889
+ }];
890
+ }
891
+ case "tokensAtMost": {
892
+ const matches = indexed(spans, rule.p);
893
+ if (matches.length === 0) requireCaptureEvidence(spans, rule.p, rule.label, `tokensAtMost(${describePredicate(rule.p)}) matched 0 spans`);
894
+ const unknown = matches.find((m) => spanTotalTokens(m.span) === void 0);
895
+ if (unknown) return [{
896
+ rule: rule.label,
897
+ spanId: unknown.span.spanId,
898
+ detail: `span ${unknown.ref} has no recorded input and output token counts, so the total is unknown`
899
+ }];
900
+ const total = matches.reduce((sum, m) => sum + spanTotalTokens(m.span), 0);
901
+ return total <= rule.max ? [] : [{
902
+ rule: rule.label,
903
+ detail: `${total} tokens across ${matches.length} span(s) matching ${describePredicate(rule.p)}, over the limit of ${rule.max}`
904
+ }];
905
+ }
906
+ case "run": return checkRun(rule, ctx.run);
907
+ case "argument": return checkArgument(rule, spans);
908
+ case "toolsOffered": return checkToolsOffered(rule, spans);
909
+ case "retrySafe": return checkRetrySafe(rule, spans);
910
+ }
911
+ }
912
+ function executeRule(rule, ctx) {
913
+ try {
914
+ const violations = checkRule(rule, ctx);
915
+ return {
916
+ status: violations.length === 0 ? "pass" : "fail",
917
+ violations
918
+ };
919
+ } catch (error) {
920
+ return {
921
+ status: "error",
922
+ violations: [],
923
+ error: error instanceof Error ? error.message : String(error)
924
+ };
925
+ }
926
+ }
927
+ // src/trace-contracts/evaluate.ts
928
+ /**
929
+ * A run derived from one span: the `run.status` attribute a run-anchor span
930
+ * carries (store-to-otlp writes it), else failed on an error status, else
931
+ * unknown. An ended span with an OK status and no declared `run.status` is
932
+ * NOT inferred as completed — a span exporter can end its root span cleanly
933
+ * without ever learning whether the underlying run actually finished (for
934
+ * example, a trace reader that saw no terminal record). `requireCompleted`
935
+ * and `allowedStatuses` must fail closed on that gap rather than pass it.
936
+ */
937
+ function runOfSpan(span) {
938
+ const declared = span.attributes?.["run.status"];
939
+ return {
940
+ status: typeof declared === "string" && RUN_STATUSES.includes(declared) ? declared : isSpanError(span) ? "failed" : void 0,
941
+ ...finite(span.startedAt) === void 0 ? {} : { startedAt: span.startedAt },
942
+ ...finite(span.endedAt) === void 0 ? {} : { endedAt: span.endedAt }
943
+ };
944
+ }
945
+ function rootsOf(spans) {
946
+ const ids = new Set(spans.map((s) => s.spanId).filter((id) => typeof id === "string"));
947
+ return spans.filter((s) => !s.parentSpanId || !ids.has(s.parentSpanId));
948
+ }
949
+ function subtree(spans, root) {
950
+ if (typeof root.spanId !== "string") return [root];
951
+ const children = /* @__PURE__ */ new Map();
952
+ for (const span of spans) if (typeof span.parentSpanId === "string") {
953
+ const list = children.get(span.parentSpanId) ?? [];
954
+ list.push(span);
955
+ children.set(span.parentSpanId, list);
956
+ }
957
+ const members = /* @__PURE__ */ new Set([root]);
958
+ const queue = [root];
959
+ while (queue.length > 0) {
960
+ const current = queue.shift();
961
+ for (const child of typeof current.spanId === "string" && children.get(current.spanId) || []) if (!members.has(child)) {
962
+ members.add(child);
963
+ queue.push(child);
964
+ }
965
+ }
966
+ return spans.filter((s) => members.has(s));
967
+ }
968
+ function statusOf(outcomes) {
969
+ if (outcomes.some((o) => o.status === "error")) return "error";
970
+ return outcomes.every((o) => o.status === "pass") ? "pass" : "fail";
971
+ }
972
+ /**
973
+ * Evaluate one contract over a span sequence. Pure and synchronous — works on
974
+ * `Span[]` from a TraceStore, `contractSpansFromOtlp` output, or any array
975
+ * satisfying `ContractSpan`. Throws
976
+ * `ValidationError` for a malformed contract; a rule that cannot be evaluated
977
+ * is reported as `error` in the verdict instead.
978
+ */
979
+ function evaluateTraceContract(contract, spans, options = {}) {
980
+ assertContract(contract, "evaluateTraceContract");
981
+ if (!Array.isArray(spans)) throw new ValidationError(`evaluateTraceContract: spans must be an array, got ${typeof spans}`);
982
+ let subject = spans;
983
+ let run;
984
+ let scopeError;
985
+ if (contract.scope) {
986
+ const roots = spans.filter((s) => predicateMatches(s, contract.scope.root));
987
+ if (roots.length === 1) {
988
+ subject = subtree(spans, roots[0]);
989
+ run = { run: runOfSpan(roots[0]) };
990
+ } else {
991
+ scopeError = `scope root ${describePredicate(contract.scope.root)} matched ${roots.length} spans; exactly one is required`;
992
+ run = { unknown: scopeError };
993
+ }
994
+ } else if (options.run) run = { run: options.run };
995
+ else {
996
+ const roots = rootsOf(spans);
997
+ run = roots.length === 1 ? { run: runOfSpan(roots[0]) } : { unknown: `the trace has ${roots.length} root spans and no run record was passed` };
998
+ }
999
+ const ctx = {
1000
+ spans: subject,
1001
+ run
1002
+ };
1003
+ const execute = (rule) => scopeError === void 0 ? executeRule(rule, ctx) : {
1004
+ status: "error",
1005
+ violations: [],
1006
+ error: scopeError
1007
+ };
1008
+ const base = contract.rules.map(execute);
1009
+ const branches = (contract.alternatives ?? []).map((alternative) => ({
1010
+ alternative,
1011
+ outcomes: alternative.rules.map(execute)
1012
+ }));
1013
+ const passedBranch = branches.find((b) => statusOf(b.outcomes) === "pass");
1014
+ const baseStatus = statusOf(base);
1015
+ let status = baseStatus;
1016
+ if (baseStatus === "pass" && branches.length > 0 && !passedBranch) status = branches.some((b) => statusOf(b.outcomes) === "error") ? "error" : "fail";
1017
+ const ruleExecutions = [...contract.rules.map((rule, i) => execution(rule.label, void 0, base[i])), ...branches.flatMap((b) => b.alternative.rules.map((rule, i) => execution(rule.label, b.alternative.id, b.outcomes[i])))];
1018
+ const violations = base.flatMap((o) => o.violations);
1019
+ if (branches.length > 0 && !passedBranch) for (const b of branches) for (const o of b.outcomes) violations.push(...o.violations.map((v) => ({
1020
+ ...v,
1021
+ rule: `${b.alternative.id}/${v.rule}`
1022
+ })));
1023
+ const errors = ruleExecutions.filter((e) => e.status === "error").map((e) => `${e.alternative ? `${e.alternative}/` : ""}${e.rule}: ${e.error}`);
1024
+ const scores = {};
1025
+ contract.rules.forEach((rule, i) => {
1026
+ const s = base[i].status;
1027
+ if (s !== "error") scores[rule.label] = s === "pass" ? 1 : 0;
1028
+ });
1029
+ if (branches.length > 0 && (passedBranch || status !== "error")) scores.anyOf = passedBranch ? 1 : 0;
1030
+ const total = contract.rules.length + (branches.length > 0 ? 1 : 0);
1031
+ const passCount = Object.values(scores).filter((s) => s === 1).length;
1032
+ const assumptions = [];
1033
+ for (const rule of [...contract.rules, ...branches.flatMap((b) => b.alternative.rules)]) if (rulePredicates(rule).some(usesCustom)) assumptions.push(`rule '${rule.label}' rests on a custom predicate function`);
1034
+ return {
1035
+ contract: contract.name,
1036
+ status,
1037
+ valid: status === "pass",
1038
+ score: passCount / total,
1039
+ scores,
1040
+ violations,
1041
+ ruleExecutions,
1042
+ errors,
1043
+ notes: `${passCount}/${total} rules passed` + (errors.length > 0 ? `; ${errors.length} could not be evaluated` : ""),
1044
+ certification: {
1045
+ strategy: "invariant",
1046
+ checker: {
1047
+ name: "agent-eval:trace-contracts",
1048
+ version: packageVersion()
1049
+ },
1050
+ assumptions,
1051
+ evidenceDigest: certificationEvidenceDigest({
1052
+ contract: contract.name,
1053
+ status,
1054
+ scores,
1055
+ violations,
1056
+ ruleExecutions
1057
+ })
1058
+ }
1059
+ };
1060
+ }
1061
+ function execution(rule, alternative, outcome) {
1062
+ return {
1063
+ rule,
1064
+ ...alternative === void 0 ? {} : { alternative },
1065
+ status: outcome.status,
1066
+ violations: outcome.violations.length,
1067
+ ...outcome.error === void 0 ? {} : { error: outcome.error }
1068
+ };
1069
+ }
1070
+ function rulePredicates(rule) {
1071
+ switch (rule.kind) {
1072
+ case "precedes": return [rule.a, rule.b];
1073
+ case "neverUnless": return [rule.p, rule.prior];
1074
+ case "run":
1075
+ case "toolsOffered":
1076
+ case "retrySafe": return [];
1077
+ default: return [rule.p];
1078
+ }
1079
+ }
1080
+ function usesCustom(p) {
1081
+ return typeof p.custom === "function" || p.not !== void 0 && usesCustom(p.not);
1082
+ }
1083
+ /**
1084
+ * Evaluate many contracts over one span sequence. Throws on an empty
1085
+ * contract list — `allValid: true` over zero contracts is a silent pass.
1086
+ */
1087
+ function checkTraceContracts(spans, contracts, options = {}) {
1088
+ if (contracts.length === 0) throw new ValidationError("checkTraceContracts: empty contract list would vacuously pass — supply at least one contract");
1089
+ const verdicts = contracts.map((c) => evaluateTraceContract(c, spans, options));
1090
+ const status = verdicts.some((v) => v.status === "error") ? "error" : verdicts.every((v) => v.status === "pass") ? "pass" : "fail";
1091
+ return {
1092
+ verdicts,
1093
+ status,
1094
+ allValid: status === "pass"
1095
+ };
1096
+ }
1097
+ // src/trace-contracts/harness-session.ts
1098
+ function epochMs(at) {
1099
+ if (at === null) return void 0;
1100
+ const value = Date.parse(at);
1101
+ return Number.isFinite(value) ? value : void 0;
1102
+ }
1103
+ function timed(start, end) {
1104
+ const startedAt = epochMs(start);
1105
+ const endedAt = epochMs(end) ?? startedAt;
1106
+ return {
1107
+ ...startedAt === void 0 ? {} : { startedAt },
1108
+ ...endedAt === void 0 ? {} : { endedAt }
1109
+ };
1110
+ }
1111
+ function contractSpansFromHarnessSession(session) {
1112
+ const root = `session:${session.nativeSessionId}`;
1113
+ const spans = [{
1114
+ spanId: root,
1115
+ parentSpanId: null,
1116
+ name: "session",
1117
+ kind: "AGENT",
1118
+ ...timed(session.startedAt, session.endedAt),
1119
+ attributes: { "session.harness": session.harness }
1120
+ }];
1121
+ const calls = new Map(session.toolCalls.map((call) => [call.id, call]));
1122
+ const placed = /* @__PURE__ */ new Set();
1123
+ const toolSpan = (id) => {
1124
+ const call = calls.get(id);
1125
+ if (call === void 0 || placed.has(id) || call.inherited === true) return;
1126
+ placed.add(id);
1127
+ const input = call.inputText ?? JSON.stringify(call.input ?? null);
1128
+ spans.push({
1129
+ spanId: `tool:${call.id}`,
1130
+ parentSpanId: root,
1131
+ name: call.name,
1132
+ kind: "TOOL",
1133
+ toolName: call.name,
1134
+ ...timed(call.startedAt, call.endedAt ?? call.result?.at ?? null),
1135
+ ...call.status === "error" || call.result?.isError === true ? { status: "error" } : call.status === "completed" ? { status: "ok" } : {},
1136
+ args: call.input,
1137
+ attributes: {
1138
+ "input.value": input,
1139
+ ...call.result?.text ? { "output.value": call.result.text } : {}
1140
+ }
1141
+ });
1142
+ };
1143
+ for (const message of session.messages) {
1144
+ if (message.inherited === true || message.role !== "assistant") continue;
1145
+ const text = message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n").trim();
1146
+ if (text !== "") spans.push({
1147
+ spanId: `llm:${message.id}`,
1148
+ parentSpanId: root,
1149
+ name: "llm.call",
1150
+ kind: "LLM",
1151
+ ...timed(message.at, message.at),
1152
+ attributes: { "output.value": text }
1153
+ });
1154
+ for (const part of message.parts) if (part.type === "tool-call") toolSpan(part.toolCallId);
1155
+ }
1156
+ for (const call of session.toolCalls) toolSpan(call.id);
1157
+ return spans;
1158
+ }
1159
+ /**
1160
+ * Decode a submitted findings value into accepted rows plus per-row
1161
+ * diagnostics.
1162
+ *
1163
+ * Accepts an array of rows, or a string carrying one (a JSON array, possibly
1164
+ * fenced). Anything else — an object, a number, null, undefined — sets
1165
+ * `topLevelError` naming the type received: a caller that asked for findings
1166
+ * and got a number has a defect to report, not an empty result to record.
1167
+ */
1168
+ function decodeRawFindingArray(value) {
1169
+ const rows = findingRows(value);
1170
+ if (typeof rows === "string") return {
1171
+ accepted: [],
1172
+ rejected: [],
1173
+ topLevelError: rows
1174
+ };
1175
+ const accepted = [];
1176
+ const rejected = [];
1177
+ for (const [index, row] of rows.entries()) {
1178
+ if (index >= 500) {
1179
+ rejected.push({
1180
+ index,
1181
+ path: "",
1182
+ code: "row-limit",
1183
+ message: `findings array exceeds 500 rows`
1184
+ });
1185
+ continue;
1186
+ }
1187
+ const decoded = decodeRow(row, index);
1188
+ if ("finding" in decoded) accepted.push(decoded.finding);
1189
+ else rejected.push(decoded.rejection);
1190
+ }
1191
+ return {
1192
+ accepted,
1193
+ rejected
1194
+ };
1195
+ }
1196
+ function decodeRow(row, index) {
1197
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return { rejection: {
1198
+ index,
1199
+ path: "",
1200
+ code: "not-an-object",
1201
+ message: `finding row must be an object, received ${describe(row)}`
1202
+ } };
1203
+ const parsed = RawAnalystFindingSchema.safeParse(row);
1204
+ if (!parsed.success) {
1205
+ const issue = parsed.error.issues[0];
1206
+ const path = (issue?.path ?? []).join(".");
1207
+ return { rejection: {
1208
+ index,
1209
+ path,
1210
+ code: path === "subject" && parseFindingSubject(row.subject) === null ? "invalid-subject" : "schema",
1211
+ message: issue?.message ?? "row does not match the schema"
1212
+ } };
1213
+ }
1214
+ return { finding: parsed.data };
1215
+ }
1216
+ /**
1217
+ * Narrow a submitted value to candidate rows, or return the message naming why
1218
+ * it is not a findings array at all.
1219
+ */
1220
+ function findingRows(value) {
1221
+ if (Array.isArray(value)) return value;
1222
+ if (typeof value === "string") {
1223
+ const parsed = coerceJson(value);
1224
+ if (parsed === void 0) return "findings must be a JSON array; the string received is not JSON";
1225
+ if (Array.isArray(parsed)) return parsed;
1226
+ const unwrapped = findingsProperty(parsed);
1227
+ if (unwrapped !== void 0) return unwrapped;
1228
+ return `findings must be a JSON array, received ${describe(parsed)}`;
1229
+ }
1230
+ const unwrapped = findingsProperty(value);
1231
+ if (unwrapped !== void 0) return unwrapped;
1232
+ return `findings must be an array, received ${describe(value)}`;
1233
+ }
1234
+ /** `{ findings: [...] }` is the one wrapper models emit often enough to unwrap. */
1235
+ function findingsProperty(value) {
1236
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
1237
+ const inner = value.findings;
1238
+ return Array.isArray(inner) ? inner : void 0;
1239
+ }
1240
+ function describe(value) {
1241
+ if (value === null) return "null";
1242
+ if (Array.isArray(value)) return "an array";
1243
+ return `a ${typeof value}`;
1244
+ }
1245
+ // src/analyst/trace-tool-callback.ts
1246
+ /** Expose one bounded trace-tool set only on an authenticated loopback socket. */
1247
+ async function startTraceToolCallback(args) {
1248
+ if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) throw new TypeError("trace tool callback maxCalls must be a positive safe integer");
1249
+ const limits = resolveExternalOptimizerCallbackLimits(args.limits, "trace tool callback limits");
1250
+ args.signal?.throwIfAborted();
1251
+ const byName = new Map(args.tools.map((tool) => [tool.name, tool]));
1252
+ if (byName.size !== args.tools.length) throw new Error("trace tool callback received duplicate tool names");
1253
+ const token = randomBytes(32).toString("hex");
1254
+ let calls = 0;
1255
+ let accepting = true;
1256
+ let closePromise;
1257
+ const activeControllers = /* @__PURE__ */ new Set();
1258
+ const activeHandlers = /* @__PURE__ */ new Set();
1259
+ const server = createServer((request, response) => {
1260
+ if (!accepting) {
1261
+ sendJsonIfOpen(response, 503, { error: "trace tool callback is closing" });
1262
+ return;
1263
+ }
1264
+ const controller = new AbortController();
1265
+ const abortRequest = () => {
1266
+ request.destroy();
1267
+ response.destroy();
1268
+ };
1269
+ activeControllers.add(controller);
1270
+ controller.signal.addEventListener("abort", abortRequest, { once: true });
1271
+ let handler;
1272
+ handler = handleRequest(request, response, controller.signal).finally(() => {
1273
+ controller.signal.removeEventListener("abort", abortRequest);
1274
+ activeControllers.delete(controller);
1275
+ activeHandlers.delete(handler);
1276
+ });
1277
+ activeHandlers.add(handler);
1278
+ handler.catch(() => void 0);
1279
+ });
1280
+ const port = await listenLocal(server);
1281
+ const close = () => {
1282
+ closePromise ??= closeCallback();
1283
+ return closePromise;
1284
+ };
1285
+ const onAbort = () => {
1286
+ close().catch(() => void 0);
1287
+ };
1288
+ args.signal?.addEventListener("abort", onAbort, { once: true });
1289
+ if (args.signal?.aborted) onAbort();
1290
+ return {
1291
+ url: `http://127.0.0.1:${port}/call`,
1292
+ token,
1293
+ calls: () => calls,
1294
+ close
1295
+ };
1296
+ async function handleRequest(request, response, signal) {
1297
+ try {
1298
+ if (request.method !== "POST" || request.url !== "/call") {
1299
+ sendJsonIfOpen(response, 404, { error: "not found" });
1300
+ return;
1301
+ }
1302
+ if (request.headers.authorization !== `Bearer ${token}`) {
1303
+ sendJsonIfOpen(response, 401, { error: "unauthorized" });
1304
+ return;
1305
+ }
1306
+ if (calls >= args.maxCalls) {
1307
+ sendJsonIfOpen(response, 429, { error: "trace tool call limit reached" });
1308
+ return;
1309
+ }
1310
+ const body = await readJson(request, limits.maxRequestBytes);
1311
+ if (!isRecord(body) || typeof body.name !== "string" || !("args" in body)) {
1312
+ sendJsonIfOpen(response, 400, { error: "name and args are required" });
1313
+ return;
1314
+ }
1315
+ const tool = byName.get(body.name);
1316
+ if (!tool) {
1317
+ sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` });
1318
+ return;
1319
+ }
1320
+ calls += 1;
1321
+ const result = await tool.handler(body.args, { signal });
1322
+ const encoded = JSON.stringify({ result });
1323
+ if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {
1324
+ sendJsonIfOpen(response, 413, { error: "trace tool response too large" });
1325
+ return;
1326
+ }
1327
+ response.writeHead(200, {
1328
+ "content-type": "application/json; charset=utf-8",
1329
+ "content-length": String(Buffer.byteLength(encoded))
1330
+ });
1331
+ response.end(encoded);
1332
+ } catch (error) {
1333
+ sendJsonIfOpen(response, signal.aborted ? 499 : 400, { error: error instanceof Error ? error.message : String(error) });
1334
+ }
1335
+ }
1336
+ async function closeCallback() {
1337
+ args.signal?.removeEventListener("abort", onAbort);
1338
+ accepting = false;
1339
+ const closingServer = closeServer(server);
1340
+ server.closeIdleConnections?.();
1341
+ for (const controller of activeControllers) controller.abort();
1342
+ const [serverResult] = await Promise.allSettled([closingServer, waitForActiveHandlers(activeHandlers)]);
1343
+ if (activeControllers.size !== 0 || activeHandlers.size !== 0) throw new Error("trace tool callback closed with active requests");
1344
+ if (serverResult?.status === "rejected") throw serverResult.reason;
1345
+ }
1346
+ }
1347
+ function readJson(request, maxRequestBytes) {
1348
+ return new Promise((resolve, reject) => {
1349
+ let size = 0;
1350
+ const chunks = [];
1351
+ request.on("data", (chunk) => {
1352
+ size += chunk.length;
1353
+ if (size > maxRequestBytes) {
1354
+ reject(/* @__PURE__ */ new Error("trace tool request too large"));
1355
+ request.destroy();
1356
+ return;
1357
+ }
1358
+ chunks.push(chunk);
1359
+ });
1360
+ request.on("error", reject);
1361
+ request.on("end", () => {
1362
+ try {
1363
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
1364
+ } catch (error) {
1365
+ reject(error);
1366
+ }
1367
+ });
1368
+ });
1369
+ }
1370
+ // src/analyst/dspy-rlm-engine.ts
1371
+ const DEFAULT_TIMEOUT_MS = 6e5;
1372
+ const DEFAULT_MAX_COST_USD = 1;
1373
+ const DEFAULT_MAX_MODEL_REQUEST_BYTES = 16777216;
1374
+ const DEFAULT_MAX_MODEL_RESPONSE_BYTES = 4194304;
1375
+ const DEFAULT_TRACE_TOOL_TIMEOUT_MS = 6e4;
1376
+ const MAX_TIMER_DELAY_MS = 2147483647;
1377
+ const BRIDGE_MODULE = "agent_eval_rpc.dspy_rlm_bridge";
1378
+ /** Bumped whenever this engine's execution behavior changes. */
1379
+ const DSPY_RLM_ENGINE_VERSION = "2.0.2";
1380
+ /** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */
1381
+ function createDspyRlmTraceEngine(options) {
1382
+ assertOptions(options);
1383
+ const maxOutputTokens = options.maxOutputTokens ?? 16384;
1384
+ if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) throw new TypeError("DSPy RLM maxOutputTokens must be a positive safe integer");
1385
+ const controlAdapter = options.controlAdapter ?? "tolerant";
1386
+ const maxReasoningTokens = options.maxReasoningTokens ?? maxOutputTokens * 4;
1387
+ if (!Number.isSafeInteger(maxReasoningTokens) || maxReasoningTokens < 0) throw new TypeError("DSPy RLM maxReasoningTokens must be a non-negative safe integer");
1388
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1389
+ assertTimerDelay(timeoutMs, "timeoutMs");
1390
+ const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD;
1391
+ if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) throw new TypeError("DSPy RLM maxCostUsd must be positive and finite");
1392
+ const pricing = options.pricing ?? pricingForModel(options.model);
1393
+ const maxModelRequestBytes = options.maxModelRequestBytes ?? DEFAULT_MAX_MODEL_REQUEST_BYTES;
1394
+ const maxModelResponseBytes = options.maxModelResponseBytes ?? DEFAULT_MAX_MODEL_RESPONSE_BYTES;
1395
+ const modelRequestTimeoutMs = options.modelRequestTimeoutMs ?? timeoutMs;
1396
+ const traceToolTimeoutMs = options.traceToolTimeoutMs ?? DEFAULT_TRACE_TOOL_TIMEOUT_MS;
1397
+ assertExternalOptimizerModelBudget({
1398
+ maxCostUsd,
1399
+ maxRequests: options.maxModelRequests ?? 1,
1400
+ maxRequestBytes: maxModelRequestBytes,
1401
+ maxResponseBytes: maxModelResponseBytes,
1402
+ maxOutputTokensPerRequest: maxOutputTokens,
1403
+ maxReasoningTokensPerRequest: maxReasoningTokens,
1404
+ pricing,
1405
+ requestTimeoutMs: modelRequestTimeoutMs
1406
+ }, "DSPy RLM model limits");
1407
+ resolveExternalOptimizerCallbackLimits(options.traceToolLimits, "DSPy RLM trace tool limits");
1408
+ assertTimerDelay(traceToolTimeoutMs, "traceToolTimeoutMs");
1409
+ const runner = sanitizedRunner(options.runner);
1410
+ const processLimits = resolveExternalOptimizerProcessLimits(runner?.limits);
1411
+ return {
1412
+ id: "dspy-rlm",
1413
+ description: "Official DSPy RLM with bounded trace tools and metered model calls.",
1414
+ model: options.model,
1415
+ version: DSPY_RLM_ENGINE_VERSION,
1416
+ executionConfig: {
1417
+ bridge_module: BRIDGE_MODULE,
1418
+ call_ref: options.callRef,
1419
+ model: options.model,
1420
+ pricing: { ...pricing },
1421
+ max_cost_usd: maxCostUsd,
1422
+ max_output_tokens: maxOutputTokens,
1423
+ max_reasoning_tokens: maxReasoningTokens,
1424
+ control_adapter: controlAdapter,
1425
+ timeout_ms: timeoutMs,
1426
+ max_model_requests: options.maxModelRequests ?? null,
1427
+ max_request_bytes: maxModelRequestBytes,
1428
+ max_response_bytes: maxModelResponseBytes,
1429
+ model_request_timeout_ms: modelRequestTimeoutMs,
1430
+ trace_tool_limits: options.traceToolLimits ?? null,
1431
+ trace_tool_timeout_ms: traceToolTimeoutMs,
1432
+ process_limits: processLimits,
1433
+ runner: runner ? "caller-supplied" : "default",
1434
+ runner_command: runner?.command ?? null
1435
+ },
1436
+ async analyze(request) {
1437
+ const callback = await startTraceToolCallback({
1438
+ tools: request.tools,
1439
+ maxCalls: request.limits.maxToolCalls,
1440
+ ...options.traceToolLimits ? { limits: options.traceToolLimits } : {},
1441
+ ...request.signal ? { signal: request.signal } : {}
1442
+ });
1443
+ let modelProxy;
1444
+ const modelExecutions = [];
1445
+ const result = await runWithCleanup({
1446
+ label: "DSPy RLM trace-analysis resources",
1447
+ run: async () => {
1448
+ modelProxy = await startExternalOptimizerModelProxy({
1449
+ call: options.call,
1450
+ callRef: options.callRef,
1451
+ recordExecution: (observation) => {
1452
+ modelExecutions.push(structuredClone(observation));
1453
+ options.recordExecution(observation);
1454
+ },
1455
+ model: options.model,
1456
+ budget: {
1457
+ maxCostUsd,
1458
+ maxRequests: resolveMaxModelRequests(options.maxModelRequests, request.limits),
1459
+ maxRequestBytes: maxModelRequestBytes,
1460
+ maxResponseBytes: maxModelResponseBytes,
1461
+ maxOutputTokensPerRequest: maxOutputTokens,
1462
+ maxReasoningTokensPerRequest: maxReasoningTokens,
1463
+ requestTimeoutMs: modelRequestTimeoutMs,
1464
+ pricing
1465
+ },
1466
+ costLedger: request.costLedger,
1467
+ channel: "analyst",
1468
+ phase: request.costPhase,
1469
+ actor: request.analystId,
1470
+ ...request.costTags ? { tags: request.costTags } : {},
1471
+ ...request.signal ? { signal: request.signal } : {}
1472
+ });
1473
+ request.log?.("trace analyst engine started", {
1474
+ engine: "dspy-rlm",
1475
+ model: options.model,
1476
+ tools: request.tools.map((tool) => tool.name),
1477
+ limits: request.limits
1478
+ });
1479
+ const parsed = parseBridgeOutput(await runExternalOptimizerProcess({
1480
+ label: "DSPy RLM trace analysis",
1481
+ tempPrefix: "agent-eval-dspy-rlm-",
1482
+ module: BRIDGE_MODULE,
1483
+ input: {
1484
+ operation: "analyze",
1485
+ question: request.question,
1486
+ instructions: request.instructions,
1487
+ modelProxy: {
1488
+ baseUrl: modelProxy.baseUrl,
1489
+ apiKey: modelProxy.apiKey,
1490
+ model: options.model,
1491
+ maxOutputTokens
1492
+ },
1493
+ toolCallback: {
1494
+ url: callback.url,
1495
+ token: callback.token,
1496
+ timeoutMs: traceToolTimeoutMs
1497
+ },
1498
+ toolSpecs: request.tools.map(({ name, description, parameters }) => ({
1499
+ name,
1500
+ description,
1501
+ parameters
1502
+ })),
1503
+ controlAdapter,
1504
+ limits: {
1505
+ maxIterations: request.limits.maxIterations,
1506
+ maxLlmCalls: request.limits.maxLlmCalls,
1507
+ maxOutputChars: request.limits.maxOutputChars
1508
+ },
1509
+ ...request.taskInputs ? { taskInputs: request.taskInputs } : {}
1510
+ },
1511
+ ...runner ? { runner } : {},
1512
+ additionalArgs: ["--max-input-bytes", String(processLimits.maxInputBytes)],
1513
+ timeoutMs,
1514
+ ...request.signal ? { signal: request.signal } : {}
1515
+ }), (index, reason) => {
1516
+ request.log?.("finding rejected: bridge row failed schema validation", {
1517
+ engine: "dspy-rlm",
1518
+ index,
1519
+ reason
1520
+ });
1521
+ });
1522
+ const successfulCompletions = modelProxy.successfulCompletions();
1523
+ const requestAttempts = modelProxy.requestAttempts();
1524
+ if (parsed.modelCalls !== successfulCompletions) throw new Error(`DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`);
1525
+ modelProxy.assertExecutionComplete();
1526
+ return {
1527
+ ...parsed,
1528
+ toolCalls: callback.calls(),
1529
+ runtime: {
1530
+ ...parsed.runtime,
1531
+ modelRequestAttempts: requestAttempts,
1532
+ modelSuccessfulCompletions: successfulCompletions,
1533
+ modelExecutions
1534
+ }
1535
+ };
1536
+ },
1537
+ cleanup: async () => {
1538
+ const errors = (await Promise.allSettled([...modelProxy ? [modelProxy.close()] : [], callback.close()])).flatMap((entry) => entry.status === "rejected" ? [entry.reason] : []);
1539
+ if (errors.length > 0) throw new AggregateError(errors, "DSPy RLM resource cleanup failed");
1540
+ if (modelProxy) request.recordActivity?.({
1541
+ modelCalls: modelProxy.successfulCompletions(),
1542
+ toolCalls: callback.calls()
1543
+ });
1544
+ }
1545
+ });
1546
+ request.log?.("trace analyst engine completed", {
1547
+ engine: "dspy-rlm",
1548
+ model_calls: result.modelCalls,
1549
+ model_request_attempts: result.runtime.modelRequestAttempts,
1550
+ tool_calls: result.toolCalls,
1551
+ findings: result.findings.length
1552
+ });
1553
+ return result;
1554
+ }
1555
+ };
1556
+ }
1557
+ function parseBridgeOutput(value, onRejectedFinding) {
1558
+ if (!isRecord(value)) throw new Error("DSPy RLM bridge output must be an object");
1559
+ if (typeof value.answer !== "string" || !value.answer.trim()) throw new Error("DSPy RLM bridge returned no answer");
1560
+ const decoded = decodeRawFindingArray(value.findings);
1561
+ if (decoded.topLevelError !== void 0) throw new Error(`DSPy RLM bridge findings must be an array: ${decoded.topLevelError}`);
1562
+ const findings = decoded.accepted;
1563
+ const rejectedFindings = decoded.rejected.length;
1564
+ for (const rejection of decoded.rejected) onRejectedFinding(rejection.index, `${rejection.code}${rejection.path ? ` at ${rejection.path}` : ""}: ${rejection.message}`);
1565
+ if (!Array.isArray(value.trajectory)) throw new Error("DSPy RLM bridge trajectory must be an array");
1566
+ if (!Number.isSafeInteger(value.modelCalls) || value.modelCalls <= 0) throw new Error("DSPy RLM bridge modelCalls must be a positive safe integer");
1567
+ if (!isRecord(value.runtime)) throw new Error("DSPy RLM bridge runtime must be an object");
1568
+ return {
1569
+ answer: value.answer,
1570
+ findings,
1571
+ trajectory: value.trajectory,
1572
+ modelCalls: value.modelCalls,
1573
+ runtime: {
1574
+ ...value.runtime,
1575
+ rejectedFindings
1576
+ }
1577
+ };
1578
+ }
1579
+ function assertOptions(options) {
1580
+ for (const [name, value] of [["callRef", options.callRef], ["model", options.model]]) if (typeof value !== "string" || !value.trim() || value !== value.trim()) throw new TypeError(`DSPy RLM ${name} must be a trimmed non-empty string`);
1581
+ if (typeof options.call !== "function") throw new TypeError("DSPy RLM call must be a function");
1582
+ if (typeof options.recordExecution !== "function") throw new TypeError("DSPy RLM recordExecution must be a function");
1583
+ if (options.maxModelRequests !== void 0 && (!Number.isSafeInteger(options.maxModelRequests) || options.maxModelRequests <= 0)) throw new TypeError("DSPy RLM maxModelRequests must be a positive safe integer");
1584
+ }
1585
+ function resolveMaxModelRequests(configured, limits) {
1586
+ if (configured !== void 0) return configured;
1587
+ const derived = limits.maxIterations + limits.maxLlmCalls + 1;
1588
+ if (!Number.isSafeInteger(derived) || derived <= 0) throw new Error("DSPy RLM analysis limits produce an invalid model request limit");
1589
+ return derived;
1590
+ }
1591
+ function assertTimerDelay(value, field) {
1592
+ if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) throw new TypeError(`DSPy RLM ${field} must be between 1 and ${MAX_TIMER_DELAY_MS}`);
1593
+ }
1594
+ function pricingForModel(model) {
1595
+ const pricing = resolveModelPricing(model);
1596
+ if (!pricing) throw new Error(`no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`);
1597
+ return {
1598
+ inputUsdPerMillion: pricing.input * 1e3,
1599
+ outputUsdPerMillion: pricing.output * 1e3
1600
+ };
1601
+ }
1602
+ function sanitizedRunner(runner) {
1603
+ if (!runner) return void 0;
1604
+ return {
1605
+ ...runner.command ? { command: runner.command } : {},
1606
+ ...runner.args ? { args: runner.args } : {},
1607
+ ...runner.env ? { env: removeCredentialEnvironment(runner.env) } : {},
1608
+ ...runner.limits ? { limits: { ...runner.limits } } : {}
1609
+ };
1610
+ }
1611
+ export { normalizePredicate as _, evaluateTraceContract as a, explainTraceContract as c, assertOrder as d, assertRule as f, RUN_STATUSES as g, ORDER_MODES as h, checkTraceContracts as i, assertContract as l, ARGUMENT_TYPES as m, decodeRawFindingArray as n, describeCheck as o, ARGUMENT_OCCURRENCES as p, contractSpansFromHarnessSession as r, describePredicate as s, createDspyRlmTraceEngine as t, assertCount as u };
1612
+
1613
+ //# sourceMappingURL=dspy-rlm-engine-DFgGrKzg.js.map