@tangle-network/agent-eval 0.85.0 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/adapters/http.d.ts +3 -3
  3. package/dist/adapters/langchain.d.ts +3 -3
  4. package/dist/adapters/otel.d.ts +6 -6
  5. package/dist/adversarial-DIVcDoI_.d.ts +88 -0
  6. package/dist/analyst/index.d.ts +11 -10
  7. package/dist/analyst/index.js +13 -8
  8. package/dist/analyst/index.js.map +1 -1
  9. package/dist/analyze-runs-DwCEkpO_.d.ts +81 -0
  10. package/dist/belief-state/index.d.ts +4 -4
  11. package/dist/belief-state/index.js +1 -1
  12. package/dist/benchmarks/index.d.ts +3 -3
  13. package/dist/campaign/index.d.ts +165 -18
  14. package/dist/campaign/index.js +289 -14
  15. package/dist/campaign/index.js.map +1 -1
  16. package/dist/chunk-45EEMHTC.js +35 -0
  17. package/dist/chunk-45EEMHTC.js.map +1 -0
  18. package/dist/{chunk-FZWAFVAA.js → chunk-4FBZZIYD.js} +2 -2
  19. package/dist/{chunk-YV7J7X5N.js → chunk-5HRORJQY.js} +22 -12
  20. package/dist/chunk-5HRORJQY.js.map +1 -0
  21. package/dist/{chunk-OTYQPHPL.js → chunk-6SOJM3VR.js} +5 -5
  22. package/dist/chunk-BOD4O7OF.js +40 -0
  23. package/dist/chunk-BOD4O7OF.js.map +1 -0
  24. package/dist/{chunk-Z7VFTS2J.js → chunk-CY6U5S3X.js} +2 -2
  25. package/dist/{chunk-VIDQF3F5.js → chunk-D3V5B42D.js} +5 -34
  26. package/dist/chunk-D3V5B42D.js.map +1 -0
  27. package/dist/{chunk-YGYXHNAQ.js → chunk-FIUKOSWI.js} +21 -8
  28. package/dist/chunk-FIUKOSWI.js.map +1 -0
  29. package/dist/{chunk-WJL2NJXN.js → chunk-GSH6QNNS.js} +2 -2
  30. package/dist/{chunk-RBNA5AZT.js → chunk-L3JOU6XM.js} +2 -2
  31. package/dist/{chunk-IDVBLYCY.js → chunk-LMZQ2Z4U.js} +56 -2
  32. package/dist/{chunk-IDVBLYCY.js.map → chunk-LMZQ2Z4U.js.map} +1 -1
  33. package/dist/{chunk-VUINJM5M.js → chunk-QAY5UIJO.js} +2 -193
  34. package/dist/chunk-QAY5UIJO.js.map +1 -0
  35. package/dist/{chunk-XQL22JDG.js → chunk-QG2OVF2D.js} +101 -7
  36. package/dist/chunk-QG2OVF2D.js.map +1 -0
  37. package/dist/chunk-REVYNR6C.js +100 -0
  38. package/dist/chunk-REVYNR6C.js.map +1 -0
  39. package/dist/{chunk-ZZ2HOPME.js → chunk-TWS7AZEY.js} +2 -2
  40. package/dist/chunk-UHMJT4T7.js +200 -0
  41. package/dist/chunk-UHMJT4T7.js.map +1 -0
  42. package/dist/chunk-UMMZHCPB.js +190 -0
  43. package/dist/chunk-UMMZHCPB.js.map +1 -0
  44. package/dist/chunk-VZSRQ272.js +149 -0
  45. package/dist/chunk-VZSRQ272.js.map +1 -0
  46. package/dist/{chunk-L5G7OUKD.js → chunk-XY4DDNEG.js} +8 -190
  47. package/dist/chunk-XY4DDNEG.js.map +1 -0
  48. package/dist/chunk-Y47J2LJ3.js +859 -0
  49. package/dist/chunk-Y47J2LJ3.js.map +1 -0
  50. package/dist/{chunk-BABOZOSN.js → chunk-ZFIBGEOL.js} +3 -3
  51. package/dist/chunk-ZFIBGEOL.js.map +1 -0
  52. package/dist/{code-agent-session-BRXmavYv.d.ts → code-agent-session-BO8nCnv3.d.ts} +1 -1
  53. package/dist/contract/index.d.ts +24 -95
  54. package/dist/contract/index.js +16 -755
  55. package/dist/contract/index.js.map +1 -1
  56. package/dist/{control-GeE8OhpN.d.ts → control-_Qb7skHX.d.ts} +2 -2
  57. package/dist/control.d.ts +5 -5
  58. package/dist/corpus-BoR-041R.d.ts +560 -0
  59. package/dist/cost-ledger-DuSqlw5B.d.ts +113 -0
  60. package/dist/counterfactual-Dwibr5IW.d.ts +85 -0
  61. package/dist/{dataset-B2kL-fSM.d.ts → dataset-BbGkaN2I.d.ts} +1 -1
  62. package/dist/{registry-DrEQ3Luj.d.ts → default-registry-zoGHUQEH.d.ts} +29 -2
  63. package/dist/diagnose.d.ts +251 -0
  64. package/dist/diagnose.js +381 -0
  65. package/dist/diagnose.js.map +1 -0
  66. package/dist/{errors-Dwqw-T_m.d.ts → errors-CzMUYo7b.d.ts} +1 -1
  67. package/dist/{feedback-trajectory-B3rErRsh.d.ts → feedback-trajectory-D9OVLrg9.d.ts} +1 -1
  68. package/dist/fuzz.d.ts +484 -0
  69. package/dist/fuzz.js +613 -0
  70. package/dist/fuzz.js.map +1 -0
  71. package/dist/governance/index.d.ts +4 -4
  72. package/dist/hosted/index.d.ts +6 -6
  73. package/dist/{index-DE3RXAXD.d.ts → index-Bx3gZ8xl.d.ts} +1 -1
  74. package/dist/index.d.ts +1073 -344
  75. package/dist/index.js +2099 -689
  76. package/dist/index.js.map +1 -1
  77. package/dist/{insight-report-3ADTfClO.d.ts → insight-report-BBwvOh6x.d.ts} +2 -2
  78. package/dist/{integrity-CJzrpUua.d.ts → integrity-VJ9A7aST.d.ts} +1 -1
  79. package/dist/{judge-calibration-DilmB3Ml.d.ts → judge-calibration-0p2QcWNE.d.ts} +1 -1
  80. package/dist/{kind-factory-CVecZZG_.d.ts → kind-factory-5b7xXXOr.d.ts} +2 -2
  81. package/dist/{llm-client-CuUg2Mn3.d.ts → llm-client-BeEcAokY.d.ts} +1 -1
  82. package/dist/matrix/index.d.ts +2 -2
  83. package/dist/meta-eval/index.d.ts +177 -3
  84. package/dist/meta-eval/index.js +260 -1
  85. package/dist/meta-eval/index.js.map +1 -1
  86. package/dist/{multi-layer-verifier-DlWCXuxL.d.ts → multi-layer-verifier-DUZXrPDA.d.ts} +7 -1
  87. package/dist/multishot/index.d.ts +25 -11
  88. package/dist/multishot/index.js +36 -7
  89. package/dist/multishot/index.js.map +1 -1
  90. package/dist/openapi.json +1 -1
  91. package/dist/pipelines/index.js +2 -2
  92. package/dist/{agent-profile-D0PBIWlV.d.ts → pre-registration-DELOEJ8v.d.ts} +144 -4
  93. package/dist/{provenance-DPpNIOJD.d.ts → provenance-LnqRT0sS.d.ts} +5 -5
  94. package/dist/{red-team-DW9Ca_tj.d.ts → red-team-BXHil6c8.d.ts} +1 -1
  95. package/dist/{release-report-hlNtD12q.d.ts → release-report-euXIV_Sk.d.ts} +3 -3
  96. package/dist/reporting.d.ts +8 -8
  97. package/dist/reporting.js +3 -3
  98. package/dist/{researcher-BLPHBbNV.d.ts → researcher-DE6Gpnb4.d.ts} +4 -4
  99. package/dist/rl.d.ts +194 -656
  100. package/dist/rl.js +236 -154
  101. package/dist/rl.js.map +1 -1
  102. package/dist/{rubric-predictive-validity-CnEl9Jc8.d.ts → rubric-predictive-validity-Cy_W-hWZ.d.ts} +1 -1
  103. package/dist/{run-campaign-4Y5V5CN3.js → run-campaign-RDGAM5KJ.js} +3 -3
  104. package/dist/{run-improvement-loop-CNqQckTj.d.ts → run-improvement-loop-5z_l5zDz.d.ts} +2 -2
  105. package/dist/{run-record-De9VarXR.d.ts → run-record-e7vj1uZQ.d.ts} +1 -1
  106. package/dist/{runtime-trajectory-BLRiaifm.d.ts → runtime-trajectory-BDgfGZSr.d.ts} +1 -1
  107. package/dist/{semantic-concept-judge-DIEgr_6v.d.ts → semantic-concept-judge-Dn8Z6KEG.d.ts} +5 -31
  108. package/dist/series-convergence-D5OWMBg6.d.ts +33 -0
  109. package/dist/{statistics-CnC1FMbx.d.ts → statistics-C7PozGrZ.d.ts} +71 -2
  110. package/dist/{summary-report-Db0dDSWP.d.ts → summary-report-DGmUucwQ.d.ts} +1 -1
  111. package/dist/traces.d.ts +58 -4
  112. package/dist/traces.js +14 -6
  113. package/dist/{types-Cu3u_x59.d.ts → types-2VVIL04s.d.ts} +2 -2
  114. package/dist/{types-D7lLRYe9.d.ts → types-BU-7W85F.d.ts} +21 -1
  115. package/dist/{types-CqPax19X.d.ts → types-mn5Aqk7x.d.ts} +1 -1
  116. package/dist/{verdict-CeEgtjyI.d.ts → verdict-C9MlYujm.d.ts} +3 -0
  117. package/dist/wire/index.d.ts +3 -3
  118. package/dist/workflow/index.d.ts +12 -11
  119. package/dist/workflow/index.js +1 -1
  120. package/package.json +36 -13
  121. package/dist/chunk-BABOZOSN.js.map +0 -1
  122. package/dist/chunk-L5G7OUKD.js.map +0 -1
  123. package/dist/chunk-SHTXZ4O2.js +0 -113
  124. package/dist/chunk-SHTXZ4O2.js.map +0 -1
  125. package/dist/chunk-VIDQF3F5.js.map +0 -1
  126. package/dist/chunk-VUINJM5M.js.map +0 -1
  127. package/dist/chunk-XQL22JDG.js.map +0 -1
  128. package/dist/chunk-YGYXHNAQ.js.map +0 -1
  129. package/dist/chunk-YV7J7X5N.js.map +0 -1
  130. /package/dist/{chunk-FZWAFVAA.js.map → chunk-4FBZZIYD.js.map} +0 -0
  131. /package/dist/{chunk-OTYQPHPL.js.map → chunk-6SOJM3VR.js.map} +0 -0
  132. /package/dist/{chunk-Z7VFTS2J.js.map → chunk-CY6U5S3X.js.map} +0 -0
  133. /package/dist/{chunk-WJL2NJXN.js.map → chunk-GSH6QNNS.js.map} +0 -0
  134. /package/dist/{chunk-RBNA5AZT.js.map → chunk-L3JOU6XM.js.map} +0 -0
  135. /package/dist/{chunk-ZZ2HOPME.js.map → chunk-TWS7AZEY.js.map} +0 -0
  136. /package/dist/{run-campaign-4Y5V5CN3.js.map → run-campaign-RDGAM5KJ.js.map} +0 -0
@@ -0,0 +1,200 @@
1
+ import {
2
+ OtlpFileTraceStore,
3
+ TraceFileMissingError,
4
+ buildTraceAnalystTools
5
+ } from "./chunk-QAY5UIJO.js";
6
+
7
+ // src/trace-analyst/prompts.ts
8
+ var TRACE_ANALYST_ACTOR_DESCRIPTION = `You answer questions about an OTLP-shaped JSONL trace dataset using the trace tools provided in the \`traces\` namespace.
9
+
10
+ DISCOVERY \u2192 NARROW \u2192 DEEP-READ protocol \u2014 follow exactly:
11
+
12
+ 1. ALWAYS call \`traces.getDatasetOverview({})\` FIRST without a regex_pattern. The result tells you total_traces, raw_jsonl_bytes, services, agents, models, and sample_trace_ids (real ids \u2014 never fabricate one).
13
+
14
+ 2. Use raw_jsonl_bytes to gauge how expensive raw scans will be. \`filters.regex_pattern\` is the one scan-heavy filter on getDatasetOverview / queryTraces / countTraces \u2014 narrow with indexed fields (has_errors, model_names, service_names, agent_names, time bounds) BEFORE adding a regex on a large dataset.
15
+
16
+ 3. To list more traces than the sample, call \`traces.queryTraces({ filters?, limit, offset? })\`. Each summary carries raw_jsonl_bytes \u2014 use it to choose between viewTrace and searchTrace BEFORE calling either.
17
+
18
+ 4. Per-trace inspection:
19
+ - SMALL trace (raw_jsonl_bytes well under 150_000): call \`traces.viewTrace({ trace_id })\`. Returns all spans. Per-attribute payloads are head-capped at ~4KB; large \`input.value\` / \`output.value\` / \`llm.input_messages\` will show a \`[trace-analyst truncated: N bytes]\` marker.
20
+ - LARGE trace (raw_jsonl_bytes near or above 150_000, or you saw an \`oversized\` response): use \`traces.searchTrace({ trace_id, regex_pattern })\` to get bounded SpanMatchRecords (span metadata + matched text + surrounding context). Then call \`traces.viewSpans({ trace_id, span_ids: [...] })\` for surgical reads (~16KB cap, 4\xD7 higher than discovery), or \`traces.searchSpan({ trace_id, span_id, regex_pattern })\` for one large span. Stays bounded regardless of trace size.
21
+ - Useful regex patterns: \`STATUS_CODE_ERROR\` (failures), tool names like \`grep\` or \`view_trace\`, error strings like \`MaxTurnsExceeded\`, model names, attribute keys.
22
+
23
+ 5. ONLY call viewTrace / viewSpans / searchTrace / searchSpan with trace/span ids you have already seen in sample_trace_ids, a queryTraces page, or a previous search result. Never invent ids.
24
+
25
+ 5a. **Result-shape contract** \u2014 searchTrace and searchSpan return \`{ trace_id, hits, total_matches, has_more }\`. Iterate \`result.hits\` (NOT result.matches). Each hit has \`{ span_id, span_name, span_kind, attribute_path, matched_text, context_before, context_after, match_offset }\`. viewTrace returns \`{ trace_id, spans }\` (or \`oversized\`). viewSpans returns \`{ trace_id, spans, missing_span_ids, truncated_attribute_count }\`. Never assume a field name \u2014 log the result shape first if unsure.
26
+
27
+ 6. If viewTrace returns an \`oversized\` summary instead of \`spans\`, DO NOT retry the same call. Read the summary's top_span_names, span_count, span_response_bytes_max, error_span_count to plan a follow-up: switch to searchTrace (or searchSpan for one large span), then viewSpans on a smaller, surgical span_ids set.
28
+
29
+ 7. If searchTrace or searchSpan returns has_more=true, REFINE the regex to be more specific rather than blindly raising max_matches.
30
+
31
+ 8. If a tool errors (invalid regex, range error), STOP and reconsider \u2014 don't retry with a guessed id or argument. Use the discovery tools above to recover.
32
+
33
+ 9. If a ~4KB-truncated payload from viewTrace / searchTrace matters for your answer, first try viewSpans on that span id (~16KB cap). If a 16KB-truncated payload from viewSpans still matters, narrow further with searchSpan against a more specific regex rather than asking for the full payload again.
34
+
35
+ 10. If maxDepth > 0 and the question splits into independent semantic branches, delegate well-defined subtasks to subagents using \`await llmQuery(...)\`. Pass narrow context and a focused query. Examples:
36
+
37
+ const reviews = await llmQuery([
38
+ { query: 'Drill into trace abc123 \u2014 what tool calls preceded the failure?', context: { trace_id: 'abc123' } },
39
+ { query: 'Drill into trace def456 \u2014 same failure mode?', context: { trace_id: 'def456' } },
40
+ ]);
41
+
42
+ OBSERVABILITY rules:
43
+ - Each non-final actor turn must emit at least one \`console.log(...)\` for evidence. Up to 3 logs per turn is fine when correlating multiple data sources (e.g. one log for findings list, one for source-file content, one for derived analysis).
44
+ - Do NOT combine \`console.log\` with \`final(...)\` or \`askClarification(...)\` in the same turn \u2014 finish gathering data first, then call final on its own turn.
45
+ - Reuse runtime variables across turns; don't recompute.
46
+ - When done, call \`await final(answer)\` with the fully-formed report. The responder rewrites the answer into output fields; if you only pass a vague summary string the responder has nothing concrete to format.
47
+
48
+ CRITICAL \u2014 \`final()\` payload contract for evidence-grounded analysis tasks:
49
+ - Pass a STRUCTURED object as the second arg with the actual data the responder needs to format the answer. Do NOT pass abstract instructions; pass evidence.
50
+ - Example for per-item verdict tasks:
51
+ \`\`\`js
52
+ await final("Format the per-item verdict report from the evidence below.", {
53
+ findings: [
54
+ { id: 'sub-1-finding-1', claim: '...', verdict: 'TRUE-POSITIVE', evidence: 'lines 42-45 of contracts/X.sol show ...' },
55
+ ...all items
56
+ ],
57
+ systemic_summary: '3 sentences I wrote based on the evidence above'
58
+ });
59
+ \`\`\`
60
+ - Calling \`final("answer", {})\` with no evidence is a failure mode \u2014 the responder will hallucinate or echo back the field names. Always include the gathered data.
61
+ - Premature final after a single viewSpans call is INSUFFICIENT for per-finding analysis tasks. Read the requested attributes (e.g. \`spans[i].attributes['redteam.finding.title']\`), and for each one perform the requested cross-reference (e.g. read the source SPAN's \`attributes['source.content']\`).
62
+
63
+ OUTPUT contract \u2014 your final answer must include:
64
+ - A clear prose conclusion answering the user's question.
65
+ - Trace ids and span ids cited as evidence for each claim.
66
+ - Failure modes named in the user's domain language, with frequency and concrete examples.
67
+
68
+ Do NOT invent trace ids, span ids, error messages, or model names. Every fact must be traceable to a tool result.`;
69
+ var TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = "trace-analyst-actor-v5-2026-05-06";
70
+ var TRACE_ANALYST_SUBAGENT_DESCRIPTION = `You are a trace-analyst subagent. Your parent has delegated a focused trace-inspection question. Use the same DISCOVERY \u2192 NARROW \u2192 DEEP-READ protocol but stay tightly scoped: do exactly what was asked, return a concise compact answer, do NOT spawn further subagents unless the parent's question is genuinely multi-branch.
71
+
72
+ Cite trace ids and span ids for every claim. Do NOT invent ids.`;
73
+
74
+ // src/trace-analyst/analyst.ts
75
+ import { AxJSRuntime, agent } from "@ax-llm/ax";
76
+ async function analyzeTraces(input, options) {
77
+ if (!input.question || typeof input.question !== "string") {
78
+ throw new TypeError("analyzeTraces: input.question must be a non-empty string");
79
+ }
80
+ const store = typeof options.source === "string" ? new OtlpFileTraceStore({ path: options.source }) : options.source;
81
+ if (store instanceof OtlpFileTraceStore) {
82
+ await store.ensureIndexed();
83
+ }
84
+ const tools = buildTraceAnalystTools({ store });
85
+ const turns = [];
86
+ let progressFs;
87
+ if (options.progressLogPath) {
88
+ const { createWriteStream } = await import("fs");
89
+ const { mkdir } = await import("fs/promises");
90
+ const { dirname } = await import("path");
91
+ await mkdir(dirname(options.progressLogPath), { recursive: true });
92
+ progressFs = createWriteStream(options.progressLogPath, { flags: "a" });
93
+ }
94
+ const actorTurnCallback = async (turn) => {
95
+ const snap = {
96
+ turn: turn.turn,
97
+ isError: turn.isError,
98
+ code: turn.code,
99
+ output: turn.output,
100
+ thought: turn.thought
101
+ };
102
+ turns.push(snap);
103
+ if (progressFs) {
104
+ try {
105
+ progressFs.write(`${JSON.stringify({ ...snap, ts: Date.now() })}
106
+ `);
107
+ } catch {
108
+ }
109
+ }
110
+ if (options.onTurn) await options.onTurn(snap);
111
+ };
112
+ const maxDepth = options.maxDepth ?? 1;
113
+ const maxTurns = options.maxTurns ?? 12;
114
+ const maxParallelSubagents = options.maxParallelSubagents ?? 2;
115
+ const maxRuntimeChars = options.maxRuntimeChars ?? 6e3;
116
+ const analyst = agent(
117
+ // `reasoning!` is an internal (Ax `!`) scratchpad field: generated first to
118
+ // force reason-before-conclude, stripped from the returned output — so the
119
+ // consumed shape stays { answer, findings }. Brings the trace-analyst to the
120
+ // same prose-first CoT ordering the kind-factory gets from its `report` field.
121
+ "question:string -> reasoning!:string, answer:string, findings:string[]",
122
+ {
123
+ agentIdentity: {
124
+ name: "TraceAnalyst",
125
+ description: "Analyzes OTLP-shaped JSONL traces using bounded discovery tools to identify systemic failure modes."
126
+ },
127
+ contextFields: ["question"],
128
+ runtime: new AxJSRuntime({
129
+ permissions: [],
130
+ blockDynamicImport: true,
131
+ allowedModules: [],
132
+ freezeIntrinsics: true,
133
+ blockShadowRealm: true,
134
+ // RLM stdout mode relies on runtime bindings persisting across turns.
135
+ preventGlobalThisExtensions: false
136
+ }),
137
+ mode: maxDepth > 0 ? "advanced" : "simple",
138
+ recursionOptions: maxDepth > 0 ? { maxDepth } : void 0,
139
+ maxTurns,
140
+ maxRuntimeChars,
141
+ maxBatchedLlmQueryConcurrency: maxParallelSubagents,
142
+ promptLevel: "detailed",
143
+ // Trace analysis depends on exact prior tool results and runtime variables.
144
+ contextPolicy: { preset: "full", budget: "balanced" },
145
+ functions: { local: tools },
146
+ actorOptions: {
147
+ description: options.actorDescription ?? TRACE_ANALYST_ACTOR_DESCRIPTION,
148
+ ...options.model ? { model: options.model } : {},
149
+ // Keep actor messages tool-call/content shaped across reasoning models.
150
+ showThoughts: false,
151
+ thinkingTokenBudget: "none"
152
+ },
153
+ responderOptions: {
154
+ ...options.model ? { model: options.model } : {},
155
+ description: options.subagentDescription ?? TRACE_ANALYST_SUBAGENT_DESCRIPTION,
156
+ showThoughts: false
157
+ },
158
+ actorTurnCallback,
159
+ bubbleErrors: [TraceFileMissingError]
160
+ }
161
+ );
162
+ let result;
163
+ try {
164
+ result = await analyst.forward(options.ai, { question: input.question });
165
+ } finally {
166
+ if (progressFs) {
167
+ await new Promise((resolve) => progressFs.end(() => resolve()));
168
+ }
169
+ }
170
+ return {
171
+ answer: typeof result.answer === "string" ? result.answer : String(result.answer ?? ""),
172
+ findings: Array.isArray(result.findings) ? result.findings.filter((s) => typeof s === "string") : [],
173
+ turns,
174
+ turnCount: turns.length,
175
+ usage: normalizeRoleArrays(analyst.getUsage()),
176
+ chatLog: normalizeRoleArrays(analyst.getChatLog()),
177
+ actorPromptVersion: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION
178
+ };
179
+ }
180
+ function normalizeRoleArrays(value) {
181
+ const record = value && typeof value === "object" ? value : {};
182
+ return {
183
+ actor: normalizeRecordArray(record.actor),
184
+ responder: normalizeRecordArray(record.responder)
185
+ };
186
+ }
187
+ function normalizeRecordArray(value) {
188
+ if (!Array.isArray(value)) return [];
189
+ return value.map(
190
+ (item) => item && typeof item === "object" ? { ...item } : { value: item }
191
+ );
192
+ }
193
+
194
+ export {
195
+ TRACE_ANALYST_ACTOR_DESCRIPTION,
196
+ TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,
197
+ TRACE_ANALYST_SUBAGENT_DESCRIPTION,
198
+ analyzeTraces
199
+ };
200
+ //# sourceMappingURL=chunk-UHMJT4T7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/trace-analyst/prompts.ts","../src/trace-analyst/analyst.ts"],"sourcesContent":["/** Ax RLM prompt for bounded trace discovery and evidence-backed analysis. */\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION = `You answer questions about an OTLP-shaped JSONL trace dataset using the trace tools provided in the \\`traces\\` namespace.\n\nDISCOVERY → NARROW → DEEP-READ protocol — follow exactly:\n\n1. ALWAYS call \\`traces.getDatasetOverview({})\\` FIRST without a regex_pattern. The result tells you total_traces, raw_jsonl_bytes, services, agents, models, and sample_trace_ids (real ids — never fabricate one).\n\n2. Use raw_jsonl_bytes to gauge how expensive raw scans will be. \\`filters.regex_pattern\\` is the one scan-heavy filter on getDatasetOverview / queryTraces / countTraces — narrow with indexed fields (has_errors, model_names, service_names, agent_names, time bounds) BEFORE adding a regex on a large dataset.\n\n3. To list more traces than the sample, call \\`traces.queryTraces({ filters?, limit, offset? })\\`. Each summary carries raw_jsonl_bytes — use it to choose between viewTrace and searchTrace BEFORE calling either.\n\n4. Per-trace inspection:\n - SMALL trace (raw_jsonl_bytes well under 150_000): call \\`traces.viewTrace({ trace_id })\\`. Returns all spans. Per-attribute payloads are head-capped at ~4KB; large \\`input.value\\` / \\`output.value\\` / \\`llm.input_messages\\` will show a \\`[trace-analyst truncated: N bytes]\\` marker.\n - LARGE trace (raw_jsonl_bytes near or above 150_000, or you saw an \\`oversized\\` response): use \\`traces.searchTrace({ trace_id, regex_pattern })\\` to get bounded SpanMatchRecords (span metadata + matched text + surrounding context). Then call \\`traces.viewSpans({ trace_id, span_ids: [...] })\\` for surgical reads (~16KB cap, 4× higher than discovery), or \\`traces.searchSpan({ trace_id, span_id, regex_pattern })\\` for one large span. Stays bounded regardless of trace size.\n - Useful regex patterns: \\`STATUS_CODE_ERROR\\` (failures), tool names like \\`grep\\` or \\`view_trace\\`, error strings like \\`MaxTurnsExceeded\\`, model names, attribute keys.\n\n5. ONLY call viewTrace / viewSpans / searchTrace / searchSpan with trace/span ids you have already seen in sample_trace_ids, a queryTraces page, or a previous search result. Never invent ids.\n\n5a. **Result-shape contract** — searchTrace and searchSpan return \\`{ trace_id, hits, total_matches, has_more }\\`. Iterate \\`result.hits\\` (NOT result.matches). Each hit has \\`{ span_id, span_name, span_kind, attribute_path, matched_text, context_before, context_after, match_offset }\\`. viewTrace returns \\`{ trace_id, spans }\\` (or \\`oversized\\`). viewSpans returns \\`{ trace_id, spans, missing_span_ids, truncated_attribute_count }\\`. Never assume a field name — log the result shape first if unsure.\n\n6. If viewTrace returns an \\`oversized\\` summary instead of \\`spans\\`, DO NOT retry the same call. Read the summary's top_span_names, span_count, span_response_bytes_max, error_span_count to plan a follow-up: switch to searchTrace (or searchSpan for one large span), then viewSpans on a smaller, surgical span_ids set.\n\n7. If searchTrace or searchSpan returns has_more=true, REFINE the regex to be more specific rather than blindly raising max_matches.\n\n8. If a tool errors (invalid regex, range error), STOP and reconsider — don't retry with a guessed id or argument. Use the discovery tools above to recover.\n\n9. If a ~4KB-truncated payload from viewTrace / searchTrace matters for your answer, first try viewSpans on that span id (~16KB cap). If a 16KB-truncated payload from viewSpans still matters, narrow further with searchSpan against a more specific regex rather than asking for the full payload again.\n\n10. If maxDepth > 0 and the question splits into independent semantic branches, delegate well-defined subtasks to subagents using \\`await llmQuery(...)\\`. Pass narrow context and a focused query. Examples:\n\n const reviews = await llmQuery([\n { query: 'Drill into trace abc123 — what tool calls preceded the failure?', context: { trace_id: 'abc123' } },\n { query: 'Drill into trace def456 — same failure mode?', context: { trace_id: 'def456' } },\n ]);\n\nOBSERVABILITY rules:\n- Each non-final actor turn must emit at least one \\`console.log(...)\\` for evidence. Up to 3 logs per turn is fine when correlating multiple data sources (e.g. one log for findings list, one for source-file content, one for derived analysis).\n- Do NOT combine \\`console.log\\` with \\`final(...)\\` or \\`askClarification(...)\\` in the same turn — finish gathering data first, then call final on its own turn.\n- Reuse runtime variables across turns; don't recompute.\n- When done, call \\`await final(answer)\\` with the fully-formed report. The responder rewrites the answer into output fields; if you only pass a vague summary string the responder has nothing concrete to format.\n\nCRITICAL — \\`final()\\` payload contract for evidence-grounded analysis tasks:\n- Pass a STRUCTURED object as the second arg with the actual data the responder needs to format the answer. Do NOT pass abstract instructions; pass evidence.\n- Example for per-item verdict tasks:\n \\`\\`\\`js\n await final(\"Format the per-item verdict report from the evidence below.\", {\n findings: [\n { id: 'sub-1-finding-1', claim: '...', verdict: 'TRUE-POSITIVE', evidence: 'lines 42-45 of contracts/X.sol show ...' },\n ...all items\n ],\n systemic_summary: '3 sentences I wrote based on the evidence above'\n });\n \\`\\`\\`\n- Calling \\`final(\"answer\", {})\\` with no evidence is a failure mode — the responder will hallucinate or echo back the field names. Always include the gathered data.\n- Premature final after a single viewSpans call is INSUFFICIENT for per-finding analysis tasks. Read the requested attributes (e.g. \\`spans[i].attributes['redteam.finding.title']\\`), and for each one perform the requested cross-reference (e.g. read the source SPAN's \\`attributes['source.content']\\`).\n\nOUTPUT contract — your final answer must include:\n- A clear prose conclusion answering the user's question.\n- Trace ids and span ids cited as evidence for each claim.\n- Failure modes named in the user's domain language, with frequency and concrete examples.\n\nDo NOT invent trace ids, span ids, error messages, or model names. Every fact must be traceable to a tool result.`\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = 'trace-analyst-actor-v5-2026-05-06'\n\n/** Subagent prompt for focused trace-inspection subtasks. */\nexport const TRACE_ANALYST_SUBAGENT_DESCRIPTION = `You are a trace-analyst subagent. Your parent has delegated a focused trace-inspection question. Use the same DISCOVERY → NARROW → DEEP-READ protocol but stay tightly scoped: do exactly what was asked, return a concise compact answer, do NOT spawn further subagents unless the parent's question is genuinely multi-branch.\n\nCite trace ids and span ids for every claim. Do NOT invent ids.`\n","import { type AxActorTurn, type AxAIService, type AxFunction, AxJSRuntime, agent } from '@ax-llm/ax'\nimport {\n TRACE_ANALYST_ACTOR_DESCRIPTION,\n TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,\n TRACE_ANALYST_SUBAGENT_DESCRIPTION,\n} from './prompts'\nimport type { TraceAnalysisStore } from './store'\nimport { OtlpFileTraceStore, TraceFileMissingError } from './store-otlp'\nimport { buildTraceAnalystTools } from './tools'\n\nexport interface AnalyzeTracesInput {\n /** The user-facing question. Domain framing belongs here, not in the\n * actor description. */\n question: string\n}\n\nexport interface AnalyzeTracesResult {\n /** The responder's prose answer. */\n answer: string\n /** Bulleted findings extracted from the responder's structured output. */\n findings: string[]\n /** Per-actor-turn snapshots captured via `actorTurnCallback`. */\n turns: AnalyzeTracesTurnSnapshot[]\n /** Total turns the actor took. */\n turnCount: number\n /** Token usage by role. */\n usage: TraceAnalystUsage\n /** Full system + assistant + tool message log by role. */\n chatLog: TraceAnalystChatLog\n /** Prompt version that produced this run. */\n actorPromptVersion: string\n}\n\nexport interface TraceAnalystUsage {\n actor: TraceAnalystUsageEntry[]\n responder: TraceAnalystUsageEntry[]\n}\n\nexport interface TraceAnalystUsageEntry {\n [key: string]: unknown\n}\n\nexport interface TraceAnalystChatLog {\n actor: TraceAnalystChatMessage[]\n responder: TraceAnalystChatMessage[]\n}\n\nexport interface TraceAnalystChatMessage {\n [key: string]: unknown\n}\n\nexport interface AnalyzeTracesTurnSnapshot {\n turn: number\n isError: boolean\n /** The JS code the actor produced for this turn. */\n code: string\n /** The formatted action-log entry the actor sees on the next turn. */\n output: string\n /** Provider thought (when `actorOptions.showThoughts` is true and the\n * provider returns it). */\n thought?: string\n}\n\nexport interface AnalyzeTracesOptions {\n /** Trace data source. Pass either an OTLP-JSONL path or a custom store. */\n source: string | TraceAnalysisStore\n /** Caller-provided AxAIService. */\n ai: AxAIService\n /** Model id forwarded to actor + responder. */\n model?: string\n /** Recursion depth. 0 = no sub-agent dispatch. Default 1. */\n maxDepth?: number\n /** Maximum actor turns. Default 12. */\n maxTurns?: number\n /** Maximum parallel sub-agent calls in batched llmQuery. Default 2. */\n maxParallelSubagents?: number\n /** Override the actor description. */\n actorDescription?: string\n /** Override the subagent description. */\n subagentDescription?: string\n /** Per-turn observability hook. */\n onTurn?: (turn: AnalyzeTracesTurnSnapshot) => void | Promise<void>\n /** Override max runtime characters per turn. Default 6000. */\n maxRuntimeChars?: number\n /** When set, every turn's snapshot is appended to this JSONL file\n * immediately. If the analyst crashes mid-loop (provider 503,\n * network error, validator reject) the partial reasoning is still\n * on disk. Replay the file with the responder afterward to recover\n * evidence. */\n progressLogPath?: string\n}\n\n/**\n * Run the trace analyst.\n *\n * Throws:\n * - `TraceFileMissingError` if `source` is a path and doesn't exist.\n * - `AxAgentClarificationError` if the analyst asks for clarification.\n * - Provider errors (auth, rate limits) propagate from the AI service.\n */\nexport async function analyzeTraces(\n input: AnalyzeTracesInput,\n options: AnalyzeTracesOptions,\n): Promise<AnalyzeTracesResult> {\n if (!input.question || typeof input.question !== 'string') {\n throw new TypeError('analyzeTraces: input.question must be a non-empty string')\n }\n\n const store: TraceAnalysisStore =\n typeof options.source === 'string'\n ? new OtlpFileTraceStore({ path: options.source })\n : options.source\n\n // Pre-warm file stores so missing inputs fail before the RLM starts.\n if (store instanceof OtlpFileTraceStore) {\n await store.ensureIndexed()\n }\n\n const tools: AxFunction[] = buildTraceAnalystTools({ store })\n const turns: AnalyzeTracesTurnSnapshot[] = []\n\n // Persist each turn as JSONL so interrupted analyst runs keep useful evidence.\n let progressFs: import('node:fs').WriteStream | undefined\n if (options.progressLogPath) {\n const { createWriteStream } = await import('node:fs')\n const { mkdir } = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await mkdir(dirname(options.progressLogPath), { recursive: true })\n progressFs = createWriteStream(options.progressLogPath, { flags: 'a' })\n }\n\n const actorTurnCallback = async (turn: AxActorTurn): Promise<void> => {\n const snap: AnalyzeTracesTurnSnapshot = {\n turn: turn.turn,\n isError: turn.isError,\n code: turn.code,\n output: turn.output,\n thought: turn.thought,\n }\n turns.push(snap)\n if (progressFs) {\n try {\n progressFs.write(`${JSON.stringify({ ...snap, ts: Date.now() })}\\n`)\n } catch {\n // Progress logging must never fail the analyst.\n }\n }\n if (options.onTurn) await options.onTurn(snap)\n }\n\n const maxDepth = options.maxDepth ?? 1\n const maxTurns = options.maxTurns ?? 12\n const maxParallelSubagents = options.maxParallelSubagents ?? 2\n const maxRuntimeChars = options.maxRuntimeChars ?? 6000\n\n const analyst = agent<{ question: string }, { answer: string; findings: string[] }>(\n // `reasoning!` is an internal (Ax `!`) scratchpad field: generated first to\n // force reason-before-conclude, stripped from the returned output — so the\n // consumed shape stays { answer, findings }. Brings the trace-analyst to the\n // same prose-first CoT ordering the kind-factory gets from its `report` field.\n 'question:string -> reasoning!:string, answer:string, findings:string[]',\n {\n agentIdentity: {\n name: 'TraceAnalyst',\n description:\n 'Analyzes OTLP-shaped JSONL traces using bounded discovery tools to identify systemic failure modes.',\n },\n contextFields: ['question'],\n runtime: new AxJSRuntime({\n permissions: [],\n blockDynamicImport: true,\n allowedModules: [],\n freezeIntrinsics: true,\n blockShadowRealm: true,\n // RLM stdout mode relies on runtime bindings persisting across turns.\n preventGlobalThisExtensions: false,\n }),\n mode: maxDepth > 0 ? 'advanced' : 'simple',\n recursionOptions: maxDepth > 0 ? { maxDepth } : undefined,\n maxTurns,\n maxRuntimeChars,\n maxBatchedLlmQueryConcurrency: maxParallelSubagents,\n promptLevel: 'detailed',\n // Trace analysis depends on exact prior tool results and runtime variables.\n contextPolicy: { preset: 'full', budget: 'balanced' },\n functions: { local: tools },\n actorOptions: {\n description: options.actorDescription ?? TRACE_ANALYST_ACTOR_DESCRIPTION,\n ...(options.model ? { model: options.model } : {}),\n // Keep actor messages tool-call/content shaped across reasoning models.\n showThoughts: false,\n thinkingTokenBudget: 'none',\n },\n responderOptions: {\n ...(options.model ? { model: options.model } : {}),\n description: options.subagentDescription ?? TRACE_ANALYST_SUBAGENT_DESCRIPTION,\n showThoughts: false,\n },\n actorTurnCallback,\n bubbleErrors: [TraceFileMissingError],\n },\n )\n\n let result: { answer: unknown; findings: unknown }\n try {\n result = await analyst.forward(options.ai, { question: input.question })\n } finally {\n if (progressFs) {\n await new Promise<void>((resolve) => progressFs!.end(() => resolve()))\n }\n }\n\n return {\n answer: typeof result.answer === 'string' ? result.answer : String(result.answer ?? ''),\n findings: Array.isArray(result.findings)\n ? result.findings.filter((s): s is string => typeof s === 'string')\n : [],\n turns,\n turnCount: turns.length,\n usage: normalizeRoleArrays(analyst.getUsage()),\n chatLog: normalizeRoleArrays(analyst.getChatLog()),\n actorPromptVersion: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,\n }\n}\n\nfunction normalizeRoleArrays(value: unknown): {\n actor: Record<string, unknown>[]\n responder: Record<string, unknown>[]\n} {\n const record = value && typeof value === 'object' ? (value as Record<string, unknown>) : {}\n return {\n actor: normalizeRecordArray(record.actor),\n responder: normalizeRecordArray(record.responder),\n }\n}\n\nfunction normalizeRecordArray(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) return []\n return value.map((item) =>\n item && typeof item === 'object' ? { ...(item as Record<string, unknown>) } : { value: item },\n )\n}\n"],"mappings":";;;;;;;AAEO,IAAM,kCAAkC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8DxC,IAAM,0CAA0C;AAGhD,IAAM,qCAAqC;AAAA;AAAA;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,WAAY,IAAI,MAAM,QAAQ,CAAC,CAAC;AAAA,IACvE;AAAA,EACF;AAEA,SAAO;AAAA,IACL,QAAQ,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS,OAAO,OAAO,UAAU,EAAE;AAAA,IACtF,UAAU,MAAM,QAAQ,OAAO,QAAQ,IACnC,OAAO,SAAS,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ,IAChE,CAAC;AAAA,IACL;AAAA,IACA,WAAW,MAAM;AAAA,IACjB,OAAO,oBAAoB,QAAQ,SAAS,CAAC;AAAA,IAC7C,SAAS,oBAAoB,QAAQ,WAAW,CAAC;AAAA,IACjD,oBAAoB;AAAA,EACtB;AACF;AAEA,SAAS,oBAAoB,OAG3B;AACA,QAAM,SAAS,SAAS,OAAO,UAAU,WAAY,QAAoC,CAAC;AAC1F,SAAO;AAAA,IACL,OAAO,qBAAqB,OAAO,KAAK;AAAA,IACxC,WAAW,qBAAqB,OAAO,SAAS;AAAA,EAClD;AACF;AAEA,SAAS,qBAAqB,OAA2C;AACvE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MAAM;AAAA,IAAI,CAAC,SAChB,QAAQ,OAAO,SAAS,WAAW,EAAE,GAAI,KAAiC,IAAI,EAAE,OAAO,KAAK;AAAA,EAC9F;AACF;","names":[]}
@@ -0,0 +1,190 @@
1
+ import {
2
+ AnalystRegistry,
3
+ DEFAULT_TRACE_ANALYST_KINDS,
4
+ createTraceAnalystKind
5
+ } from "./chunk-D3V5B42D.js";
6
+ import {
7
+ makeFinding
8
+ } from "./chunk-45EEMHTC.js";
9
+
10
+ // src/trace-analyst/behavioral-metrics.ts
11
+ var INPUT_GROWTH_FACTOR = 3;
12
+ var MIN_TOOL_CALLS = 3;
13
+ var VERIFY_RE = /verif|eval|inspect|check|assert|validat|review|confirm/i;
14
+ function num(v) {
15
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
16
+ }
17
+ function inputTokensOf(s) {
18
+ return num(s.attributes["llm.input_tokens"]) ?? num(s.attributes["llm.usage.input_tokens"]);
19
+ }
20
+ function outputTokensOf(s) {
21
+ return num(s.attributes["llm.output_tokens"]) ?? num(s.attributes["llm.usage.output_tokens"]);
22
+ }
23
+ function stepOf(s) {
24
+ return num(s.attributes.step);
25
+ }
26
+ function toolNameOf(s) {
27
+ if (s.tool_name) return s.tool_name;
28
+ const t = s.attributes["tool.name"];
29
+ return typeof t === "string" && t.length > 0 ? t : null;
30
+ }
31
+ function computeTraceMetrics(spans) {
32
+ const ordered = [...spans].sort((a, b) => {
33
+ const sa = stepOf(a);
34
+ const sb = stepOf(b);
35
+ if (sa !== null && sb !== null && sa !== sb) return sa - sb;
36
+ return a.start_time.localeCompare(b.start_time);
37
+ });
38
+ const inputTokenTrajectory = [];
39
+ const outputTokenTrajectory = [];
40
+ const toolHistogram = {};
41
+ let hasSelfVerification = false;
42
+ for (const s of ordered) {
43
+ const inT = inputTokensOf(s);
44
+ if (inT !== null) inputTokenTrajectory.push(inT);
45
+ const outT = outputTokensOf(s);
46
+ if (outT !== null) outputTokenTrajectory.push(outT);
47
+ const tool = toolNameOf(s);
48
+ if (tool) {
49
+ toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1;
50
+ if (VERIFY_RE.test(tool)) hasSelfVerification = true;
51
+ }
52
+ }
53
+ const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0);
54
+ const distinctTools = Object.keys(toolHistogram).length;
55
+ const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls;
56
+ const signals = [];
57
+ if (inputTokenTrajectory.length >= 3) {
58
+ const first = inputTokenTrajectory[0];
59
+ const last = inputTokenTrajectory[inputTokenTrajectory.length - 1];
60
+ const growth = first > 0 ? last / first : 0;
61
+ if (last > first && growth >= INPUT_GROWTH_FACTOR) {
62
+ signals.push({
63
+ code: "monotonic-input-growth",
64
+ severity: "high",
65
+ detail: `LLM input tokens grew ${growth.toFixed(1)}x (${first}\u2192${last}) across ${inputTokenTrajectory.length} calls \u2014 full history re-sent each step with no compression.`,
66
+ evidence: {
67
+ first,
68
+ last,
69
+ growth_x: Number(growth.toFixed(2)),
70
+ calls: inputTokenTrajectory.length
71
+ }
72
+ });
73
+ }
74
+ }
75
+ if (outputTokenTrajectory.length >= 3) {
76
+ const first = outputTokenTrajectory[0];
77
+ const last = outputTokenTrajectory[outputTokenTrajectory.length - 1];
78
+ if (last < first) {
79
+ signals.push({
80
+ code: "output-length-decay",
81
+ severity: "medium",
82
+ detail: `LLM output tokens shrank ${first}\u2192${last} over ${outputTokenTrajectory.length} calls \u2014 less planning/reasoning per step as context grows.`,
83
+ evidence: { first, last, calls: outputTokenTrajectory.length }
84
+ });
85
+ }
86
+ }
87
+ if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {
88
+ const only = Object.keys(toolHistogram)[0];
89
+ signals.push({
90
+ code: "single-tool-dependency",
91
+ severity: "medium",
92
+ detail: `All ${totalToolCalls} tool calls are \`${only}\` \u2014 no tool diversity and no fallback path.`,
93
+ evidence: { tool: only, calls: totalToolCalls, distinct_tools: 1 }
94
+ });
95
+ }
96
+ if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) {
97
+ signals.push({
98
+ code: "no-self-verification",
99
+ severity: "medium",
100
+ detail: `${totalToolCalls} tool calls and none verify/inspect/check state \u2014 the agent never validates its own actions.`,
101
+ evidence: { tool_calls: totalToolCalls, verification_calls: 0 }
102
+ });
103
+ }
104
+ return {
105
+ llmCallCount: inputTokenTrajectory.length,
106
+ inputTokenTrajectory,
107
+ outputTokenTrajectory,
108
+ toolHistogram,
109
+ totalToolCalls,
110
+ distinctTools,
111
+ toolDiversityRatio,
112
+ hasSelfVerification,
113
+ signals
114
+ };
115
+ }
116
+
117
+ // src/analyst/behavioral-analyst.ts
118
+ var RECOMMENDED_ACTION = {
119
+ "monotonic-input-growth": "Add a context-budget instruction: once prior context exceeds a threshold, summarize earlier steps into a short status line instead of re-sending full history.",
120
+ "output-length-decay": "Require a minimum planning/reasoning budget per step so late steps do not degrade into terse, error-prone commands.",
121
+ "single-tool-dependency": "Direct the agent to use the full toolset (verify / inspect / alternate actions), not a single execute call, and to plan a fallback when a call returns an unexpected result.",
122
+ "no-self-verification": "After every state-mutating action, verify the result (eval / inspect / assert) before proceeding."
123
+ };
124
+ var ANALYST_ID = "efficiency-behavioral";
125
+ function deriveEfficiencyFindings(metrics, opts = {}) {
126
+ const analystId = opts.analystId ?? ANALYST_ID;
127
+ return metrics.signals.map(
128
+ (sig) => makeFinding({
129
+ analyst_id: analystId,
130
+ area: "efficiency",
131
+ subject: sig.code,
132
+ // kebab — passes the cluster grammar; stable key for diffFindings
133
+ claim: sig.detail,
134
+ severity: sig.severity,
135
+ // Deterministic arithmetic over spans, not a model judgment → certain.
136
+ confidence: 1,
137
+ evidence_refs: [
138
+ {
139
+ kind: "metric",
140
+ uri: `metric://efficiency/${sig.code}`,
141
+ excerpt: JSON.stringify(sig.evidence)
142
+ }
143
+ ],
144
+ recommended_action: RECOMMENDED_ACTION[sig.code],
145
+ metadata: { deterministic: true, evidence: sig.evidence },
146
+ ...opts.producedAt ? { produced_at: opts.producedAt } : {}
147
+ })
148
+ );
149
+ }
150
+ function behavioralAnalyst() {
151
+ return {
152
+ id: ANALYST_ID,
153
+ description: "Deterministic behavioral/efficiency findings over OTLP spans \u2014 token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.",
154
+ inputKind: "trace-store",
155
+ cost: { kind: "deterministic" },
156
+ version: "1.0.0",
157
+ async analyze(store) {
158
+ const overview = await store.getOverview();
159
+ const spans = [];
160
+ for (const traceId of overview.sample_trace_ids) {
161
+ const viewed = await store.viewTrace({ trace_id: traceId });
162
+ if (viewed.spans) spans.push(...viewed.spans);
163
+ }
164
+ return deriveEfficiencyFindings(computeTraceMetrics(spans));
165
+ }
166
+ };
167
+ }
168
+
169
+ // src/analyst/default-registry.ts
170
+ function buildDefaultAnalystRegistry(opts = {}) {
171
+ const registry = new AnalystRegistry(opts.registry);
172
+ if (opts.includeBehavioral !== false) {
173
+ registry.register(behavioralAnalyst());
174
+ }
175
+ if (opts.ai) {
176
+ const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS;
177
+ for (const spec of kinds) {
178
+ registry.register(createTraceAnalystKind(spec, { ai: opts.ai, model: opts.model }));
179
+ }
180
+ }
181
+ return registry;
182
+ }
183
+
184
+ export {
185
+ computeTraceMetrics,
186
+ deriveEfficiencyFindings,
187
+ behavioralAnalyst,
188
+ buildDefaultAnalystRegistry
189
+ };
190
+ //# sourceMappingURL=chunk-UMMZHCPB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/trace-analyst/behavioral-metrics.ts","../src/analyst/behavioral-analyst.ts","../src/analyst/default-registry.ts"],"sourcesContent":["/**\n * Deterministic behavioral metrics over OTLP spans — pure arithmetic, no LLM.\n *\n * These are the model-independent multiplier: the four trace-quality signals a\n * tolerant analyzer (e.g. HALO) re-derives per run inside the model — token\n * growth, output decay, tool monoculture, missing self-verification — computed\n * here once, in TypeScript, with zero model judgment. A finding that falls out\n * of arithmetic is trivially model-agnostic and cannot hallucinate the trend.\n *\n * General, not trace-specific: the detectors key off token trajectories and\n * tool usage present in any agentic OTLP trace, not any one benchmark.\n */\n\nimport type { TraceAnalystSpan } from './types'\n\nexport type SuboptimalCode =\n | 'monotonic-input-growth'\n | 'output-length-decay'\n | 'single-tool-dependency'\n | 'no-self-verification'\n\nexport interface SuboptimalSignal {\n code: SuboptimalCode\n severity: 'high' | 'medium' | 'low'\n /** Human-readable claim, with the backing numbers inlined. */\n detail: string\n /** The exact figures the detector fired on — auditable, no model in the loop. */\n evidence: Record<string, number | string | boolean>\n}\n\nexport interface BehavioralMetrics {\n llmCallCount: number\n inputTokenTrajectory: number[]\n outputTokenTrajectory: number[]\n toolHistogram: Record<string, number>\n totalToolCalls: number\n distinctTools: number\n /** distinct/total tool calls; 1.0 when there are no tool calls. */\n toolDiversityRatio: number\n hasSelfVerification: boolean\n signals: SuboptimalSignal[]\n}\n\n/** ≥ this input-token growth ratio across a run, with no compression, fires. */\nconst INPUT_GROWTH_FACTOR = 3\n/** Tool-usage signals need at least this many calls to be meaningful. */\nconst MIN_TOOL_CALLS = 3\n/** Tool names matching this are self-verification, not state mutation. */\nconst VERIFY_RE = /verif|eval|inspect|check|assert|validat|review|confirm/i\n\nfunction num(v: unknown): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\nfunction inputTokensOf(s: TraceAnalystSpan): number | null {\n return num(s.attributes['llm.input_tokens']) ?? num(s.attributes['llm.usage.input_tokens'])\n}\nfunction outputTokensOf(s: TraceAnalystSpan): number | null {\n return num(s.attributes['llm.output_tokens']) ?? num(s.attributes['llm.usage.output_tokens'])\n}\nfunction stepOf(s: TraceAnalystSpan): number | null {\n return num(s.attributes.step)\n}\nfunction toolNameOf(s: TraceAnalystSpan): string | null {\n if (s.tool_name) return s.tool_name\n const t = s.attributes['tool.name']\n return typeof t === 'string' && t.length > 0 ? t : null\n}\n\n/**\n * Reduce a span list to behavioral metrics + fired suboptimality signals.\n * Pure + deterministic: same spans → same output, on any machine, no model.\n */\nexport function computeTraceMetrics(spans: readonly TraceAnalystSpan[]): BehavioralMetrics {\n // Order by step (when present) then start_time so trajectories reflect run order.\n const ordered = [...spans].sort((a, b) => {\n const sa = stepOf(a)\n const sb = stepOf(b)\n if (sa !== null && sb !== null && sa !== sb) return sa - sb\n return a.start_time.localeCompare(b.start_time)\n })\n\n const inputTokenTrajectory: number[] = []\n const outputTokenTrajectory: number[] = []\n const toolHistogram: Record<string, number> = {}\n let hasSelfVerification = false\n\n for (const s of ordered) {\n const inT = inputTokensOf(s)\n if (inT !== null) inputTokenTrajectory.push(inT)\n const outT = outputTokensOf(s)\n if (outT !== null) outputTokenTrajectory.push(outT)\n const tool = toolNameOf(s)\n if (tool) {\n toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1\n if (VERIFY_RE.test(tool)) hasSelfVerification = true\n }\n }\n\n const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0)\n const distinctTools = Object.keys(toolHistogram).length\n const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls\n\n const signals: SuboptimalSignal[] = []\n\n if (inputTokenTrajectory.length >= 3) {\n const first = inputTokenTrajectory[0]!\n const last = inputTokenTrajectory[inputTokenTrajectory.length - 1]!\n const growth = first > 0 ? last / first : 0\n if (last > first && growth >= INPUT_GROWTH_FACTOR) {\n signals.push({\n code: 'monotonic-input-growth',\n severity: 'high',\n detail: `LLM input tokens grew ${growth.toFixed(1)}x (${first}→${last}) across ${inputTokenTrajectory.length} calls — full history re-sent each step with no compression.`,\n evidence: {\n first,\n last,\n growth_x: Number(growth.toFixed(2)),\n calls: inputTokenTrajectory.length,\n },\n })\n }\n }\n\n if (outputTokenTrajectory.length >= 3) {\n const first = outputTokenTrajectory[0]!\n const last = outputTokenTrajectory[outputTokenTrajectory.length - 1]!\n if (last < first) {\n signals.push({\n code: 'output-length-decay',\n severity: 'medium',\n detail: `LLM output tokens shrank ${first}→${last} over ${outputTokenTrajectory.length} calls — less planning/reasoning per step as context grows.`,\n evidence: { first, last, calls: outputTokenTrajectory.length },\n })\n }\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {\n const only = Object.keys(toolHistogram)[0]!\n signals.push({\n code: 'single-tool-dependency',\n severity: 'medium',\n detail: `All ${totalToolCalls} tool calls are \\`${only}\\` — no tool diversity and no fallback path.`,\n evidence: { tool: only, calls: totalToolCalls, distinct_tools: 1 },\n })\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) {\n signals.push({\n code: 'no-self-verification',\n severity: 'medium',\n detail: `${totalToolCalls} tool calls and none verify/inspect/check state — the agent never validates its own actions.`,\n evidence: { tool_calls: totalToolCalls, verification_calls: 0 },\n })\n }\n\n return {\n llmCallCount: inputTokenTrajectory.length,\n inputTokenTrajectory,\n outputTokenTrajectory,\n toolHistogram,\n totalToolCalls,\n distinctTools,\n toolDiversityRatio,\n hasSelfVerification,\n signals,\n }\n}\n","/**\n * `behavioralAnalyst` — a DETERMINISTIC analyst (cost.kind = 'deterministic',\n * never calls the LLM). It produces the efficiency/behavioral findings a\n * tolerant agentic analyzer (HALO) re-derives per run inside the model —\n * context bloat, output decay, tool monoculture, missing self-verification —\n * directly from arithmetic over spans (`computeTraceMetrics`).\n *\n * Why it matters: these findings are model-agnostic BY CONSTRUCTION (no model\n * in the loop), so they cannot return 0 on a weak model the way the Ax-RLM\n * does — and they are strictly more reliable than HALO, which spends tokens\n * re-deriving the same numbers and can hallucinate the trend. The agentic\n * RLM kinds remain for SEMANTIC findings that genuinely need a model; this\n * analyst owns the behavioral class.\n */\n\nimport {\n type BehavioralMetrics,\n computeTraceMetrics,\n type SuboptimalCode,\n} from '../trace-analyst/behavioral-metrics'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { TraceAnalystSpan } from '../trace-analyst/types'\nimport { type Analyst, type AnalystFinding, makeFinding } from './types'\n\nconst RECOMMENDED_ACTION: Record<SuboptimalCode, string> = {\n 'monotonic-input-growth':\n 'Add a context-budget instruction: once prior context exceeds a threshold, summarize earlier steps into a short status line instead of re-sending full history.',\n 'output-length-decay':\n 'Require a minimum planning/reasoning budget per step so late steps do not degrade into terse, error-prone commands.',\n 'single-tool-dependency':\n 'Direct the agent to use the full toolset (verify / inspect / alternate actions), not a single execute call, and to plan a fallback when a call returns an unexpected result.',\n 'no-self-verification':\n 'After every state-mutating action, verify the result (eval / inspect / assert) before proceeding.',\n}\n\nconst ANALYST_ID = 'efficiency-behavioral'\n\n/**\n * Map computed signals → structured AnalystFindings. Pure: no LLM, no clock\n * dependence beyond `produced_at` (overridable for deterministic tests).\n */\nexport function deriveEfficiencyFindings(\n metrics: BehavioralMetrics,\n opts: { analystId?: string; producedAt?: string } = {},\n): AnalystFinding[] {\n const analystId = opts.analystId ?? ANALYST_ID\n return metrics.signals.map((sig) =>\n makeFinding({\n analyst_id: analystId,\n area: 'efficiency',\n subject: sig.code, // kebab — passes the cluster grammar; stable key for diffFindings\n claim: sig.detail,\n severity: sig.severity,\n // Deterministic arithmetic over spans, not a model judgment → certain.\n confidence: 1,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `metric://efficiency/${sig.code}`,\n excerpt: JSON.stringify(sig.evidence),\n },\n ],\n recommended_action: RECOMMENDED_ACTION[sig.code],\n metadata: { deterministic: true, evidence: sig.evidence },\n ...(opts.producedAt ? { produced_at: opts.producedAt } : {}),\n }),\n )\n}\n\n/** The deterministic behavioral/efficiency analyst (no LLM, any-model). */\nexport function behavioralAnalyst(): Analyst<TraceAnalysisStore> {\n return {\n id: ANALYST_ID,\n description:\n 'Deterministic behavioral/efficiency findings over OTLP spans — token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.',\n inputKind: 'trace-store',\n cost: { kind: 'deterministic' },\n version: '1.0.0',\n async analyze(store) {\n const overview = await store.getOverview()\n const spans: TraceAnalystSpan[] = []\n for (const traceId of overview.sample_trace_ids) {\n const viewed = await store.viewTrace({ trace_id: traceId })\n if (viewed.spans) spans.push(...viewed.spans)\n }\n return deriveEfficiencyFindings(computeTraceMetrics(spans))\n },\n }\n}\n","/**\n * `buildDefaultAnalystRegistry` — the canonical analyst suite, so consumers\n * stop hand-wiring `new AnalystRegistry()` + per-kind `createTraceAnalystKind`.\n *\n * The deterministic `behavioralAnalyst` is ALWAYS registered (it needs no\n * model and is model-agnostic by construction). The agentic RLM kinds are\n * registered only when an `ai` service is supplied — so a caller with no LLM\n * still gets the full behavioral/efficiency diagnosis, and the substrate's\n * \"any model (including no model)\" guarantee holds at the suite level.\n */\n\nimport type { AxAIService } from '@ax-llm/ax'\nimport { behavioralAnalyst } from './behavioral-analyst'\nimport { createTraceAnalystKind, type TraceAnalystKindSpec } from './kind-factory'\nimport { DEFAULT_TRACE_ANALYST_KINDS } from './kinds'\nimport { AnalystRegistry, type AnalystRegistryOptions } from './registry'\n\nexport interface DefaultAnalystRegistryOptions {\n /** Ax service for the agentic RLM kinds. Omit → only the deterministic analyst. */\n ai?: AxAIService\n /** Model for the agentic kinds (falls back to the ai service default). */\n model?: string\n /** Which agentic kinds to register when `ai` is present. Default = the shipped suite. */\n kinds?: readonly TraceAnalystKindSpec[]\n /** Set false to omit the deterministic behavioral analyst (default: include). */\n includeBehavioral?: boolean\n /** Forwarded to the AnalystRegistry constructor (signal, tags, priorFindings). */\n registry?: AnalystRegistryOptions\n}\n\nexport function buildDefaultAnalystRegistry(\n opts: DefaultAnalystRegistryOptions = {},\n): AnalystRegistry {\n const registry = new AnalystRegistry(opts.registry)\n if (opts.includeBehavioral !== false) {\n registry.register(behavioralAnalyst())\n }\n if (opts.ai) {\n const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS\n for (const spec of kinds) {\n registry.register(createTraceAnalystKind(spec, { ai: opts.ai, model: opts.model }))\n }\n }\n return registry\n}\n"],"mappings":";;;;;;;;;;AA4CA,IAAM,sBAAsB;AAE5B,IAAM,iBAAiB;AAEvB,IAAM,YAAY;AAElB,SAAS,IAAI,GAA2B;AACtC,SAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,IAAI,IAAI;AAC3D;AACA,SAAS,cAAc,GAAoC;AACzD,SAAO,IAAI,EAAE,WAAW,kBAAkB,CAAC,KAAK,IAAI,EAAE,WAAW,wBAAwB,CAAC;AAC5F;AACA,SAAS,eAAe,GAAoC;AAC1D,SAAO,IAAI,EAAE,WAAW,mBAAmB,CAAC,KAAK,IAAI,EAAE,WAAW,yBAAyB,CAAC;AAC9F;AACA,SAAS,OAAO,GAAoC;AAClD,SAAO,IAAI,EAAE,WAAW,IAAI;AAC9B;AACA,SAAS,WAAW,GAAoC;AACtD,MAAI,EAAE,UAAW,QAAO,EAAE;AAC1B,QAAM,IAAI,EAAE,WAAW,WAAW;AAClC,SAAO,OAAO,MAAM,YAAY,EAAE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AM,WAAW,IAAI,gBAAgB,KAAK,QAAQ;AAClD,MAAI,KAAK,sBAAsB,OAAO;AACpC,aAAS,SAAS,kBAAkB,CAAC;AAAA,EACvC;AACA,MAAI,KAAK,IAAI;AACX,UAAM,QAAQ,KAAK,SAAS;AAC5B,eAAW,QAAQ,OAAO;AACxB,eAAS,SAAS,uBAAuB,MAAM,EAAE,IAAI,KAAK,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC;AAAA,IACpF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,149 @@
1
+ // src/rl/active-curriculum.ts
2
+ function varianceBasedCurriculum(observations, candidateCells, opts) {
3
+ const variancePrior = opts.variancePrior ?? 0.05;
4
+ const floor = opts.floorPerCell ?? 1;
5
+ const budget = opts.budget;
6
+ const grouped = /* @__PURE__ */ new Map();
7
+ for (const o of observations) {
8
+ const k = `${o.variantId}::${o.scenarioId}`;
9
+ const arr = grouped.get(k) ?? [];
10
+ arr.push(o.score);
11
+ grouped.set(k, arr);
12
+ }
13
+ const cellStats = candidateCells.map((c) => {
14
+ const k = `${c.variantId}::${c.scenarioId}`;
15
+ const samples = grouped.get(k) ?? [];
16
+ const n = samples.length;
17
+ const mean = n === 0 ? 0.5 : samples.reduce((s, v) => s + v, 0) / n;
18
+ const variance = n < 2 ? variancePrior : samples.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1) + variancePrior;
19
+ const weight = Math.sqrt(variance) + 1 / Math.sqrt(Math.max(1, n));
20
+ return { variantId: c.variantId, scenarioId: c.scenarioId, n, mean, variance, weight };
21
+ });
22
+ const floorTotal = floor * cellStats.length;
23
+ if (floorTotal >= budget) {
24
+ const each = Math.max(1, Math.floor(budget / Math.max(1, cellStats.length)));
25
+ return cellStats.map((c) => ({
26
+ variantId: c.variantId,
27
+ scenarioId: c.scenarioId,
28
+ count: each,
29
+ reason: `floor allocation (budget tight; n=${c.n})`
30
+ }));
31
+ }
32
+ const remaining = budget - floorTotal;
33
+ const totalWeight = cellStats.reduce((s, c) => s + c.weight, 0);
34
+ return cellStats.map((c) => {
35
+ const proportional = totalWeight === 0 ? 0 : Math.round(c.weight / totalWeight * remaining);
36
+ return {
37
+ variantId: c.variantId,
38
+ scenarioId: c.scenarioId,
39
+ count: floor + proportional,
40
+ reason: `variance ${c.variance.toFixed(3)} (n=${c.n}, mean=${c.mean.toFixed(3)})`
41
+ };
42
+ });
43
+ }
44
+ function thompsonCurriculum(observations, candidateCells, opts) {
45
+ const threshold = opts.decisionThreshold ?? 0.5;
46
+ const alpha0 = opts.priorAlpha ?? 1;
47
+ const beta0 = opts.priorBeta ?? 1;
48
+ const rng = makeRng(opts.seed);
49
+ const grouped = /* @__PURE__ */ new Map();
50
+ for (const o of observations) {
51
+ const k = `${o.variantId}::${o.scenarioId}`;
52
+ const cur = grouped.get(k) ?? { passes: 0, failures: 0 };
53
+ const pass = o.pass ?? o.score >= threshold;
54
+ if (pass) cur.passes += 1;
55
+ else cur.failures += 1;
56
+ grouped.set(k, cur);
57
+ }
58
+ const stats = candidateCells.map((c) => {
59
+ const k = `${c.variantId}::${c.scenarioId}`;
60
+ const cur = grouped.get(k) ?? { passes: 0, failures: 0 };
61
+ const a = alpha0 + cur.passes;
62
+ const b = beta0 + cur.failures;
63
+ const sampled = sampleBeta(a, b, rng);
64
+ const distance = Math.abs(sampled - threshold);
65
+ const variance = a * b / ((a + b) ** 2 * (a + b + 1));
66
+ const sigma = Math.max(0.05, Math.sqrt(variance));
67
+ const weight = Math.exp(-((distance / sigma) ** 2));
68
+ return {
69
+ variantId: c.variantId,
70
+ scenarioId: c.scenarioId,
71
+ n: cur.passes + cur.failures,
72
+ sampled,
73
+ sigma,
74
+ weight,
75
+ a,
76
+ b
77
+ };
78
+ });
79
+ const totalWeight = stats.reduce((s, c) => s + c.weight, 0);
80
+ return stats.map((c) => {
81
+ const proportional = totalWeight === 0 ? 0 : Math.round(c.weight / totalWeight * opts.budget);
82
+ return {
83
+ variantId: c.variantId,
84
+ scenarioId: c.scenarioId,
85
+ count: Math.max(0, proportional),
86
+ reason: `Beta(${c.a.toFixed(1)},${c.b.toFixed(1)}) sample=${c.sampled.toFixed(3)} (target ${threshold})`
87
+ };
88
+ });
89
+ }
90
+ function observationsFromRunRecords(runs, opts = {}) {
91
+ const threshold = opts.passThreshold ?? 0.5;
92
+ const useHoldout = opts.useHoldout ?? true;
93
+ const out = [];
94
+ for (const r of runs) {
95
+ if (!r.scenarioId) continue;
96
+ const score = useHoldout ? r.outcome.holdoutScore ?? r.outcome.searchScore : r.outcome.searchScore ?? r.outcome.holdoutScore;
97
+ if (typeof score !== "number" || !Number.isFinite(score)) continue;
98
+ out.push({
99
+ variantId: r.candidateId,
100
+ scenarioId: r.scenarioId,
101
+ score,
102
+ pass: score >= threshold
103
+ });
104
+ }
105
+ return out;
106
+ }
107
+ function makeRng(seed) {
108
+ if (seed === void 0) return Math.random;
109
+ let s = seed >>> 0;
110
+ return () => {
111
+ s = s + 1831565813 >>> 0;
112
+ let t = s;
113
+ t = Math.imul(t ^ t >>> 15, t | 1);
114
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
115
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
116
+ };
117
+ }
118
+ function sampleBeta(alpha, beta, rng) {
119
+ const a = Math.max(1, alpha);
120
+ const b = Math.max(1, beta);
121
+ const x = sampleGamma(a, rng);
122
+ const y = sampleGamma(b, rng);
123
+ return x / (x + y);
124
+ }
125
+ function sampleGamma(shape, rng) {
126
+ const d = shape - 1 / 3;
127
+ const c = 1 / Math.sqrt(9 * d);
128
+ while (true) {
129
+ let x;
130
+ let v;
131
+ do {
132
+ const u1 = rng() || 1e-12;
133
+ const u2 = rng() || 1e-12;
134
+ x = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
135
+ v = 1 + c * x;
136
+ } while (v <= 0);
137
+ v = v * v * v;
138
+ const u = rng();
139
+ if (u < 1 - 0.0331 * x ** 4) return d * v;
140
+ if (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v))) return d * v;
141
+ }
142
+ }
143
+
144
+ export {
145
+ varianceBasedCurriculum,
146
+ thompsonCurriculum,
147
+ observationsFromRunRecords
148
+ };
149
+ //# sourceMappingURL=chunk-VZSRQ272.js.map