import { N as NotFoundError, R as ReplayError } from './errors-Dwqw-T_m.js';
import { P as ProviderRedactor, R as RawProviderSink, d as RawProviderEvent } from './raw-provider-sink-C46HDghv.js';
export { F as FileSystemRawProviderSink, a as FileSystemRawProviderSinkOptions, I as InMemoryRawProviderSink, b as InMemoryRawProviderSinkOptions, N as NoopRawProviderSink, c as RawProviderDirection, e as RawProviderSinkFilter, f as defaultProviderRedactor, p as providerFromBaseUrl } from './raw-provider-sink-C46HDghv.js';
import { R as RunCompleteHook, a as RunCompleteHookContext } from './emitter-DEZwY14K.js';
export { S as SpanHandle, T as TraceEmitter, b as TraceEmitterOptions, l as llmSpanFromProvider } from './emitter-DEZwY14K.js';
export { b as RunIntegrityError, R as RunIntegrityExpectations, c as RunIntegrityIssue, d as RunIntegrityIssueCode, a as RunIntegrityReport, e as assertRunCaptured, t as throwIfRunIncomplete } from './integrity-CJzrpUua.js';
import { T as TraceStore } from './store-CKUAgsJz.js';
export { E as EventFilter, F as FileSystemTraceStore, a as FileSystemTraceStoreOptions, I as InMemoryTraceStore, R as RunFilter, S as SpanFilter } from './store-CKUAgsJz.js';
export { a as aggregateLlm, b as argHash, g as groupBy, j as judgeSpans, l as llmSpans, r as runFailureClass, c as runsForScenario, t as toolSpans } from './query-CqTxMwDw.js';
export { A as Artifact, B as BudgetLedgerEntry, h as BudgetSpec, E as EventKind, i as FAILURE_CLASSES, F as FailureClass, G as GenericSpan, J as JudgeSpan, L as LlmSpan, M as Message, d as RetrievalSpan, R as Run, g as RunLayer, b as RunOutcome, f as RunStatus, e as SandboxSpan, S as Span, j as SpanBase, c as SpanKind, k as SpanStatus, l as TRACE_SCHEMA_VERSION, T as ToolSpan, a as TraceEvent, m as isJudgeSpan, n as isLlmSpan, o as isRetrievalSpan, p as isSandboxSpan, q as isToolSpan } from './schema-m0gsnbt3.js';
import { AxAIService, AxFunction } from '@ax-llm/ax';
import { T as TraceAnalysisStore, f as TraceAnalystFilters, a as DatasetOverview, Q as QueryTracesPage, l as ViewTraceResult, V as ViewSpansResult, b as SearchTraceResult, S as SearchSpanResult } from './store-jzKpMl16.js';
export { D as DEFAULT_TRACE_ANALYST_BUDGETS, c as SpanMatchRecord, d as TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, e as TraceAnalystByteBudgets, g as TraceAnalystSpan, h as TraceAnalystSpanKind, i as TraceAnalystSpanStatus, j as TraceAnalystTraceSummary, k as ViewTraceOversized } from './store-jzKpMl16.js';

/**
 * `captureFetchToRawSink` — wrap a `fetch` so every request / response / error
 * against a provider is recorded into a `RawProviderSink` as the canonical
 * `RawProviderEvent` triple. The one substrate copy of the fetch-capture
 * pattern four consumers hand-roll (legal ships two copies).
 *
 * The returned value is a plain `typeof fetch` — pass it as the `fetchImpl` to
 * any OpenAI-compatible backend factory. Capture is best-effort by default: a
 * sink write that throws does NOT take down the underlying LLM call (set
 * `failClosed` to change that). Uses the existing `defaultProviderRedactor` +
 * `providerFromBaseUrl` — no new redaction policy.
 */

interface CaptureFetchContext {
    /** Logical run id stamped on every captured event. Required — without it
     *  the raw events can't be paired with their parent `Run`. */
    runId: string;
    /** Optional logical span id (enables span-level sink filtering). */
    spanId?: string;
    /** Resolved base URL (normalised, no trailing slash). Used for the event's
     *  `baseUrl` and for endpoint-path extraction. */
    baseUrl: string;
    /** Model id the caller intends to invoke. Stamped on every event. */
    model: string;
    /** Provider override. When omitted, `providerFromBaseUrl(baseUrl)`. */
    provider?: string;
}
interface CaptureFetchOptions {
    /** Override the capture-time redactor. Default `defaultProviderRedactor`. */
    redactor?: ProviderRedactor;
    /** Cap on captured response-body bytes; beyond it the body is truncated and
     *  `body_truncated` is added to `redactedFields`. Default 2 MiB. */
    responseBodyByteCap?: number;
    /** When true, a sink-write failure propagates to the caller. Default false
     *  — capture is best-effort so a sink failure never kills the LLM call. */
    failClosed?: boolean;
}
declare function captureFetchToRawSink(fetch: typeof globalThis.fetch, sink: RawProviderSink, ctx: CaptureFetchContext, opts?: CaptureFetchOptions): typeof globalThis.fetch;

/**
 * OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so
 * traces render natively in Jaeger / Honeycomb / Langfuse / Grafana.
 *
 * Wire format only. We do NOT depend on the @opentelemetry SDK — that
 * would drag in polyfills incompatible with Workers/Edge. Consumers
 * push the JSON to their collector of choice via HTTP.
 *
 * Reference: OTLP 1.3.2 (ResourceSpans / ScopeSpans / Span).
 */

declare const OTEL_AGENT_EVAL_SCOPE: {
    name: string;
    version: string;
};
interface OtlpSpan {
    traceId: string;
    spanId: string;
    parentSpanId?: string;
    name: string;
    kind: number;
    startTimeUnixNano: string;
    endTimeUnixNano: string;
    attributes: Array<{
        key: string;
        value: {
            stringValue?: string;
            intValue?: string;
            doubleValue?: number;
            boolValue?: boolean;
        };
    }>;
    events?: Array<{
        timeUnixNano: string;
        name: string;
        attributes?: OtlpSpan['attributes'];
    }>;
    status?: {
        code: number;
        message?: string;
    };
}
interface OtlpResourceSpans {
    resource: {
        attributes: OtlpSpan['attributes'];
    };
    scopeSpans: Array<{
        scope: typeof OTEL_AGENT_EVAL_SCOPE;
        spans: OtlpSpan[];
    }>;
}
interface OtlpExport {
    resourceSpans: OtlpResourceSpans[];
}
/** Export a single run's spans + events in OTLP/JSON. */
declare function exportRunAsOtlp(store: TraceStore, runId: string, resourceAttrs?: Record<string, string | number | boolean>): Promise<OtlpExport>;

/**
 * OTEL span exporter — streams spans to an OTLP/HTTP collector.
 *
 * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env
 * when no explicit config is given. Batches spans and flushes periodically
 * or when the batch fills. No @opentelemetry SDK dependency — minimal
 * OTLP/JSON serializer (~120 LOC) using the existing otel.ts helpers.
 */
interface OtelExportConfig {
    /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */
    endpoint?: string;
    /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */
    headers?: Record<string, string>;
    /** Batch size before flush. Default 64. */
    batchSize?: number;
    /** Flush interval ms. Default 5000. */
    flushIntervalMs?: number;
    /** Resource attributes stamped on every export. */
    resourceAttributes?: Record<string, string | number | boolean>;
    /** Service name. Default 'agent-eval'. */
    serviceName?: string;
}
interface OtelExporter {
    /** Called by the TraceEmitter on every span close. */
    exportSpan(span: ExportableSpan): void;
    /** Force flush pending spans. */
    flush(): Promise<void>;
    /** Shutdown cleanly — flushes remaining spans and stops the timer. */
    shutdown(): Promise<void>;
}
interface ExportableSpan {
    traceId: string;
    spanId: string;
    parentSpanId?: string;
    name: string;
    kind: string;
    startedAt: number;
    endedAt?: number;
    status?: string;
    error?: string;
    model?: string;
    inputTokens?: number;
    outputTokens?: number;
    costUsd?: number;
    attributes?: Record<string, unknown>;
}
/**
 * Create an OTEL exporter. Returns undefined when no endpoint is configured
 * (neither via config nor env) — callers should check before attaching.
 */
declare function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined;

/**
 * OTEL bridge — connects TraceEmitter span lifecycle to the OtelExporter.
 *
 * When an OtelExporter is active, every span that closes through the
 * TraceEmitter is also pushed to the exporter for real-time streaming to
 * the user's OTEL collector.
 *
 * The bridge is opt-in: attach via `otelRunCompleteHook(exporter)` as a
 * RunCompleteHook, or wrap the store with `createOtelTracingStore` for
 * real-time per-span export.
 */

/**
 * Create a RunCompleteHook that exports all spans from the completed run
 * to the OTEL exporter, then flushes.
 */
declare function otelRunCompleteHook(exporter: OtelExporter): RunCompleteHook;
/**
 * Create an auto-exporting TraceStore wrapper that intercepts updateSpan
 * calls. When a span gets an endedAt, it's exported immediately. This
 * gives real-time streaming instead of batch-at-end.
 *
 * This is the preferred integration path: wrap the store before
 * constructing the TraceEmitter.
 */
declare function createOtelTracingStore(inner: TraceStore, exporter: OtelExporter, traceId: string): TraceStore;

/**
 * Redaction — remove PII / secrets from trace payloads before persist.
 *
 * Pre-persistence rules mean raw traces in storage are already scrubbed.
 * Unredacted variants (for debugging / post-mortems) live in a separate
 * storage layer with stricter access controls; this module only covers
 * the default scrub-then-persist path.
 *
 * Rules compose: pass an array of `RedactionRule`, each is applied in
 * order. Strings that match get replaced with a tagged sentinel so the
 * eval framework can count how many redactions happened per run
 * (surfaced via `redaction_applied` events).
 */
interface RedactionRule {
    id: string;
    pattern: RegExp;
    /** Replacement — e.g. '[PII:email]'. Defaults to `[redacted:{id}]`. */
    replacement?: string;
}
interface RedactionReport {
    redactionCount: number;
    byRule: Record<string, number>;
}
/** OWASP / common-sense defaults — extend per-domain. */
declare const DEFAULT_REDACTION_RULES: RedactionRule[];
declare const REDACTION_VERSION = "1.0.0";
/**
 * Redact a single string. Returns the new string and a per-rule count of
 * how many substitutions fired.
 */
declare function redactString(input: string, rules?: RedactionRule[]): {
    output: string;
    report: RedactionReport;
};
/**
 * Walk a JSON-ish value applying `redactString` to every string leaf.
 * Arrays and plain objects are recursed; other types pass through
 * untouched. Circular references throw — traces should be tree-shaped.
 */
declare function redactValue(value: unknown, rules?: RedactionRule[], report?: RedactionReport): {
    value: unknown;
    report: RedactionReport;
};

interface AnalyzeTracesInput {
    /** The user-facing question. Domain framing belongs here, not in the
     *  actor description. */
    question: string;
}
interface AnalyzeTracesResult {
    /** The responder's prose answer. */
    answer: string;
    /** Bulleted findings extracted from the responder's structured output. */
    findings: string[];
    /** Per-actor-turn snapshots captured via `actorTurnCallback`. */
    turns: AnalyzeTracesTurnSnapshot[];
    /** Total turns the actor took. */
    turnCount: number;
    /** Token usage by role. */
    usage: TraceAnalystUsage;
    /** Full system + assistant + tool message log by role. */
    chatLog: TraceAnalystChatLog;
    /** Prompt version that produced this run. */
    actorPromptVersion: string;
}
interface TraceAnalystUsage {
    actor: TraceAnalystUsageEntry[];
    responder: TraceAnalystUsageEntry[];
}
interface TraceAnalystUsageEntry {
    [key: string]: unknown;
}
interface TraceAnalystChatLog {
    actor: TraceAnalystChatMessage[];
    responder: TraceAnalystChatMessage[];
}
interface TraceAnalystChatMessage {
    [key: string]: unknown;
}
interface AnalyzeTracesTurnSnapshot {
    turn: number;
    isError: boolean;
    /** The JS code the actor produced for this turn. */
    code: string;
    /** The formatted action-log entry the actor sees on the next turn. */
    output: string;
    /** Provider thought (when `actorOptions.showThoughts` is true and the
     *  provider returns it). */
    thought?: string;
}
interface AnalyzeTracesOptions {
    /** Trace data source. Pass either an OTLP-JSONL path or a custom store. */
    source: string | TraceAnalysisStore;
    /** Caller-provided AxAIService. */
    ai: AxAIService;
    /** Model id forwarded to actor + responder. */
    model?: string;
    /** Recursion depth. 0 = no sub-agent dispatch. Default 1. */
    maxDepth?: number;
    /** Maximum actor turns. Default 12. */
    maxTurns?: number;
    /** Maximum parallel sub-agent calls in batched llmQuery. Default 2. */
    maxParallelSubagents?: number;
    /** Override the actor description. */
    actorDescription?: string;
    /** Override the subagent description. */
    subagentDescription?: string;
    /** Per-turn observability hook. */
    onTurn?: (turn: AnalyzeTracesTurnSnapshot) => void | Promise<void>;
    /** Override max runtime characters per turn. Default 6000. */
    maxRuntimeChars?: number;
    /** When set, every turn's snapshot is appended to this JSONL file
     *  immediately. If the analyst crashes mid-loop (provider 503,
     *  network error, validator reject) the partial reasoning is still
     *  on disk. Replay the file with the responder afterward to recover
     *  evidence. */
    progressLogPath?: string;
}
/**
 * Run the trace analyst.
 *
 * Throws:
 *   - `TraceFileMissingError` if `source` is a path and doesn't exist.
 *   - `AxAgentClarificationError` if the analyst asks for clarification.
 *   - Provider errors (auth, rate limits) propagate from the AI service.
 */
declare function analyzeTraces(input: AnalyzeTracesInput, options: AnalyzeTracesOptions): Promise<AnalyzeTracesResult>;

/**
 * Trace-analyst auto-execution hook.
 *
 * Wires `analyzeTraces` into a `TraceEmitter`'s `onRunComplete` so a
 * direct matrix run produces an analysis artifact without an out-of-band
 * step. Designed for the case where the consumer reports "the analyst
 * never ran" — the cause is almost always orchestration, not the analyst.
 *
 * Usage:
 *
 *   const emitter = new TraceEmitter(store, {
 *     onRunComplete: [traceAnalystOnRunComplete({ analyze: opts, save })],
 *   })
 *
 * Hooks are best-effort by default — they never crash the underlying run.
 * The caller decides whether to gate the run on the analysis result via
 * the `gateOn` callback.
 */

interface TraceAnalystHookOptions {
    /**
     * Options forwarded to `analyzeTraces`. The hook supplies the question
     * if you don't pass one — defaulting to a launch-grade prompt that asks
     * for failure modes, surprising findings, and a recommendation.
     */
    analyze: Omit<AnalyzeTracesOptions, 'source'> & {
        source?: AnalyzeTracesOptions['source'];
    };
    /**
     * Override the question. The default is intentionally generic:
     * "Summarise what happened in this run, surface any failure modes,
     *  surprising findings, or evidence the verdict is wrong."
     */
    question?: string;
    /**
     * Persist the result. The hook calls this with the analysis output and
     * the run context. Common implementations write to a TraceAnalysisStore
     * or append to a per-run JSONL.
     */
    save?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => Promise<void>;
    /**
     * Predicate gating execution per run. Default: every completed run.
     * Use to skip aborted runs, debug runs, or runs without LLM activity.
     */
    shouldRun?: (ctx: RunCompleteHookContext) => boolean;
    /**
     * Optional gate: if set and returns false, the hook records the failure
     * as a log event on the run instead of staying quiet. The caller can
     * then trigger downstream alerts off `analyst_gate_failed` log events.
     */
    gateOn?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => boolean;
}
declare function traceAnalystOnRunComplete(opts: TraceAnalystHookOptions): RunCompleteHook;

interface TraceInsightTask {
    id: string;
    name: string;
    prompt?: string;
    difficulty?: string;
    tags?: string[];
    outcome?: string;
    score?: number;
    gaps?: string[];
}
interface TraceInsightSuite {
    name: string;
    collectionId?: string;
    tasks: TraceInsightTask[];
}
interface TraceInsightFinding {
    kind: string;
    severity?: string;
    taskIds: string[];
    evidence?: string;
    proposedFixClass?: string;
}
interface TraceInsightQuestion {
    id: string;
    question: string;
    why: string;
}
interface TraceInsightPanelRole {
    id: string;
    name: string;
    responsibility: string;
}
interface TraceInsightPromptInput {
    suite: TraceInsightSuite;
    findings?: TraceInsightFinding[];
    agent?: Record<string, unknown>;
    totals?: Record<string, unknown>;
    maxRepresentativeTraces?: number;
}
interface TraceInsightContext {
    suite: TraceInsightSuite;
    scope: string;
    keywords: string[];
    questions: TraceInsightQuestion[];
    panel: TraceInsightPanelRole[];
    findings: TraceInsightFinding[];
    agent: Record<string, unknown> | null;
    totals: Record<string, unknown> | null;
}
interface TraceInsightQualityGate {
    id: string;
    label: string;
    passed: boolean;
    severity: 'critical' | 'high' | 'medium' | 'low';
    detail: string;
}
interface TraceInsightReadiness {
    score: number;
    grade: 'external-ready' | 'internal-review' | 'raw-analysis';
    gates: TraceInsightQualityGate[];
}
declare function tokenizeDomainWords(value: string): string[];
declare function inferDomainKeywords(suite: TraceInsightSuite): string[];
declare function domainEvidencePattern(keywords: string[]): RegExp;
declare function describeTraceInsightScope(suite: TraceInsightSuite): string;
declare function planTraceInsightQuestions(input: TraceInsightPromptInput): TraceInsightQuestion[];
declare function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext;
declare function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness;
declare function defaultTraceInsightPanel(): TraceInsightPanelRole[];
declare function buildTraceInsightPrompt(input: TraceInsightPromptInput): string;

/**
 * `flattenOtlpExportToNdjson` — flatten an `OtlpExport` (the shape
 * `exportRunAsOtlp` produces) into the per-line JSON the analyst's
 * `OtlpFileTraceStore` index reads. Replaces three per-consumer OTLP
 * flatteners with one canonical projection.
 *
 * Pure function, no I/O — the caller does `.map(JSON.stringify).join('\n')`
 * and writes the file (consumers want control over rotation + naming).
 */

interface OtlpFlatLine {
    trace_id: string;
    span_id: string;
    parent_span_id: string | null;
    name: string;
    kind: string;
    start_time: string;
    end_time: string;
    status: {
        code: 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR' | 'STATUS_CODE_UNSET';
        message?: string;
    };
    resource: {
        attributes: Record<string, string | number | boolean>;
    };
    attributes: Record<string, string | number | boolean>;
    events?: Array<{
        name: string;
        timeUnixNano?: string;
        attributes?: Record<string, unknown>;
    }>;
}
interface FlattenOtlpOptions {
    /** `'openinference'` (default) mirrors per-span attributes into the
     *  OpenInference vocabulary the analyst's `inferKind` reads
     *  (`llm.model`→`llm.model_name`, `tool.name`→`inference.tool.name`,
     *  `span.kind`→`openinference.span.kind` uppercased). `'none'` passes
     *  attributes through untouched. */
    attributeVocabulary?: 'openinference' | 'none';
    /** Override the numeric-kind → otlp-string mapping. */
    kindMap?: Partial<Record<number, string>>;
}
declare function flattenOtlpExportToNdjson(otlpExport: OtlpExport, opts?: FlattenOtlpOptions): OtlpFlatLine[];

/** Ax RLM prompt for bounded trace discovery and evidence-backed analysis. */
declare 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 \u2192 NARROW \u2192 DEEP-READ protocol \u2014 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 \u2014 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 \u2014 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 \u2014 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\u00D7 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** \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.\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 \u2014 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 \u2014 what tool calls preceded the failure?', context: { trace_id: 'abc123' } },\n      { query: 'Drill into trace def456 \u2014 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 \u2014 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 \u2014 `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 \u2014 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 \u2014 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.";
declare const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = "trace-analyst-actor-v5-2026-05-06";
/** Subagent prompt for focused trace-inspection subtasks. */
declare const 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.\n\nCite trace ids and span ids for every claim. Do NOT invent ids.";

/**
 * `OtlpFileTraceStore` — read-only OTLP-JSONL trace store for the
 * trace-analyst.
 *
 * Wire shape. Each line of the input file is one OTLP-shaped span. The
 * store understands flattened OTLP JSONL plus the OpenInference vocab.
 * We project upstream's full
 * span shape down to `TraceAnalystSpan` lazily — full materialisation
 * only happens for the spans the agent actually requests.
 *
 * Indexing. On first read the store builds an in-memory index keyed
 * by `trace_id` carrying:
 *   - byte offsets + lengths for each span line (for surgical reads
 *     without re-parsing the whole file)
 *   - a `TraceAnalystTraceSummary` rollup
 *   - sets of services / agents / models / tools / has_errors
 *   - byte size of the trace's JSONL slab
 *
 * Memory bound. The index keeps span metadata only — names, kinds,
 * offsets, status. Attribute payloads stay on disk until requested.
 * For a 50MB JSONL with 50k spans, the index is ~5MB.
 *
 * Concurrency. The store builds the index once on first read and
 * caches it. Subsequent reads reuse the index. The file is opened on
 * each read; we never hold a long-lived FD.
 */

interface OtlpFileTraceStoreOptions {
    /** Path to the OTLP-JSONL file. */
    path: string;
    /** Override the discovery (`viewTrace`) per-attribute byte cap. */
    perAttributeViewBudget?: number;
    /** Override the surgical (`viewSpans`) per-attribute byte cap. */
    perAttributeSpanBudget?: number;
    /** Override the per-call ceiling that triggers oversized summaries. */
    perCallByteCeiling?: number;
    /** Override the per-match text budget. */
    perMatchTextBudget?: number;
}
declare class OtlpFileTraceStore implements TraceAnalysisStore {
    private readonly path;
    private readonly perAttributeViewBudget;
    private readonly perAttributeSpanBudget;
    private readonly perCallByteCeiling;
    private readonly perMatchTextBudget;
    private indexPromise?;
    /** Cached UTF-8 buffer of the file. We pin it once because every
     *  read needs slice access and re-reading on each call balloons the
     *  syscall count. */
    private bufferPromise?;
    constructor(opts: OtlpFileTraceStoreOptions);
    getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview>;
    queryTraces(opts: {
        filters?: TraceAnalystFilters;
        limit: number;
        offset?: number;
    }): Promise<QueryTracesPage>;
    countTraces(filters?: TraceAnalystFilters): Promise<number>;
    viewTrace(opts: {
        trace_id: string;
        per_attribute_byte_cap?: number;
    }): Promise<ViewTraceResult>;
    viewSpans(opts: {
        trace_id: string;
        span_ids: readonly string[];
        per_attribute_byte_cap?: number;
    }): Promise<ViewSpansResult>;
    searchTrace(opts: {
        trace_id: string;
        regex_pattern: string;
        max_matches?: number;
    }): Promise<SearchTraceResult>;
    searchSpan(opts: {
        trace_id: string;
        span_id: string;
        regex_pattern: string;
        max_matches?: number;
    }): Promise<SearchSpanResult>;
    /** Force the index to materialise. Useful to amortise startup cost
     *  before the first agent call. */
    ensureIndexed(): Promise<void>;
    private buffer;
    private index;
    private buildIndex;
    private matchedTraces;
    private toSummary;
    private projectSpan;
    private buildOversizedSummary;
    private scanSpanForMatches;
}
declare class TraceFileMissingError extends NotFoundError {
    constructor(path: string);
}
declare class TraceNotFoundError extends NotFoundError {
    readonly trace_id: string;
    constructor(trace_id: string);
}
declare class SpanNotFoundError extends NotFoundError {
    readonly trace_id: string;
    readonly span_id: string;
    constructor(trace_id: string, span_id: string);
}

/**
 * Trace-analyst tool surface — six namespaced AxFunctions the analyst
 * agent calls from generated JS code via `traces.<name>(...)`.
 *
 * Discovery → narrow → deep-read protocol. Tool names + ordering
 * support RLM discovery:
 *
 *   1. `getDatasetOverview` (cheap)  — first call, sizes the dataset
 *   2. `queryTraces`                 — paginated summaries with `raw_jsonl_bytes`
 *   3. `countTraces`                 — cheap pre-flight before regex
 *   4. `viewTrace`                   — full span list, oversized → summary
 *   5. `viewSpans`                   — surgical 16KB-cap reads
 *   6. `searchTrace` / `searchSpan`  — bounded regex hits
 *
 * Failure mode. Tool handlers throw on bad input (invalid trace ids,
 * out-of-range pagination, malformed regex). Ax converts thrown errors
 * into actor-visible `[ERROR]` strings so the analyst can adjust on
 * the next turn instead of looping.
 */

interface BuildTraceAnalystToolsOpts {
    store: TraceAnalysisStore;
    /** Override the default sample-trace-id slot count (20). Mostly for tests. */
    sampleTraceLimit?: number;
}
/**
 * Build the trace-analyst function set. Pass the result into
 * `agent(...).functions.local`.
 */
declare function buildTraceAnalystTools(opts: BuildTraceAnalystToolsOpts): AxFunction[];
/**
 * Convenience: same shape as `buildTraceAnalystTools` but returns the
 * grouped form expected when registering trace tools alongside other
 * agent function modules. */
declare function traceAnalystFunctionGroup(opts: BuildTraceAnalystToolsOpts): {
    namespace: string;
    title: string;
    selectionCriteria: string;
    description: string;
    functions: AxFunction[];
};

/**
 * Replay-from-raw-events — turn every captured campaign run into a
 * re-runnable artifact.
 *
 * `RawProviderSink` captures every provider HTTP envelope; `runEvalCampaign`
 * makes that capture the default. Together they make every past run a
 * complete fingerprint of what happened on the wire — enough to replay
 * the run without burning new LLM cost.
 *
 * Three use cases this primitive enables:
 *
 *   1. **Post-hoc judging** — apply a new judge / rubric / scoring callback
 *      to last week's runs without re-calling any LLM. The cost of trying
 *      a new rubric drops from "another full sweep" to a CPU-bound replay.
 *   2. **Determinism audits** — replay the same campaign and verify the
 *      raw responses match byte-for-byte. Any drift is a non-determinism
 *      bug (in the harness, the prompt builder, the sandbox, …).
 *   3. **Free judge calibration** — run two judges on identical responses
 *      and measure inter-judge agreement without doubling LLM spend.
 *
 * The interface is deliberately fetch-shaped. Inject `createReplayFetch`
 * into `LlmClientOptions.fetch` and every `callLlm` transparently reads
 * from the cache instead of calling the network. No new code path through
 * the LLM client is needed; the cache hit is invisible to the runner.
 */

declare class ReplayCacheMissError extends ReplayError {
    readonly url: string;
    readonly requestKey: string;
    constructor(url: string, requestKey: string, message?: string);
}
interface ReplayCacheEntry {
    request: RawProviderEvent;
    response: RawProviderEvent;
}
interface ReplayCacheStats {
    total: number;
    byProvider: Record<string, number>;
    byModel: Record<string, number>;
    /** Spans for which we have a request but no response (run aborted mid-call). */
    orphanRequests: number;
}
/**
 * In-memory deterministic cache of (request → response) keyed on a stable
 * hash of the request body. Built from a `RawProviderSink` containing
 * paired `request` and `response` events from a previous run.
 *
 * The cache is the source of truth for replay; `createReplayFetch` is a
 * thin wrapper that reads from it.
 */
declare class ReplayCache {
    private byKey;
    private orphans;
    private byProvider;
    private byModel;
    /**
     * Build a cache from a sink's events. The sink must implement `list()`.
     * Filter by `runId` / `spanId` to scope to a specific replay.
     */
    static fromSink(sink: RawProviderSink, filter?: {
        runId?: string;
        spanId?: string;
    }): Promise<ReplayCache>;
    /** Build a cache from an in-memory event list. */
    static fromEvents(events: RawProviderEvent[]): Promise<ReplayCache>;
    /** Number of cacheable (request, response) pairs in the cache. */
    size(): number;
    stats(): ReplayCacheStats;
    /** Iterate every cached `(request, response)` pair in insertion order. */
    entries(): IterableIterator<ReplayCacheEntry>;
    /**
     * Look up a cached response by hashing the (model, messages, temperature,
     * maxTokens, response_format) shape. Returns `undefined` on miss; the
     * caller decides whether to throw, fall back to the network, or skip.
     */
    lookup(requestBody: unknown): Promise<ReplayCacheEntry | undefined>;
}
interface ReplayFetchOptions {
    /**
     * Behaviour on cache miss. Default `'throw'`. `'fallback'` calls the
     * `fallbackFetch` (typically `globalThis.fetch`) so a partial replay can
     * still complete; `'fail-closed'` returns a synthetic 599 response so the
     * call site sees a non-retriable failure.
     */
    onMiss?: 'throw' | 'fallback' | 'fail-closed';
    fallbackFetch?: typeof fetch;
    /** Optional callback fired once per replayed call (for telemetry / counters). */
    onHit?: (info: {
        url: string;
        provider: string;
        model: string;
    }) => void;
    /** Optional callback fired on cache miss before the `onMiss` policy applies. */
    onMissNotify?: (info: {
        url: string;
        requestBody: unknown;
    }) => void;
}
/**
 * Build a `fetch`-shaped function that serves cached responses out of a
 * `ReplayCache` for any URL ending in `/chat/completions`. Pass through
 * `LlmClientOptions.fetch` and `callLlm` becomes free.
 *
 * Non-`/chat/completions` URLs are passed straight to the fallback fetch
 * (default: `globalThis.fetch`). This matters because non-LLM HTTP work
 * (judge HTTP servers, sandbox callbacks) sometimes flows through the same
 * `fetch` and shouldn't be intercepted.
 */
declare function createReplayFetch(cache: ReplayCache, opts?: ReplayFetchOptions): typeof fetch;
/**
 * Convenience iterator over `(request, response)` pairs in a sink — for
 * post-hoc scoring that doesn't need a `fetch` shim. The judge or scorer
 * runs purely in-process over cached LLM outputs.
 */
declare function iterateRawCalls(sink: RawProviderSink, filter?: {
    runId?: string;
    spanId?: string;
}): AsyncGenerator<ReplayCacheEntry>;

export { type AnalyzeTracesInput, type AnalyzeTracesOptions, type AnalyzeTracesResult, type AnalyzeTracesTurnSnapshot, type CaptureFetchContext, type CaptureFetchOptions, DEFAULT_REDACTION_RULES, DatasetOverview, type ExportableSpan, type FlattenOtlpOptions, OTEL_AGENT_EVAL_SCOPE, type OtelExportConfig, type OtelExporter, type OtlpExport, OtlpFileTraceStore, type OtlpFileTraceStoreOptions, type OtlpFlatLine, type OtlpResourceSpans, type OtlpSpan, ProviderRedactor, QueryTracesPage, REDACTION_VERSION, RawProviderEvent, RawProviderSink, type RedactionReport, type RedactionRule, ReplayCache, type ReplayCacheEntry, ReplayCacheMissError, type ReplayCacheStats, type ReplayFetchOptions, RunCompleteHook, RunCompleteHookContext, SearchSpanResult, SearchTraceResult, SpanNotFoundError, TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION, TRACE_ANALYST_SUBAGENT_DESCRIPTION, TraceAnalysisStore, TraceAnalystFilters, type TraceAnalystHookOptions, TraceFileMissingError, type TraceInsightContext, type TraceInsightFinding, type TraceInsightPanelRole, type TraceInsightPromptInput, type TraceInsightQualityGate, type TraceInsightQuestion, type TraceInsightReadiness, type TraceInsightSuite, type TraceInsightTask, TraceNotFoundError, TraceStore, ViewSpansResult, ViewTraceResult, analyzeTraces, buildTraceAnalystTools, buildTraceInsightContext, buildTraceInsightPrompt, captureFetchToRawSink, createOtelExporter, createOtelTracingStore, createReplayFetch, defaultTraceInsightPanel, describeTraceInsightScope, domainEvidencePattern, exportRunAsOtlp, flattenOtlpExportToNdjson, inferDomainKeywords, iterateRawCalls, otelRunCompleteHook, planTraceInsightQuestions, redactString, redactValue, scoreTraceInsightReadiness, tokenizeDomainWords, traceAnalystFunctionGroup, traceAnalystOnRunComplete };
