@tangle-network/agent-eval 0.117.0 → 0.118.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 (143) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/analyst/index.d.ts +2772 -21
  3. package/dist/analyst/index.js +7 -6
  4. package/dist/analyst/index.js.map +1 -1
  5. package/dist/belief-state/index.d.ts +706 -10
  6. package/dist/belief-state/index.js +2 -1
  7. package/dist/belief-state/index.js.map +1 -1
  8. package/dist/benchmarks/index.d.ts +958 -14
  9. package/dist/benchmarks/index.js +12 -10
  10. package/dist/builder-eval/index.d.ts +449 -4
  11. package/dist/builder-eval/index.js +4 -3
  12. package/dist/builder-eval/index.js.map +1 -1
  13. package/dist/campaign/index.d.ts +4276 -74
  14. package/dist/campaign/index.js +12 -10
  15. package/dist/{chunk-VF3XSYTI.js → chunk-33JA4TFA.js} +6 -6
  16. package/dist/{chunk-4JLWXDYA.js → chunk-3EHHMC6E.js} +2 -2
  17. package/dist/{chunk-CCZIVI3F.js → chunk-BFW56GTT.js} +2 -2
  18. package/dist/{chunk-YZPO4UHR.js → chunk-DP3BBMYJ.js} +100 -143
  19. package/dist/chunk-DP3BBMYJ.js.map +1 -0
  20. package/dist/{chunk-E4BUPP7Z.js → chunk-HKUCJ437.js} +38 -66
  21. package/dist/chunk-HKUCJ437.js.map +1 -0
  22. package/dist/{chunk-HZHNRYHK.js → chunk-K6N6XJJX.js} +2 -2
  23. package/dist/chunk-KSDQVPLR.js +286 -0
  24. package/dist/chunk-KSDQVPLR.js.map +1 -0
  25. package/dist/chunk-MA6HLL3S.js +65 -0
  26. package/dist/chunk-MA6HLL3S.js.map +1 -0
  27. package/dist/{chunk-MGEHEHSN.js → chunk-OIIMMLRB.js} +11 -11
  28. package/dist/{chunk-DXZRATT5.js → chunk-OYZAPX5G.js} +3 -3
  29. package/dist/chunk-PXE2VKMX.js +140 -0
  30. package/dist/chunk-PXE2VKMX.js.map +1 -0
  31. package/dist/{chunk-ZUXV7UWZ.js → chunk-Q442S5AS.js} +73 -19
  32. package/dist/{chunk-ZUXV7UWZ.js.map → chunk-Q442S5AS.js.map} +1 -1
  33. package/dist/{chunk-ODVOOEWQ.js → chunk-QBRSJK47.js} +2 -2
  34. package/dist/{chunk-S2F4J57L.js → chunk-QKEGNI5B.js} +77 -32
  35. package/dist/chunk-QKEGNI5B.js.map +1 -0
  36. package/dist/{chunk-5UF54T55.js → chunk-S3UZOQ5Y.js} +34 -7
  37. package/dist/chunk-S3UZOQ5Y.js.map +1 -0
  38. package/dist/{chunk-FQNLDL4D.js → chunk-SVH2ANFD.js} +136 -4
  39. package/dist/chunk-SVH2ANFD.js.map +1 -0
  40. package/dist/{chunk-GQCZRZ7L.js → chunk-U5CHZ5M3.js} +9 -9
  41. package/dist/{chunk-TVVP3ZZQ.js → chunk-VQMK5FMP.js} +2 -1
  42. package/dist/{chunk-TVVP3ZZQ.js.map → chunk-VQMK5FMP.js.map} +1 -1
  43. package/dist/chunk-WDHBCA3M.js +31 -0
  44. package/dist/chunk-WDHBCA3M.js.map +1 -0
  45. package/dist/{chunk-HQPHZGL6.js → chunk-YLMUS4MM.js} +9 -9
  46. package/dist/{chunk-LQUTGLOZ.js → chunk-ZET2UAYW.js} +15 -65
  47. package/dist/chunk-ZET2UAYW.js.map +1 -0
  48. package/dist/contract/index.d.ts +4012 -38
  49. package/dist/contract/index.js +56 -29
  50. package/dist/contract/index.js.map +1 -1
  51. package/dist/control.d.ts +1013 -9
  52. package/dist/control.js +4 -3
  53. package/dist/fuzz.d.ts +194 -4
  54. package/dist/fuzz.js +3 -3
  55. package/dist/hosted/index.d.ts +498 -17
  56. package/dist/index.d.ts +10982 -1286
  57. package/dist/index.js +97 -80
  58. package/dist/index.js.map +1 -1
  59. package/dist/matrix/index.d.ts +139 -4
  60. package/dist/meta-eval/index.d.ts +862 -15
  61. package/dist/meta-eval/index.js +2 -1
  62. package/dist/meta-eval/index.js.map +1 -1
  63. package/dist/multishot/index.d.ts +214 -14
  64. package/dist/openapi.json +1 -1
  65. package/dist/pipelines/index.d.ts +392 -7
  66. package/dist/pipelines/index.js +5 -3
  67. package/dist/pipelines/index.js.map +1 -1
  68. package/dist/reporting.d.ts +1277 -17
  69. package/dist/rl.d.ts +2359 -28
  70. package/dist/rl.js +6 -5
  71. package/dist/rl.js.map +1 -1
  72. package/dist/storyboard/index.d.ts +86 -1
  73. package/dist/trace-attributes.d.ts +16 -0
  74. package/dist/trace-attributes.js +32 -0
  75. package/dist/trace-attributes.js.map +1 -0
  76. package/dist/traces.d.ts +1970 -697
  77. package/dist/traces.js +49 -32
  78. package/dist/wire/index.d.ts +655 -9
  79. package/docs/insight-report.md +44 -0
  80. package/package.json +9 -3
  81. package/dist/adversarial-B7loGVVX.d.ts +0 -19
  82. package/dist/analyst-C8HHvfJp.d.ts +0 -88
  83. package/dist/analyze-runs--2x39HZ7.d.ts +0 -81
  84. package/dist/baseline-DKq3gJpP.d.ts +0 -141
  85. package/dist/calibration-C8MTS7cw.d.ts +0 -101
  86. package/dist/chunk-5UF54T55.js.map +0 -1
  87. package/dist/chunk-E4BUPP7Z.js.map +0 -1
  88. package/dist/chunk-FQNLDL4D.js.map +0 -1
  89. package/dist/chunk-LQUTGLOZ.js.map +0 -1
  90. package/dist/chunk-S2F4J57L.js.map +0 -1
  91. package/dist/chunk-YZPO4UHR.js.map +0 -1
  92. package/dist/code-agent-session-CjZsVd19.d.ts +0 -87
  93. package/dist/control-6vuGfmDH.d.ts +0 -258
  94. package/dist/cost-ledger-DWy3XdJc.d.ts +0 -183
  95. package/dist/dataset-NENEzRgk.d.ts +0 -115
  96. package/dist/default-registry-DaK8b3fv.d.ts +0 -155
  97. package/dist/emitter-CjD7vUwv.d.ts +0 -122
  98. package/dist/errors-oeQrLqXC.d.ts +0 -74
  99. package/dist/failure-cluster-DOAcSJ87.d.ts +0 -76
  100. package/dist/feedback-trajectory-BUnM58xL.d.ts +0 -348
  101. package/dist/gepa-eESocoDi.d.ts +0 -642
  102. package/dist/index-PdX4VnPA.d.ts +0 -423
  103. package/dist/insight-report-DY4nDW9Q.d.ts +0 -310
  104. package/dist/integrity-DqlBiLyK.d.ts +0 -81
  105. package/dist/judge-calibration-7C-IDmKr.d.ts +0 -145
  106. package/dist/kind-factory-ClZmO25A.d.ts +0 -171
  107. package/dist/llm-client-qoDd18Qz.d.ts +0 -289
  108. package/dist/multi-layer-verifier-BsqKuLyN.d.ts +0 -150
  109. package/dist/off-policy-DiwuKKg7.d.ts +0 -132
  110. package/dist/outcome-store-rnXLEqSn.d.ts +0 -63
  111. package/dist/policy-edit-wG9uFEFm.d.ts +0 -455
  112. package/dist/pre-registration-BWQhJ3vz.d.ts +0 -761
  113. package/dist/provenance-DpjwyseI.d.ts +0 -541
  114. package/dist/query-CF7PG61p.d.ts +0 -35
  115. package/dist/raw-provider-sink-C46HDghv.d.ts +0 -132
  116. package/dist/release-report-C8G2i5Xi.d.ts +0 -236
  117. package/dist/researcher-C8XyxQsu.d.ts +0 -387
  118. package/dist/rubric-predictive-validity-p49lLVrE.d.ts +0 -105
  119. package/dist/run-record-BDH49H2E.d.ts +0 -360
  120. package/dist/runtime-trajectory-DGBIUt4B.d.ts +0 -49
  121. package/dist/schema-B3Q3l9Z_.d.ts +0 -201
  122. package/dist/semantic-concept-judge-CXnPEJbf.d.ts +0 -723
  123. package/dist/sequential-5iSVfzl2.d.ts +0 -139
  124. package/dist/series-convergence-D5OWMBg6.d.ts +0 -33
  125. package/dist/statistics-KUnG73jH.d.ts +0 -494
  126. package/dist/storage-DrX3v_5B.d.ts +0 -50
  127. package/dist/store-C1YxJDEK.d.ts +0 -248
  128. package/dist/store-DGqD0Pyo.d.ts +0 -116
  129. package/dist/summary-report-C5bKFfm-.d.ts +0 -445
  130. package/dist/test-graded-scenario-B0ybnPY7.d.ts +0 -166
  131. package/dist/types-BSw1rOUB.d.ts +0 -634
  132. package/dist/types-BUxNaJ8c.d.ts +0 -108
  133. package/dist/types-BkfcQnxV.d.ts +0 -313
  134. package/dist/verdict-C9MlYujm.d.ts +0 -35
  135. /package/dist/{chunk-VF3XSYTI.js.map → chunk-33JA4TFA.js.map} +0 -0
  136. /package/dist/{chunk-4JLWXDYA.js.map → chunk-3EHHMC6E.js.map} +0 -0
  137. /package/dist/{chunk-CCZIVI3F.js.map → chunk-BFW56GTT.js.map} +0 -0
  138. /package/dist/{chunk-HZHNRYHK.js.map → chunk-K6N6XJJX.js.map} +0 -0
  139. /package/dist/{chunk-MGEHEHSN.js.map → chunk-OIIMMLRB.js.map} +0 -0
  140. /package/dist/{chunk-DXZRATT5.js.map → chunk-OYZAPX5G.js.map} +0 -0
  141. /package/dist/{chunk-ODVOOEWQ.js.map → chunk-QBRSJK47.js.map} +0 -0
  142. /package/dist/{chunk-GQCZRZ7L.js.map → chunk-U5CHZ5M3.js.map} +0 -0
  143. /package/dist/{chunk-HQPHZGL6.js.map → chunk-YLMUS4MM.js.map} +0 -0
package/dist/control.d.ts CHANGED
@@ -1,9 +1,1013 @@
1
- export { A as ActionExecutionPolicy, a as ActionPolicyDecision, C as ControlRunToRunRecordOptions, e as ProposeReviewConfig, f as ProposeReviewControlAction, g as ProposeReviewControlConfig, h as ProposeReviewControlResult, i as ProposeReviewControlState, j as ProposeReviewReport, p as RunEvidenceMetadata, s as controlRunToRunRecord, u as evaluateActionPolicy, x as runProposeReview, y as runProposeReviewAsControlLoop, z as scoreFromEvals } from './control-6vuGfmDH.js';
2
- export { d as ControlActionFailureMode, e as ControlActionOutcome, f as ControlBudget, g as ControlContext, h as ControlDecision, a as ControlEvalResult, i as ControlRunResult, j as ControlRuntimeConfig, k as ControlRuntimeError, C as ControlSeverity, l as ControlStep, m as ControlStopPolicies, S as StopDecision, B as allCriticalPassed, M as objectiveEval, T as runAgentControlLoop, V as stopOnNoProgress, W as stopOnRepeatedAction, X as subjectiveEval } from './feedback-trajectory-BUnM58xL.js';
3
- import './emitter-CjD7vUwv.js';
4
- import './schema-B3Q3l9Z_.js';
5
- import './store-DGqD0Pyo.js';
6
- import './run-record-BDH49H2E.js';
7
- import '@tangle-network/agent-interface';
8
- import './errors-oeQrLqXC.js';
9
- import './dataset-NENEzRgk.js';
1
+ type RunStatus = 'running' | 'completed' | 'failed' | 'aborted';
2
+ interface BudgetSpec {
3
+ tokens?: number;
4
+ wallMs?: number;
5
+ calls?: number;
6
+ usd?: number;
7
+ }
8
+ interface RunOutcome$1 {
9
+ score?: number;
10
+ pass?: boolean;
11
+ failureClass?: FailureClass;
12
+ notes?: string;
13
+ }
14
+ /**
15
+ * Layer — optional classification in a nested build workflow.
16
+ * `builder`: the meta-agent editing a project (e.g. agent-builder Forge chat).
17
+ * `app-build`: sandbox harness that compiled + tested the generated scaffold.
18
+ * `app-runtime`: a run of the generated agent against a domain scenario.
19
+ * `meta`: any meta-eval (judge replay, correlation analysis).
20
+ */
21
+ type RunLayer = 'builder' | 'app-build' | 'app-runtime' | 'meta' | 'custom';
22
+ interface Run {
23
+ runId: string;
24
+ /**
25
+ * Stable identifier of the scenario being executed.
26
+ *
27
+ * Always populated on the persisted Run — but `TraceEmitter.startRun` accepts
28
+ * input WITHOUT this field, substituting a sensible default
29
+ * (`run.layer ?? run.tags?.['kind'] ?? 'runtime'`) when the caller has no
30
+ * curated scenario to anchor to (runtime / operator / meta-eval runs). This
31
+ * keeps the persisted shape unambiguous for downstream filters + aggregations
32
+ * while removing the boilerplate of inventing placeholder ids at the call site.
33
+ */
34
+ scenarioId: string;
35
+ variantId?: string;
36
+ datasetVersion?: string;
37
+ /** Git SHA of agent code at run time. */
38
+ codeSha?: string;
39
+ /** Hash of the prompt template + any system prompt. */
40
+ promptSha?: string;
41
+ /** Model id + date + system-prompt hash, concatenated. */
42
+ modelFingerprint?: string;
43
+ seed?: number;
44
+ /** Arbitrary environment markers (shell, docker version, tz). */
45
+ envFingerprint?: Record<string, string>;
46
+ /** Version of the redaction rules applied to this run. */
47
+ redactionVersion?: string;
48
+ /** Parent run in a nested build workflow. A builder run's children are
49
+ * app-build runs; those children are app-runtime runs. */
50
+ parentRunId?: string;
51
+ /** Stable project identifier — groups runs across chats + sessions. */
52
+ projectId?: string;
53
+ /** Chat/conversation identifier within a project. */
54
+ chatId?: string;
55
+ /** Layer classification — hint for aggregation; not enforced. */
56
+ layer?: RunLayer;
57
+ startedAt: number;
58
+ endedAt?: number;
59
+ status: RunStatus;
60
+ outcome?: RunOutcome$1;
61
+ budget?: BudgetSpec;
62
+ /** Free-form labels for downstream grouping. */
63
+ tags?: Record<string, string>;
64
+ }
65
+ type SpanKind = 'agent' | 'llm' | 'tool' | 'retrieval' | 'judge' | 'sandbox' | 'custom';
66
+ type SpanStatus = 'ok' | 'error';
67
+ interface SpanBase {
68
+ spanId: string;
69
+ parentSpanId?: string;
70
+ runId: string;
71
+ kind: SpanKind;
72
+ name: string;
73
+ startedAt: number;
74
+ endedAt?: number;
75
+ status?: SpanStatus;
76
+ error?: string;
77
+ /** Anything not covered by typed fields. Kept deliberately free-form. */
78
+ attributes?: Record<string, unknown>;
79
+ }
80
+ interface Message {
81
+ role: 'system' | 'user' | 'assistant' | 'tool';
82
+ content: string;
83
+ tokens?: number;
84
+ /** Multi-modal content descriptors; blobs themselves live in Artifacts. */
85
+ images?: Array<{
86
+ artifactId?: string;
87
+ url?: string;
88
+ mime?: string;
89
+ }>;
90
+ }
91
+ interface LlmSpan extends SpanBase {
92
+ kind: 'llm';
93
+ model: string;
94
+ messages: Message[];
95
+ output?: string;
96
+ inputTokens?: number;
97
+ /** All generated tokens, including the reasoning subset when present. */
98
+ outputTokens?: number;
99
+ cachedTokens?: number;
100
+ cacheWriteTokens?: number;
101
+ /** Reasoning-token subset of `outputTokens`. */
102
+ reasoningTokens?: number;
103
+ costUsd?: number;
104
+ finishReason?: string;
105
+ }
106
+ interface ToolSpan extends SpanBase {
107
+ kind: 'tool';
108
+ toolName: string;
109
+ args: unknown;
110
+ /** False when the source observed the call but did not capture its arguments. */
111
+ argsCaptured?: boolean;
112
+ result?: unknown;
113
+ latencyMs?: number;
114
+ }
115
+ interface RetrievalSpan extends SpanBase {
116
+ kind: 'retrieval';
117
+ query: string;
118
+ hits: Array<{
119
+ docId: string;
120
+ score: number;
121
+ content?: string;
122
+ }>;
123
+ }
124
+ interface JudgeSpan extends SpanBase {
125
+ kind: 'judge';
126
+ judgeId: string;
127
+ /** Span this judgment applies to. */
128
+ targetSpanId: string;
129
+ dimension: string;
130
+ /** Numeric score (free-range; interpretation up to the judge). */
131
+ score: number;
132
+ rationale?: string;
133
+ evidence?: string;
134
+ }
135
+ interface SandboxSpan extends SpanBase {
136
+ kind: 'sandbox';
137
+ image?: string;
138
+ command?: string;
139
+ exitCode?: number;
140
+ testsTotal?: number;
141
+ testsPassed?: number;
142
+ stdoutHash?: string;
143
+ stderrHash?: string;
144
+ /** Duration in ms; the harness fills this explicitly (endedAt - startedAt may miss setup). */
145
+ wallMs?: number;
146
+ }
147
+ interface GenericSpan extends SpanBase {
148
+ kind: 'agent' | 'custom';
149
+ }
150
+ type Span = LlmSpan | ToolSpan | RetrievalSpan | JudgeSpan | SandboxSpan | GenericSpan;
151
+ type EventKind = 'log' | 'error' | 'budget_decrement' | 'budget_breach' | 'state_mutation' | 'policy_violation' | 'redaction_applied' | 'custom';
152
+ interface TraceEvent {
153
+ eventId: string;
154
+ runId: string;
155
+ spanId?: string;
156
+ kind: EventKind;
157
+ timestamp: number;
158
+ payload: Record<string, unknown>;
159
+ }
160
+ interface BudgetLedgerEntry {
161
+ runId: string;
162
+ dimension: keyof BudgetSpec;
163
+ limit: number;
164
+ consumed: number;
165
+ remaining: number;
166
+ timestamp: number;
167
+ breached: boolean;
168
+ /** Span that triggered this entry, if any. */
169
+ spanId?: string;
170
+ }
171
+ interface Artifact {
172
+ artifactId: string;
173
+ runId: string;
174
+ spanId?: string;
175
+ contentType: string;
176
+ sizeBytes: number;
177
+ /** sha256 in hex. */
178
+ hash: string;
179
+ /** External storage URL (R2, S3, filesystem path). */
180
+ storageUrl?: string;
181
+ /** Inline content for small blobs — keep under ~64KB. */
182
+ inlineContent?: string;
183
+ }
184
+ type FailureClass = 'success' | 'reasoning_error' | 'tool_selection_error' | 'tool_argument_error' | 'tool_recovery_failure' | 'hallucination' | 'instruction_following' | 'safety_refusal_miss' | 'policy_violation' | 'budget_exceeded' | 'format_drift' | 'permission_escalation' | 'pii_leak' | 'cost_overrun' | 'timeout' | 'sandbox_failure' | 'missing_user_data' | 'missing_domain_data' | 'missing_codebase_context' | 'missing_runtime_context' | 'missing_credentials' | 'missing_integration_connection' | 'missing_integration_scope' | 'integration_approval_required' | 'integration_auth_expired' | 'integration_provider_failure' | 'bad_integration_manifest' | 'unsafe_integration_write_denied' | 'stale_external_data' | 'bad_retrieval' | 'insufficient_evidence' | 'contradictory_evidence' | 'ambiguous_user_intent' | 'knowledge_readiness_blocked' | 'unknown';
185
+
186
+ interface RunFilter {
187
+ scenarioId?: string;
188
+ variantId?: string;
189
+ status?: RunStatus;
190
+ since?: number;
191
+ until?: number;
192
+ tag?: {
193
+ key: string;
194
+ value: string;
195
+ };
196
+ parentRunId?: string;
197
+ projectId?: string;
198
+ chatId?: string;
199
+ layer?: RunLayer;
200
+ }
201
+ interface SpanFilter {
202
+ runId?: string;
203
+ parentSpanId?: string;
204
+ kind?: SpanKind;
205
+ name?: string;
206
+ toolName?: string;
207
+ judgeId?: string;
208
+ since?: number;
209
+ until?: number;
210
+ }
211
+ interface EventFilter {
212
+ runId?: string;
213
+ spanId?: string;
214
+ kind?: EventKind;
215
+ since?: number;
216
+ until?: number;
217
+ }
218
+ interface TraceStore {
219
+ appendRun(run: Run): Promise<void>;
220
+ updateRun(runId: string, patch: Partial<Run>): Promise<void>;
221
+ appendSpan(span: Span): Promise<void>;
222
+ updateSpan(spanId: string, patch: Partial<Span>): Promise<void>;
223
+ appendEvent(event: TraceEvent): Promise<void>;
224
+ appendArtifact(artifact: Artifact): Promise<void>;
225
+ appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void>;
226
+ getRun(runId: string): Promise<Run | undefined>;
227
+ listRuns(filter?: RunFilter): Promise<Run[]>;
228
+ spans(filter?: SpanFilter): Promise<Span[]>;
229
+ events(filter?: EventFilter): Promise<TraceEvent[]>;
230
+ budget(runId: string): Promise<BudgetLedgerEntry[]>;
231
+ artifacts(runId: string): Promise<Artifact[]>;
232
+ }
233
+
234
+ /**
235
+ * TraceEmitter — hierarchical span builder that auto-parents using an
236
+ * internal stack. One emitter per Run; emitters do NOT share state.
237
+ *
238
+ * Convenience methods (`llm`, `tool`, `retrieval`, `judge`, `sandbox`)
239
+ * return a `SpanHandle` with `.end()` / `.fail()` so callers don't
240
+ * have to thread spanIds manually. For async workflows that can't use
241
+ * the stack (e.g. fan-out parallel calls), pass `parentSpanId`
242
+ * explicitly.
243
+ */
244
+
245
+ interface SpanHandle<S extends Span = Span> {
246
+ span: S;
247
+ end(patch?: Partial<S>): Promise<void>;
248
+ fail(error: string | Error, patch?: Partial<S>): Promise<void>;
249
+ }
250
+ interface RunCompleteHookContext {
251
+ runId: string;
252
+ emitter: TraceEmitter;
253
+ store: TraceStore;
254
+ /** Outcome the caller passed to `endRun` (undefined for `abortRun`). */
255
+ outcome?: RunOutcome$1;
256
+ /** Final run status. */
257
+ status: 'completed' | 'failed' | 'aborted';
258
+ }
259
+ type RunCompleteHook = (ctx: RunCompleteHookContext) => Promise<void> | void;
260
+ interface TraceEmitterOptions {
261
+ runId?: string;
262
+ /** Inject a clock for deterministic tests. */
263
+ now?: () => number;
264
+ /** Inject an id generator for deterministic tests. */
265
+ id?: () => string;
266
+ /**
267
+ * Hooks fired after `endRun` / `abortRun` writes the final run state.
268
+ * Designed for trace-analyst auto-execution, integrity assertions, and
269
+ * outbound notifications. Hooks run sequentially in the order supplied.
270
+ *
271
+ * By default a hook that throws is swallowed and logged as a `note` event
272
+ * on the run — auto-orchestration must not crash the underlying flow.
273
+ * Set `hookErrors: 'throw'` to propagate.
274
+ */
275
+ onRunComplete?: RunCompleteHook[];
276
+ /** `'swallow'` (default) | `'throw'`. */
277
+ hookErrors?: 'swallow' | 'throw';
278
+ }
279
+ declare class TraceEmitter {
280
+ private store;
281
+ private stack;
282
+ private _runId;
283
+ private now;
284
+ private id;
285
+ private hooks;
286
+ private hookErrors;
287
+ constructor(store: TraceStore, options?: TraceEmitterOptions);
288
+ get runId(): string;
289
+ get traceStore(): TraceStore;
290
+ /** Append a hook after construction (e.g. attach the trace analyst). */
291
+ addRunCompleteHook(hook: RunCompleteHook): void;
292
+ /**
293
+ * Begin a Run.
294
+ *
295
+ * `scenarioId` is required on the persisted Run shape — every Run downstream
296
+ * gets a non-empty scenarioId so filters and aggregations stay simple — but
297
+ * the INPUT here accepts it as optional. When omitted, startRun substitutes
298
+ * a sensible default (`run.layer ?? run.tags?.['kind'] ?? 'runtime'`) so
299
+ * runtime / operator / meta-eval runs that have no curated-scenario corpus
300
+ * to anchor to don't have to invent placeholder strings at the call site.
301
+ */
302
+ startRun(run: Omit<Run, 'runId' | 'scenarioId' | 'startedAt' | 'status'> & {
303
+ scenarioId?: string;
304
+ }): Promise<Run>;
305
+ endRun(outcome?: RunOutcome$1): Promise<void>;
306
+ abortRun(reason: string): Promise<void>;
307
+ private runHooks;
308
+ span<S extends Span = Span>(init: {
309
+ kind: SpanKind;
310
+ name: string;
311
+ parentSpanId?: string;
312
+ attributes?: Record<string, unknown>;
313
+ } & Partial<Omit<S, 'spanId' | 'runId' | 'startedAt' | 'kind' | 'name'>>): Promise<SpanHandle<S>>;
314
+ private handle;
315
+ private pop;
316
+ llm(init: Omit<LlmSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<LlmSpan>>;
317
+ tool(init: Omit<ToolSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<ToolSpan>>;
318
+ retrieval(init: Omit<RetrievalSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<RetrievalSpan>>;
319
+ recordJudge(verdict: Omit<JudgeSpan, 'spanId' | 'runId' | 'kind' | 'startedAt' | 'endedAt'>): Promise<JudgeSpan>;
320
+ sandbox(init: Omit<SandboxSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<SandboxSpan>>;
321
+ emit(event: {
322
+ kind: EventKind;
323
+ spanId?: string;
324
+ payload?: Record<string, unknown>;
325
+ }): Promise<TraceEvent>;
326
+ recordBudget(entry: Omit<BudgetLedgerEntry, 'runId' | 'timestamp'> & {
327
+ timestamp?: number;
328
+ }): Promise<BudgetLedgerEntry>;
329
+ recordArtifact(artifact: Omit<Artifact, 'artifactId' | 'runId'>): Promise<Artifact>;
330
+ /**
331
+ * Runs `fn` inside a span; auto-ends on success, auto-fails on throw.
332
+ * Returns the fn's return value. Use this for the 95% case.
333
+ */
334
+ within<T>(init: Parameters<TraceEmitter['span']>[0], fn: (handle: SpanHandle) => Promise<T>): Promise<T>;
335
+ }
336
+
337
+ /**
338
+ * Policy-based agent control runtime.
339
+ *
340
+ * This is the minimal reusable loop behind driver-agent patterns:
341
+ *
342
+ * observe state -> validate -> decide next action -> act -> observe -> ...
343
+ *
344
+ * It deliberately does not model named "topologies". Direct execution,
345
+ * critic/revise, driver intervention, specialist calls, and human escalation
346
+ * are all just actions chosen by the control policy.
347
+ */
348
+
349
+ type ControlSeverity = 'info' | 'warning' | 'error' | 'critical';
350
+ type ControlActionFailureMode = 'continue' | 'stop';
351
+ interface ControlEvalResult {
352
+ /** Stable validator or judge id. */
353
+ id: string;
354
+ /** Whether this check passed. */
355
+ passed: boolean;
356
+ /** Optional normalized score. 1 = best, 0 = worst. */
357
+ score?: number;
358
+ /** Objective validators should usually be "error" or "critical" when failed. */
359
+ severity?: ControlSeverity;
360
+ /** Human-readable result. */
361
+ detail?: string;
362
+ /** Small evidence string or pointer. Avoid large payloads. */
363
+ evidence?: string;
364
+ /** True when the result came from deterministic state, not LLM judgment. */
365
+ objective?: boolean;
366
+ /** Structured details for downstream control policies and reports. */
367
+ metadata?: Record<string, unknown>;
368
+ }
369
+ interface ControlBudget {
370
+ maxSteps: number;
371
+ maxWallMs?: number;
372
+ maxCostUsd?: number;
373
+ }
374
+ interface ControlStopPolicies<TState, TAction> {
375
+ /**
376
+ * Stop after N consecutive steps with no state fingerprint change and
377
+ * less than `minScoreDelta` score movement. Disabled when omitted.
378
+ */
379
+ maxNoProgressSteps?: number;
380
+ /**
381
+ * Stop after the same action fingerprint is selected N consecutive
382
+ * times. Disabled when omitted.
383
+ */
384
+ maxRepeatedActions?: number;
385
+ /** Minimum score movement that counts as progress. Default 0.001. */
386
+ minScoreDelta?: number;
387
+ /** Override the default JSON/string fingerprint for state comparisons. */
388
+ stateFingerprint?: (state: TState) => string;
389
+ /** Override the default JSON/string fingerprint for repeated-action checks. */
390
+ actionFingerprint?: (action: TAction) => string;
391
+ }
392
+ interface ControlContext<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult> {
393
+ intent: string;
394
+ state: TState;
395
+ evals: TEval[];
396
+ history: ControlStep<TState, TAction, TActionResult, TEval>[];
397
+ budget: ControlBudget;
398
+ stepIndex: number;
399
+ wallMs: number;
400
+ spentCostUsd: number;
401
+ remainingCostUsd?: number;
402
+ abortSignal: AbortSignal;
403
+ emitter?: TraceEmitter;
404
+ }
405
+ type ControlDecision<TAction> = {
406
+ type: 'continue';
407
+ action: TAction;
408
+ reason?: string;
409
+ } | {
410
+ type: 'stop';
411
+ reason: string;
412
+ pass?: boolean;
413
+ score?: number;
414
+ };
415
+ interface StopDecision {
416
+ stop: boolean;
417
+ pass: boolean;
418
+ reason: string;
419
+ score?: number;
420
+ failureClass?: FailureClass;
421
+ }
422
+ interface ControlActionOutcome<TActionResult> {
423
+ ok: boolean;
424
+ result?: TActionResult;
425
+ error?: string;
426
+ costUsd?: number;
427
+ durationMs: number;
428
+ }
429
+ interface ControlRuntimeError {
430
+ phase: 'observe' | 'validate' | 'decide' | 'act' | 'stop-policy' | 'on-step' | 'trace';
431
+ stepIndex: number;
432
+ message: string;
433
+ }
434
+ interface ControlStep<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult> {
435
+ index: number;
436
+ decision: ControlDecision<TAction>;
437
+ beforeState: TState;
438
+ afterState: TState;
439
+ evalsBefore: TEval[];
440
+ evalsAfter: TEval[];
441
+ actionOutcome?: ControlActionOutcome<TActionResult>;
442
+ startedAt: string;
443
+ endedAt: string;
444
+ }
445
+ interface ControlRunResult<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult> {
446
+ intent: string;
447
+ pass: boolean;
448
+ completed: boolean;
449
+ reason: string;
450
+ score?: number;
451
+ steps: ControlStep<TState, TAction, TActionResult, TEval>[];
452
+ finalState: TState | undefined;
453
+ finalEvals: TEval[];
454
+ wallMs: number;
455
+ spentCostUsd: number;
456
+ /** null when the run executed without a TraceEmitter wired (no run record was persisted). */
457
+ runId: string | null;
458
+ failureClass?: FailureClass;
459
+ runtimeErrors: ControlRuntimeError[];
460
+ stoppedBy: 'policy' | 'stop-policy' | 'budget' | 'abort' | 'runtime-error';
461
+ }
462
+ interface ControlRuntimeConfig<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult> {
463
+ intent: string;
464
+ budget?: Partial<ControlBudget>;
465
+ signal?: AbortSignal;
466
+ /** Defaults to `continue`: action failures are recorded, then the policy gets another chance. */
467
+ actionFailure?: ControlActionFailureMode;
468
+ /**
469
+ * Extract cost from an action result. Used for `maxCostUsd` budget
470
+ * enforcement and trace budget ledger emission.
471
+ */
472
+ getActionCostUsd?: (ctx: {
473
+ action: TAction;
474
+ result: TActionResult;
475
+ state: TState;
476
+ evals: TEval[];
477
+ history: ControlStep<TState, TAction, TActionResult, TEval>[];
478
+ }) => number | undefined;
479
+ /** Read typed task/product state. Prefer structured state over transcript-only context. */
480
+ observe: (ctx: {
481
+ history: ControlStep<TState, TAction, TActionResult, TEval>[];
482
+ abortSignal: AbortSignal;
483
+ }) => Promise<TState> | TState;
484
+ /** Objective validators first, subjective judges only where objective state is insufficient. */
485
+ validate: (ctx: {
486
+ intent: string;
487
+ state: TState;
488
+ history: ControlStep<TState, TAction, TActionResult, TEval>[];
489
+ abortSignal: AbortSignal;
490
+ }) => Promise<TEval[]> | TEval[];
491
+ /** Choose the next control action. Can call a worker, ask user, run critic, inspect state, or stop. */
492
+ decide: (ctx: ControlContext<TState, TAction, TActionResult, TEval>) => Promise<ControlDecision<TAction>> | ControlDecision<TAction>;
493
+ /** Execute the action selected by the policy. */
494
+ act: (action: TAction, ctx: ControlContext<TState, TAction, TActionResult, TEval>) => Promise<TActionResult> | TActionResult;
495
+ /** Final stopping policy. Called before decide and after each action. */
496
+ shouldStop?: (ctx: ControlContext<TState, TAction, TActionResult, TEval>) => Promise<StopDecision> | StopDecision;
497
+ /** Optional hook for tracing or live progress updates. */
498
+ onStep?: (step: ControlStep<TState, TAction, TActionResult, TEval>) => Promise<void> | void;
499
+ /** Optional generic stuck-loop policies. Custom `shouldStop` still runs first. */
500
+ stopPolicies?: ControlStopPolicies<TState, TAction>;
501
+ /** Optional trace sink. Emits one run plus one span per control step. */
502
+ store?: TraceStore;
503
+ scenarioId?: string;
504
+ projectId?: string;
505
+ variantId?: string;
506
+ }
507
+ declare function runAgentControlLoop<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult>(config: ControlRuntimeConfig<TState, TAction, TActionResult, TEval>): Promise<ControlRunResult<TState, TAction, TActionResult, TEval>>;
508
+ declare function stopOnNoProgress<TState, TAction>(maxNoProgressSteps: number, options?: Omit<ControlStopPolicies<TState, TAction>, 'maxNoProgressSteps'>): ControlStopPolicies<TState, TAction>;
509
+ declare function stopOnRepeatedAction<TState, TAction>(maxRepeatedActions: number, options?: Omit<ControlStopPolicies<TState, TAction>, 'maxRepeatedActions'>): ControlStopPolicies<TState, TAction>;
510
+ declare function objectiveEval(input: Omit<ControlEvalResult, 'objective'>): ControlEvalResult;
511
+ declare function subjectiveEval(input: Omit<ControlEvalResult, 'objective'>): ControlEvalResult;
512
+ declare function allCriticalPassed(evals: ControlEvalResult[]): boolean;
513
+
514
+ type FeedbackLabelSource = 'user' | 'judge' | 'environment' | 'metric' | 'policy' | 'system';
515
+ type FeedbackLabelKind = 'approve' | 'reject' | 'select' | 'edit' | 'rank' | 'rate' | 'comment' | 'metric_outcome' | 'policy_block' | 'revision_request';
516
+ type FeedbackSeverity = 'info' | 'warning' | 'error' | 'critical';
517
+ interface ProposedSideEffect {
518
+ type: string;
519
+ risk?: 'low' | 'medium' | 'high';
520
+ costUsd?: number;
521
+ externalSideEffect?: boolean;
522
+ requiresApproval?: boolean;
523
+ metadata?: Record<string, unknown>;
524
+ }
525
+ interface FeedbackLabel {
526
+ id?: string;
527
+ source: FeedbackLabelSource;
528
+ kind: FeedbackLabelKind;
529
+ value: unknown;
530
+ reason?: string;
531
+ severity?: FeedbackSeverity;
532
+ createdAt: string;
533
+ metadata?: Record<string, unknown>;
534
+ }
535
+
536
+ interface ActionExecutionPolicy {
537
+ allowedTypes?: string[];
538
+ blockedTypes?: string[];
539
+ alwaysRequireApprovalTypes?: string[];
540
+ autoApproveTypes?: string[];
541
+ requireApprovalForExternalSideEffects?: boolean;
542
+ requireApprovalAboveCostUsd?: number;
543
+ maxActionCostUsd?: number;
544
+ remainingBudgetUsd?: number;
545
+ expectedOutcomeRequired?: boolean;
546
+ killCriteriaRequired?: boolean;
547
+ }
548
+ interface ActionPolicyDecision {
549
+ allowed: boolean;
550
+ blocked: boolean;
551
+ requiresApproval: boolean;
552
+ reasons: string[];
553
+ label?: FeedbackLabel;
554
+ }
555
+ declare function evaluateActionPolicy(action: ProposedSideEffect, policy?: ActionExecutionPolicy, options?: {
556
+ createdAt?: string;
557
+ }): ActionPolicyDecision;
558
+
559
+ /**
560
+ * Propose / Verify / Review — the core multi-shot primitive.
561
+ *
562
+ * shot N: propose(state, priorReview) → new state
563
+ * verify(state) → pass/fail, optional layers
564
+ * review(state, verification, memory) → observations + next-shot
565
+ * instruction + shouldContinue
566
+ * memory.append(entry)
567
+ *
568
+ * Roles are strictly separated:
569
+ *
570
+ * - The WORKER is whatever the caller wraps in `propose`. It is
571
+ * stateful — caller owns its resume/session mechanism.
572
+ * - The VERIFIER grades the state. It produces the ground truth.
573
+ * The reviewer cannot overturn or downgrade a verification layer.
574
+ * - The REVIEWER is stateless per call. Its continuity is the
575
+ * `ReviewMemoryStore` — durable JSONL by default, or any store
576
+ * implementing the interface. It reads memory + trace summary +
577
+ * verification and directs the NEXT proposer shot.
578
+ *
579
+ * This shape is load-bearing. The reviewer never grades; the verifier
580
+ * never directs. Two processes, two prompts, two concerns — which is
581
+ * what keeps the loop from confirmation-biasing itself into "all
582
+ * passed" when it didn't.
583
+ *
584
+ * Short-circuits and soft-fails are both first-class:
585
+ * - verify.pass === true → reviewer LLM call is skipped, memory
586
+ * records a success entry, loop exits.
587
+ * - review throws → the shot still counts; the loop uses the
588
+ * last-known instruction (or `fallbackInstruction`) for the next
589
+ * propose call. A transient reviewer failure must NEVER abort a
590
+ * valid arc.
591
+ *
592
+ * Composable: `propose` itself can be another `runProposeReview` call.
593
+ * That's the dogfooding path — a harness built on this primitive is in
594
+ * turn evaluable by it.
595
+ */
596
+
597
+ interface Verification {
598
+ pass: boolean;
599
+ score?: number;
600
+ failingLayers?: string[];
601
+ details?: unknown;
602
+ }
603
+ interface Review {
604
+ observations: string;
605
+ diagnosis: string;
606
+ nextShotInstruction: string;
607
+ shouldContinue: boolean;
608
+ confidence: number;
609
+ }
610
+ interface ReviewMemoryEntry extends Review {
611
+ shot: number;
612
+ timestamp: number;
613
+ verification: {
614
+ pass: boolean;
615
+ score?: number;
616
+ failingLayers?: string[];
617
+ };
618
+ }
619
+ interface ProposeInput<State> {
620
+ shot: number;
621
+ goal: string;
622
+ state: State;
623
+ priorReview: Review | null;
624
+ abortSignal: AbortSignal;
625
+ emitter?: TraceEmitter;
626
+ }
627
+ interface ProposeOutput<State, Summary = unknown> {
628
+ state: State;
629
+ traceSummary?: Summary;
630
+ }
631
+ interface ReviewInput<State, Summary = unknown> {
632
+ shot: number;
633
+ goal: string;
634
+ state: State;
635
+ verification: Verification;
636
+ traceSummary: Summary | undefined;
637
+ memory: ReviewMemoryEntry[];
638
+ }
639
+ type ProposeFn<State, Summary = unknown> = (input: ProposeInput<State>) => Promise<ProposeOutput<State, Summary>>;
640
+ type VerifyFn<State> = (state: State) => Promise<Verification>;
641
+ type ReviewFn<State, Summary = unknown> = (input: ReviewInput<State, Summary>) => Promise<Review>;
642
+ interface ReviewMemoryStore {
643
+ load(): Promise<ReviewMemoryEntry[]>;
644
+ append(entry: ReviewMemoryEntry): Promise<void>;
645
+ }
646
+ interface ProposeReviewConfig<State, Summary = unknown> {
647
+ goal: string;
648
+ initialState: State;
649
+ propose: ProposeFn<State, Summary>;
650
+ verify: VerifyFn<State>;
651
+ review: ReviewFn<State, Summary>;
652
+ /** Hard shot cap. Default 10. */
653
+ maxShots?: number;
654
+ /** Wall-clock cap in ms. Default 10 min. */
655
+ maxWallMs?: number;
656
+ /**
657
+ * If the reviewer returns confidence ≤ floor on `confidenceFloorWindow`
658
+ * consecutive shots, terminate early. Default floor 0.3, window 2.
659
+ * Set window to 0 or floor to <0 to disable.
660
+ */
661
+ confidenceFloor?: number;
662
+ confidenceFloorWindow?: number;
663
+ /** Defaults to an in-memory store if omitted. */
664
+ memory?: ReviewMemoryStore;
665
+ /** If provided, emit a Run + per-shot spans. */
666
+ store?: TraceStore;
667
+ scenarioId?: string;
668
+ projectId?: string;
669
+ variantId?: string;
670
+ /**
671
+ * Used when the reviewer soft-fails on shot 1 (no prior instruction to
672
+ * fall back to). Default is a generic "inspect failures and fix".
673
+ */
674
+ fallbackInstruction?: string;
675
+ }
676
+ interface ProposeReviewShot<State, Summary = unknown> {
677
+ shot: number;
678
+ state: State;
679
+ verification: Verification;
680
+ traceSummary: Summary | undefined;
681
+ review: Review;
682
+ reviewAvailable: boolean;
683
+ reviewError?: string;
684
+ durationMs: number;
685
+ }
686
+ interface ProposeReviewReport<State, Summary = unknown> {
687
+ runId: string | null;
688
+ completed: boolean;
689
+ shots: ProposeReviewShot<State, Summary>[];
690
+ finalState: State;
691
+ finalVerification: Verification;
692
+ failureClass?: FailureClass;
693
+ wallMs: number;
694
+ score: number;
695
+ }
696
+ declare function runProposeReview<State, Summary = unknown>(config: ProposeReviewConfig<State, Summary>): Promise<ProposeReviewReport<State, Summary>>;
697
+
698
+ interface ProposeReviewControlState<State, Summary = unknown> {
699
+ shot: number;
700
+ state: State;
701
+ priorReview: Review | null;
702
+ verification: Verification;
703
+ traceSummary?: Summary;
704
+ memory: ReviewMemoryEntry[];
705
+ completed: boolean;
706
+ reviewAvailable: boolean;
707
+ reviewError?: string;
708
+ }
709
+ interface ProposeReviewControlAction {
710
+ type: 'propose-review-shot';
711
+ shot: number;
712
+ }
713
+ interface ProposeReviewControlResult<State, Summary = unknown> {
714
+ state: State;
715
+ verification: Verification;
716
+ traceSummary?: Summary;
717
+ review: Review | null;
718
+ reviewAvailable: boolean;
719
+ reviewError?: string;
720
+ }
721
+ interface ProposeReviewControlConfig<State, Summary = unknown> {
722
+ goal: string;
723
+ initialState: State;
724
+ propose: ProposeFn<State, Summary>;
725
+ verify: VerifyFn<State>;
726
+ review: ReviewFn<State, Summary>;
727
+ maxShots?: number;
728
+ maxWallMs?: number;
729
+ memory?: ReviewMemoryStore;
730
+ store?: TraceStore;
731
+ scenarioId?: string;
732
+ projectId?: string;
733
+ variantId?: string;
734
+ fallbackInstruction?: string;
735
+ confidenceFloor?: number;
736
+ confidenceFloorWindow?: number;
737
+ failureClassFromVerification?: (verification: Verification) => FailureClass | undefined;
738
+ actionFailure?: ControlRuntimeConfig<ProposeReviewControlState<State, Summary>, ProposeReviewControlAction, ProposeReviewControlResult<State, Summary>>['actionFailure'];
739
+ }
740
+ declare function runProposeReviewAsControlLoop<State, Summary = unknown>(config: ProposeReviewControlConfig<State, Summary>): Promise<ControlRunResult<ProposeReviewControlState<State, Summary>, ProposeReviewControlAction, ProposeReviewControlResult<State, Summary>>>;
741
+
742
+ type AgentProfileCellSchemaVersion = 'agent-profile-cell/v1';
743
+ type AgentProfileDimensionValue = string | number | boolean | null;
744
+ interface AgentProfileSource {
745
+ /** Runtime/profile contract being fingerprinted, e.g. `agent-interface-profile`. */
746
+ kind: string;
747
+ /** sha256 over the canonical source profile object. */
748
+ hash: string;
749
+ }
750
+ interface AgentProfileHarness {
751
+ id: string;
752
+ version?: string;
753
+ hash?: string;
754
+ }
755
+ interface AgentProfileCell {
756
+ schemaVersion: AgentProfileCellSchemaVersion;
757
+ cellId: string;
758
+ profileId: string;
759
+ sourceProfile: AgentProfileSource;
760
+ harness?: AgentProfileHarness;
761
+ model?: string;
762
+ promptHash?: string;
763
+ dimensions?: Record<string, AgentProfileDimensionValue>;
764
+ }
765
+
766
+ /**
767
+ * Paper-grade RunRecord schema + runtime validator.
768
+ *
769
+ * Every run that participates in a promotion gate, paper table, or
770
+ * researcher loop SHOULD be recorded as a `RunRecord`. The mandatory
771
+ * fields are exactly those the paper "Two Loops, Three Roles" requires
772
+ * for reproducibility: who/what/when/cost/seed/hash, plus the search vs
773
+ * holdout split tag and either a `searchScore` or a `holdoutScore`.
774
+ *
775
+ * This is intentionally NOT a replacement for the rich `Run` /
776
+ * `ProposeReviewReport` / `ScenarioResult` types already in the
777
+ * package. Those are runtime structures with full provenance. A
778
+ * `RunRecord` is the analysis-time projection — the JSON-friendly
779
+ * row you'd put in a parquet file or paste into a notebook.
780
+ *
781
+ * Validate at the boundary:
782
+ *
783
+ * const rec = validateRunRecord(rawJson) // throws on missing
784
+ * const ok = isRunRecord(rawJson) // boolean check
785
+ * const rec = parseRunRecordSafe(rawJson) // { ok, value | error }
786
+ *
787
+ * The validator runs in pure TS — zod is intentionally NOT a
788
+ * dependency. Round-trip tested in `tests/run-record.test.ts`.
789
+ */
790
+
791
+ /** Search/dev/holdout split tag. 'search' is the paper-grade alias for the
792
+ * combined train+test pool that the optimizer is allowed to read. */
793
+ type RunSplitTag = 'search' | 'dev' | 'holdout';
794
+ interface RunTokenUsage {
795
+ input: number;
796
+ /** All generated tokens charged as output, including reasoning tokens. */
797
+ output: number;
798
+ /** Reasoning-token subset of `output`, when the provider reports it. */
799
+ reasoning?: number;
800
+ /** Prompt tokens served from a provider cache. */
801
+ cached?: number;
802
+ /** Prompt tokens written into a provider cache. */
803
+ cacheWrite?: number;
804
+ }
805
+ /**
806
+ * How a run's USD amount was obtained.
807
+ *
808
+ * `costUsd` remains mandatory for wire compatibility. New producers should
809
+ * always populate this discriminated union so a missing bill is never
810
+ * mistaken for an observed zero-dollar run. For `uncaptured`, `costUsd` uses
811
+ * the legacy `0` sentinel while this field carries the truthful null.
812
+ */
813
+ type RunCostProvenance = {
814
+ kind: 'observed';
815
+ usd: number;
816
+ } | {
817
+ kind: 'estimated';
818
+ usd: number;
819
+ } | {
820
+ kind: 'uncaptured';
821
+ usd: null;
822
+ };
823
+ interface RunJudgeMetadata {
824
+ model: string;
825
+ promptVersion: string;
826
+ /** [0,1] confidence the judge declared. Constant judge confidence
827
+ * across many runs is a fallback signal (see `canary.ts`). */
828
+ confidence: number;
829
+ /** True if the judge degraded to a fallback path (rules-only,
830
+ * prior-call cache, etc.). The canary uses this to alert. */
831
+ fallback: boolean;
832
+ }
833
+ /**
834
+ * Per-judge / per-dimension breakdown for runs scored by an ensemble of
835
+ * judges over a multi-dimensional rubric.
836
+ *
837
+ * The collapsed `outcome.searchScore` / `holdoutScore` carries the
838
+ * composite the gate uses. The full breakdown belongs here so consumers
839
+ * can answer "which judge disagreed?", "which dimension dragged the
840
+ * composite down?", and "did half the panel fail?" without re-running.
841
+ *
842
+ * `perJudge[judgeId][dim]` is the canonical source; `perDimMean` and
843
+ * `composite` are convenience projections — derivable but precomputed so
844
+ * downstream IRR primitives (`interRaterReliability`,
845
+ * `corpusInterRaterAgreement`) and reporters don't pay the same
846
+ * aggregation twice.
847
+ *
848
+ * Fail-loud discipline: judges that errored out land in `failedJudges`
849
+ * by id. A missing key in `perJudge` is ambiguous (silent zero vs not
850
+ * run); the explicit list makes a partial-failure recorded as such.
851
+ */
852
+ interface JudgeScoresRecord {
853
+ /** Per-judge per-dimension scores. `{ "kimi-k2.6": { helpfulness: 0.8, clarity: 0.7 }, ... }`. */
854
+ perJudge: Record<string, Record<string, number>>;
855
+ /** Per-dim mean across judges. Convenience — derivable from `perJudge`. */
856
+ perDimMean: Record<string, number>;
857
+ /** Composite mean across all dims and judges. Mirrors the score
858
+ * the gate sees on `outcome.searchScore` / `holdoutScore`. */
859
+ composite: number;
860
+ /** Judges that errored or returned an unparseable verdict. Recorded
861
+ * by id (e.g. `['glm-5.1']`) so a partial-failure case is explicit,
862
+ * not inferred from missing keys in `perJudge`. */
863
+ failedJudges?: string[];
864
+ /** Free-form notes the judges emitted (joined across judges or
865
+ * first-judge only — consumer's choice). */
866
+ notes?: string;
867
+ }
868
+ interface RunOutcome {
869
+ /** Score on the search/optimization split. Optional because a
870
+ * holdout-only evaluation only fills `holdoutScore`. */
871
+ searchScore?: number;
872
+ /** Score on the held-out split. Optional because a search-only run
873
+ * only fills `searchScore`. At least one must be present. */
874
+ holdoutScore?: number;
875
+ /** Bag of any other metric the run produced — judge dimensions,
876
+ * pass/fail counters, latency stats, etc. Numeric only — keeps
877
+ * reporters honest. */
878
+ raw: Record<string, number>;
879
+ /** Per-judge / per-dim breakdown. Consumers writing ensemble
880
+ * judgements populate this; substrate primitives like
881
+ * `interRaterReliability` and `corpusInterRaterAgreement` accept
882
+ * these records as input. Optional — single-judge or scalar-only
883
+ * runs leave it unset. */
884
+ judgeScores?: JudgeScoresRecord;
885
+ /** Authenticity / realness verdict — did the run build the REAL thing on the
886
+ * intended infra, or fake it (see `./authenticity`)? Optional: only domains
887
+ * with an authenticity config populate it. Carried in the corpus so the
888
+ * flywheel / off-policy learning can optimize for real completion, not gamed
889
+ * pass-rate. `score` is 0-1; `gated` is the anti-Goodhart flag — a gated run
890
+ * must not count as a real success regardless of `score`. */
891
+ realness?: {
892
+ score: number;
893
+ gated: boolean;
894
+ reason?: string;
895
+ };
896
+ }
897
+ /**
898
+ * Mandatory paper-grade fields for a single evaluation run. Optional
899
+ * fields are extension points; mandatory fields throw if missing.
900
+ *
901
+ * Hash discipline:
902
+ * - `promptHash` is the sha256 of the EFFECTIVE prompt sent to the
903
+ * model (after any steering bundle merge).
904
+ * - `configHash` is the sha256 of the effective run config (model,
905
+ * temperature, tools, judges, splits). The pair (promptHash,
906
+ * configHash) uniquely identifies an experiment cell.
907
+ *
908
+ * Model snapshot discipline:
909
+ * - `model` MUST encode a snapshot version. Bare aliases like
910
+ * `claude-sonnet-4` or `gpt-4o` are banned — they remap silently.
911
+ * Use `claude-sonnet-4-6@2025-04-15` or `gpt-4o-2024-11-20`.
912
+ */
913
+ interface RunRecord {
914
+ /** UUID for the run. */
915
+ runId: string;
916
+ /** Logical experiment grouping (a treatment vs a baseline within
917
+ * the same sweep should share `experimentId`). */
918
+ experimentId: string;
919
+ /** Stable identifier for the candidate (variant) being run. The
920
+ * promotion gate compares two `candidateId`s on matched items. */
921
+ candidateId: string;
922
+ /** RNG seed for the run. Always recorded — silent re-seeding is
923
+ * the most common cause of non-reproducible numbers. */
924
+ seed: number;
925
+ /** Model identifier WITH snapshot version. */
926
+ model: string;
927
+ /** sha256 of the effective prompt (post-steering). */
928
+ promptHash: string;
929
+ /** sha256 of the effective config. */
930
+ configHash: string;
931
+ /** Git SHA the harness was run from. */
932
+ commitSha: string;
933
+ /** End-to-end wall-clock duration in milliseconds. */
934
+ wallMs: number;
935
+ /** Time spent queued before execution started, if known. */
936
+ queueMs?: number;
937
+ /** Total USD cost. Mandatory — runs without a cost number are
938
+ * unbounded by definition and must not be admitted into the gate.
939
+ * `0` is retained as the compatibility sentinel for an uncaptured amount;
940
+ * inspect `costProvenance` before treating it as observed. */
941
+ costUsd: number;
942
+ /** Observed, model-priced estimate, or genuinely uncaptured USD amount.
943
+ * Optional only so existing serialized RunRecords remain valid. */
944
+ costProvenance?: RunCostProvenance;
945
+ /** Token usage breakdown. */
946
+ tokenUsage: RunTokenUsage;
947
+ /** Judge-side metadata, if a judge was used. */
948
+ judgeMetadata?: RunJudgeMetadata;
949
+ /** Per-split scores + raw bag. */
950
+ outcome: RunOutcome;
951
+ /** Canonical, cross-agent failure class drawn from the shared
952
+ * `FAILURE_CLASSES` taxonomy. This is the aggregation key that makes
953
+ * "which failure dominates across the whole fleet" answerable in ONE
954
+ * vocabulary — every agent classifies against the same enum. Producers
955
+ * set it via the substrate classifier; leave unset only when the failure
956
+ * genuinely can't be classified. */
957
+ failureClass?: FailureClass;
958
+ /** Free-form domain-specific failure detail, scoped UNDER `failureClass`
959
+ * (e.g. failureClass='tool_recovery_failure', failureMode='forge_build_unsatisfied').
960
+ * The within-agent drill-down; `failureClass` is the cross-agent key. */
961
+ failureMode?: string;
962
+ /** Which split this run was drawn from. */
963
+ splitTag: RunSplitTag;
964
+ /**
965
+ * Stable scenario identifier the run was scored against. Optional for
966
+ * backwards compatibility, but **strongly recommended**: every primitive
967
+ * that pairs runs by scenario (preferences, paired stats, BT tournament)
968
+ * keys on this. The campaign artifact populates it canonically; legacy
969
+ * runs without it fall back to inference from `outcome.raw.scenario_id`
970
+ * or `experimentId`.
971
+ */
972
+ scenarioId?: string;
973
+ /**
974
+ * Canonical identity for the agent profile cell that produced this row:
975
+ * profile artifact hash plus optional harness/model/prompt/reporting
976
+ * dimensions. Use `agentProfile.cellId` to group persona sweeps and
977
+ * longitudinal reports by the complete source profile, not by a loose
978
+ * candidate label or opaque config hash.
979
+ */
980
+ agentProfile?: AgentProfileCell;
981
+ }
982
+
983
+ interface RunEvidenceMetadata {
984
+ experimentId: string;
985
+ candidateId: string;
986
+ seed: number;
987
+ model: string;
988
+ promptHash: string;
989
+ configHash: string;
990
+ commitSha: string;
991
+ splitTag: RunSplitTag;
992
+ tokenUsage: RunTokenUsage;
993
+ queueMs?: number;
994
+ judgeMetadata?: RunRecord['judgeMetadata'];
995
+ raw?: Record<string, number>;
996
+ }
997
+ interface ControlRunToRunRecordOptions extends RunEvidenceMetadata {
998
+ runId?: string;
999
+ score?: number;
1000
+ failureMode?: string;
1001
+ }
1002
+ /**
1003
+ * Project a completed control-loop run into the strict RunRecord shape used by
1004
+ * release gates, optimizer tables, and research reports.
1005
+ *
1006
+ * The control loop owns live execution evidence. The caller still supplies the
1007
+ * experiment-cell metadata because prompt/config hashes, split assignment,
1008
+ * model snapshot, and commit SHA are product/harness concerns.
1009
+ */
1010
+ declare function controlRunToRunRecord<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult>(run: ControlRunResult<TState, TAction, TActionResult, TEval>, options: ControlRunToRunRecordOptions): RunRecord;
1011
+ declare function scoreFromEvals(evals: readonly ControlEvalResult[]): number | undefined;
1012
+
1013
+ export { type ActionExecutionPolicy, type ActionPolicyDecision, type ControlActionFailureMode, type ControlActionOutcome, type ControlBudget, type ControlContext, type ControlDecision, type ControlEvalResult, type ControlRunResult, type ControlRunToRunRecordOptions, type ControlRuntimeConfig, type ControlRuntimeError, type ControlSeverity, type ControlStep, type ControlStopPolicies, type ProposeReviewConfig, type ProposeReviewControlAction, type ProposeReviewControlConfig, type ProposeReviewControlResult, type ProposeReviewControlState, type ProposeReviewReport, type RunEvidenceMetadata, type StopDecision, allCriticalPassed, controlRunToRunRecord, evaluateActionPolicy, objectiveEval, runAgentControlLoop, runProposeReview, runProposeReviewAsControlLoop, scoreFromEvals, stopOnNoProgress, stopOnRepeatedAction, subjectiveEval };