import { A as AgentEvalError, C as CaptureIntegrityError } from './errors-CzMUYo7b.js';
import { R as RawProviderSink, P as ProviderRedactor } from './raw-provider-sink-C46HDghv.js';

/**
 * LLM client with graceful degrade.
 *
 * OpenAI-compatible `/v1/chat/completions` client with:
 *   - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).
 *   - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).
 *   - Graceful json_schema → json_object degrade on 400 with schema-reject body.
 *   - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.
 *   - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI
 *     directly, cli-bridge subscriptions, and any router that speaks the spec.
 *
 * Usage:
 *   const { value, result } = await callLlmJson<MyType>(
 *     { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },
 *     { baseUrl: 'https://router.tangle.tools/v1', apiKey: process.env.KEY },
 *   )
 *
 * This is THE llm-calling seam for agent-eval primitives that need structured
 * output (semantic concept judge, reviewer directives, critic scores). Primitives
 * that need free-form text use `callLlm` and parse output themselves.
 */

interface LlmMessage {
    role: 'system' | 'user' | 'assistant';
    /**
     * Either a plain text content string OR a multimodal content array
     * (text + image_url parts) for vision-capable models.
     */
    content: string | Array<{
        type: 'text';
        text: string;
    } | {
        type: 'image_url';
        image_url: {
            url: string;
            detail?: 'auto' | 'low' | 'high';
        };
    }>;
}
interface LlmCallRequest {
    model: string;
    messages: LlmMessage[];
    /** Optional JSON-mode response format (response_format: json_object). */
    jsonMode?: boolean;
    /** Optional structured output via JSON Schema. Falls back to json_object on 400. */
    jsonSchema?: {
        name: string;
        schema: Record<string, unknown>;
    };
    temperature?: number;
    maxTokens?: number;
    /** Per-call timeout, default 300s. */
    timeoutMs?: number;
}
interface LlmUsage {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
    /** Proxies populate this when prompt caching is on. */
    cachedPromptTokens?: number;
}
interface LlmCallResult {
    /** The text content of the first choice. Empty string if none. */
    content: string;
    usage: LlmUsage;
    /**
     * Cost in USD. Pulled from proxy's `_response_cost` field when present;
     * `null` when neither the proxy nor the caller can derive it.
     */
    costUsd: number | null;
    /** Model name actually used (echoed from response). */
    model: string;
    /** Wall-clock duration of the HTTP call (last attempt, if retried). */
    durationMs: number;
    /**
     * `finish_reason` echoed from the first choice (`stop`, `length`,
     * `content_filter`, `tool_calls`, ...). `null` when the provider omits it.
     * Exposed so a free-form `callLlm` caller CAN detect a truncated answer
     * (`length`) instead of treating a cut-off completion as complete. Note:
     * `callLlm` does not itself reject on it — acting on this signal is the
     * caller's responsibility (in-repo free-form drivers do not yet enforce it).
     */
    finishReason?: string | null;
    /**
     * True when `content.trim()` is empty. An empty completion is a silent zero
     * for free-form `callLlm` callers; this flag is the signal a caller can
     * inspect to fail loud rather than proceed on an empty string. `callLlm`
     * surfaces it but does not throw on it.
     */
    contentEmpty?: boolean;
    /** Raw response body. */
    raw: Record<string, unknown>;
}
declare class LlmCallError extends AgentEvalError {
    readonly status: number;
    readonly body: string;
    readonly model: string;
    constructor(message: string, status: number, body: string, model: string);
}
interface LlmClientOptions {
    /** Base URL (without trailing slash). Must end at the `/v1` prefix. */
    baseUrl?: string;
    /** Bearer token — either `apiKey` or `bearer` populates `Authorization: Bearer ...`. */
    apiKey?: string;
    bearer?: string;
    /** Override for the `Authorization` header (e.g. `X-Auth: ...`). Takes precedence over apiKey/bearer. */
    authHeader?: {
        name: string;
        value: string;
    };
    /** Default timeout in ms. Per-call can override. */
    defaultTimeoutMs?: number;
    /**
     * Caller-supplied abort signal — e.g. a campaign-wide cancel. Linked to
     * each attempt's per-attempt timeout controller, so aborting it cancels
     * the in-flight fetch. A caller abort is FATAL: it is not retried even
     * though an AbortError otherwise matches the transient patterns.
     */
    signal?: AbortSignal;
    /**
     * Cross-attempt wall-clock budget in ms, measured from the first attempt.
     * Before launching each attempt the loop checks the remaining budget and
     * stops retrying once it is exhausted, rather than waiting the full
     * per-attempt timeout on every retry. Bounds total time independent of
     * `maxRetries` × `timeoutMs`.
     */
    deadlineMs?: number;
    /** Max retry attempts on retriable errors. Default 3 (1 initial + 2 retries). */
    maxRetries?: number;
    /** Fetch implementation — defaults to global `fetch`. Override for custom transport (e.g. tests). */
    fetch?: typeof fetch;
    /**
     * Optional raw HTTP capture sink. When provided, every request, response,
     * and error (across all retry attempts) is recorded to the sink, with auth
     * headers and credential-shaped body fields redacted by default. This is
     * the layer-1 forensics primitive: structured `LlmSpan`s record intent,
     * raw events record what actually crossed the wire.
     */
    rawSink?: RawProviderSink;
    /**
     * Logical provider id attached to raw events. When omitted, derived from
     * `baseUrl` via `providerFromBaseUrl`.
     */
    provider?: string;
    /** Trace context attached to raw events; populated by emitter-aware callers. */
    traceContext?: {
        runId?: string;
        spanId?: string;
    };
    /** Override the redaction strategy for this call. Defaults to `defaultProviderRedactor`. */
    redactor?: ProviderRedactor;
}
/**
 * True when an error is a transient transport/network fault worth retrying,
 * as opposed to a deterministic failure (4xx schema reject, JSON parse) that
 * a retry cannot fix. Inspects `LlmCallError.status`, then the error's
 * name/message/code, then recurses into `error.cause` — undici nests the
 * real socket fault one or more levels under `.cause`.
 *
 * This is THE retry classifier for the package: `callLlm` and
 * `withJudgeRetry` both route through it, so a connection-class error is
 * treated identically whether it surfaces in the HTTP client or a
 * TCloud-backed judge.
 */
declare function isTransientLlmError(err: unknown): boolean;
/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */
declare function backoffMs(attempt: number): number;
/**
 * Strip a ```json / ``` code fence if the model emitted one.
 * Idempotent for naked JSON. Some models (claude-code via router, certain
 * deepseek models) wrap output even under json_object.
 */
declare function stripFencedJson(raw: string): string;
/**
 * Low-level call. Returns raw content + usage + cost. Retries on transient
 * failures; does NOT degrade schema here — callers that want graceful
 * degrade use `callLlmJson`.
 */
declare function callLlm(req: LlmCallRequest, opts?: LlmClientOptions): Promise<LlmCallResult>;
/**
 * Structured-output call. Returns parsed JSON plus the raw result envelope.
 * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —
 * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept
 * the `response_format.json_schema` shape but DO accept `json_object`.
 */
declare function callLlmJson<T = unknown>(req: LlmCallRequest, opts?: LlmClientOptions): Promise<{
    value: T;
    result: LlmCallResult;
}>;
type LlmRouteAssertionReason = 'no_explicit_base_url' | 'base_url_blocked' | 'base_url_not_allowed' | 'no_auth' | 'wrong_provider';
declare class LlmRouteAssertionError extends CaptureIntegrityError {
    readonly reason: LlmRouteAssertionReason;
    readonly baseUrl: string;
    constructor(message: string, reason: LlmRouteAssertionReason, baseUrl: string);
}
interface LlmRouteRequirements {
    /**
     * Throw if `opts.baseUrl` is undefined, i.e. the call would fall back to
     * `DEFAULT_BASE_URL`. Set this for evaluation runs where silently using
     * the public/free-tier router is a defect — the launch reviewer needs to
     * know exactly which provider answered.
     */
    requireExplicitBaseUrl?: boolean;
    /**
     * Allowlist of acceptable base URLs. Strings match by prefix
     * (case-insensitive); RegExps test against the full base URL.
     */
    allowedBaseUrls?: Array<string | RegExp>;
    /** Blocklist that takes precedence over `allowedBaseUrls`. */
    blockedBaseUrls?: Array<string | RegExp>;
    /** Throw if no auth header / api key is configured. */
    requireAuth?: boolean;
    /**
     * Logical provider id the configured `baseUrl` is expected to match (via
     * `providerFromBaseUrl`). Mainly useful when paired with `requireExplicitBaseUrl`.
     */
    expectedProvider?: string;
}
/**
 * Fail-loud assertion that the configured LLM client points at the route
 * the caller intends. Designed for the matrix-runner preflight: invoke
 * once before any LLM call to catch misconfiguration before a sweep burns
 * dollars on the wrong provider.
 *
 * Throws `LlmRouteAssertionError`. Pure — no I/O — so it's safe to call
 * from constructors and CI gates.
 */
declare function assertLlmRoute(opts: LlmClientOptions, req?: LlmRouteRequirements): void;
/**
 * Probe whether a model is reachable. Returns latency + null error on
 * success; `ok=false` + error message on any failure (HTTP, timeout,
 * network, parse). Designed for sweep preflights — fail loud at the
 * boundary before burning a 30-leaf run on a misconfigured router.
 *
 * Sends a tiny `ping` message with `maxTokens=64`. Reasoning models
 * (glm-5.1, deepseek-v4) can burn the entire budget on internal reasoning
 * for short prompts, so don't tighten this further. We don't validate
 * content; HTTP 200 means reachable.
 */
declare function probeLlm(model: string, opts?: LlmClientOptions & {
    timeoutMs?: number;
}): Promise<{
    ok: boolean;
    latencyMs: number;
    error: string | null;
}>;
/**
 * Stateful client — construct once with defaults, call many times.
 * Thin wrapper around the free functions; exists for callers that want
 * to inject a single configured instance into multiple primitives.
 */
declare class LlmClient {
    private readonly opts;
    constructor(opts?: LlmClientOptions);
    call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult>;
    callJson<T = unknown>(req: LlmCallRequest, per?: LlmClientOptions): Promise<{
        value: T;
        result: LlmCallResult;
    }>;
}

export { type LlmClientOptions as L, type LlmRouteRequirements as a, type LlmCallRequest as b, type LlmCallResult as c, LlmCallError as d, LlmClient as e, type LlmMessage as f, LlmRouteAssertionError as g, type LlmUsage as h, assertLlmRoute as i, backoffMs as j, callLlm as k, callLlmJson as l, isTransientLlmError as m, probeLlm as p, stripFencedJson as s };
