import { Tracer, Span, Meter, Context, Histogram, Counter, Gauge, SpanOptions } from '@opentelemetry/api';

/** Normalized events for a single provider-pinned conversation. */
type AxChatSessionEvent = {
    type: 'response';
    response: AxChatResponse;
    responseId: string;
} | {
    type: 'response.completed';
    response: AxChatResponse;
    responseId: string;
} | {
    type: 'tool.call';
    responseId: string;
    call: NonNullable<AxChatResponse['results'][number]['functionCalls']>[number];
} | {
    type: 'steering';
    status: 'accepted' | 'pending' | 'failed';
    steerId?: string;
    requiredCallIds?: readonly string[];
    responseId?: string;
    error?: string;
};
/** Optional AxAI capability. The caller owns execution; providers own transport. */
interface AxChatSession {
    readonly model: string;
    /** Aborts when the transport closes or fails, including between responses. */
    readonly signal?: AbortSignal;
    events(): AsyncIterable<AxChatSessionEvent>;
    submitToolResults(results: readonly AxFunctionResult[]): Promise<void>;
    continue(): Promise<void>;
    steer(text: string): Promise<'native' | 'next-response'>;
    setThinkingTokenBudget(level: NonNullable<AxAIServiceOptions['thinkingTokenBudget']>): Promise<'next-response'>;
    close(): void;
}

declare const AX_MCP_EXTENSION_APPS = "io.modelcontextprotocol/ui";
declare const AX_MCP_EXTENSION_OAUTH_CLIENT_CREDENTIALS = "io.modelcontextprotocol/oauth-client-credentials";
declare const AX_MCP_EXTENSION_ENTERPRISE_MANAGED_AUTHORIZATION = "io.modelcontextprotocol/enterprise-managed-authorization";
declare const AX_MCP_TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
type AxMCPOfficialExtension = typeof AX_MCP_EXTENSION_APPS | typeof AX_MCP_TASKS_EXTENSION | typeof AX_MCP_EXTENSION_OAUTH_CLIENT_CREDENTIALS | typeof AX_MCP_EXTENSION_ENTERPRISE_MANAGED_AUTHORIZATION;
interface AxMCPExtensionCapability {
    version?: string;
    [key: string]: unknown;
}

declare const AX_MCP_SUPPORTED_PROTOCOL_VERSIONS: readonly ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
type AxMCPProtocolVersion = (typeof AX_MCP_SUPPORTED_PROTOCOL_VERSIONS)[number];
type AxMCPJSONSchema = Record<string, unknown>;
type AxMCPMeta = Record<string, unknown>;
/** Result discriminator introduced by MCP 2026-07-28. */
type AxMCPResultType = 'complete' | 'input_required' | 'task' | (string & {});
/** Cache metadata carried by cacheable MCP 2026-07-28 results. */
interface AxMCPCacheableResult {
    resultType?: AxMCPResultType;
    ttlMs?: number;
    cacheScope?: 'private' | 'public';
    _meta?: AxMCPMeta;
}
interface AxMCPJSONRPCRequest<T = unknown> {
    jsonrpc: '2.0';
    id: string | number;
    method: string;
    params?: T;
}
interface AxMCPJSONRPCSuccessResponse<T = unknown> {
    jsonrpc: '2.0';
    id: string | number | null;
    result: T;
}
interface AxMCPJSONRPCErrorResponse {
    jsonrpc: '2.0';
    id: string | number | null;
    error: {
        code: number;
        message: string;
        data?: unknown;
    };
}
type AxMCPJSONRPCResponse<T = unknown> = AxMCPJSONRPCSuccessResponse<T> | AxMCPJSONRPCErrorResponse;
interface AxMCPJSONRPCNotification<T = Record<string, unknown>> {
    jsonrpc: '2.0';
    method: string;
    params?: T;
}
type AxMCPJSONRPCMessage = AxMCPJSONRPCRequest | AxMCPJSONRPCNotification | AxMCPJSONRPCResponse;
interface AxMCPBatchRequest<T = unknown> {
    method: string;
    params?: T;
}
interface AxMCPBatchResponse<T = unknown> {
    request: AxMCPBatchRequest;
    response: AxMCPJSONRPCResponse<T>;
}
interface AxMCPIcon {
    src: string;
    mimeType?: string;
    sizes?: string[];
}
interface AxMCPImplementationInfo {
    name: string;
    title?: string;
    version: string;
    description?: string;
    icons?: AxMCPIcon[];
    websiteUrl?: string;
}
interface AxMCPClientCapabilities {
    roots?: {
        listChanged?: boolean;
    };
    sampling?: Record<string, unknown>;
    elicitation?: Record<string, unknown>;
    tasks?: Record<string, unknown>;
    extensions?: Record<string, AxMCPExtensionCapability>;
    experimental?: Record<string, unknown>;
}
interface AxMCPServerCapabilities {
    logging?: Record<string, unknown>;
    prompts?: {
        listChanged?: boolean;
        [key: string]: unknown;
    };
    resources?: {
        subscribe?: boolean;
        listChanged?: boolean;
        [key: string]: unknown;
    };
    tools?: {
        listChanged?: boolean;
        [key: string]: unknown;
    };
    completions?: Record<string, unknown>;
    tasks?: Record<string, unknown>;
    extensions?: Record<string, AxMCPExtensionCapability>;
    experimental?: Record<string, unknown>;
    [key: string]: unknown;
}
interface AxMCPInitializeParams {
    protocolVersion: string;
    capabilities: AxMCPClientCapabilities;
    clientInfo: AxMCPImplementationInfo;
    _meta?: AxMCPMeta;
}
interface AxMCPInitializeResult {
    protocolVersion: string;
    capabilities: AxMCPServerCapabilities;
    serverInfo: AxMCPImplementationInfo;
    instructions?: string;
    _meta?: AxMCPMeta;
}
/** Result of the MCP 2026-07-28 `server/discover` method. */
interface AxMCPDiscoverResult {
    resultType: 'complete';
    supportedVersions: string[];
    capabilities: AxMCPServerCapabilities;
    instructions?: string;
    ttlMs: number;
    cacheScope: 'private' | 'public';
    _meta?: AxMCPMeta;
}
/** Notification selection for MCP 2026-07-28 `subscriptions/listen`. */
interface AxMCPSubscriptionFilter {
    toolsListChanged?: boolean;
    promptsListChanged?: boolean;
    resourcesListChanged?: boolean;
    resourceSubscriptions?: string[];
    /** Tasks extension v2 task IDs whose status notifications are requested. */
    taskIds?: string[];
}
interface AxMCPSubscriptionsListenParams {
    notifications: AxMCPSubscriptionFilter;
    _meta?: AxMCPMeta;
}
interface AxMCPSubscriptionsAcknowledgedParams {
    notifications: AxMCPSubscriptionFilter;
    _meta?: AxMCPMeta;
}
interface AxMCPAnnotations {
    audience?: ('user' | 'assistant')[];
    priority?: number;
    lastModified?: string;
    [key: string]: unknown;
}
interface AxMCPToolAnnotations {
    title?: string;
    readOnlyHint?: boolean;
    destructiveHint?: boolean;
    idempotentHint?: boolean;
    openWorldHint?: boolean;
    [key: string]: unknown;
}
interface AxMCPBaseAnnotated {
    annotations?: AxMCPAnnotations;
    _meta?: AxMCPMeta;
}
interface AxMCPTextContent extends AxMCPBaseAnnotated {
    type: 'text';
    text: string;
}
interface AxMCPImageContent extends AxMCPBaseAnnotated {
    type: 'image';
    data: string;
    mimeType: string;
}
interface AxMCPAudioContent extends AxMCPBaseAnnotated {
    type: 'audio';
    data: string;
    mimeType: string;
}
interface AxMCPTextResourceContents extends AxMCPBaseAnnotated {
    uri: string;
    mimeType?: string;
    text: string;
}
interface AxMCPBlobResourceContents extends AxMCPBaseAnnotated {
    uri: string;
    mimeType?: string;
    blob: string;
}
interface AxMCPEmbeddedResource extends AxMCPBaseAnnotated {
    type: 'resource';
    resource: AxMCPTextResourceContents | AxMCPBlobResourceContents;
}
interface AxMCPResourceLink extends AxMCPBaseAnnotated {
    type: 'resource_link';
    uri: string;
    name?: string;
    title?: string;
    description?: string;
    mimeType?: string;
}
type AxMCPContent = AxMCPTextContent | AxMCPImageContent | AxMCPAudioContent | AxMCPResourceLink | AxMCPEmbeddedResource;
interface AxMCPResource extends AxMCPBaseAnnotated {
    uri: string;
    name: string;
    title?: string;
    description?: string;
    mimeType?: string;
    size?: number;
    icons?: AxMCPIcon[];
}
interface AxMCPResourceTemplate extends AxMCPBaseAnnotated {
    uriTemplate: string;
    name: string;
    title?: string;
    description?: string;
    mimeType?: string;
    icons?: AxMCPIcon[];
}
interface AxMCPTool {
    name: string;
    title?: string;
    description?: string;
    icons?: AxMCPIcon[];
    inputSchema: AxMCPJSONSchema;
    outputSchema?: AxMCPJSONSchema;
    execution?: {
        taskSupport?: 'forbidden' | 'optional' | 'required';
        [key: string]: unknown;
    };
    annotations?: AxMCPToolAnnotations;
    _meta?: AxMCPMeta;
}
type AxMCPFunctionDescription = AxMCPTool;
interface AxMCPPaginatedRequest {
    cursor?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPToolsListResult extends AxMCPCacheableResult {
    tools: AxMCPTool[];
    nextCursor?: string;
    _meta?: AxMCPMeta;
    /**
     * Older Ax tests/examples accepted these fields. Keep them optional so
     * older servers and fixtures remain type-compatible.
     */
    name?: string;
    description?: string;
}
interface AxMCPToolCallParams {
    name: string;
    arguments?: unknown;
    task?: AxMCPTaskMetadata;
    inputResponses?: Record<string, AxMCPInputResponse>;
    requestState?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPToolCallResult {
    content?: AxMCPContent[];
    structuredContent?: unknown;
    isError?: boolean;
    resultType?: AxMCPResultType;
    _meta?: AxMCPMeta;
}
interface AxMCPResourcesListResult extends AxMCPCacheableResult {
    resources: AxMCPResource[];
    nextCursor?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPResourceTemplatesListResult extends AxMCPCacheableResult {
    resourceTemplates: AxMCPResourceTemplate[];
    nextCursor?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPResourceReadResult extends AxMCPCacheableResult {
    contents: (AxMCPTextResourceContents | AxMCPBlobResourceContents)[];
    _meta?: AxMCPMeta;
}
interface AxMCPPromptArgument {
    name: string;
    title?: string;
    description?: string;
    required?: boolean;
}
interface AxMCPPrompt extends AxMCPBaseAnnotated {
    name: string;
    title?: string;
    description?: string;
    arguments?: AxMCPPromptArgument[];
    icons?: AxMCPIcon[];
}
interface AxMCPPromptMessage {
    role: 'user' | 'assistant';
    content: AxMCPContent;
}
interface AxMCPPromptsListResult extends AxMCPCacheableResult {
    prompts: AxMCPPrompt[];
    nextCursor?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPPromptGetResult {
    description?: string;
    messages: AxMCPPromptMessage[];
    resultType?: AxMCPResultType;
    _meta?: AxMCPMeta;
}
interface AxMCPInputResponseRequestParams {
    inputResponses?: Record<string, AxMCPInputResponse>;
    requestState?: string;
}
type AxMCPCompletionReference = {
    type: 'ref/prompt';
    name: string;
    title?: string;
} | {
    type: 'ref/resource';
    uri: string;
};
interface AxMCPCompletionArgument {
    name: string;
    value: string;
}
interface AxMCPCompletionRequest {
    ref: AxMCPCompletionReference;
    argument: AxMCPCompletionArgument;
    context?: {
        arguments?: Record<string, string>;
    };
    _meta?: AxMCPMeta;
}
interface AxMCPCompletionResult {
    completion: {
        values: string[];
        total?: number;
        hasMore?: boolean;
    };
    resultType?: AxMCPResultType;
    _meta?: AxMCPMeta;
}
type AxMCPLoggingLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';
interface AxMCPRoot {
    uri: string;
    name?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPListRootsResult {
    roots: AxMCPRoot[];
}
type AxMCPTaskStatus = 'working' | 'input_required' | 'completed' | 'failed' | 'cancelled';
interface AxMCPTaskMetadata {
    ttl?: number;
}
interface AxMCPTask {
    taskId: string;
    status: AxMCPTaskStatus;
    statusMessage?: string;
    createdAt: string;
    lastUpdatedAt: string;
    /** Legacy Tasks draft TTL. */
    ttl?: number | null;
    pollInterval?: number;
    /** MCP Tasks extension v2 time-to-live. */
    ttlMs?: number | null;
    /** MCP Tasks extension v2 suggested polling interval. */
    pollIntervalMs?: number;
    /** Present when a v2 task is waiting for client input. */
    inputRequests?: Record<string, AxMCPInputRequest>;
    /** Present when a v2 task completed successfully. */
    result?: unknown;
    /** Present when a v2 task failed with a protocol error. */
    error?: AxMCPJSONRPCErrorResponse['error'];
}
interface AxMCPLegacyCreateTaskResult {
    task: AxMCPTask;
    _meta?: AxMCPMeta;
    [key: string]: unknown;
}
/** Flattened CreateTaskResult from `io.modelcontextprotocol/tasks` v2. */
type AxMCPCreateTaskResult = AxMCPTask & {
    resultType: 'task';
    _meta?: AxMCPMeta;
};
type AxMCPToolCallOutcome = {
    kind: 'complete';
    result: AxMCPToolCallResult;
} | {
    kind: 'task';
    task: AxMCPCreateTaskResult;
};
interface AxMCPTasksListResult {
    tasks: AxMCPTask[];
    nextCursor?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPTaskResult<T = unknown> {
    result: T;
    _meta?: AxMCPMeta;
}
interface AxMCPSamplingMessage {
    role: 'user' | 'assistant';
    content: AxMCPContent;
}
interface AxMCPSamplingToolChoice {
    mode?: 'auto' | 'required' | 'none';
    [key: string]: unknown;
}
interface AxMCPSamplingCreateMessageParams {
    messages: AxMCPSamplingMessage[];
    modelPreferences?: Record<string, unknown>;
    systemPrompt?: string;
    includeContext?: 'none' | 'thisServer' | 'allServers';
    temperature?: number;
    maxTokens: number;
    stopSequences?: string[];
    metadata?: Record<string, unknown>;
    tools?: AxMCPTool[];
    toolChoice?: AxMCPSamplingToolChoice;
    task?: AxMCPTaskMetadata;
    _meta?: AxMCPMeta;
}
interface AxMCPSamplingCreateMessageResult {
    role: 'assistant';
    content: AxMCPContent;
    model: string;
    stopReason?: string;
    _meta?: AxMCPMeta;
}
type AxMCPElicitationAction = 'accept' | 'decline' | 'cancel';
type AxMCPElicitationCreateParams = {
    mode?: 'form';
    message: string;
    requestedSchema: AxMCPJSONSchema;
    task?: AxMCPTaskMetadata;
    _meta?: AxMCPMeta;
} | {
    mode: 'url';
    message: string;
    url: string;
    elicitationId: string;
    task?: AxMCPTaskMetadata;
    _meta?: AxMCPMeta;
};
interface AxMCPElicitationCreateResult {
    action: AxMCPElicitationAction;
    content?: Record<string, unknown>;
    _meta?: AxMCPMeta;
}
/** A server request embedded in an MCP 2026-07-28 MRTR result. */
type AxMCPInputRequest = {
    method: 'sampling/createMessage';
    params: AxMCPSamplingCreateMessageParams;
} | {
    method: 'roots/list';
    params?: {
        _meta?: AxMCPMeta;
    };
} | {
    method: 'elicitation/create';
    params: AxMCPElicitationCreateParams;
};
/** A bare client result keyed to an embedded MRTR request. */
type AxMCPInputResponse = AxMCPSamplingCreateMessageResult | AxMCPListRootsResult | AxMCPElicitationCreateResult;
/** An intermediate MCP 2026-07-28 result requesting another input round. */
interface AxMCPInputRequiredResult {
    resultType: 'input_required';
    inputRequests?: Record<string, AxMCPInputRequest>;
    requestState?: string;
    _meta?: AxMCPMeta;
}
interface AxMCPProgressNotificationParams {
    progressToken: string | number;
    progress: number;
    total?: number;
    message?: string;
    _meta?: AxMCPMeta;
}
declare function axMCPToolInputSchemaToFunctionSchema(schema: AxMCPJSONSchema | undefined): AxFunctionJSONSchema;

interface AxMCPRequestOptions {
    signal?: AbortSignal;
    /** Additional headers for this request when the transport supports them. */
    headers?: Readonly<Record<string, string>>;
    /** Overrides the desired modern per-request logging level. */
    logLevel?: AxMCPLoggingLevel;
    /** Await modern task results or expose the durable task handle. */
    taskHandling?: 'await' | 'expose';
}
type AxMCPEra = 'modern' | 'legacy';
interface AxMCPListeningHandle {
    /** Resolves when the server acknowledges that the listener is ready. */
    readonly ready?: Promise<void>;
    /** Resolves when listening stops and rejects when the listener fails. */
    readonly done: Promise<void>;
    close(): void | Promise<void>;
}
interface AxMCPListeningOptions {
    signal?: AbortSignal;
}
type AxMCPTransportLifecycleState = 'reconnected';
interface AxMCPTransport {
    /** Indicates whether optimizer/evaluation use can cause live side effects. */
    readonly evaluationMode?: 'live' | 'record' | 'replay' | 'sandbox';
    /** Transport-level era preference, such as WebSocket's legacy-only binding. */
    readonly eraHint?: AxMCPEra;
    /** Stable key used to cache era detection, normally the HTTP origin. */
    readonly eraCacheKey?: string;
    /** Applies the client-selected protocol era to transport behavior. */
    setEra?(era: AxMCPEra): void;
    /** One-shot metadata for the most recently completed request ID. */
    takeRequestMetadata?(id: string | number): Readonly<{
        retryCount?: number;
    }> | undefined;
    /**
     * Sends a JSON-RPC request or notification and returns the response
     * @param message The JSON-RPC request or notification to send
     * @returns A Promise that resolves to the JSON-RPC response
     */
    send(message: Readonly<AxMCPJSONRPCRequest<unknown>>, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPJSONRPCResponse<unknown>>;
    /** Sends one version-gated JSON-RPC batch on transports that support it. */
    sendBatch?(messages: readonly Readonly<AxMCPJSONRPCRequest<unknown>>[], options?: Readonly<AxMCPRequestOptions>): Promise<readonly AxMCPJSONRPCResponse<unknown>[]>;
    /**
     * Sends a JSON-RPC notification
     * @param message The JSON-RPC notification to send
     */
    sendNotification(message: Readonly<AxMCPJSONRPCNotification>): Promise<void>;
    /**
     * Sends a JSON-RPC response for a server-initiated request.
     * Transports that cannot receive server requests do not need to implement it.
     */
    sendResponse?(message: Readonly<AxMCPJSONRPCResponse>): Promise<void>;
    /**
     * Registers a handler for server-initiated JSON-RPC requests and
     * notifications that arrive outside a direct client request response.
     */
    setMessageHandler?(handler: (message: Readonly<AxMCPJSONRPCMessage>) => void | Promise<void>): void;
    /** Registers transport lifecycle events that require client-level recovery. */
    setLifecycleHandler?(handler: (state: AxMCPTransportLifecycleState) => void | Promise<void>): void;
    /**
     * Stores the negotiated MCP protocol version for transports that must emit
     * it on later frames or HTTP requests.
     */
    setProtocolVersion?(protocolVersion: string): void;
    /**
     * Connects to the transport if needed
     * This method is optional and only required for transports that need connection setup
     */
    connect?(): Promise<void>;
    /** Starts a nonblocking server-message listener when the transport needs one. */
    startListening?(options?: Readonly<AxMCPListeningOptions>): AxMCPListeningHandle | Promise<AxMCPListeningHandle>;
    /** Opens a long-lived stream carried by a specific JSON-RPC request. */
    openRequestStream?(request: Readonly<AxMCPJSONRPCRequest<unknown>>, options?: Readonly<AxMCPListeningOptions>): AxMCPListeningHandle | Promise<AxMCPListeningHandle>;
    /** Terminates a negotiated transport session when supported. */
    terminateSession?(): Promise<void>;
    /** Releases transport resources. Implementations should be idempotent. */
    close?(): void | Promise<void>;
}

interface AxMCPFunctionOverride {
    /** Original function name to override */
    name: string;
    /** Updates to apply to the function */
    updates: {
        /** Alternative name for the function */
        name?: string;
        /** Alternative description for the function */
        description?: string;
    };
}
interface AxMCPCatalogSnapshot {
    namespace: string;
    protocolVersion?: string;
    revision: number;
    serverInfo?: AxMCPImplementationInfo;
    serverCapabilities: AxMCPServerCapabilities;
    tools: readonly AxMCPTool[];
    prompts: readonly AxMCPPrompt[];
    resources: readonly AxMCPResource[];
    resourceTemplates: readonly AxMCPResourceTemplate[];
    subscriptions: readonly string[];
    cache: Readonly<Partial<Record<AxMCPCatalogCacheName, AxMCPCacheInfo>>>;
}
type AxMCPCatalogCacheName = 'tools' | 'prompts' | 'resources' | 'resourceTemplates';
interface AxMCPCacheInfo {
    ttlMs?: number;
    cacheScope?: 'private' | 'public';
    fetchedAt: number;
    expiresAt?: number;
}
type AxMCPClientEvent = {
    type: 'catalog_changed';
    catalog: 'tools' | 'prompts' | 'resources';
    revision: number;
} | {
    type: 'resource_updated';
    uri: string;
} | {
    type: 'logging';
    params: Readonly<Record<string, unknown>>;
} | {
    type: 'progress';
    params: Readonly<AxMCPProgressNotificationParams>;
} | {
    type: 'task_status';
    task: Readonly<AxMCPTask>;
} | {
    type: 'lifecycle';
    state: 'reconnected';
} | {
    type: 'notification';
    notification: Readonly<AxMCPJSONRPCNotification>;
};
interface AxMCPClientListeningOptions {
    signal?: AbortSignal;
    retryDelayMs?: number;
    onError?: (error: unknown) => void | Promise<void>;
}
interface AxMCPEraStore {
    get(key: string): AxMCPEra | undefined | Promise<AxMCPEra | undefined>;
    set(key: string, era: AxMCPEra): void | Promise<void>;
}
interface AxMCPClientOptions {
    /** Enable debug logging */
    debug?: boolean;
    /** Logger function for debug output */
    logger?: AxLoggerFunction;
    /** MCP protocol version to request during initialize. Defaults to latest. */
    protocolVersion?: string;
    /** Protocol era selection. Auto-detection is the default. */
    era?: 'auto' | AxMCPEra;
    /** Optional persistence for origin-scoped automatic era detection. */
    eraStore?: AxMCPEraStore;
    /** Protocol versions this client can accept during negotiation. */
    supportedProtocolVersions?: readonly string[];
    /** Client metadata sent in initialize. */
    clientInfo?: Partial<AxMCPImplementationInfo>;
    /** Extra client capabilities to advertise. Advertise only implemented ones. */
    capabilities?: AxMCPClientCapabilities;
    /** Optional MCP extensions advertised during initialize. */
    extensions?: Record<string, AxMCPExtensionCapability>;
    /** Optional roots support. When set, Ax advertises and answers roots/list. */
    roots?: readonly AxMCPRoot[];
    /** Stable namespace used when this client is attached to Ax programs. */
    namespace?: string;
    /** Maximum concurrent tool or task-augmented tool calls for this server. */
    maxConcurrency?: number;
    /** Maximum MCP 2026-07-28 multi round-trip input rounds. Defaults to 5. */
    maxInputRounds?: number;
    /** Enables TTL-aware caching for modern resources/read results. */
    readCache?: boolean;
    /** Advertise the modern Tasks v2 extension. Defaults to true. */
    tasksExtension?: boolean;
    /** Maximum pages accepted from any single catalog listing. */
    maxPaginationPages?: number;
    /** Reinitialize expired HTTP sessions for safe requests. Defaults to safe. */
    sessionRecovery?: 'safe' | 'none';
    /** Optional protocol tracer; request spans contain sanitized MCP metadata. */
    tracer?: Tracer;
    /** Default modern per-request logging level. */
    logLevel?: AxMCPLoggingLevel;
    /** Host policy hook invoked before an MCP tool is called. */
    authorizeToolCall?: (call: Readonly<{
        client: AxMCPClient;
        namespace: string;
        tool: AxMCPTool;
        arguments: unknown;
    }>) => boolean | undefined | Promise<boolean | undefined>;
    /** List of function overrides for tool/prompt/resource wrappers. */
    functionOverrides?: AxMCPFunctionOverride[];
    /** Generic notification callback for all server notifications. */
    onNotification?: (notification: Readonly<AxMCPJSONRPCNotification>) => void | Promise<void>;
    onToolsChanged?: () => void | Promise<void>;
    onPromptsChanged?: () => void | Promise<void>;
    onResourcesChanged?: () => void | Promise<void>;
    onResourceUpdated?: (uri: string) => void | Promise<void>;
    onLoggingMessage?: (params: Readonly<Record<string, unknown>>) => void | Promise<void>;
    /** Handles server-initiated sampling/createMessage requests. */
    sampling?: (params: Readonly<AxMCPSamplingCreateMessageParams>, context: Readonly<{
        client: AxMCPClient;
        namespace: string;
    }>) => AxMCPSamplingCreateMessageResult | Promise<AxMCPSamplingCreateMessageResult>;
    /** Handles server-initiated elicitation/create requests. */
    elicitation?: (params: Readonly<AxMCPElicitationCreateParams>, context: Readonly<{
        client: AxMCPClient;
        namespace: string;
    }>) => AxMCPElicitationCreateResult | Promise<AxMCPElicitationCreateResult>;
    onProgress?: (params: Readonly<AxMCPProgressNotificationParams>) => void | Promise<void>;
    onTaskStatus?: (task: Readonly<AxMCPTask>) => void | Promise<void>;
}
declare class AxMCPClient {
    private readonly transport;
    private readonly options;
    private functions;
    private tools;
    private prompts;
    private resources;
    private resourceTemplates;
    private promptFunctions;
    private resourceFunctions;
    private activeRequests;
    private serverCapabilities;
    private negotiatedProtocolVersion?;
    private era?;
    private discoverResult?;
    private logLevel?;
    private serverInfo?;
    private serverInstructions?;
    private logger;
    private initPromise?;
    private initialized;
    private refreshPromise?;
    private readonly catalogCache;
    private readonly resourceReadCache;
    private catalogRevision;
    private negotiatedExtensions;
    private activeToolCalls;
    private readonly toolCallQueue;
    private readonly tasks;
    private readonly invalidToolHeaderWarnings;
    private readonly resourceSubscriptionOwners;
    private resourceSubscriptionTransition;
    private activeModernListening?;
    private modernListenRestartRequested;
    private activeSubscriptionId?;
    private modernListenReadyResolve?;
    private readonly taskStatusListeners;
    private readonly eventListeners;
    private sessionRecoveryPromise?;
    constructor(transport: AxMCPTransport, options?: Readonly<AxMCPClientOptions>);
    init(): Promise<void>;
    private initialize;
    private initializeForEra;
    private initializeLegacy;
    private clientInfo;
    private negotiateExtensions;
    private applyEra;
    private knownEra;
    private rememberEra;
    private requestDiscovery;
    private isDiscoverResult;
    private applyModernDiscovery;
    getEra(): AxMCPEra | undefined;
    discover(): Promise<AxMCPDiscoverResult>;
    refresh(options?: Readonly<{
        force?: boolean;
    }>): Promise<void>;
    private refreshCatalog;
    getProtocolVersion(): string | undefined;
    getEvaluationMode(): 'live' | 'record' | 'replay' | 'sandbox';
    /** @deprecated JSON-RPC batching is a compatibility API for MCP 2025-03-26 only. */
    batch(requests: readonly Readonly<AxMCPBatchRequest>[], options?: Readonly<AxMCPRequestOptions>): Promise<readonly AxMCPBatchResponse[]>;
    getServerInfo(): AxMCPImplementationInfo | undefined;
    getServerInstructions(): string | undefined;
    getServerCapabilities(): AxMCPServerCapabilities;
    getNegotiatedExtensions(): Readonly<Record<string, AxMCPExtensionCapability>>;
    hasExtension(name: string): boolean;
    getNamespace(): string;
    getTools(): readonly AxMCPTool[];
    getPrompts(): readonly AxMCPPrompt[];
    getResources(): readonly AxMCPResource[];
    getResourceTemplates(): readonly AxMCPResourceTemplate[];
    getCatalogRevision(): number;
    inspectCatalog(options?: Readonly<{
        refresh?: boolean;
    }>): Promise<AxMCPCatalogSnapshot>;
    close(): Promise<void>;
    private buildClientCapabilities;
    private isCapabilityEnabled;
    private hasSubCapability;
    private discoverFunctions;
    private discoverPromptFunctions;
    private discoverResourceFunctions;
    private recordCatalogCache;
    private cacheInfo;
    private isCatalogCacheFresh;
    private toolToFunction;
    private promptToFunction;
    private resourceToFunction;
    private resourceTemplateToFunction;
    private formatPromptMessages;
    private extractContent;
    private formatToolResult;
    private formatResourceContents;
    private sanitizeName;
    private parseUriTemplate;
    private expandUriTemplate;
    ping(timeout?: number): Promise<void>;
    toFunction(): AxFunction[];
    getCapabilities(): {
        tools: boolean;
        resources: boolean;
        prompts: boolean;
    };
    hasToolsCapability(): boolean;
    hasPromptsCapability(): boolean;
    hasResourcesCapability(): boolean;
    hasCompletionsCapability(): boolean;
    hasLoggingCapability(): boolean;
    hasTasksCapability(): boolean;
    listTools(cursor?: string): Promise<AxMCPToolsListResult>;
    callTool(name: string, args: unknown, options: Readonly<AxMCPRequestOptions & {
        taskHandling: 'expose';
    }>): Promise<AxMCPCreateTaskResult>;
    callTool(name: string, args?: unknown, options?: Readonly<AxMCPRequestOptions & {
        taskHandling?: 'await' | undefined;
    }>): Promise<AxMCPToolCallResult>;
    callTool(name: string, args: unknown, options: Readonly<AxMCPRequestOptions>): Promise<AxMCPToolCallResult | AxMCPCreateTaskResult>;
    callToolOutcome(name: string, args?: unknown, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPToolCallOutcome>;
    /** @deprecated Legacy Tasks draft API. Modern tasks are server-directed. */
    callToolTask(name: string, args?: unknown, task?: AxMCPTaskMetadata, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPLegacyCreateTaskResult>;
    private authorizedTool;
    private requestToolCallOutcome;
    private acceptToolParamHeaders;
    private toolRequestOptions;
    private refreshToolsAfterHeaderMismatch;
    /** @deprecated The modern Tasks v2 extension does not expose tasks/list. */
    listTasks(cursor?: string): Promise<AxMCPTasksListResult>;
    getTask(taskId: string): Promise<AxMCPTask>;
    /** @deprecated Modern task results are embedded in tasks/get. */
    getTaskResult<T = AxMCPToolCallResult>(taskId: string): Promise<T>;
    provideTaskInput(taskId: string, inputResponses: Readonly<Record<string, AxMCPInputResponse>>): Promise<void>;
    cancelTask(taskId: string): Promise<AxMCPTask | undefined>;
    getKnownTasks(): readonly AxMCPTask[];
    private isModernTask;
    subscribeTaskStatus(listener: (task: Readonly<AxMCPTask>) => void | Promise<void>): () => void;
    subscribeEvents(listener: (event: Readonly<AxMCPClientEvent>) => void | Promise<void>): () => void;
    startListening(options?: Readonly<AxMCPClientListeningOptions>): Promise<AxMCPListeningHandle>;
    private modernSubscriptionFilter;
    waitForTask<T = AxMCPToolCallResult>(taskId: string, options?: Readonly<{
        signal?: AbortSignal;
        timeoutMs?: number;
        defaultPollIntervalMs?: number;
    }>): Promise<T>;
    listPrompts(cursor?: string): Promise<AxMCPPromptsListResult>;
    getPrompt(name: string, args?: Record<string, string>, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPPromptGetResult>;
    listResources(cursor?: string): Promise<AxMCPResourcesListResult>;
    listResourceTemplates(cursor?: string): Promise<AxMCPResourceTemplatesListResult>;
    readResource(uri: string, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPResourceReadResult>;
    subscribeResource(uri: string): Promise<void>;
    unsubscribeResource(uri: string): Promise<void>;
    /** Acquires one logical owner for a resource subscription. */
    acquireResourceSubscription(uri: string, owner: string): Promise<void>;
    /** Releases one logical owner without disturbing other subscribers. */
    releaseResourceSubscription(uri: string, owner: string): Promise<void>;
    getResourceSubscriptions(): readonly string[];
    private restoreResourceSubscriptions;
    private handleTransportLifecycle;
    complete(ref: AxMCPCompletionReference, argument: AxMCPCompletionArgument, context?: AxMCPCompletionRequest['context']): Promise<AxMCPCompletionResult>;
    /** @deprecated Set `logLevel` on the client or an individual modern request. */
    setLoggingLevel(level: AxMCPLoggingLevel): Promise<void>;
    cancelRequest(id: string): void;
    private handleInboundMessage;
    private handleServerRequest;
    private handleServerNotification;
    private stripSubscriptionId;
    private recordTask;
    private emitEvent;
    private listeningDelay;
    private assertPaginationPage;
    private withToolCallSlot;
    private acquireToolCallSlot;
    private releaseToolCallSlot;
    private toolConcurrencyLimit;
    private delayWithSignal;
    private requestWithInputRounds;
    private sendRequest;
    private buildModernRequestParams;
    private mutualVersion;
    private isSafeSessionRecoveryMethod;
    private recoverSession;
    private sendNotification;
    private assertResourceSubscriptionCapability;
    private restartModernListener;
    private withResourceSubscriptionTransition;
}

type AxMCPSSRFProtectionContext = 'mcp-endpoint' | 'oauth-resource-metadata' | 'oauth-authorization-server-metadata' | 'oauth-authorization' | 'oauth-registration' | 'oauth-token' | 'redirect';
interface AxMCPSSRFProtectionOptions {
    /**
     * Disable URL validation. Intended only for controlled development and test
     * environments.
     */
    disabled?: boolean;
    /** Allow plain HTTP. HTTPS is required by default. */
    allowHTTP?: boolean;
    /** Allow loopback hosts such as localhost, 127.0.0.1, and ::1. */
    allowLoopback?: boolean;
    /** Allow private, link-local, and otherwise reserved IP literal hosts. */
    allowPrivateNetwork?: boolean;
    /** Exact hostnames that should bypass host classification checks. */
    allowedHosts?: readonly string[];
    /**
     * Optional application-specific validator. Throw to reject the URL.
     * Use this for DNS pinning or deployment-specific egress policy.
     */
    validateURL?: (url: URL, context: AxMCPSSRFProtectionContext) => void | Promise<void>;
}
type AxMCPFetchOptions = RequestInit & {
    /** Host fetch implementation, including an mTLS-capable TLS stack if needed. */
    fetch?: typeof globalThis.fetch;
    ssrfProtection?: AxMCPSSRFProtectionOptions;
    ssrfContext?: AxMCPSSRFProtectionContext;
    maxRedirects?: number;
};

interface AxMCPDPoPProofRequest {
    url: string;
    method: string;
    accessToken?: string;
    nonce?: string;
}
interface AxMCPDPoPOptions {
    privateKey?: CryptoKey;
    publicJwk?: JsonWebKey;
    createProof?: (request: Readonly<AxMCPDPoPProofRequest>) => string | Promise<string>;
    now?: () => number;
    jti?: () => string;
}
declare class AxMCPDPoPProofFactory {
    private readonly options;
    private keyPair?;
    constructor(options?: Readonly<AxMCPDPoPOptions>);
    createProof(request: Readonly<AxMCPDPoPProofRequest>): Promise<string>;
    private getKeys;
    private publicOnlyJwk;
}

type AxMCPTokenSet = {
    accessToken: string;
    refreshToken?: string;
    expiresAt?: number;
    issuer?: string;
    tokenType?: string;
    scope?: string;
    idToken?: string;
};
type TokenSet = AxMCPTokenSet;
interface AxMCPOAuthTokenIntrospection {
    active: boolean;
    scope?: string;
    client_id?: string;
    username?: string;
    token_type?: string;
    exp?: number;
    iat?: number;
    nbf?: number;
    sub?: string;
    aud?: string | readonly string[];
    iss?: string;
    jti?: string;
    [key: string]: unknown;
}
type AxMCPOAuthTokenEndpointAuthMethod = 'none' | 'client_secret_basic' | 'client_secret_post' | 'client_secret_jwt' | 'private_key_jwt';
interface AxMCPOAuthClientRegistration {
    client_id: string;
    client_secret?: string;
    client_id_issued_at?: number;
    client_secret_expires_at?: number;
    registration_access_token?: string;
    registration_client_uri?: string;
    token_endpoint_auth_method?: AxMCPOAuthTokenEndpointAuthMethod;
}
type AxMCPEnterpriseIdentityAssertionType = 'urn:ietf:params:oauth:token-type:id_token' | 'urn:ietf:params:oauth:token-type:saml2' | (string & {});
interface AxMCPEnterpriseAuthorizationContext {
    /** MCP authorization-server issuer discovered for the protected resource. */
    authorizationServerUrl: string;
    /** Canonical MCP protected-resource identifier from RFC 9728 discovery. */
    resourceUrl: string;
    scope?: string;
}
interface AxMCPEnterpriseManagedAuthorizationOptions {
    /**
     * Supplies an already-issued ID-JAG. Use this when an organization owns the
     * IdP exchange outside Ax. When omitted, Ax performs the RFC 8693 exchange
     * using the identity-provider options below.
     */
    getAuthorizationGrant?: (context: Readonly<AxMCPEnterpriseAuthorizationContext>) => string | Promise<string>;
    /** IdP token endpoint used to exchange the user's identity assertion. */
    identityProviderTokenEndpoint?: string;
    /** Supplies the ID token or SAML assertion retained from enterprise SSO. */
    getIdentityAssertion?: (context: Readonly<AxMCPEnterpriseAuthorizationContext>) => string | Readonly<{
        assertion: string;
        type?: AxMCPEnterpriseIdentityAssertionType;
    }> | Promise<string | Readonly<{
        assertion: string;
        type?: AxMCPEnterpriseIdentityAssertionType;
    }>>;
    identityProviderClientId?: string;
    identityProviderClientSecret?: string;
    identityProviderTokenEndpointAuthMethod?: AxMCPOAuthTokenEndpointAuthMethod;
    /** Creates an IdP client assertion for secret/private-key JWT auth. */
    createIdentityProviderClientAssertion?: (request: Readonly<{
        method: 'client_secret_jwt' | 'private_key_jwt';
        clientId: string;
        audience: string;
    }>) => string | Promise<string>;
    /** Additional organization-defined RFC 8693 parameters. */
    identityProviderParameters?: Readonly<Record<string, string>>;
}
interface AxMCPOAuthJWTValidationOptions {
    /** Set false only when the host independently verifies every returned ID token. */
    validateIdTokens?: boolean;
    allowedAlgorithms?: readonly string[];
    clockToleranceSeconds?: number;
    now?: () => number;
    ssrfProtection?: AxMCPSSRFProtectionOptions;
    fetch?: typeof globalThis.fetch;
}
interface AxMCPMTLSOptions {
    /**
     * Fetch implementation whose host TLS stack presents the configured client
     * certificate. Browsers may satisfy this through their certificate UI;
     * server runtimes typically inject an agent/dispatcher-backed fetch.
     */
    fetch: typeof globalThis.fetch;
    /** Require RFC 8705 certificate-bound access tokens in AS metadata. */
    requireCertificateBoundAccessTokens?: boolean;
}
interface AxMCPOAuthOptions {
    grantType?: 'authorization_code' | 'client_credentials';
    dpop?: AxMCPDPoPOptions;
    /** Official Enterprise-Managed Authorization extension (ID-JAG flow). */
    enterpriseManagedAuthorization?: AxMCPEnterpriseManagedAuthorizationOptions;
    /** OIDC ID-token signature and claim validation. Enabled by default. */
    jwtValidation?: AxMCPOAuthJWTValidationOptions;
    /** RFC 8705 mutual-TLS channel and certificate-bound token policy. */
    mtls?: AxMCPMTLSOptions;
    /** Custom fetch for OAuth endpoints when mTLS is not required. */
    fetch?: typeof globalThis.fetch;
    /** RFC 9126 pushed authorization request behavior. */
    usePAR?: boolean | 'auto';
    /** RFC 9101 request-object producer. The callback must sign the claims. */
    createAuthorizationRequestJWT?: (claims: Readonly<Record<string, unknown>>) => string | Promise<string>;
    /** RFC 9396 rich authorization details. */
    authorizationDetails?: readonly Record<string, unknown>[];
    /** Additional RFC 8707 resource indicators. */
    resources?: readonly string[];
    clientId?: string;
    clientSecret?: string;
    /** HTTPS URL used as the client_id when CIMD is advertised by the server. */
    clientMetadataDocumentUrl?: string;
    tokenEndpointAuthMethod?: AxMCPOAuthTokenEndpointAuthMethod;
    /** Creates JWT client assertions for secret/private-key authentication. */
    createClientAssertion?: (request: Readonly<{
        method: 'client_secret_jwt' | 'private_key_jwt';
        clientId: string;
        audience: string;
    }>) => string | Promise<string>;
    redirectUri?: string;
    scopes?: string[];
    /**
     * SSRF protection for OAuth discovery, registration, and token URLs supplied
     * by MCP servers and authorization metadata. Enabled by default.
     */
    ssrfProtection?: AxMCPSSRFProtectionOptions;
    selectAuthorizationServer?: (issuers: string[], resourceMetadata: unknown) => Promise<string> | string;
    onAuthCode?: (authorizationUrl: string, context: Readonly<{
        state: string;
        nonce: string;
        redirectUri: string;
    }>) => Promise<{
        code: string;
        state: string;
        redirectUri?: string;
        /** RFC 9207 authorization-server issuer from the authorization response. */
        iss?: string;
    }>;
    tokenStore?: {
        getToken: (key: string) => Promise<TokenSet | null> | TokenSet | null;
        setToken: (key: string, token: TokenSet) => Promise<void> | void;
        clearToken?: (key: string) => Promise<void> | void;
    };
    registrationStore?: {
        getRegistration: (issuer: string) => AxMCPOAuthClientRegistration | null | Promise<AxMCPOAuthClientRegistration | null>;
        setRegistration: (issuer: string, registration: AxMCPOAuthClientRegistration) => void | Promise<void>;
        clearRegistration?: (issuer: string) => void | Promise<void>;
    };
}

interface AxMCPAuthenticationRequest {
    url: string;
    method: string;
    headers: Readonly<Record<string, string>>;
    body?: string;
}
interface AxMCPAuthenticationResult {
    headers?: Record<string, string>;
    query?: Record<string, string>;
}
interface AxMCPAuthenticationStrategy {
    authenticate(request: Readonly<AxMCPAuthenticationRequest>): AxMCPAuthenticationResult | Promise<AxMCPAuthenticationResult | undefined> | undefined;
}
type AxMCPAuthentication = AxMCPAuthenticationStrategy | readonly AxMCPAuthenticationStrategy[];
type SecretProvider = string | (() => string | Promise<string>);
declare function axMCPBearerAuthentication(token: SecretProvider, tokenType?: string): AxMCPAuthenticationStrategy;
declare function axMCPBasicAuthentication(username: SecretProvider, password: SecretProvider): AxMCPAuthenticationStrategy;
declare function axMCPAPIKeyAuthentication(options: {
    key: SecretProvider;
    name?: string;
    in?: 'header' | 'query';
    prefix?: string;
}): AxMCPAuthenticationStrategy;
declare function axMCPHMACAuthentication(options: {
    keyId: string;
    secret: SecretProvider;
    signatureHeader?: string;
    timestampHeader?: string;
    nonceHeader?: string;
    now?: () => number;
    nonce?: () => string;
}): AxMCPAuthenticationStrategy;
declare function axApplyMCPAuthentication(url: string, init: Readonly<RequestInit>, authentication?: AxMCPAuthentication): Promise<{
    url: string;
    init: RequestInit;
}>;

interface AxMCPStreamableHTTPTransportOptions {
    headers?: Record<string, string>;
    authorization?: string;
    /** Composable bearer, API key, Basic, HMAC, or caller-defined authentication. */
    authentication?: AxMCPAuthentication;
    oauth?: AxMCPOAuthOptions;
    /** Host-provided fetch implementation for all HTTP transport requests. */
    fetch?: typeof globalThis.fetch;
    /** RFC 8705 mutual-TLS channel; also inherited by OAuth unless overridden. */
    mtls?: AxMCPMTLSOptions;
    /**
     * SSRF protection for the configured MCP endpoint. HTTPS and public hosts are
     * required by default; set allowHTTP/allowLoopback for controlled local
     * development, or disabled for trusted test fixtures.
     */
    ssrfProtection?: AxMCPSSRFProtectionOptions;
    /**
     * Attempt legacy HTTP+SSE fallback when an initialize POST gets a legacy
     * status. Defaults to false; use AxMCPHTTPSSETransport when you know the
     * server is legacy SSE-only.
     */
    legacySSEFallback?: boolean;
    /** Per-request timeout. Defaults to 30 seconds. */
    timeoutMs?: number;
    /** Maximum decoded response body size. Defaults to 16 MiB. */
    maxResponseBytes?: number;
    /** Maximum validated redirect hops for GET/HEAD requests. Defaults to 5. */
    maxRedirects?: number;
    /** Retry policy for safe MCP operations on 429/502/503/504. */
    retry?: false | {
        maxAttempts?: number;
        baseDelayMs?: number;
        maxDelayMs?: number;
        statuses?: readonly number[];
    };
}

interface AxUCPSchemaValidationOptions {
    fetch?: typeof globalThis.fetch;
    ssrfProtection?: AxMCPSSRFProtectionOptions;
    maxDocuments?: number;
    maxDepth?: number;
}
declare class AxUCPSchemaValidationError extends Error {
    readonly instancePath: string;
    readonly schemaPath: string;
    constructor(instancePath: string, schemaPath: string, message: string);
}
/** Bounded, dependency-free JSON Schema 2020-12 validator for UCP schemas. */
declare class AxUCPSchemaValidator {
    private readonly options;
    private readonly documents;
    constructor(options?: Readonly<AxUCPSchemaValidationOptions>);
    validate(value: unknown, schemaUrl: string): Promise<void>;
    clearCache(): void;
    private loadDocument;
    private resolveReference;
    private validateSchema;
    private validateObject;
    private validateString;
    private validateNumber;
    private matchesType;
    private fail;
    private escape;
    private deepEqual;
}

interface AxUCPHTTPMessageSignatureOptions {
    keyId: string;
    algorithm?: string;
    label?: string;
    components?: readonly ('@method' | '@authority' | '@path' | '@query' | 'ucp-agent' | 'content-digest' | 'content-type' | 'request-id' | 'idempotency-key')[];
    created?: () => number;
    nonce?: () => string;
    sign(signatureBase: Uint8Array, context: Readonly<{
        signatureInput: string;
    }>): Uint8Array | ArrayBuffer | Promise<Uint8Array | ArrayBuffer>;
}
type AxUCPHTTPMessageSignatureErrorCode = 'signature_missing' | 'signature_invalid' | 'key_not_found' | 'digest_mismatch' | 'algorithm_unsupported' | 'signature_expired' | 'signature_replayed';
declare class AxUCPHTTPMessageSignatureError extends Error {
    readonly code: AxUCPHTTPMessageSignatureErrorCode;
    constructor(code: AxUCPHTTPMessageSignatureErrorCode, message: string);
}
interface AxUCPHTTPMessageVerificationOptions {
    /** Reject responses without signature headers. */
    required?: boolean;
    /** Require a `created` signature parameter and limit its age. */
    maxAgeSeconds?: number;
    clockToleranceSeconds?: number;
    allowedAlgorithms?: readonly ('ES256' | 'ES384')[];
    now?: () => number;
    /** When enabled, reject re-use of a signature nonce or signature value. */
    replayProtection?: boolean;
}
declare function axSignUCPRequest(request: Readonly<{
    url: string;
    method: string;
    headers: Record<string, string>;
    body?: string;
}>, options: Readonly<AxUCPHTTPMessageSignatureOptions>): Promise<Record<string, string>>;
/** Stateful RFC 9421 response verifier with profile-key rotation support. */
declare class AxUCPHTTPMessageVerifier {
    private readonly options;
    private readonly seen;
    constructor(options?: Readonly<AxUCPHTTPMessageVerificationOptions>);
    verify(response: Response, context: Readonly<{
        body: string;
        signingKeys: readonly Record<string, unknown>[];
        refreshSigningKeys?: () => readonly Record<string, unknown>[] | Promise<readonly Record<string, unknown>[]>;
    }>): Promise<void>;
    verifyRequest(request: Request, context: Readonly<{
        body: string;
        signingKeys: readonly Record<string, unknown>[];
        refreshSigningKeys?: () => readonly Record<string, unknown>[] | Promise<readonly Record<string, unknown>[]>;
    }>): Promise<void>;
    clearReplayCache(): void;
    private normalizeAlgorithm;
    private componentValue;
}

declare const AX_UCP_OPERATIONS: readonly ["search_catalog", "lookup_catalog", "get_product", "create_cart", "get_cart", "update_cart", "cancel_cart", "create_checkout", "get_checkout", "update_checkout", "complete_checkout", "cancel_checkout", "get_order"];
type AxUCPOperation = (typeof AX_UCP_OPERATIONS)[number] | (string & {});
type AxUCPTransportKind = 'mcp' | 'rest';
type AxUCPValue = Record<string, unknown>;
interface AxUCPVersionedDeclaration {
    version: string;
    spec?: string;
    schema?: string;
    extends?: string | readonly string[];
    [key: string]: unknown;
}
interface AxUCPService extends AxUCPVersionedDeclaration {
    transport: AxUCPTransportKind;
    endpoint: string;
}
interface AxUCPPaymentHandler extends AxUCPVersionedDeclaration {
    id: string;
    available_instruments?: readonly AxUCPValue[];
    config?: AxUCPValue;
}
interface AxUCPProfileBody {
    version: string;
    supported_versions?: Record<string, string>;
    services: Record<string, readonly AxUCPService[]>;
    capabilities: Record<string, readonly AxUCPVersionedDeclaration[]>;
    payment_handlers?: Record<string, readonly AxUCPPaymentHandler[]>;
}
interface AxUCPProfile {
    ucp: AxUCPProfileBody;
    signing_keys?: readonly AxUCPValue[];
}
interface AxUCPNegotiatedProfile {
    version: string;
    service: AxUCPService;
    capabilities: Record<string, readonly AxUCPVersionedDeclaration[]>;
    paymentHandlers: Record<string, readonly AxUCPPaymentHandler[]>;
    signingKeys: readonly AxUCPValue[];
    businessProfile: AxUCPProfile;
}
interface AxUCPMessage {
    type: 'error' | 'warning' | 'info';
    code?: string;
    content: string;
    severity?: 'recoverable' | 'unrecoverable';
    [key: string]: unknown;
}
interface AxUCPResponseMetadata {
    version: string;
    status?: 'success' | 'error';
    capabilities?: Record<string, readonly AxUCPVersionedDeclaration[]>;
    payment_handlers?: Record<string, readonly AxUCPPaymentHandler[]>;
    [key: string]: unknown;
}
interface AxUCPOutcome extends AxUCPValue {
    ucp: AxUCPResponseMetadata;
    messages?: readonly AxUCPMessage[];
    continue_url?: string;
}
interface AxUCPCallOptions {
    idempotencyKey?: string;
    signal?: AbortSignal;
}
interface AxUCPClientOptions {
    /** Business origin or explicit /.well-known/ucp profile URL. */
    profileUrl: string;
    /** Public platform profile URL injected into every request. */
    agentProfile: string;
    namespace?: string;
    version?: string;
    transport?: 'auto' | AxUCPTransportKind;
    platformCapabilities?: Record<string, readonly AxUCPVersionedDeclaration[]>;
    headers?: Record<string, string>;
    mcp?: AxMCPStreamableHTTPTransportOptions;
    /** Built-in RFC 9421 header construction with caller-provided key signing. */
    httpMessageSignature?: AxUCPHTTPMessageSignatureOptions;
    /** Built-in RFC 9421 response verification using business profile keys. */
    httpMessageVerification?: AxUCPHTTPMessageVerificationOptions;
    /** Compatibility mode for UCP MCP endpoints that reject initialize. */
    skipMCPInitialization?: boolean;
    /** Optional request signer. Return additional or replacement headers. */
    signRequest?: (request: Readonly<{
        url: string;
        method: string;
        headers: Record<string, string>;
        body: string;
    }>) => Record<string, string> | Promise<Record<string, string>>;
    /** Optional response verifier for RFC 9421 or deployment-specific policy. */
    verifyResponse?: (response: Response, context: Readonly<{
        profile: AxUCPNegotiatedProfile;
    }>) => void | Promise<void>;
    /** OAuth/PKCE account linking used after UCP identity challenges. */
    identityLinkingOAuth?: AxMCPOAuthOptions;
    /** Host-managed user identity token for pre-authorized commerce calls. */
    getIdentityToken?: () => AxMCPTokenSet | null | Promise<AxMCPTokenSet | null>;
    /** Additional business profile URLs trusted to sign lifecycle webhooks. */
    trustedBusinessProfileUrls?: readonly string[];
    webhookMaxAgeSeconds?: number;
    /** Marks a configured endpoint as an evaluation sandbox or replay source. */
    evaluationMode?: 'live' | 'replay' | 'sandbox';
    /** Validate outcomes against negotiated capability schema documents. */
    schemaValidation?: false | AxUCPSchemaValidationOptions;
}
interface AxUCPBuyerContext extends AxUCPValue {
    country?: string;
    region?: string;
    postal_code?: string;
}
interface AxUCPAttribution extends AxUCPValue {
    source?: string;
    medium?: string;
    campaign?: string;
    click_id?: string;
}
interface AxUCPDiscounts extends AxUCPValue {
    codes?: readonly string[];
    applied?: readonly AxUCPValue[];
}
interface AxUCPFulfillment extends AxUCPValue {
    methods?: readonly AxUCPValue[];
    groups?: readonly AxUCPValue[];
    destinations?: readonly AxUCPValue[];
}
interface AxUCPPayment extends AxUCPValue {
    instruments?: readonly AxUCPValue[];
    handlers?: readonly AxUCPPaymentHandler[];
}
interface AxUCPCartInput extends AxUCPValue {
    line_items?: readonly AxUCPValue[];
    context?: AxUCPBuyerContext;
    attribution?: AxUCPAttribution;
    discounts?: AxUCPDiscounts;
}
interface AxUCPCheckoutInput extends AxUCPValue {
    line_items?: readonly AxUCPValue[];
    buyer?: AxUCPValue;
    context?: AxUCPBuyerContext;
    attribution?: AxUCPAttribution;
    discounts?: AxUCPDiscounts;
    fulfillment?: AxUCPFulfillment;
    payment?: AxUCPPayment;
}
interface AxUCPCheckoutCompletion extends AxUCPValue {
    payment?: AxUCPPayment;
    signals?: AxUCPValue;
}
interface AxUCPIdentityLinkingConfig extends AxUCPValue {
    scopes?: Record<string, AxUCPValue>;
    providers?: readonly AxUCPValue[];
}
interface AxUCPOrderEvent extends AxUCPOutcome {
    id: string;
    checkout_id: string;
    event_id?: string;
    created_time?: string;
}
interface AxUCPCatalogSearchRequest extends AxUCPValue {
    query?: string;
    context?: AxUCPValue;
    signals?: AxUCPValue;
    attribution?: AxUCPValue;
    filters?: AxUCPValue;
    pagination?: AxUCPValue;
}
interface AxUCPCatalogLookupRequest extends AxUCPValue {
    ids: readonly string[];
    context?: AxUCPValue;
    filters?: AxUCPValue;
}
interface AxUCPProductRequest extends AxUCPValue {
    id: string;
    selected?: readonly AxUCPValue[];
    preferences?: readonly string[];
    context?: AxUCPValue;
}

declare class AxUCPClient {
    private readonly options;
    private negotiated?;
    private mcpClient?;
    private mcpTransport?;
    private readonly responseVerifier?;
    private readonly identityOAuth?;
    private identityToken?;
    private readonly webhookIds;
    private readonly schemaValidator?;
    constructor(options: Readonly<AxUCPClientOptions>);
    init(): Promise<void>;
    getProfile(): AxUCPNegotiatedProfile;
    getNamespace(): string;
    getEvaluationMode(): 'live' | 'replay' | 'sandbox';
    getOperationNames(): readonly string[];
    getOperationBindings(): AxFunction[];
    getPaymentHandlers(): AxUCPNegotiatedProfile['paymentHandlers'];
    getIdentityLinkingConfig(): AxUCPIdentityLinkingConfig | undefined;
    getIdentityLinkingScopes(): readonly string[];
    verifyOrderEvent(request: Request): Promise<AxUCPOrderEvent>;
    /** Returns the live MCP client used by AxGen/AxAgent native integration. */
    getMCPClient(): AxMCPClient | undefined;
    close(): Promise<void>;
    searchCatalog(catalog: Readonly<AxUCPCatalogSearchRequest>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    lookupCatalog(catalog: Readonly<AxUCPCatalogLookupRequest>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    getProduct(catalog: Readonly<AxUCPProductRequest>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    createCart(cart: Readonly<AxUCPCartInput>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    getCart(id: string, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    updateCart(id: string, cart: Readonly<AxUCPCartInput>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    cancelCart(id: string, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    createCheckout(checkout: Readonly<AxUCPCheckoutInput>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    getCheckout(id: string, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    updateCheckout(id: string, checkout: Readonly<AxUCPCheckoutInput>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    completeCheckout(id: string, options: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    completeCheckout(id: string, completion: Readonly<AxUCPCheckoutCompletion>, options: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    cancelCheckout(id: string, options: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    getOrder(id: string, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    call(operation: string, input: Readonly<AxUCPValue>, options?: Readonly<AxUCPCallOptions>): Promise<AxUCPOutcome>;
    private profileURL;
    private fetchProfile;
    private selectService;
    private negotiateCapabilities;
    private withAgentMetadata;
    private callREST;
    private restRequest;
    private outcomeFromMCPResponse;
    private requireIdempotency;
    private isStateChanging;
    private operationBody;
    validateAgainstSchema(value: unknown, schemaUrl: string): Promise<void>;
    private validateOutcome;
}

type AxMCPInheritance = 'all' | 'none' | readonly string[];
interface AxMCPContinuationState {
    clients: readonly {
        namespace: string;
        tasks: readonly {
            taskId: string;
            status: AxMCPTask['status'];
        }[];
        subscriptions: readonly string[];
    }[];
}
type AxMCPTaskSnapshot = Readonly<Record<string, readonly string[]>>;
type AxMCPContextRequest = {
    client: AxMCPClient | string;
    prompt: {
        name: string;
        arguments?: Record<string, string>;
    };
} | {
    client: AxMCPClient | string;
    resource: {
        uri: string;
    };
};
type AxMCPResolvedContext = {
    type: 'prompt';
    namespace: string;
    name: string;
    result: AxMCPPromptGetResult;
} | {
    type: 'resource';
    namespace: string;
    uri: string;
    result: AxMCPResourceReadResult;
};
declare function axResolveMCPExecutionContext(options: Readonly<{
    mcp?: AxMCPClient | readonly AxMCPClient[];
    ucp?: AxUCPClient | readonly AxUCPClient[];
    mcpInheritance?: AxMCPInheritance;
    _mcpExecutionContext?: AxMCPExecutionContext;
}>, defaults?: Readonly<{
    mcp?: AxMCPClient | readonly AxMCPClient[];
    ucp?: AxUCPClient | readonly AxUCPClient[];
    mcpInheritance?: AxMCPInheritance;
}>): Promise<AxMCPExecutionContext | undefined>;
/** Run-scoped MCP state shared by Ax programs. */
declare class AxMCPExecutionContext {
    readonly inheritance: AxMCPInheritance;
    private readonly clientsByNamespace;
    private readonly ucpClientsByNamespace;
    private readonly continuationSubscriptionOwner;
    constructor(clients: AxMCPClient | readonly AxMCPClient[], inheritance?: AxMCPInheritance, ucpClients?: AxUCPClient | readonly AxUCPClient[]);
    get clients(): readonly AxMCPClient[];
    get ucpClients(): readonly AxUCPClient[];
    /** Derive the client view that a nested user program is allowed to receive. */
    forChild(inheritance?: AxMCPInheritance): AxMCPExecutionContext | undefined;
    initialize(): Promise<void>;
    getClient(client: AxMCPClient | string): AxMCPClient;
    getUCPClient(client: AxUCPClient | string): AxUCPClient;
    /** Bind raw MCP tools without using the lossy client.toFunction() adapter. */
    getToolBindings(): AxFunction[];
    getCatalogRevision(): string;
    getContinuationState(): AxMCPContinuationState;
    getTaskSnapshot(): AxMCPTaskSnapshot;
    cancelTasksCreatedSince(snapshot: AxMCPTaskSnapshot): Promise<void>;
    restoreContinuationState(state: Readonly<AxMCPContinuationState> | undefined): Promise<void>;
    resolveContext(requests?: readonly AxMCPContextRequest[]): Promise<AxMCPResolvedContext[]>;
    resolveContextPrompt(requests?: readonly AxMCPContextRequest[]): Promise<AxChatRequest['chatPrompt']>;
    private bindTool;
    private contentToText;
    private contentToUserParts;
    private assertUniqueToolNames;
}
/** Remove parent attachment options and pass only the permitted live context. */
declare function axMCPChildExecutionOptions<T extends Readonly<{
    mcp?: unknown;
    ucp?: unknown;
    mcpContext?: unknown;
    _mcpExecutionContext?: AxMCPExecutionContext;
    eventContext?: unknown;
    eventInheritance?: 'all' | 'none';
}>>(options: T): T;

/** The Standard Schema v1 interface. Structurally compatible with `@standard-schema/spec`. */
interface StandardSchemaV1<Input = unknown, Output = Input> {
    readonly '~standard': StandardSchemaV1.Props<Input, Output>;
}
declare namespace StandardSchemaV1 {
    interface Props<Input = unknown, Output = Input> {
        readonly version: 1;
        readonly vendor: string;
        readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
        readonly types?: Types<Input, Output> | undefined;
    }
    type Result<Output> = SuccessResult<Output> | FailureResult;
    interface SuccessResult<Output> {
        readonly value: Output;
        readonly issues?: undefined;
    }
    interface FailureResult {
        readonly issues: ReadonlyArray<Issue>;
    }
    interface Issue {
        readonly message: string;
        readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
    }
    interface PathSegment {
        readonly key: PropertyKey;
    }
    interface Types<Input = unknown, Output = Input> {
        readonly input: Input;
        readonly output: Output;
    }
    type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
    type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
}
/**
 * Per-field companion options for Standard Schema (zod/valibot/arktype) inputs
 * and outputs. These encode ax-specific hints that schema libraries don't
 * represent natively.
 */
interface AxFieldOptions {
    /** Mark this input field as a prefix-cache breakpoint (Anthropic-style). */
    cache?: boolean;
    /** Mark this output field as internal scratchpad (stripped from the final result). */
    internal?: boolean;
}

/**
 * Narrow a StandardSchemaV1 output type to a record so it satisfies the
 * builder's `Record<string, any>` constraint. Non-object schemas collapse to
 * `Record<string, any>` — acceptable because decomposition has already happened
 * at the value level before this type is reached.
 */
type AsRecord<T> = T extends Record<string, any> ? T : Record<string, any>;
interface AxFieldType {
    readonly type: 'string' | 'number' | 'boolean' | 'json' | 'image' | 'audio' | 'file' | 'url' | 'date' | 'dateRange' | 'datetime' | 'datetimeRange' | 'class' | 'code' | 'object';
    readonly isArray?: boolean;
    readonly options?: readonly string[];
    readonly fields?: Record<string, AxFieldType>;
    readonly description?: string;
    readonly isOptional?: boolean;
    readonly isInternal?: boolean;
    readonly minLength?: number;
    readonly maxLength?: number;
    readonly minimum?: number;
    readonly maximum?: number;
    readonly pattern?: string;
    readonly valueDescriptions?: Readonly<Record<string, string>>;
    readonly patternDescription?: string;
    readonly format?: string;
    readonly language?: string;
}
declare class AxSignatureBuilder<_TInput extends Record<string, any> = {}, _TOutput extends Record<string, any> = {}> {
    private inputFields;
    private outputFields;
    private desc?;
    /**
     * Add an input field to the signature. Three shapes:
     *
     * 1. **Native fluent field** — `.input('name', f.string())`. Supports every
     *    LLM-optimized affordance (`.cache()`, `.internal()`, multimodal, etc.).
     * 2. **Per-field Standard Schema** — `.input('name', z.string().min(3), { cache: true })`.
     *    Pass any zod/valibot/arktype schema. Companion `opts` adds ax-specific
     *    hints (`cache`, `internal`) that schema libraries don't represent.
     * 3. **Whole-object Standard Schema** — `.input(z.object({...}), { fields: { ctx: { cache: true } } })`.
     *    Decomposed into per-key fields in declaration order.
     *
     * @example
     * ```ts
     * f()
     *   .input(z.object({
     *     context: z.string(),
     *     question: z.string().describe('User question'),
     *   }), { fields: { context: { cache: true } } })
     *   .output('answer', f.string())
     *   .build();
     * ```
     */
    input<K extends string, T extends AxFluentFieldInfo<any, any, any, any, any, any, any> | AxFluentFieldType<any, any, any, any, any, any, any>>(name: K, fieldInfo: T, prepend?: boolean): AxSignatureBuilder<AddFieldToShape<_TInput, K, T, 'input'>, _TOutput>;
    input<K extends string, T extends StandardSchemaV1>(name: K, schema: T, opts?: AxFieldOptions): AxSignatureBuilder<_TInput & {
        [P in K]: StandardSchemaV1.InferOutput<T>;
    }, _TOutput>;
    input<T extends StandardSchemaV1>(schema: T, opts?: {
        fields?: Record<string, AxFieldOptions>;
    }): AxSignatureBuilder<AsRecord<StandardSchemaV1.InferOutput<T>>, _TOutput>;
    /**
     * Add an output field to the signature. Same three shapes as
     * {@link AxSignatureBuilder.input}.
     */
    output<K extends string, T extends AxFluentFieldInfo<any, any, any, any, any, any, any> | AxFluentFieldType<any, any, any, any, any, any, any>>(name: K, fieldInfo: T, prepend?: boolean): AxSignatureBuilder<_TInput, AddFieldToShape<_TOutput, K, T, 'output'>>;
    output<K extends string, T extends StandardSchemaV1>(name: K, schema: T, opts?: AxFieldOptions): AxSignatureBuilder<_TInput, _TOutput & {
        [P in K]: StandardSchemaV1.InferOutput<T>;
    }>;
    output<T extends StandardSchemaV1>(schema: T, opts?: {
        fields?: Record<string, AxFieldOptions>;
    }): AxSignatureBuilder<_TInput, AsRecord<StandardSchemaV1.InferOutput<T>>>;
    /**
     * Add pre-existing input fields (e.g., extracted from another signature).
     * Type safety is lost for these fields since they are dynamically defined.
     */
    addInputFields(fields: readonly AxIField[]): AxSignatureBuilder<Record<string, any>, _TOutput>;
    /**
     * Add pre-existing output fields (e.g., extracted from another signature).
     * Type safety is lost for these fields since they are dynamically defined.
     */
    addOutputFields(fields: readonly AxIField[]): AxSignatureBuilder<_TInput, Record<string, any>>;
    /**
     * Set the description for the signature
     * @param description - Description text
     */
    description(description: string): AxSignatureBuilder<_TInput, _TOutput>;
    /**
     * Enforce structured outputs (JSON) for this signature, even if fields are simple.
     */
    useStructured(): AxSignatureBuilder<_TInput, _TOutput>;
    /**
     * Build the final AxSignature instance
     */
    build(): AxSignature<_TInput, _TOutput>;
}
declare class AxFluentFieldType<TType extends AxFieldType['type'] = AxFieldType['type'], TIsArray extends boolean = false, TOptions extends readonly string[] | undefined = undefined, TIsOptional extends boolean = false, TIsInternal extends boolean = false, TFields extends Record<string, AxFluentFieldInfo | AxFluentFieldType> | undefined = undefined, TIsCached extends boolean = false> implements AxFieldType {
    readonly type: TType;
    readonly isArray: TIsArray;
    readonly options?: TOptions;
    readonly description?: string;
    readonly isOptional: TIsOptional;
    readonly isInternal: TIsInternal;
    readonly isCached: TIsCached;
    readonly fields?: any;
    readonly minLength?: number;
    readonly maxLength?: number;
    readonly minimum?: number;
    readonly maximum?: number;
    readonly pattern?: string;
    readonly valueDescriptions?: Readonly<Record<string, string>>;
    readonly patternDescription?: string;
    readonly format?: string;
    readonly language?: string;
    readonly itemDescription?: string;
    constructor(fieldType: {
        type: TType;
        isArray: TIsArray;
        options?: TOptions;
        description?: string;
        itemDescription?: string;
        isOptional: TIsOptional;
        isInternal: TIsInternal;
        isCached: TIsCached;
        fields?: TFields;
        minLength?: number;
        maxLength?: number;
        minimum?: number;
        maximum?: number;
        pattern?: string;
        valueDescriptions?: Readonly<Record<string, string>>;
        patternDescription?: string;
        format?: string;
        language?: string;
    });
    /** Describe individual boolean outcomes or class labels without changing their value types. */
    describeValues<const D extends Readonly<Record<string, string>>>(descriptions: D & Record<Exclude<keyof D, TType extends 'boolean' ? 'true' | 'false' : TType extends 'class' ? NonNullable<TOptions>[number] : never>, never>): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    optional(): AxFluentFieldType<TType, TIsArray, TOptions, true, TIsInternal, TFields, TIsCached>;
    array(desc?: string): AxFluentFieldType<TType, true, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    internal(): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, true, TFields, TIsCached>;
    /**
     * Mark this input field for caching. When contextCache is enabled,
     * cached fields are rendered in a separate user message with cache: true,
     * allowing them to be cached by the LLM provider.
     */
    cache(): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, true>;
    /**
     * Set minimum value for numbers or minimum length for strings
     */
    min(value: number): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    /**
     * Set maximum value for numbers or maximum length for strings
     */
    max(value: number): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    /**
     * Set email format validation for strings
     */
    email(): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    /**
     * Set URL/URI format validation for strings
     */
    url(): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    /**
     * Set regex pattern validation for strings
     * @param pattern - Regular expression pattern to match
     * @param description - Human-readable description of what the pattern validates (e.g., "Must be a valid username with only lowercase letters, numbers, and underscores")
     */
    regex(pattern: string, description: string): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    /**
     * Set date format validation for strings
     */
    date(): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    /**
     * Set datetime format validation for strings
     */
    datetime(): AxFluentFieldType<TType, TIsArray, TOptions, TIsOptional, TIsInternal, TFields, TIsCached>;
    /**
     * Standard Schema v1 surface — lets ax fields flow through any library that
     * accepts `StandardSchemaV1` (tRPC, TanStack Form, Vercel AI SDK, etc.).
     */
    get '~standard'(): StandardSchemaV1.Props<unknown, unknown>;
}
type ValidateNoMediaTypes<TFields> = {
    [K in keyof TFields]: TFields[K] extends {
        type: infer T;
    } ? T extends 'image' | 'audio' | 'file' ? {
        __error: `Type '${T extends string ? T : never}' cannot be used in f.object(). Media types (image, audio, file) are only allowed as top-level input fields, not within nested objects.`;
        __suggestion: 'Use string, number, boolean, or nested f.object() instead.';
    } : TFields[K] extends {
        fields: infer TNestedFields;
    } ? TNestedFields extends Record<string, any> ? TFields[K] & {
        fields: ValidateNoMediaTypes<TNestedFields>;
    } : TFields[K] : TFields[K] : TFields[K];
};
/**
 * Fluent field builder for creating type-safe signature fields.
 *
 * The `f` object provides factory methods for all supported field types, each returning
 * a chainable builder that allows adding constraints and modifiers.
 *
 * **Basic Usage:**
 * When called as a function, `f()` returns a new `AxSignatureBuilder` for programmatic
 * signature construction. More commonly, use its type methods directly.
 *
 * **Type Methods:**
 * - `f.string(desc?)` - Text content
 * - `f.number(desc?)` - Numeric values
 * - `f.boolean(desc?)` - True/false values
 * - `f.json(desc?)` - Arbitrary JSON objects
 * - `f.datetime(desc?)` - ISO 8601 datetime strings
 * - `f.date(desc?)` - Date in YYYY-MM-DD format
 * - `f.datetimeRange(desc?)` - `{ start: Date; end: Date }` datetime ranges
 * - `f.dateRange(desc?)` - `{ start: Date; end: Date }` date ranges
 * - `f.class(options, desc?)` - Classification with predefined choices
 * - `f.image(desc?)` - Image input (multimodal)
 * - `f.audio(desc?)` - Audio input
 * - `f.file(desc?)` - File input
 * - `f.url(desc?)` - URL strings
 * - `f.email(desc?)` - Email addresses
 * - `f.code(language?, desc?)` - Code blocks
 * - `f.object(fields, desc?)` - Nested object with typed fields
 *
 * **Modifier Methods (chainable):**
 * - `.optional()` - Mark field as optional
 * - `.array(desc?)` - Convert to array of this type
 * - `.internal()` - Hide from final output (for intermediate reasoning)
 * - `.cache()` - Mark for context caching
 * - `.min(value)` - Minimum length (strings) or value (numbers)
 * - `.max(value)` - Maximum length (strings) or value (numbers)
 * - `.regex(pattern, desc)` - Regex validation for strings
 * - `.email()` - Email format validation for strings
 * - `.url()` - URL format validation for strings
 *
 * @example Basic field types
 * ```typescript
 * const sig = f()
 *   .input('name', f.string('User name'))
 *   .input('age', f.number('Age in years'))
 *   .output('greeting', f.string('Personalized greeting'))
 *   .build();
 * ```
 *
 * @example With constraints
 * ```typescript
 * const sig = f()
 *   .input('email', f.string().email())
 *   .input('score', f.number('Score between 0-100').min(0).max(100))
 *   .input('tags', f.string('Tag').array('List of tags'))
 *   .output('isValid', f.boolean())
 *   .build();
 * ```
 *
 * @example Classification
 * ```typescript
 * const sig = f()
 *   .input('text', f.string('Text to classify'))
 *   .output('sentiment', f.class(['positive', 'negative', 'neutral'] as const))
 *   .output('confidence', f.number().min(0).max(1))
 *   .build();
 * ```
 *
 * @example Nested objects
 * ```typescript
 * const sig = f()
 *   .input('query', f.string())
 *   .output('result', f.object({
 *     title: f.string('Article title'),
 *     score: f.number('Relevance score'),
 *     metadata: f.object({
 *       author: f.string().optional(),
 *       date: f.date()
 *     })
 *   }))
 *   .build();
 * ```
 *
 * @example Optional and internal fields
 * ```typescript
 * const sig = f()
 *   .input('context', f.string().optional())
 *   .input('question', f.string())
 *   .output('reasoning', f.string('Step-by-step thinking').internal())
 *   .output('answer', f.string())
 *   .build();
 * ```
 */
declare const f: (() => AxSignatureBuilder) & {
    /**
     * Creates a string field type.
     *
     * Strings are the default and most common field type. Use modifiers to add
     * validation constraints.
     *
     * @param desc - Optional description explaining the field's purpose
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.string('User question')
     * f.string().min(10).max(1000)  // Length constraints
     * f.string().email()             // Email format
     * f.string().regex('^[A-Z]', 'Must start with uppercase')
     * ```
     */
    string: (desc?: string) => AxFluentFieldType<"string", false, undefined, false, false, undefined, false>;
    /**
     * Creates a number field type.
     *
     * Numbers can be integers or floats. Use `.min()` and `.max()` to constrain the range.
     *
     * @param desc - Optional description explaining the field's purpose
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.number('Age in years')
     * f.number().min(0).max(100)     // Constrained range
     * f.number('Rating').min(1).max(5)
     * ```
     */
    number: (desc?: string) => AxFluentFieldType<"number", false, undefined, false, false, undefined, false>;
    /**
     * Creates a boolean field type.
     *
     * Booleans represent true/false values. Useful for yes/no questions,
     * flags, and binary decisions.
     *
     * @param desc - Optional description explaining what true/false means
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.boolean('Whether the text contains personally identifiable information')
     * f.boolean('Is the sentiment positive')
     * ```
     */
    boolean: (desc?: string) => AxFluentFieldType<"boolean", false, undefined, false, false, undefined, false>;
    /**
     * Creates a JSON field type for arbitrary structured data.
     *
     * Use this when you need flexible object output without a predefined schema.
     * For structured data with known fields, prefer `f.object()` for type safety.
     *
     * @param desc - Optional description of the expected JSON structure
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.json('Extracted entities as key-value pairs')
     * f.json('Configuration object')
     * ```
     */
    json: (desc?: string) => AxFluentFieldType<"json", false, undefined, false, false, undefined, false>;
    /**
     * Creates a datetime field type for ISO 8601 timestamps.
     *
     * Values are formatted as full ISO 8601 datetime strings (e.g., "2024-01-15T14:30:00Z").
     * For date-only values, use `f.date()` instead.
     *
     * @param desc - Optional description explaining the datetime's purpose
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.datetime('When the event occurred')
     * f.datetime('Appointment start time')
     * ```
     */
    datetime: (desc?: string) => AxFluentFieldType<"datetime", false, undefined, false, false, undefined, false>;
    /**
     * Creates a datetime range field type.
     *
     * Values normalize to `{ start: Date; end: Date }`. Prefer ISO 8601
     * interval strings such as `2024-01-15T14:30:00Z/2024-01-15T15:30:00Z`
     * or JSON objects with `start` and `end`.
     */
    datetimeRange: (desc?: string) => AxFluentFieldType<"datetimeRange", false, undefined, false, false, undefined, false>;
    /**
     * Creates a date field type for YYYY-MM-DD formatted dates.
     *
     * Values are formatted as date strings without time components (e.g., "2024-01-15").
     * For datetime values with time, use `f.datetime()` instead.
     *
     * @param desc - Optional description explaining the date's purpose
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.date('Date of birth')
     * f.date('Publication date')
     * ```
     */
    date: (desc?: string) => AxFluentFieldType<"date", false, undefined, false, false, undefined, false>;
    /**
     * Creates a date range field type.
     *
     * Values normalize to `{ start: Date; end: Date }`. Prefer interval strings
     * such as `2024-01-15/2024-01-20` or JSON objects with `start` and `end`.
     */
    dateRange: (desc?: string) => AxFluentFieldType<"dateRange", false, undefined, false, false, undefined, false>;
    /**
     * Creates a classification field type with predefined options.
     *
     * The AI will always return exactly one of the provided options.
     * Use `as const` for the options array to get literal type inference.
     *
     * @param options - Array of allowed values (use `as const` for type safety)
     * @param desc - Optional description of the classification task
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.class(['positive', 'negative', 'neutral'] as const, 'Sentiment')
     * f.class(['bug', 'feature', 'question', 'docs'] as const, 'Issue type')
     * f.class(['low', 'medium', 'high', 'critical'] as const).optional()
     * ```
     */
    class: <const TOptions extends readonly string[]>(options: TOptions, desc?: string) => AxFluentFieldType<"class", false, TOptions, false, false, undefined, false>;
    /**
     * Creates an image field type for multimodal inputs.
     *
     * Pass images as base64-encoded data URLs or URLs to external images.
     * Only supported as input fields with multimodal models (GPT-4V, Claude 3, Gemini, etc.).
     *
     * **Note:** Cannot be used in nested `f.object()` fields - only as top-level inputs.
     *
     * @param desc - Optional description of what the image contains or its purpose
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.image('Product photo to analyze')
     * f.image('Screenshot of the UI bug')
     * f.image().array('Multiple images to compare')
     * ```
     */
    image: (desc?: string) => AxFluentFieldType<"image", false, undefined, false, false, undefined, false>;
    /**
     * Creates an audio field type for audio inputs.
     *
     * Pass audio as base64-encoded data or URLs. Only supported as input fields
     * with models that support audio processing.
     *
     * **Note:** Cannot be used in nested `f.object()` fields - only as top-level inputs.
     *
     * @param desc - Optional description of the audio content
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.audio('Voice recording to transcribe')
     * f.audio('Audio clip for analysis')
     * ```
     */
    audio: (desc?: string) => AxFluentFieldType<"audio", false, undefined, false, false, undefined, false>;
    /**
     * Creates a file field type for document inputs.
     *
     * Pass files as base64-encoded data or file references. Only supported as input
     * fields with models that support file processing (PDFs, documents, etc.).
     *
     * **Note:** Cannot be used in nested `f.object()` fields - only as top-level inputs.
     *
     * @param desc - Optional description of the expected file content
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.file('PDF document to summarize')
     * f.file('Resume to parse')
     * ```
     */
    file: (desc?: string) => AxFluentFieldType<"file", false, undefined, false, false, undefined, false>;
    /**
     * Creates a URL field type with URI format validation.
     *
     * The AI will be instructed to return a valid URL. Use for outputs that
     * should be clickable links or API endpoints.
     *
     * @param desc - Optional description of what the URL should point to
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.url('Link to the source')
     * f.url('API endpoint URL')
     * f.url().optional()
     * ```
     */
    url: (desc?: string) => AxFluentFieldType<"url", false, undefined, false, false, undefined, false>;
    /**
     * Creates an email field type with email format validation.
     *
     * Shorthand for `f.string().email()`. The AI will be instructed to return
     * a valid email address format.
     *
     * @param desc - Optional description of whose email or for what purpose
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.email('Contact email address')
     * f.email().optional()
     * ```
     */
    email: (desc?: string) => AxFluentFieldType<"string", false, undefined, false, false, undefined, false>;
    /**
     * Creates a code field type for source code blocks.
     *
     * Code fields preserve formatting and are rendered in code blocks.
     * Optionally specify a language for syntax highlighting context.
     *
     * @param language - Optional programming language (e.g., 'typescript', 'python')
     * @param desc - Optional description of what the code should do
     * @returns A chainable field builder
     *
     * @example
     * ```typescript
     * f.code('typescript', 'Generated TypeScript function')
     * f.code('python', 'Python script to solve the problem')
     * f.code()  // Language-agnostic code
     * ```
     */
    code: (language?: string, desc?: string) => AxFluentFieldType<"code", false, undefined, false, false, undefined, false>;
    /**
     * Creates a nested object field type with typed properties.
     *
     * Use this when you need structured output with known fields. Each property
     * in the fields object should be created using `f.string()`, `f.number()`, etc.
     *
     * Objects can be nested to create complex hierarchical structures.
     *
     * **Restrictions:**
     * - Media types (`image`, `audio`, `file`) cannot be used in nested objects
     * - Deep nesting may reduce AI output quality
     *
     * @param fields - Object mapping field names to field types created with `f.*` methods
     * @param desc - Optional description of what the object represents
     * @returns A chainable field builder
     *
     * @example Simple object
     * ```typescript
     * f.object({
     *   name: f.string('Person name'),
     *   age: f.number('Age in years'),
     *   isActive: f.boolean()
     * }, 'User profile')
     * ```
     *
     * @example Nested objects
     * ```typescript
     * f.object({
     *   title: f.string(),
     *   author: f.object({
     *     name: f.string(),
     *     email: f.email().optional()
     *   }),
     *   tags: f.string().array()
     * })
     * ```
     *
     * @example Array of objects
     * ```typescript
     * f.object({
     *   item: f.string(),
     *   quantity: f.number().min(1)
     * }).array('List of order items')
     * ```
     */
    object: <TFields extends Record<string, AxFluentFieldInfo<any, any, any, any, any, any, any> | AxFluentFieldType<any, any, any, any, any, any, any>>>(fields: TFields & ValidateNoMediaTypes<TFields>, desc?: string) => AxFluentFieldType<"object", false, undefined, false, false, TFields, false>;
};
interface AxField {
    name: string;
    title?: string;
    description?: string;
    type?: {
        name: 'string' | 'number' | 'boolean' | 'json' | 'image' | 'audio' | 'file' | 'url' | 'date' | 'dateRange' | 'datetime' | 'datetimeRange' | 'class' | 'code' | 'object';
        isArray?: boolean;
        options?: string[];
        fields?: Record<string, AxFieldType>;
        minLength?: number;
        maxLength?: number;
        minimum?: number;
        maximum?: number;
        pattern?: string;
        valueDescriptions?: Readonly<Record<string, string>>;
        patternDescription?: string;
        format?: string;
        language?: string;
        description?: string;
    };
    isOptional?: boolean;
    isInternal?: boolean;
    isCached?: boolean;
    /** Original Standard Schema (zod/valibot/arktype) stored so custom refinements and transforms run at parse time. */
    schema?: StandardSchemaV1;
}
type AxIField = Omit<AxField, 'title'> & {
    title: string;
};
type AxDateRangeValue = {
    start: Date;
    end: Date;
};
type InferAudioValueType<T extends {
    isArray?: boolean;
}, TMode extends 'input' | 'output'> = TMode extends 'output' ? T['isArray'] extends true ? AxChatAudioOutput[] : AxChatAudioOutput : T['isArray'] extends true ? AxAudioInput[] : AxAudioInput;
type InferClassValueType<T extends {
    isArray?: boolean;
    options?: readonly string[] | undefined;
}> = NonNullable<T['options']> extends readonly (infer U)[] ? [U] extends [never] ? T['isArray'] extends true ? string[] : string : T['isArray'] extends true ? U[] : U : T['isArray'] extends true ? string[] : string;
type InferFieldValueType<T, TMode extends 'input' | 'output' = 'input'> = T extends AxFieldType | AxFluentFieldType ? T['type'] extends 'string' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'number' ? T['isArray'] extends true ? number[] : number : T['type'] extends 'boolean' ? T['isArray'] extends true ? boolean[] : boolean : T['type'] extends 'json' ? T['isArray'] extends true ? any[] : any : T['type'] extends 'date' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'dateRange' ? T['isArray'] extends true ? AxDateRangeValue[] : AxDateRangeValue : T['type'] extends 'datetime' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'datetimeRange' ? T['isArray'] extends true ? AxDateRangeValue[] : AxDateRangeValue : T['type'] extends 'image' ? T['isArray'] extends true ? {
    mimeType: string;
    data: string;
}[] : {
    mimeType: string;
    data: string;
} : T['type'] extends 'audio' ? InferAudioValueType<T, TMode> : T['type'] extends 'file' ? T['isArray'] extends true ? ({
    mimeType: string;
    data: string;
} | {
    mimeType: string;
    fileUri: string;
})[] : {
    mimeType: string;
    data: string;
} | {
    mimeType: string;
    fileUri: string;
} : T['type'] extends 'url' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'code' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'class' ? InferClassValueType<T> : T['type'] extends 'object' ? T extends {
    fields: infer F;
} ? F extends Record<string, any> ? T['isArray'] extends true ? {
    [K in keyof F]: InferFluentType<F[K], TMode>;
}[] : {
    [K in keyof F]: InferFluentType<F[K], TMode>;
} : any : any : any : any;
interface AxFluentFieldInfo<TType extends AxFieldType['type'] = AxFieldType['type'], TIsArray extends boolean = false, TOptions extends readonly string[] = readonly string[], TIsOptional extends boolean = false, _TIsInternal extends boolean = false, TFields extends Record<string, AxFluentFieldInfo | AxFluentFieldType> | undefined = undefined, _TIsCached extends boolean = false> {
    readonly type: TType;
    readonly isArray?: TIsArray;
    readonly options?: TOptions;
    readonly fields?: TFields;
    readonly description?: string;
    readonly itemDescription?: string;
    readonly isOptional?: TIsOptional;
    readonly isInternal?: boolean;
    readonly isCached?: boolean;
    readonly minLength?: number;
    readonly maxLength?: number;
    readonly minimum?: number;
    readonly maximum?: number;
    readonly pattern?: string;
    readonly valueDescriptions?: Readonly<Record<string, string>>;
    readonly patternDescription?: string;
    readonly format?: string;
    readonly language?: string;
}
type InferFluentType<T extends AxFluentFieldInfo<any, any, any, any> | AxFluentFieldType, TMode extends 'input' | 'output' = 'input'> = T['type'] extends 'string' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'number' ? T['isArray'] extends true ? number[] : number : T['type'] extends 'boolean' ? T['isArray'] extends true ? boolean[] : boolean : T['type'] extends 'json' ? T['isArray'] extends true ? any[] : any : T['type'] extends 'date' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'dateRange' ? T['isArray'] extends true ? AxDateRangeValue[] : AxDateRangeValue : T['type'] extends 'datetime' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'datetimeRange' ? T['isArray'] extends true ? AxDateRangeValue[] : AxDateRangeValue : T['type'] extends 'image' ? T['isArray'] extends true ? {
    mimeType: string;
    data: string;
}[] : {
    mimeType: string;
    data: string;
} : T['type'] extends 'audio' ? InferAudioValueType<T, TMode> : T['type'] extends 'file' ? T['isArray'] extends true ? ({
    mimeType: string;
    data: string;
} | {
    mimeType: string;
    fileUri: string;
})[] : {
    mimeType: string;
    data: string;
} | {
    mimeType: string;
    fileUri: string;
} : T['type'] extends 'url' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'code' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'class' ? InferClassValueType<T> : T['type'] extends 'object' ? T extends {
    fields: infer F;
} ? F extends Record<string, any> ? T['isArray'] extends true ? {
    [K in keyof F]: InferFluentType<F[K], TMode>;
}[] : {
    [K in keyof F]: InferFluentType<F[K], TMode>;
} : any : any : any;
type _IsInternal<T> = T extends {
    readonly isInternal: true;
} ? true : false;
type _IsOptional<T> = T extends {
    readonly isOptional: true;
} ? true : false;
type AddFieldToShape<S extends Record<string, any>, K extends string, T extends AxFluentFieldInfo<any, any, any, any> | AxFluentFieldType, TMode extends 'input' | 'output' = 'input'> = _IsInternal<T> extends true ? S : _IsOptional<T> extends true ? S & {
    readonly [P in K]?: InferFluentType<T, TMode>;
} : S & {
    readonly [P in K]: InferFluentType<T, TMode>;
};
type AddedFieldShape<K extends string, T, TMode extends 'input' | 'output'> = _IsOptional<T> extends true ? {
    [P in K]?: InferFieldValueType<T, TMode>;
} : {
    [P in K]: InferFieldValueType<T, TMode>;
};
type AxFunctionBuilderExample = {
    code: string;
    title?: string;
    description?: string;
    language?: string;
};
type AxTypedFunctionHandler<TArgs, TReturn> = (args: Readonly<TArgs>, extra?: Parameters<AxFunctionHandler>[1]) => TReturn | Promise<TReturn>;
type AxFunctionBuilderResult<TArgs extends Record<string, any>, TReturn, THasExamples extends boolean> = Omit<AxFunction, 'func' | 'parameters' | 'returns'> & {
    func: AxTypedFunctionHandler<TArgs, TReturn>;
    parameters: AxFunctionJSONSchema;
    returns?: AxFunctionJSONSchema;
} & (THasExamples extends true ? {
    examples: readonly AxFunctionBuilderExample[];
} : {});
declare class AxFunctionBuilder<TArgs extends Record<string, any> = {}, TReturn = unknown, THasExamples extends boolean = false> {
    private readonly name;
    private desc?;
    private ns?;
    private argFields;
    private returnFields;
    private returnFieldType?;
    private returnMode?;
    private returnJsonSchema?;
    private fnHandler?;
    private fnExamples;
    private executionMode;
    execution(mode: 'blocking' | 'background'): this;
    constructor(name: string);
    description(text: string): AxFunctionBuilder<TArgs, TReturn, THasExamples>;
    namespace(text: string): AxFunctionBuilder<TArgs, TReturn, THasExamples>;
    /**
     * Declare a tool argument. Three shapes:
     *
     * 1. **Fluent** — `.arg('name', f.string('desc'))`
     * 2. **Per-field Standard Schema** — `.arg('name', z.string(), { cache: true })`
     * 3. **Whole-object Standard Schema** — `.arg(z.object({ topic: z.string(), ... }))`
     *
     * Shapes 2 and 3 accept anything implementing Standard Schema v1
     * (zod / valibot / arktype).
     */
    arg<K extends string, T extends AxFluentFieldInfo<any, any, any, any, any, any, any> | AxFluentFieldType<any, any, any, any, any, any, any>>(name: K, fieldInfo: T): AxFunctionBuilder<AddFieldToShape<TArgs, K, T>, TReturn, THasExamples>;
    arg<K extends string, T extends StandardSchemaV1>(name: K, schema: T, opts?: AxFieldOptions): AxFunctionBuilder<TArgs & {
        [P in K]: StandardSchemaV1.InferOutput<T>;
    }, TReturn, THasExamples>;
    arg<T extends StandardSchemaV1>(schema: T, opts?: {
        fields?: Record<string, AxFieldOptions>;
    }): AxFunctionBuilder<AsRecord<StandardSchemaV1.InferOutput<T>>, TReturn, THasExamples>;
    /**
     * Declare the tool return shape. Two shapes:
     *
     * 1. **Fluent** — `.returns(f.string())` (single return value)
     * 2. **Standard Schema** — `.returns(z.object({...}))` decomposes into
     *    named return fields; any non-object zod schema is a single JSON-Schema
     *    return.
     *
     * Mutually exclusive with `.returnsField()`.
     */
    returns<T extends AxFluentFieldInfo<any, any, any, any, any, any, any> | AxFluentFieldType<any, any, any, any, any, any, any>>(fieldInfo: T): AxFunctionBuilder<TArgs, InferFluentType<T>, THasExamples>;
    returns<T extends StandardSchemaV1>(schema: T, opts?: {
        fields?: Record<string, AxFieldOptions>;
    }): AxFunctionBuilder<TArgs, StandardSchemaV1.InferOutput<T>, THasExamples>;
    /**
     * Declare a single named return field. Two shapes:
     *
     * 1. **Fluent** — `.returnsField('answer', f.string())`
     * 2. **Per-field Standard Schema** — `.returnsField('answer', z.string(), { internal: true })`
     *
     * Mutually exclusive with `.returns()`.
     */
    returnsField<K extends string, T extends AxFluentFieldInfo<any, any, any, any, any, any, any> | AxFluentFieldType<any, any, any, any, any, any, any>>(name: K, fieldInfo: T): AxFunctionBuilder<TArgs, AddFieldToShape<TReturn extends Record<string, any> ? TReturn : {}, K, T>, THasExamples>;
    returnsField<K extends string, T extends StandardSchemaV1>(name: K, schema: T, opts?: AxFieldOptions): AxFunctionBuilder<TArgs, (TReturn extends Record<string, any> ? TReturn : {}) & {
        [P in K]: StandardSchemaV1.InferOutput<T>;
    }, THasExamples>;
    example(example: AxFunctionBuilderExample): AxFunctionBuilder<TArgs, TReturn, true>;
    examples(examples: readonly AxFunctionBuilderExample[]): AxFunctionBuilder<TArgs, TReturn, true>;
    handler(handler: AxTypedFunctionHandler<TArgs, TReturn>): AxFunctionBuilder<TArgs, TReturn, THasExamples>;
    build(): AxFunctionBuilderResult<TArgs, TReturn, THasExamples>;
}
/**
 * Creates a fluent builder for defining callable functions/tools with typed
 * args, return schemas, namespaces, and optional AxAgent discovery examples.
 *
 * @example
 * ```typescript
 * const search = fn('search')
 *   .description('Search the product catalog')
 *   .namespace('db')
 *   .arg('query', f.string('Search query'))
 *   .arg('limit', f.number('Maximum results').optional())
 *   .returnsField('results', f.string('Result item').array())
 *   .handler(async ({ query, limit = 5 }) => ({ results: [`hit: ${query}:${limit}`] }))
 *   .build();
 * ```
 */
declare const fn: <TName extends string>(name: TName) => AxFunctionBuilder<{}, unknown, false>;
interface AxSignatureConfig {
    description?: string;
    inputs: readonly AxField[];
    outputs: readonly AxField[];
}
type AxSignatureInput = Readonly<AxSignature | string | AxSignatureConfig>;
declare class AxSignature<_TInput extends Record<string, any> = Record<string, any>, _TOutput extends Record<string, any> = Record<string, any>> {
    private description?;
    private inputFields;
    private outputFields;
    private sigHash;
    private sigString;
    private validatedAtHash?;
    private constructor();
    /**
     * Static factory method for type inference.
     * Creates a typed AxSignature instance from a signature string.
     */
    static create<const T extends string>(signature: T): AxSignature<ParseSignature<T>['inputs'], ParseSignature<T>['outputs']>;
    static from<TInput extends Record<string, any> = Record<string, any>, TOutput extends Record<string, any> = Record<string, any>>(signature?: AxSignatureInput): AxSignature<TInput, TOutput>;
    static empty(): AxSignature;
    private parseParsedField;
    private parseField;
    setDescription: (desc: string) => void;
    addInputField: (field: Readonly<AxField>) => void;
    addOutputField: (field: Readonly<AxField>) => void;
    setInputFields: (fields: readonly AxField[]) => void;
    setOutputFields: (fields: readonly AxField[]) => void;
    getInputFields: () => Readonly<AxIField[]>;
    getOutputFields: () => Readonly<AxIField[]>;
    getDescription: () => string | undefined;
    appendInputField: <K extends string, const T extends AxFieldType>(name: K, fieldType: T) => AxSignature<_TInput & AddedFieldShape<K, T, "input">, _TOutput>;
    prependInputField: <K extends string, const T extends AxFieldType>(name: K, fieldType: T) => AxSignature<AddedFieldShape<K, T, "input"> & _TInput, _TOutput>;
    appendOutputField: <K extends string, const T extends AxFieldType>(name: K, fieldType: T) => AxSignature<_TInput, _TOutput & AddedFieldShape<K, T, "output">>;
    prependOutputField: <K extends string, const T extends AxFieldType>(name: K, fieldType: T) => AxSignature<_TInput, AddedFieldShape<K, T, "output"> & _TOutput>;
    private invalidateValidationCache;
    private toTitle;
    private updateHashLight;
    private updateHash;
    private validateSignatureConsistency;
    private _forceComplexFields;
    private _hasComplexFields?;
    hasComplexFields: () => boolean;
    private computeHasComplexFields;
    validate: () => boolean;
    hash: () => string;
    toString: () => string;
    toJSON: () => {
        id: string;
        description: string | undefined;
        inputFields: AxIField[];
        outputFields: AxIField[];
    };
    toJSONSchema: () => AxFunctionJSONSchema;
    toInputJSONSchema: () => AxFunctionJSONSchema;
}

type AxEventTrust = 'trusted' | 'authenticated' | 'untrusted';
type AxEventScalar = string | number | boolean | null;
type AxEventValue = AxEventScalar | readonly AxEventValue[] | {
    readonly [key: string]: AxEventValue;
};
interface AxEventEnvelope<T = AxEventValue> {
    specversion: '1.0';
    id: string;
    source: string;
    type: string;
    subject?: string;
    time?: string;
    datacontenttype?: string;
    dataschema?: string;
    data?: T;
    extensions?: Readonly<Record<string, AxEventScalar>>;
}
interface AxEventIdentity {
    tenantId?: string;
    accountId?: string;
    userId?: string;
    sessionId?: string;
}
interface AxEventCorrelationKey {
    kind: string;
    value: string;
}
interface AxEventIngress<T = AxEventValue> {
    event: Readonly<AxEventEnvelope<T>>;
    identity?: Readonly<AxEventIdentity>;
    trust?: AxEventTrust;
    correlation?: readonly Readonly<AxEventCorrelationKey>[];
    partitionKey?: string;
}
interface AxEventPublishReceipt {
    eventId: string;
    accepted: boolean;
    duplicate: boolean;
    durability: 'volatile' | 'persistent';
    deliveryIds: readonly string[];
}
interface AxEventClock {
    now(): number;
    sleep(ms: number, signal?: AbortSignal): Promise<void>;
}
declare class AxSystemEventClock implements AxEventClock {
    now(): number;
    sleep(ms: number, signal?: AbortSignal): Promise<void>;
}
/** Deterministic clock for conformance tests, replay, and host schedulers. */
declare class AxManualEventClock implements AxEventClock {
    private value;
    private sleepers;
    constructor(value?: number);
    now(): number;
    sleep(ms: number, signal?: AbortSignal): Promise<void>;
    advanceBy(ms: number): void;
    set(time: number): void;
}
declare class AxEventBackpressureError extends Error {
    constructor(message?: string);
}
declare class AxEventContinuationNotFoundError extends Error {
    readonly correlation: Readonly<AxEventCorrelationKey>;
    constructor(correlation: Readonly<AxEventCorrelationKey>);
}
declare class AxEventOutcomeUnknownError extends Error {
    constructor(message: string, options?: ErrorOptions);
}
declare class AxEventInputError extends Error {
    readonly code = "event_input_invalid";
    constructor(message: string, options?: ErrorOptions);
}
type AxEventRouteAction = 'observe' | 'invalidate' | 'resume' | 'wake';
interface AxEventMatcher {
    sources?: readonly string[];
    types?: readonly string[];
    subjects?: readonly string[];
    extensions?: Readonly<Record<string, AxEventScalar>>;
}
interface AxEventContinuationRegistration {
    correlation: readonly Readonly<AxEventCorrelationKey>[];
    expiresAt?: number;
    metadata?: Readonly<Record<string, AxEventValue>>;
}
interface AxEventContinuation {
    id: string;
    targetId: string;
    routeId: string;
    instanceKey: string;
    identityScope: string;
    correlation: readonly Readonly<AxEventCorrelationKey>[];
    createdAt: number;
    expiresAt?: number;
    stateVersion?: number;
    metadata?: Readonly<Record<string, AxEventValue>>;
}
interface AxEventContext {
    readonly runtimeId: string;
    readonly runId: string;
    readonly deliveryId: string;
    readonly routeId: string;
    readonly targetId?: string;
    readonly instanceKey: string;
    readonly ingress: Readonly<AxEventIngress>;
    readonly identity: Readonly<AxEventIdentity>;
    readonly trust: AxEventTrust;
    readonly attempt: number;
    readonly idempotencyKey: string;
    readonly fencingToken?: number;
    readonly abortSignal: AbortSignal;
    readonly continuation?: Readonly<AxEventContinuation>;
    registerContinuation(registration: Readonly<AxEventContinuationRegistration>): string;
}
type AxEventInheritance = 'all' | 'none';
interface AxProgramStateEnvelope {
    schemaVersion: number;
    programVersion: string;
    revision: number;
    state: unknown;
    updatedAt: number;
}
interface AxProgramStateStore {
    load(key: string): Promise<Readonly<AxProgramStateEnvelope> | undefined>;
    compareAndSet(key: string, expectedRevision: number | undefined, state: Readonly<Omit<AxProgramStateEnvelope, 'revision'>>, fence?: Readonly<{
        deliveryId: string;
        fencingToken: number;
    }>): Promise<Readonly<AxProgramStateEnvelope>>;
    delete(key: string): Promise<void>;
}
interface AxEventProgramStateAdapter<P = AxProgrammable<any, any>> {
    schemaVersion: number;
    programVersion: string;
    restore(program: P, state: unknown): void | Promise<void>;
    capture(program: P): unknown | Promise<unknown>;
    migrateState?(args: Readonly<{
        state: unknown;
        fromSchemaVersion: number;
        fromProgramVersion: string;
        toSchemaVersion: number;
        toProgramVersion: string;
    }>): unknown | Promise<unknown>;
}
interface AxEventTargetInputContext {
    eventContext: Readonly<AxEventContext>;
    continuation?: Readonly<AxEventContinuation>;
}
type AxEventPathSegment = string | number;
type AxEventPathRoot = 'constant' | 'correlation' | 'data' | 'envelope' | 'extensions' | 'identity' | 'trust' | 'continuation';
/** Immutable, segment-safe selector over an event ingress and continuation. */
interface AxEventPath<T = unknown> {
    readonly root: AxEventPathRoot;
    readonly segments?: readonly AxEventPathSegment[];
    readonly correlationKind?: string;
    readonly value?: T;
}
interface AxEventInputFieldMapping {
    readonly field: string;
    readonly path: Readonly<AxEventPath>;
}
interface AxEventInputPlan<IN = any> {
    readonly project?: Readonly<AxEventPath>;
    readonly fields: readonly Readonly<AxEventInputFieldMapping>[];
    /** Phantom type used for contextual target input inference. */
    readonly __input?: IN;
}
interface AxEventInputBuilder<IN = any> {
    project(path: Readonly<AxEventPath>): AxEventInputBuilder<IN>;
    field<K extends Extract<keyof IN, string>>(field: K, path: Readonly<AxEventPath>): AxEventInputBuilder<IN>;
    build(): Readonly<AxEventInputPlan<IN>>;
}
type AxEventInputDefinition<IN = any> = Readonly<AxEventInputPlan<IN>> | Readonly<AxEventInputBuilder<IN>> | ((builder: AxEventInputBuilder<IN>) => Readonly<AxEventInputPlan<IN>> | Readonly<AxEventInputBuilder<IN>>);
interface AxEventContinuationPlan {
    readonly kind: string;
    readonly value: Readonly<AxEventPath>;
    readonly expiresInMs?: number;
    readonly metadata?: Readonly<Record<string, Readonly<AxEventPath>>>;
}
interface AxEventTarget<IN = any, OUT = any> {
    id: string;
    ai: Readonly<AxAIService>;
    program?: AxProgrammable<IN, OUT>;
    createProgram?: (instance: Readonly<{
        targetId: string;
        instanceKey: string;
        identity: Readonly<AxEventIdentity>;
    }>) => AxProgrammable<IN, OUT> | Promise<AxProgrammable<IN, OUT>>;
    /** Required when createProgram is combined with declarative input plans. */
    inputSignature?: Readonly<AxSignature>;
    input?: Readonly<AxEventInputPlan<IN>>;
    wakeInput?: Readonly<AxEventInputPlan<IN>>;
    resumeInput?: Readonly<AxEventInputPlan<IN>>;
    waitFor?: readonly Readonly<AxEventContinuationPlan>[];
    mapInput?: (ingress: Readonly<AxEventIngress>, context: Readonly<AxEventTargetInputContext>) => IN | Promise<IN>;
    forwardOptions?: Readonly<AxProgramForwardOptions<string>>;
    execution?: 'forward' | 'streaming';
    state?: AxEventProgramStateAdapter<AxProgrammable<IN, OUT>>;
    sinks?: readonly AxEventSink<OUT>[];
    retrySafety?: 'idempotent' | 'unknown';
}
interface AxEventSinkContext<OUT = unknown> {
    run: Readonly<AxEventRun<OUT>>;
    eventContext: Readonly<AxEventContext>;
    idempotencyKey: string;
    signal: AbortSignal;
}
interface AxEventSink<OUT = unknown> {
    id: string;
    write(output: OUT, context: Readonly<AxEventSinkContext<OUT>>): void | Promise<void>;
    writeChunk?(chunk: Readonly<AxGenDeltaOut<OUT>>, context: Readonly<AxEventSinkContext<OUT>>): void | Promise<void>;
}
interface AxEventInvalidator {
    invalidate(ingress: Readonly<AxEventIngress>, context: Readonly<AxEventContext>): void | Promise<void>;
}
interface AxEventRoute {
    id: string;
    match: Readonly<AxEventMatcher> | ((ingress: Readonly<AxEventIngress>) => boolean | Promise<boolean>);
    action: AxEventRouteAction;
    target?: AxEventTarget<any, any>;
    instanceKey?: (ingress: Readonly<AxEventIngress>) => string | Promise<string>;
    requireAuthenticated?: boolean;
    authorize?: (ingress: Readonly<AxEventIngress>) => boolean | Promise<boolean>;
    observe?: (ingress: Readonly<AxEventIngress>, context: Readonly<AxEventContext>) => void | Promise<void>;
    invalidator?: AxEventInvalidator;
    correlation?: (ingress: Readonly<AxEventIngress>) => Readonly<AxEventCorrelationKey> | undefined;
    /** Hold matching deliveries for this long before they become claimable. */
    debounceMs?: number;
    /** Explicitly replace an older queued delivery in the debounce window. */
    coalesce?: 'latest';
    /** Allow this route to run out of order for the same target/instance. */
    ordering?: 'strict' | 'relaxed';
}
type AxEventDeliveryStatus = 'queued' | 'claimed' | 'running' | 'waiting_event' | 'succeeded' | 'failed' | 'cancelled' | 'dead_lettered' | 'output_persistence_failed' | 'outcome_unknown';
interface AxEventDelivery {
    id: string;
    sequence: number;
    ingress: Readonly<AxEventIngress>;
    identityScope: string;
    routeId: string;
    action: AxEventRouteAction;
    targetId?: string;
    instanceKey: string;
    status: AxEventDeliveryStatus;
    attempt: number;
    availableAt: number;
    acceptedAt: number;
    claimedBy?: string;
    runId?: string;
    error?: string;
    sizeBytes: number;
    retrySafety: 'idempotent' | 'unknown';
    ordering: 'strict' | 'relaxed';
    leaseExpiresAt?: number;
    fencingToken?: number;
    invocationStarted?: boolean;
    recoveredFromExpiredLease?: boolean;
}
type AxEventRunStatus = 'queued' | 'running' | 'waiting_event' | 'succeeded' | 'failed' | 'cancelled' | 'output_persistence_failed' | 'outcome_unknown';
interface AxEventSinkAttempt {
    sinkId: string;
    attempts: number;
    status: 'pending' | 'succeeded' | 'failed';
    error?: string;
}
interface AxEventRun<OUT = unknown> {
    id: string;
    deliveryId: string;
    routeId: string;
    targetId?: string;
    instanceKey: string;
    status: AxEventRunStatus;
    attempt: number;
    startedAt: number;
    finishedAt?: number;
    output?: OUT;
    chunks?: readonly AxGenDeltaOut<OUT>[];
    error?: string;
    continuationIds?: readonly string[];
    sinks?: readonly AxEventSinkAttempt[];
    fencingToken?: number;
    outputRef?: string;
}
interface AxEventDeadLetter {
    id: string;
    kind: 'delivery' | 'sink';
    deliveryId: string;
    runId?: string;
    sinkId?: string;
    reason: string;
    createdAt: number;
}
interface AxEventStoreCapabilities {
    durability: 'volatile' | 'persistent';
    coordination: 'single-worker' | 'multi-worker';
    leases: boolean;
    transactions: boolean;
    compareAndSet: boolean;
    outputPersistence: boolean;
    conformance?: Readonly<{
        multiWorker?: string;
        schemaVersion?: number;
    }>;
}
interface AxEventEnqueueRequest {
    ingress: Readonly<AxEventIngress>;
    deliveries: readonly Readonly<Pick<AxEventDelivery, 'routeId' | 'action' | 'targetId' | 'instanceKey' | 'sizeBytes'> & {
        availableAt?: number;
        coalesce?: 'latest';
        retrySafety?: 'idempotent' | 'unknown';
        ordering?: 'strict' | 'relaxed';
    }>[];
    acceptedAt: number;
    publishTimeoutMs: number;
}
interface AxEventStore {
    readonly capabilities: Readonly<AxEventStoreCapabilities>;
    enqueue(request: Readonly<AxEventEnqueueRequest>, signal?: AbortSignal): Promise<AxEventPublishReceipt>;
    claim(workerId: string, now: number, leaseMs?: number): Promise<AxEventDelivery | undefined>;
    renewClaim(deliveryId: string, workerId: string, fencingToken: number, leaseExpiresAt: number): Promise<void>;
    getDelivery(deliveryId: string): Promise<Readonly<AxEventDelivery> | undefined>;
    saveDelivery(delivery: Readonly<AxEventDelivery>): Promise<void>;
    saveRun(run: Readonly<AxEventRun>): Promise<void>;
    getRun(runId: string): Promise<Readonly<AxEventRun> | undefined>;
    registerContinuation(continuation: Readonly<AxEventContinuation>): Promise<void>;
    findContinuation(identityScope: string, correlation: Readonly<AxEventCorrelationKey>, now: number): Promise<Readonly<AxEventContinuation> | undefined>;
    completeContinuation(id: string): Promise<void>;
    addDeadLetter(deadLetter: Readonly<AxEventDeadLetter>): Promise<void>;
    getDeadLetter(id: string): Promise<Readonly<AxEventDeadLetter> | undefined>;
    removeDeadLetter(id: string): Promise<void>;
    listDeadLetters(): Promise<readonly Readonly<AxEventDeadLetter>[]>;
    redriveDelivery(deliveryId: string, now: number): Promise<void>;
    nextAvailableAt(now: number): Promise<number | undefined>;
    waitForWork(signal?: AbortSignal): Promise<void>;
    isIdle(): Promise<boolean>;
    close?(): void | Promise<void>;
}
interface AxEventSourceHandle {
    close(): void | Promise<void>;
}
interface AxEventSourceContext {
    signal: AbortSignal;
    publish(ingress: Readonly<AxEventIngress>, signal?: AbortSignal): Promise<AxEventPublishReceipt>;
    reportError(error: unknown): void;
}
interface AxEventSource {
    id: string;
    requiresDurable?: boolean;
    start(context: Readonly<AxEventSourceContext>): undefined | AxEventSourceHandle | Promise<AxEventSourceHandle | undefined>;
}
interface AxEventRuntimeOptions {
    id?: string;
    routes: readonly AxEventRoute[];
    sources?: readonly AxEventSource[];
    store?: AxEventStore;
    programStateStore?: AxProgramStateStore;
    clock?: AxEventClock;
    workerId?: string;
    workerConcurrency?: number;
    maxAttempts?: number;
    retryBaseMs?: number;
    retryMaxMs?: number;
    publishTimeoutMs?: number;
    allowVolatile?: boolean;
    onSourceError?: (sourceId: string, error: unknown) => void | Promise<void>;
    coordination?: 'single-worker' | 'multi-worker';
    leaseMs?: number;
    heartbeatMs?: number;
}
interface AxEventPayloadStore {
    put(key: string, value: unknown): Promise<string>;
    get(reference: string): Promise<unknown>;
    delete(reference: string): Promise<void>;
}
interface AxEventCloseOptions {
    drain?: boolean;
    timeoutMs?: number;
}

type AxRunUpdate = {
    id: number;
    target: string;
} & ({
    type: 'steer';
    text: string;
} | {
    type: 'thinking';
    level: NonNullable<AxAIServiceOptions['thinkingTokenBudget']>;
});
type AxRunControlEvent = {
    type: 'queued' | 'applied' | 'started' | 'completed' | 'failed' | 'aborted' | 'model.output' | 'tool.started' | 'tool.completed';
    path: string;
    updateId?: number;
    callId?: string;
    pendingCallIds?: readonly string[];
    timing?: 'native' | 'next-response';
    error?: unknown;
};
/** A controller can be shared by a root run and its descendants. */
declare class AxRunControl {
    private readonly controller;
    private readonly updates;
    private readonly listeners;
    private readonly wakeListeners;
    private nextId;
    get signal(): AbortSignal;
    steer(text: string, options?: {
        target?: string;
    }): void;
    setThinkingTokenBudget(level: NonNullable<AxAIServiceOptions['thinkingTokenBudget']>, options?: {
        target?: string;
    }): void;
    abort(): void;
    onEvent(listener: (event: AxRunControlEvent) => void): () => void;
    /** @internal */
    pending(path: string, after: number): readonly AxRunUpdate[];
    /** @internal */
    subscribe(listener: () => void): () => void;
    /** @internal */
    emit(event: AxRunControlEvent): void;
    private enqueue;
}
declare const runControl: () => AxRunControl;

interface RetryConfig {
    maxRetries: number;
    initialDelayMs: number;
    maxDelayMs: number;
    backoffFactor: number;
    retryableStatusCodes: number[];
}
interface AxAPIResponseMetadata {
    requestId: string;
    status: number;
    statusText: string;
    headers: Headers;
    url: string;
    retryCount: number;
}
interface RequestValidation {
    validateRequest?: (request: unknown) => boolean | Promise<boolean>;
}
interface ResponseValidation {
    validateResponse?: (response: unknown) => boolean | Promise<boolean>;
}
interface AxAPI {
    name?: string;
    url?: string | URL;
    headers?: Record<string, string>;
    /** HTTP method for JSON API requests. Defaults to POST. */
    method?: 'GET' | 'POST' | 'PUT' | 'PATCH';
    /** @deprecated Use `method: 'PUT'` instead. */
    put?: boolean;
    localCall?: <TRequest, TResponse>(data: TRequest, stream?: boolean) => Promise<TResponse | ReadableStream<TResponse>>;
}
interface AxAPIConfig extends AxAPI, RequestValidation, ResponseValidation {
    url?: string | URL;
    stream?: boolean;
    debug?: boolean;
    verbose?: boolean;
    fetch?: typeof fetch;
    span?: Span;
    timeout?: number;
    retry?: Partial<RetryConfig>;
    abortSignal?: AbortSignal;
    corsProxy?: string;
    onResponseMetadata?: (metadata: Readonly<AxAPIResponseMetadata>) => void;
    /** Resolve headers for each HTTP attempt, including retries. */
    resolveHeaders?: (request: {
        method: string;
        url: string;
        retryCount: number;
    }) => Promise<Record<string, string>>;
    /** Whether to include request body in error messages. Defaults to true. Set to false when request may contain sensitive data or large base64 content. */
    includeRequestBodyInErrors?: boolean;
}
declare class AxAIServiceError extends Error {
    readonly url: string;
    readonly requestBody: unknown;
    readonly responseBody: unknown;
    readonly timestamp: string;
    readonly errorId: string;
    readonly context: Record<string, unknown>;
    readonly includeRequestBodyInErrors: boolean;
    constructor(message: string, url: string, requestBody: unknown, responseBody: unknown, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
    toString(): string;
}
declare class AxAIServiceStatusError extends AxAIServiceError {
    readonly status: number;
    readonly statusText: string;
    constructor(status: number, statusText: string, url: string, requestBody: unknown, responseBody: unknown, context?: Record<string, unknown>, retryCount?: number, includeRequestBodyInErrors?: boolean);
}
declare class AxAIServiceNetworkError extends AxAIServiceError {
    readonly originalError: Error;
    constructor(originalError: Error, url: string, requestBody: unknown, responseBody: unknown, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
}
declare class AxAIServiceResponseError extends AxAIServiceError {
    constructor(message: string, url: string, requestBody?: unknown, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
}
declare class AxAIServiceStreamTerminatedError extends AxAIServiceError {
    readonly lastChunk?: unknown | undefined;
    constructor(url: string, requestBody?: unknown, lastChunk?: unknown | undefined, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
}
declare class AxAIServiceTimeoutError extends AxAIServiceError {
    constructor(url: string, timeoutMs: number, requestBody?: unknown, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
}
declare class AxTokenLimitError extends AxAIServiceStatusError {
    constructor(status: number, statusText: string, url: string, requestBody: unknown, responseBody: unknown, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
}
declare class AxAIServiceAbortedError extends AxAIServiceError {
    constructor(url: string, reason?: string, requestBody?: unknown, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
}
declare class AxAIServiceAuthenticationError extends AxAIServiceError {
    constructor(url: string, requestBody: unknown, responseBody: unknown, context?: Record<string, unknown>, includeRequestBodyInErrors?: boolean);
}
declare class AxAIRefusalError extends Error {
    readonly refusalMessage: string;
    readonly model?: string | undefined;
    readonly requestId?: string | undefined;
    readonly category?: string | null | undefined;
    readonly explanation?: string | null | undefined;
    readonly timestamp: string;
    readonly errorId: string;
    constructor(refusalMessage: string, model?: string | undefined, requestId?: string | undefined, category?: string | null | undefined, explanation?: string | null | undefined);
    toString(): string;
}
/**
 * Error thrown when an AI provider doesn't support a required media type.
 *
 * This error is thrown during content processing when a provider cannot handle
 * a specific media type and no suitable fallback mechanism is available or configured.
 *
 * @example
 * ```typescript
 * try {
 *   await textOnlyProvider.chat(imageRequest);
 * } catch (error) {
 *   if (error instanceof AxMediaNotSupportedError) {
 *     console.log(`${error.mediaType} not supported by ${error.provider}`);
 *     if (error.fallbackAvailable) {
 *       console.log('Consider using content processing services');
 *     }
 *   }
 * }
 * ```
 */
declare class AxMediaNotSupportedError extends Error {
    readonly mediaType: string;
    readonly provider: string;
    readonly fallbackAvailable: boolean;
    /** ISO timestamp when the error occurred */
    readonly timestamp: string;
    /** Unique identifier for this error instance */
    readonly errorId: string;
    /**
     * Creates a new media not supported error.
     *
     * @param mediaType - The type of media that is not supported (e.g., 'Images', 'Audio')
     * @param provider - The name of the AI provider that doesn't support the media type
     * @param fallbackAvailable - Whether fallback processing options are available
     */
    constructor(mediaType: string, provider: string, fallbackAvailable?: boolean);
    toString(): string;
}
/**
 * Error thrown when content processing/transformation fails.
 *
 * This error wraps underlying failures from content processing services like
 * image-to-text, audio transcription, file text extraction, or URL content fetching.
 * It provides context about what type of content was being processed and at which step.
 *
 * @example
 * ```typescript
 * try {
 *   await axProcessContentForProvider(content, provider, {
 *     imageToText: imageService.analyze
 *   });
 * } catch (error) {
 *   if (error instanceof AxContentProcessingError) {
 *     console.log(`Failed processing ${error.contentType} during ${error.processingStep}`);
 *     console.log('Original error:', error.originalError.message);
 *   }
 * }
 * ```
 */
declare class AxContentProcessingError extends Error {
    readonly originalError: Error;
    readonly contentType: string;
    readonly processingStep: string;
    /** ISO timestamp when the error occurred */
    readonly timestamp: string;
    /** Unique identifier for this error instance */
    readonly errorId: string;
    /**
     * Creates a new content processing error.
     *
     * @param originalError - The underlying error that caused the processing failure
     * @param contentType - The type of content being processed (e.g., 'image', 'audio', 'file')
     * @param processingStep - The specific processing step that failed (e.g., 'vision analysis', 'transcription')
     */
    constructor(originalError: Error, contentType: string, processingStep: string);
    toString(): string;
}

type AxAudioFormat = 'wav' | 'mp3' | 'flac' | 'opus' | 'aac' | 'pcm16' | 'pcm' | 'raw' | 'mulaw' | 'ulaw' | 'alaw' | 'ogg';
type AxChatAudioConfig = {
    input?: {
        format?: AxAudioFormat;
        mimeType?: string;
        sampleRate?: number;
        channels?: number;
    };
    output?: {
        enabled?: boolean;
        voice?: string | {
            id: string;
        };
        format?: AxAudioFormat;
        mimeType?: string;
        sampleRate?: number;
        channels?: number;
        includeTranscript?: boolean;
    };
    live?: {
        turnTimeoutMs?: number;
        enableAffectiveDialog?: boolean;
        proactiveAudio?: boolean;
    };
};
type AxChatAudioOutput = {
    data: string;
    id?: string;
    mimeType?: string;
    format?: AxAudioFormat;
    transcript?: string;
    expiresAt?: number;
    sampleRate?: number;
    channels?: number;
    isDelta?: boolean;
};
type AxAudioInput = {
    data: string;
    format?: AxAudioFormat;
    mimeType?: string;
    filename?: string;
    sampleRate?: number;
    channels?: number;
};
type AxTranscriptionRequest<TModel = string> = {
    audio: AxAudioInput;
    model?: TModel;
    language?: string;
    prompt?: string;
    temperature?: number;
    responseFormat?: 'json' | 'verbose_json' | 'text';
    /** Portable speech-turn behavior for providers that support it. */
    mode?: 'push_to_talk' | 'endpointing' | 'diarization';
    /** Expected spoken languages used to bias recognition without forcing one language. */
    languageBias?: string[];
    /** Domain words and names used to bias recognition. */
    keywords?: string[];
    /** Shape of partial transcript events when a provider offers streaming transcription. */
    partialMode?: 'cumulative' | 'delta';
    /** Ask the provider to emit audio processing progress when supported. */
    emitAudioProgress?: boolean;
    /** Optional caller correlation identifier. */
    sessionId?: string;
};
type AxTranscriptionSegment = {
    id?: number | string;
    text: string;
    start?: number;
    end?: number;
    speaker?: string | number;
};
type AxTranscriptionResponse = {
    text: string;
    language?: string;
    duration?: number;
    segments?: AxTranscriptionSegment[];
    words?: AxTranscriptionSegment[];
    sessionId?: string;
    /** Latest provider-reported amount of audio processed. */
    audioProcessedMs?: number;
};
type AxSpeechRequest<TModel = string> = {
    text: string;
    model?: TModel;
    voice?: string | {
        id: string;
    };
    format?: AxAudioFormat;
    mimeType?: string;
    sampleRate?: number;
    speed?: number;
    language?: string;
};
type AxSpeechResponse = AxChatAudioOutput;
type AxSpeechConfig = {
    transcribe?: Omit<AxTranscriptionRequest, 'audio'>;
    speak?: Omit<AxSpeechRequest, 'text'>;
    fields?: Record<string, Omit<AxSpeechRequest, 'text'>>;
};

interface AxAIFeatures {
    asyncTools?: boolean;
    nativeSteering?: boolean;
    reasoningUpdates?: boolean;
    functions: boolean;
    /** Whether Ax may emulate functions in prompts when native tools are absent. */
    functionEmulation?: boolean;
    streaming: boolean;
    functionCot?: boolean;
    hasThinkingBudget?: boolean;
    hasShowThoughts?: boolean;
    /** Whether the provider supports complex structured outputs (JSON schema) */
    structuredOutputs?: boolean;
    /** Ordered, verified structured-output strategies for the selected model. */
    structuredOutputModes?: readonly AxStructuredOutputRung[];
    /**
     * Whether a JSON response format (the `native` and `json_object` rungs) works
     * in a request that also declares native functions. When `false`, the `auto`
     * structured-output mode uses the `function` rung while the model may call
     * user functions. Omitted means yes.
     */
    responseFormatWithFunctions?: boolean;
    /** Requires an output schema even for scalar-only signatures (typed inference). */
    requiresStructuredOutput?: boolean;
    /** Enhanced media capability specifications */
    media: {
        /** Image processing capabilities */
        images: {
            /** Whether the provider supports image inputs */
            supported: boolean;
            /** Supported image MIME types (e.g., ['image/jpeg', 'image/png']) */
            formats: string[];
            /** Maximum image size in bytes */
            maxSize?: number;
            /** Supported detail/quality levels for image processing */
            detailLevels?: ('high' | 'low' | 'auto')[];
        };
        /** Audio processing capabilities */
        audio: {
            /** Whether the provider supports audio inputs */
            supported: boolean;
            /** Supported audio formats (e.g., ['wav', 'mp3']) */
            formats: string[];
            /** Maximum audio duration in seconds */
            maxDuration?: number;
            /** Audio output capabilities for conversational audio models */
            output?: {
                /** Whether the provider supports generated audio responses */
                supported: boolean;
                /** Supported generated audio formats */
                formats: string[];
                /** Default output sample rate, when fixed by the provider */
                sampleRate?: number;
                /** Known built-in voice names, when enumerable */
                voices?: string[];
            };
        };
        /** File processing capabilities */
        files: {
            /** Whether the provider supports file inputs */
            supported: boolean;
            /** Supported file MIME types (e.g., ['application/pdf', 'text/plain']) */
            formats: string[];
            /** Maximum file size in bytes */
            maxSize?: number;
            /** How files are uploaded to the provider */
            uploadMethod: 'inline' | 'upload' | 'cloud' | 'none';
        };
        /** URL and web content capabilities */
        urls: {
            /** Whether the provider supports URL inputs */
            supported: boolean;
            /** Whether the provider can perform web searches */
            webSearch: boolean;
            /** Whether the provider can fetch web page content */
            contextFetching: boolean;
        };
    };
    /** Content caching capabilities */
    caching: {
        /** Whether the provider supports content caching */
        supported: boolean;
        /** Types of caching available */
        types: ('ephemeral' | 'persistent')[];
        /** Whether explicit cache breakpoints are needed. If false, provider has automatic lookback and cache_control is always applied to system and last tool when caching is detected. Defaults to true. */
        cacheBreakpoints?: boolean;
    };
    /** Whether the provider supports thinking/reasoning modes */
    thinking: boolean;
    /** Whether the provider supports multi-turn conversations */
    multiTurn: boolean;
    /** Portable request-level service tiers verified for the selected model. */
    serviceTiers?: readonly AxServiceTier[];
}
interface AxBaseAIArgs<TModel, TEmbedModel, TModelKey> {
    name: string;
    apiURL?: string;
    headers: () => Promise<Record<string, string>>;
    profile?: string;
    credentialProvider?: AxAICredentialProvider;
    modelInfo: Readonly<AxModelInfo[]>;
    defaults: Readonly<{
        model: TModel;
        embedModel?: TEmbedModel;
    }>;
    options?: Readonly<AxAIServiceOptions>;
    supportFor: AxAIFeatures | ((model: TModel) => AxAIFeatures);
    models?: AxAIInputModelList<TModel, TEmbedModel, TModelKey>;
}
declare const axBaseAIDefaultConfig: () => AxModelConfig;
declare const axBaseAIDefaultCreativeConfig: () => AxModelConfig;
declare class AxBaseAI<TModel, TEmbedModel, TChatRequest, TEmbedRequest, TChatResponse, TChatResponseDelta, TEmbedResponse, TModelKey> implements AxAIService<TModel, TEmbedModel, TModelKey> {
    #private;
    private readonly aiImpl;
    private rt?;
    private fetch?;
    private tracer?;
    private meter?;
    private timeout?;
    private excludeContentFromTrace?;
    private models?;
    private abortSignal?;
    private logger?;
    private corsProxy?;
    private retry?;
    private customLabels?;
    private usageContext?;
    private contextCache?;
    private serviceTier?;
    private beta?;
    private includeRequestBodyInErrors?;
    private modelInfo;
    private modelUsage?;
    private embedModelUsage?;
    private defaults;
    private lastUsedModelConfig?;
    private lastUsedChatModel?;
    private lastUsedEmbedModel?;
    protected apiURL?: string;
    protected name: string;
    protected id: string;
    protected headers: () => Promise<Record<string, string>>;
    private readonly credentialProvider?;
    private readonly credentialProfile;
    private chatCredentialOperation;
    protected supportFor: AxAIFeatures | ((model: TModel) => AxAIFeatures);
    private metrics;
    constructor(aiImpl: Readonly<AxAIServiceImpl<TModel, TEmbedModel, TChatRequest, TEmbedRequest, TChatResponse, TChatResponseDelta, TEmbedResponse>>, { name, apiURL, headers, profile, credentialProvider, modelInfo, defaults, options, supportFor, models, }: Readonly<AxBaseAIArgs<TModel, TEmbedModel, TModelKey>>);
    private getEffectiveDebug;
    private getEffectiveTracer;
    private getEffectiveMeter;
    private getEffectiveRateLimiter;
    private getEffectiveLogger;
    private getEffectiveAbortSignal;
    private getMetricsInstruments;
    setName(name: string): void;
    getId(): string;
    setAPIURL(apiURL: string): void;
    setHeaders(headers: () => Promise<Record<string, string>>): void;
    get debug(): boolean;
    private sessionOptions;
    setOptions(options: Readonly<AxAIServiceOptions>): void;
    getOptions(): Readonly<AxAIServiceOptions>;
    getLogger(): AxLoggerFunction;
    private getMergedCustomLabels;
    private getMergedUsageContext;
    getModelList(): ({
        readonly key: TModelKey;
        readonly description: string;
        readonly model: string;
        readonly embedModel?: undefined;
    } | {
        readonly key: TModelKey;
        readonly description: string;
        readonly embedModel: string;
        readonly model?: undefined;
    })[];
    getName(): string;
    getFeatures(model?: TModel): AxAIFeatures;
    getLastUsedChatModel(): TModel | undefined;
    getLastUsedEmbedModel(): TEmbedModel | undefined;
    getLastUsedModelConfig(): AxModelConfig | undefined;
    transcribe(req: Readonly<AxTranscriptionRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
    private calculatePercentile;
    private updateLatencyMetrics;
    private updateErrorMetrics;
    private recordEstimatedCost;
    private recordTokenUsage;
    private calculateRequestSize;
    private calculateResponseSize;
    private detectMultimodalContent;
    private calculateContextWindowUsage;
    private estimateCostByName;
    private recordFunctionCallMetrics;
    private recordTimeoutMetric;
    private recordAbortMetric;
    private recordChatMetrics;
    private recordEmbedMetrics;
    getMetrics(): AxAIServiceMetrics;
    getEstimatedCost(modelUsage?: AxModelUsage): number;
    chat(req: Readonly<AxChatRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatResponse | ReadableStream<AxChatResponse>>;
    private resolveChatModelConfig;
    validateChatRequest(req: Readonly<AxChatRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): void;
    private _chat1;
    private cleanupFunctionSchema;
    /**
     * Peeks the first raw streaming delta and, if the provider classifies it as a retryable
     * transient error (e.g. an Anthropic `overloaded_error` SSE event), re-issues the request
     * with exponential backoff — the same policy {@link apiCall} applies to an HTTP 529 status,
     * so streaming and non-streaming overloads behave identically. The first delta is classified
     * on the raw chunk (no stateful transform runs), so peeking has no side effects. After the
     * retry budget is exhausted the original error delta is replayed so it surfaces normally
     * (and the balancer can still fail over). A non-error first delta is replayed unchanged.
     *
     * Note: re-issuing cancels the previous stream's reader best-effort; the underlying fetch
     * body of the abandoned overloaded request is released by GC rather than promptly aborted,
     * since apiCall's streams don't propagate cancel. Acceptable for the transient-overload case.
     */
    private retryTransientStreamStart;
    private _chat2;
    embed(req: Readonly<AxEmbedRequest<TEmbedModel>>, options?: Readonly<AxAIServiceOptions>): Promise<AxEmbedResponse>;
    private _embed1;
    private _embed2;
    protected buildHeaders(headers?: Record<string, string>, request?: Omit<AxAICredentialRequest, 'profile'>): Promise<Record<string, string>>;
    protected setChatCredentialOperation(operation: 'chat' | 'responses'): void;
    private getModelByKey;
    private getModel;
    private getEmbedModel;
    /**
     * Handle context caching for providers that support it.
     * This method manages cache lookup, creation, TTL refresh, and cache operations.
     *
     * Behavior: If contextCache is present, caching is enabled.
     * - If `name` is provided, use that cache directly
     * - Otherwise, auto-create/reuse cache based on content hash
     */
    private handleContextCaching;
    /**
     * Use an existing cache by name to prepare the chat request.
     */
    private useCacheByName;
    private invalidateManagedContextCache;
    private getContextCacheToolState;
    /**
     * Execute a context cache operation (create/update/delete).
     */
    private executeCacheOperation;
    /**
     * Estimate the number of tokens in cacheable content.
     * Uses a simple heuristic of ~4 characters per token.
     * Includes: system prompts (always) + messages/parts marked with cache: true.
     */
    private estimateCacheableTokens;
}

/** Portable request-level inference service tiers. */
type AxServiceTier = 'auto' | 'standard' | 'flex' | 'priority';
/** Normalized service tier that actually handled a request. */
type AxAppliedServiceTier = Exclude<AxServiceTier, 'auto'> | 'batch';
/** Per-token pricing overrides for a non-standard service tier. */
type AxServiceTierPricing = {
    promptTokenCostPer1M?: number;
    completionTokenCostPer1M?: number;
    cacheReadTokenCostPer1M?: number;
    cacheWriteTokenCostPer1M?: number;
    longContextPromptTokenCostPer1M?: number;
    longContextCompletionTokenCostPer1M?: number;
    longContextCacheReadTokenCostPer1M?: number;
    longContextCacheWriteTokenCostPer1M?: number;
};
type AxAIInputModelList<TModel, TEmbedModel, TModelKey> = (AxAIModelListBase<TModelKey> & {
    isInternal?: boolean;
    /** Optional per-model config applied when this key is used (callers still override) */
    modelConfig?: Omit<AxModelConfig, 'model' | 'embedModel'>;
    /** Optional per-model options applied when this key is used (callers still override) */
    thinkingTokenBudget?: AxAIServiceOptions['thinkingTokenBudget'];
    showThoughts?: AxAIServiceOptions['showThoughts'];
    serviceTier?: AxAIServiceOptions['serviceTier'];
    stream?: AxAIServiceOptions['stream'];
    debug?: AxAIServiceOptions['debug'];
    useExpensiveModel?: AxAIServiceOptions['useExpensiveModel'];
    beta?: AxAIServiceOptions['beta'];
} & ({
    model: TModel;
} | {
    embedModel: TEmbedModel;
}))[];
type AxAIModelListBase<TModelKey> = {
    key: TModelKey;
    description: string;
};
type AxAIModelList<TModelKey> = (AxAIModelListBase<TModelKey> & ({
    model: string;
} | {
    embedModel: string;
}))[];
type AxModelInfo = {
    name: string;
    currency?: string;
    characterIsToken?: boolean;
    promptTokenCostPer1M?: number;
    completionTokenCostPer1M?: number;
    cacheReadTokenCostPer1M?: number;
    cacheWriteTokenCostPer1M?: number;
    /** Prompt token cost for requests exceeding longContextThreshold */
    longContextPromptTokenCostPer1M?: number;
    /** Completion token cost for requests exceeding longContextThreshold */
    longContextCompletionTokenCostPer1M?: number;
    /** Cache read token cost for requests exceeding longContextThreshold */
    longContextCacheReadTokenCostPer1M?: number;
    /** Total input token count (including cached) above which long-context rates apply */
    longContextThreshold?: number;
    /** Prompt token cost when a provider speed tier such as Anthropic fast mode is active. */
    fastPromptTokenCostPer1M?: number;
    /** Completion token cost when a provider speed tier such as Anthropic fast mode is active. */
    fastCompletionTokenCostPer1M?: number;
    /** Cache read token cost when a provider speed tier such as Anthropic fast mode is active. */
    fastCacheReadTokenCostPer1M?: number;
    /** Cache write token cost when a provider speed tier such as Anthropic fast mode is active. */
    fastCacheWriteTokenCostPer1M?: number;
    /** Token pricing overrides selected from the tier that actually served a request. */
    serviceTierPricing?: Partial<Record<'flex' | 'priority', AxServiceTierPricing>>;
    longContextCacheWriteTokenCostPer1M?: number;
    aliases?: string[];
    supported?: {
        thinkingBudget?: boolean;
        showThoughts?: boolean;
        structuredOutputs?: boolean;
        /** Ordered, verified structured-output strategies for this exact model. */
        structuredOutputModes?: readonly AxStructuredOutputRung[];
        /** Portable request tiers verified for this exact model. */
        serviceTiers?: readonly AxServiceTier[];
        /** Whether this model can return generated images from `chat()`. */
        imageOutput?: boolean;
        /** Public Ax operations verified for this exact model. */
        operations?: readonly ('chat' | 'transcribe')[];
    };
    notSupported?: {
        temperature?: boolean;
        topP?: boolean;
    };
    audio?: {
        input?: boolean;
        output?: boolean;
    };
    /** Exact provider-declared model input and output modalities. */
    modalities?: {
        input: readonly ('text' | 'image' | 'audio' | 'video' | 'pdf')[];
        output: readonly ('text' | 'image')[];
    };
    maxTokens?: number;
    isExpensive?: boolean;
    contextWindow?: number;
    isDeprecated?: boolean;
    /** ISO date (YYYY-MM-DD) the upstream provider will stop serving this model. */
    deprecatedOn?: string;
    /** Provider data-use policy that materially differs between model variants. */
    dataUse?: {
        providerTraining: 'not-used' | 'allowed';
        appliesTo?: readonly ('prompt' | 'completion')[];
    };
};
/** A concrete strategy Ax can use to obtain a typed structured result. */
type AxStructuredOutputRung = 'native' | 'function' | 'json_object';
/** Structured-output selection policy. `auto` follows provider/model preference order. */
type AxStructuredOutputMode = 'auto' | AxStructuredOutputRung;
type AxAICredentialRequest = Readonly<{
    profile: string;
    operation: 'chat' | 'models' | 'stream_chat' | 'embed' | 'responses' | 'transcribe' | 'speak' | 'realtime';
    method: string;
    url: string;
}>;
/** Supplies fresh authentication headers immediately before each HTTP attempt. */
type AxAICredentialProvider = (request: AxAICredentialRequest) => Promise<Record<string, string>>;
type AxTokenUsage = {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
    thoughtsTokens?: number;
    reasoningTokens?: number;
    cacheCreationTokens?: number;
    cacheReadTokens?: number;
    serviceTier?: AxAppliedServiceTier;
    speed?: 'standard' | 'fast';
};
/**
 * Request-scoped attribution attached to normalized AI usage events.
 *
 * Keep identity and request metadata here instead of in process-global state so
 * concurrent multi-tenant calls cannot leak attribution across requests.
 */
type AxUsageContext = {
    tenantId?: string;
    userId?: string;
    requestId?: string;
    runId?: string;
    parentRunId?: string;
    feature?: string;
    attributes?: Record<string, string | number | boolean>;
};
/** A normalized usage event emitted once for a completed AI operation. */
type AxUsageEvent = {
    operation: 'chat' | 'embed';
    ai: string;
    model: string;
    tokens: AxTokenUsage;
    context?: AxUsageContext;
    sessionId?: string;
    remoteId?: string;
    remoteRequestId?: string;
    remoteSessionId?: string;
    streaming: boolean;
};
/**
 * Best-effort global usage observer.
 *
 * Ax does not await observers before returning model results. Production
 * observers should synchronously enqueue the event into a durable pipeline.
 */
type AxUsageObserver = (event: Readonly<AxUsageEvent>) => void | Promise<void>;
/**
 * Configuration options for AI model behavior.
 *
 * These settings control how the model generates responses. They can be set
 * as defaults when creating an AI instance, or overridden per-request.
 *
 * @example
 * ```typescript
 * const config: AxModelConfig = {
 *   maxTokens: 2000,
 *   temperature: 0.7,
 *   topP: 0.9
 * };
 * ```
 */
type AxModelConfig = {
    /**
     * Maximum number of tokens to generate in the response.
     *
     * **Token estimation guide:**
     * - ~750 tokens ≈ 1 page of English text
     * - ~100 tokens ≈ 75 words
     * - ~4 characters ≈ 1 token (English)
     *
     * Set higher for long-form content (articles, code), lower for concise
     * responses (classifications, short answers).
     *
     * @example 500 for short responses, 2000 for detailed explanations, 4000+ for long-form content
     */
    maxTokens?: number;
    /**
     * Controls randomness in generation. Range: 0 to 2.
     *
     * **Use case guide:**
     * - `0` - Deterministic, always picks most likely token. Best for factual Q&A,
     *   classification, code generation where consistency matters.
     * - `0.3-0.5` - Low creativity. Good for structured outputs, summaries.
     * - `0.7` - Balanced (default for most models). Good for general conversation.
     * - `1.0` - High creativity. Good for brainstorming, creative writing.
     * - `1.5-2.0` - Very high randomness. Often produces incoherent output.
     *
     * @default Varies by provider, typically 0.7-1.0
     */
    temperature?: number;
    /**
     * Nucleus sampling: only consider tokens with cumulative probability >= topP.
     * Range: 0 to 1.
     *
     * Lower values make output more focused and deterministic. Alternative to
     * temperature for controlling randomness.
     *
     * **Recommendation:** Adjust either temperature OR topP, not both.
     *
     * @example 0.1 for focused output, 0.9 for diverse output
     */
    topP?: number;
    /**
     * Only consider the top K most likely tokens at each step.
     *
     * Lower values (e.g., 10-40) make output more focused. Not supported by all
     * providers (OpenAI doesn't support this; Anthropic, Google do).
     *
     * @example 40 for focused output, 100 for more variety
     */
    topK?: number;
    /**
     * Penalizes tokens that have already appeared in the output.
     * Range: -2.0 to 2.0.
     *
     * Positive values reduce repetition by penalizing tokens that have appeared
     * at all, regardless of frequency. Useful for encouraging diverse vocabulary.
     *
     * - `0` - No penalty (default)
     * - `0.5-1.0` - Mild penalty, reduces obvious repetition
     * - `1.5-2.0` - Strong penalty, may hurt coherence
     *
     * @example 0.6 to reduce repetitive phrasing
     */
    presencePenalty?: number;
    /**
     * Penalizes tokens based on how frequently they've appeared.
     * Range: -2.0 to 2.0.
     *
     * Unlike presencePenalty, this scales with frequency: tokens that appear many
     * times get penalized more. Useful for preventing the model from repeating
     * the same phrases verbatim.
     *
     * @example 0.5 to discourage word/phrase repetition
     */
    frequencyPenalty?: number;
    /**
     * Sequences that will stop generation when encountered.
     *
     * The model stops generating as soon as any stop sequence is produced.
     * The stop sequence itself is NOT included in the output.
     *
     * @example ['\\n\\n', 'END', '---'] to stop at double newlines or markers
     */
    stopSequences?: string[];
    /**
     * Similar to stopSequences, but the sequence IS included in the output.
     *
     * @example ['</answer>'] to include closing tag in output
     */
    endSequences?: string[];
    /**
     * Enable streaming responses for real-time output.
     *
     * When true, the response is returned as a stream of chunks, allowing
     * you to display partial results as they're generated.
     */
    stream?: boolean;
    /** Conversational audio input/output configuration for chat models. */
    audio?: AxChatAudioConfig;
    /**
     * Number of completions to generate for each prompt.
     *
     * Generates multiple independent responses. Useful with result pickers
     * to select the best response. Increases cost proportionally.
     *
     * @example 3 to generate three alternatives and pick the best
     */
    n?: number;
    /** Provider reasoning/effort hint. Currently used by Anthropic. */
    effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
    /** Provider speed tier. Currently used by Anthropic fast mode. */
    speed?: 'standard' | 'fast';
    /** Advisory full-task token budget. Currently used by Anthropic Opus task budgets. */
    taskBudget?: {
        type: 'tokens';
        total: number;
        remaining?: number;
    };
};
type AxFunctionHandler = (args?: any, extra?: Readonly<{
    sessionId?: string;
    traceId?: string;
    debug?: boolean;
    ai?: AxAIService;
    control?: AxRunControl;
    executionPath?: string;
    step?: AxStepContext;
    abortSignal?: AbortSignal;
    protocol?: AxAgentCompletionProtocol;
    /** Immutable event provenance for autonomous or resumed execution. */
    eventContext?: AxEventContext;
    /** @internal Shared native MCP state for nested programmable functions. */
    _mcpExecutionContext?: AxMCPExecutionContext;
}>) => unknown;
type AxAgentCompletionProtocol = Readonly<{
    final: (...args: unknown[]) => never;
    askClarification: (...args: unknown[]) => never;
    guideAgent: (guidance: string) => never;
    success: (message: string) => Promise<void>;
    failed: (message: string) => Promise<void>;
}>;
type AxFunctionJSONSchema = {
    type: string | string[];
    properties?: Record<string, AxFunctionJSONSchema & {
        enum?: string[];
        description: string;
    }>;
    required?: string[];
    items?: AxFunctionJSONSchema;
    enum?: string[];
    title?: string;
    additionalProperties?: boolean;
};
type AxFunction = {
    /** Background tools permit independent model work while they execute. */
    execution?: 'blocking' | 'background';
    name: string;
    description: string;
    componentId?: string;
    parameters?: AxFunctionJSONSchema;
    returns?: AxFunctionJSONSchema;
    namespace?: string;
    /** Native protocol identity retained independently of provider tool names. */
    protocol?: {
        kind: 'mcp';
        namespace: string;
        name: string;
        annotations?: Record<string, unknown>;
        meta?: Record<string, unknown>;
    } | {
        kind: 'ucp';
        namespace: string;
        name: string;
        meta?: Record<string, unknown>;
    };
    func: AxFunctionHandler;
};
type AxFunctionResult = Extract<AxChatRequest['chatPrompt'][number], {
    role: 'function';
}> & {
    index: number;
};
/** Single thinking block item with its signature */
type AxThoughtBlockItem = {
    data: string;
    encrypted: boolean;
    signature?: string;
    /** Provider output-item identifier required for stateless replay. */
    id?: string;
    /** Human-readable reasoning summary, separate from encrypted provider state. */
    summary?: string;
    /** Opaque encrypted reasoning state returned by Responses-style APIs. */
    encryptedContent?: string;
    /** Output phase used to preserve reasoning/tool ordering across replay. */
    phase?: 'commentary' | 'final_answer';
};
/** Generated image returned by an image-capable model through `chat()`. */
type AxChatImageOutput = {
    id?: string;
    data?: string;
    url?: string;
    mimeType?: string;
    isDelta?: boolean;
};
type AxChatResponseResult = {
    index: number;
    content?: string;
    /** Responses-style output phase for commentary/final-answer ordering. */
    phase?: 'commentary' | 'final_answer';
    thought?: string;
    /** Array of thinking blocks, each with its own signature */
    thoughtBlocks?: AxThoughtBlockItem[];
    name?: string;
    /** Latest provider-reported amount of realtime audio processed. */
    audioProcessedMs?: number;
    /** Replace the previous snapshot for this result id; content contains only finalized speech. */
    transcript?: {
        text: string;
        isFinal: boolean;
    };
    id?: string;
    audio?: AxChatAudioOutput;
    images?: AxChatImageOutput[];
    functionCalls?: {
        id: string;
        type: 'function';
        function: {
            name: string;
            params?: string | object;
        };
    }[];
    citations?: AxCitation[];
    finishReason?: 'stop' | 'length' | 'function_call' | 'content_filter' | 'error';
    logprobs?: {
        content?: {
            token: string;
            logprob: number;
            topLogprobs?: {
                token: string;
                logprob: number;
            }[];
        }[];
    };
};
type AxCitation = {
    url: string;
    title?: string;
    description?: string;
    license?: string;
    publicationDate?: string;
    snippet?: string;
    /** File Search multimodal (Gemini, May 2026): media chunk id. */
    mediaId?: string;
    /** File Search multimodal (Gemini, May 2026): page numbers cited within the source. */
    pageNumbers?: number[];
};
type AxModelUsage = {
    ai: string;
    model: string;
    tokens?: AxTokenUsage;
    citations?: AxCitation[];
};
type AxDebugChatResponseUsage = AxModelUsage & {
    systemPromptCharacters?: number;
    exampleChatContextCharacters?: number;
    mutableChatContextCharacters?: number;
    chatContextCharacters?: number;
    totalPromptCharacters?: number;
    estimatedCost?: number;
};
type AxProviderMetadata = Record<string, Record<string, unknown>>;
type AxChatResponse = {
    /** Ax-local session identifier used for conversation tracking and memory isolation. */
    sessionId?: string;
    /** Provider response/message/completion identifier. */
    remoteId?: string;
    /** Provider request identifier, usually from response headers. */
    remoteRequestId?: string;
    /** Provider conversation/session identifier when distinct from Ax's local sessionId. */
    remoteSessionId?: string;
    /** Provider-specific metadata that should flow through adapters. */
    providerMetadata?: AxProviderMetadata;
    results: readonly AxChatResponseResult[];
    modelUsage?: AxModelUsage;
};
type AxEmbedResponse = {
    /** Provider response/embedding request identifier when available. */
    remoteId?: string;
    /** Ax-local session identifier used for conversation tracking. */
    sessionId?: string;
    /** Provider request identifier, usually from response headers. */
    remoteRequestId?: string;
    /** Provider conversation/session identifier when distinct from Ax's local sessionId. */
    remoteSessionId?: string;
    /** Provider-specific metadata that should flow through adapters. */
    providerMetadata?: AxProviderMetadata;
    embeddings: readonly (readonly number[])[];
    modelUsage?: AxModelUsage;
};
type AxModelInfoWithProvider = AxModelInfo & {
    provider: string;
};
type AxFunctionResultContent = readonly ({
    type: 'text';
    text: string;
} | {
    type: 'image';
    mimeType: string;
    image: string;
    altText?: string;
} | {
    type: 'audio';
    data: string;
    mimeType?: string;
    transcription?: string;
} | {
    type: 'file';
    data: string;
    filename?: string;
    mimeType: string;
    extractedText?: string;
} | {
    type: 'url';
    url: string;
    title?: string;
    description?: string;
    cachedContent?: string;
})[];
type AxChatRequest<TModel = string> = {
    chatPrompt: ({
        role: 'system';
        content: string;
        cache?: boolean;
    } | {
        role: 'user';
        name?: string;
        content: string | ({
            type: 'text';
            text: string;
            cache?: boolean;
        } | {
            type: 'image';
            mimeType: string;
            image: string;
            details?: 'high' | 'low' | 'auto';
            cache?: boolean;
            /** Optimization preference for image processing */
            optimize?: 'quality' | 'size' | 'auto';
            /** Fallback text description when images aren't supported */
            altText?: string;
        } | {
            type: 'audio';
            data: string;
            format?: AxAudioFormat;
            mimeType?: string;
            sampleRate?: number;
            channels?: number;
            cache?: boolean;
            /** Pre-transcribed text content for fallback */
            transcription?: string;
            /** Duration of audio in seconds */
            duration?: number;
        } | {
            /** File content type with inline data */
            type: 'file';
            /** File data as base64 */
            data: string;
            /** Original filename */
            filename?: string;
            /** MIME type of the file */
            mimeType: string;
            cache?: boolean;
            /** Pre-extracted text content for fallback */
            extractedText?: string;
        } | {
            /** File content type with cloud storage URI */
            type: 'file';
            /** File URI (e.g., gs:// URL) */
            fileUri: string;
            /** Original filename */
            filename?: string;
            /** MIME type of the file */
            mimeType: string;
            cache?: boolean;
            /** Pre-extracted text content for fallback */
            extractedText?: string;
        } | {
            /** URL/Link content type */
            type: 'url';
            /** The URL to fetch content from */
            url: string;
            cache?: boolean;
            /** Pre-fetched content for providers without web access */
            cachedContent?: string;
            /** Page title for context */
            title?: string;
            /** Page description for context */
            description?: string;
        })[];
        cache?: boolean;
    } | {
        role: 'assistant';
        content?: string;
        name?: string;
        functionCalls?: {
            id: string;
            type: 'function';
            function: {
                name: string;
                params?: string | object;
            };
        }[];
        /** Concatenated thinking content */
        thought?: string;
        /** Array of thinking blocks, each with its own signature */
        thoughtBlocks?: AxThoughtBlockItem[];
        /** Previous assistant audio response reference for audio-capable chat models */
        audio?: {
            id: string;
            transcript?: string;
        };
        /** Generated images retained for stateless Responses replay. */
        images?: AxChatImageOutput[];
        /** Responses-style output phase retained for replay. */
        phase?: 'commentary' | 'final_answer';
        cache?: boolean;
    } | {
        role: 'function';
        result: string;
        /** Native structured/multimodal tool content, mapped by each provider. */
        content?: AxFunctionResultContent;
        isError?: boolean;
        functionId: string;
        /** Raw structured protocol result retained in memory and continuation state. */
        protocolResult?: {
            protocol: NonNullable<AxFunction['protocol']>;
            value: unknown;
        };
        cache?: boolean;
    })[];
    /** Provider capability preferences and requirements */
    capabilities?: {
        /** Whether the request requires image support */
        requiresImages?: boolean;
        /** Whether the request requires audio support */
        requiresAudio?: boolean;
        /** Whether the request requires generated audio responses */
        requiresAudioOutput?: boolean;
        /** Whether the request requires file support */
        requiresFiles?: boolean;
        /** Whether the request requires web search capabilities */
        requiresWebSearch?: boolean;
        /** How to handle unsupported content types */
        fallbackBehavior?: 'error' | 'degrade' | 'skip';
    };
    /** Content processing preferences and hints */
    processing?: {
        /** Whether to apply image compression */
        imageCompression?: boolean;
        /** Whether to apply audio transcription */
        audioTranscription?: boolean;
        /** Whether to extract text from files */
        fileTextExtraction?: boolean;
        /** Whether to fetch content from URLs */
        urlContentFetching?: boolean;
    };
    functions?: Readonly<{
        name: string;
        description: string;
        parameters?: AxFunctionJSONSchema;
        execution?: 'blocking' | 'background';
        /** Mark this function for caching (creates breakpoint after tools) */
        cache?: boolean;
    }>[];
    functionCall?: 'none' | 'auto' | 'required' | {
        type: 'function';
        function: {
            name: string;
        };
    };
    responseFormat?: {
        type: 'json_object' | 'json_schema';
        schema?: any;
        /**
         * Original per-value guidance for adapters that can represent it structurally.
         * The standard schema's descriptions already contain the readable guidance.
         * These annotations are not JSON Schema keywords and are not sent as such.
         */
        fieldDescriptions?: Readonly<Record<string, {
            description?: string;
            valueDescriptions: Readonly<Record<string, string>>;
        }>>;
    };
    modelConfig?: AxModelConfig;
    model?: TModel;
};
interface AxAIServiceMetrics {
    latency: {
        chat: {
            mean: number;
            p95: number;
            p99: number;
            samples: number[];
        };
        embed: {
            mean: number;
            p95: number;
            p99: number;
            samples: number[];
        };
    };
    errors: {
        chat: {
            count: number;
            rate: number;
            total: number;
        };
        embed: {
            count: number;
            rate: number;
            total: number;
        };
    };
}
type AxInternalChatRequest<TModel> = Omit<AxChatRequest, 'model'> & Required<Pick<AxChatRequest<TModel>, 'model'>>;
type AxEmbedRequest<TEmbedModel = string> = {
    texts?: readonly string[];
    embedModel?: TEmbedModel;
};
type AxInternalEmbedRequest<TEmbedModel> = Omit<AxEmbedRequest, 'embedModel'> & Required<Pick<AxEmbedRequest<TEmbedModel>, 'embedModel'>>;
type AxRateLimitInfo = Readonly<{
    operation: 'chat' | 'embed';
    /** Canonical provider identifier. */
    provider: string;
    /** @deprecated Use `provider`. */
    ai: string;
    model: string;
    streaming: boolean;
    /** Usage from the previous completed operation on this service, when available. */
    previousModelUsage?: AxModelUsage;
    /** @deprecated Use `previousModelUsage`. */
    modelUsage?: AxModelUsage;
}>;
type AxRateLimiterFunction = <T = unknown>(reqFunc: () => Promise<T | ReadableStream<T>>, info: AxRateLimitInfo) => Promise<T | ReadableStream<T>>;
type AxLoggerData = {
    name: 'ChatRequestChatPrompt';
    step: number;
    value: AxChatRequest['chatPrompt'];
} | {
    name: 'FunctionResults';
    value: AxFunctionResult[];
} | {
    name: 'ChatResponseResults';
    value: AxChatResponseResult[];
} | {
    name: 'ChatResponseStreamingResult';
    index: number;
    value: AxChatResponseResult & {
        delta?: string;
    };
} | {
    name: 'ChatResponseStreamingDoneResult';
    index: number;
    value: AxChatResponseResult;
} | {
    name: 'FunctionError';
    index: number;
    fixingInstructions: string;
    error: unknown;
} | {
    name: 'ValidationError';
    index: number;
    fixingInstructions: string;
    error: unknown;
} | {
    name: 'RefusalError';
    index: number;
    error: unknown;
} | {
    name: 'ResultPickerUsed';
    sampleCount: number;
    selectedIndex: number;
    latency: number;
} | {
    name: 'Notification';
    id: string;
    value: string;
} | {
    name: 'EmbedRequest';
    embedModel: string;
    value: readonly string[];
} | {
    name: 'EmbedResponse';
    totalEmbeddings: number;
    value: {
        length: number;
        sample: number[];
        truncated: boolean;
    }[];
} | {
    name: 'ChatResponseUsage';
    value: AxDebugChatResponseUsage;
} | {
    name: 'ChatResponseCitations';
    value: AxCitation[];
};
type AxLoggerFunction = (message: AxLoggerData) => void;
/**
 * Entry stored in the context cache registry.
 * Used for persisting cache metadata across process restarts.
 */
type AxContextCacheRegistryEntry = {
    /** Provider-specific cache resource name (e.g., "cachedContents/abc123") */
    cacheName: string;
    /** When the cache expires (timestamp in milliseconds) */
    expiresAt: number;
    /** Number of tokens in the cached content */
    tokenCount?: number;
};
/**
 * External registry for persisting context cache metadata.
 * Useful for serverless/short-lived processes where in-memory storage is lost.
 * Registry keys identify cacheable content, not users or accounts. Applications
 * that require tenant isolation must add a stable tenant/account namespace and
 * must not fall back to a shared global namespace.
 *
 * @example
 * // Redis-backed registry
 * const tenantId = getRequiredTenantId();
 * const registry: AxContextCacheRegistry = {
 *   get: async (key) => {
 *     const data = await redis.get(`cache:${tenantId}:${key}`);
 *     return data ? JSON.parse(data) : undefined;
 *   },
 *   set: async (key, entry) => {
 *     const ttl = Math.max(1, Math.ceil((entry.expiresAt - Date.now()) / 1000));
 *     await redis.set(`cache:${tenantId}:${key}`, JSON.stringify(entry), 'EX', ttl);
 *   },
 * };
 */
type AxContextCacheRegistry = {
    /** Look up a cache entry by key */
    get: (key: string) => Promise<AxContextCacheRegistryEntry | undefined> | AxContextCacheRegistryEntry | undefined;
    /** Store a cache entry */
    set: (key: string, entry: Readonly<AxContextCacheRegistryEntry>) => Promise<void> | void;
};
/**
 * Options for explicit context caching (e.g., Gemini/Vertex context caching).
 * Allows caching large prompt prefixes for cost savings and lower latency.
 *
 * When this option is present, caching is enabled. The system will:
 * - Automatically cache the system prompt and any content marked with `cache: true`
 * - Reuse existing caches when content hash matches
 * - Create new caches when content changes
 * - Auto-refresh TTL when cache is near expiration
 * - Recreate or fall back uncached when an automatic refresh fails
 * - Retry a provider-rejected automatically managed cache once without it
 */
type AxContextCacheOptions = {
    /**
     * Explicit cache resource name/ID.
     * If provided, this cache will be used directly (bypasses auto-creation).
     * Explicit names are not automatically invalidated or retried without cache.
     * If omitted, a cache will be created/looked up automatically.
     */
    name?: string;
    /**
     * TTL (Time To Live) in seconds for the cache.
     * Default: 3600 (1 hour). Maximum varies by provider.
     */
    ttlSeconds?: number;
    /**
     * Minimum token threshold for creating explicit caches.
     * Content below this threshold won't create explicit caches (implicit caching still applies).
     * Default: 2048 (Gemini minimum requirement)
     */
    minTokens?: number;
    /**
     * Window in seconds before expiration to trigger automatic TTL refresh.
     * Default: 300 (5 minutes)
     */
    refreshWindowSeconds?: number;
    /**
     * External registry for persisting cache metadata.
     * If provided, cache lookups and storage will use this registry instead of in-memory storage.
     * Useful for serverless/short-lived processes.
     * Namespace registry operations by tenant/account when caches must not be shared.
     */
    registry?: AxContextCacheRegistry;
    /**
     * Controls where the cache breakpoint is set in the prompt prefix.
     * Prefix order: System → Functions → Examples → User Input
     *
     * - 'after-examples' (default): Cache includes system + functions + examples
     * - 'after-functions': Cache includes system + functions only (use when examples are dynamic)
     * - 'system': Cache includes only system prompt (use when functions are dynamic)
     */
    cacheBreakpoint?: 'system' | 'after-functions' | 'after-examples';
};
/**
 * Information about a context cache entry (returned after creation or lookup).
 */
type AxContextCacheInfo = {
    /** Provider-specific cache resource name */
    name: string;
    /** When the cache expires (ISO 8601 timestamp) */
    expiresAt: string;
    /** Number of tokens in the cached content */
    tokenCount?: number;
    /** Hash of the cached content for validation */
    contentHash?: string;
};
/**
 * Runtime options for AI service requests.
 *
 * These options control how requests are made to the AI service, including
 * debugging, rate limiting, streaming, function calling, and extended thinking.
 *
 * @example
 * ```typescript
 * const options: AxAIServiceOptions = {
 *   stream: true,
 *   thinkingTokenBudget: 'medium',
 *   debug: true
 * };
 * await gen.forward(ai, values, options);
 * ```
 */
type AxAIServiceOptions = {
    /** Automatically use native async capabilities when available. */
    asyncMode?: 'auto' | 'off';
    control?: AxRunControl;
    /** Stable execution scope for targeted run updates. */
    executionPath?: string;
    /** @internal Identifies whether a forced tool choice came from Ax itself. */
    functionCallSource?: 'ax' | 'caller';
    /**
     * Enable debug logging for troubleshooting.
     *
     * When true, logs detailed information about prompts, responses, and
     * the generation pipeline. Useful for understanding AI behavior.
     */
    debug?: boolean;
    /**
     * Enable low-level HTTP request/response logging.
     *
     * More verbose than `debug`. Shows raw HTTP traffic including headers.
     * Useful for debugging API issues.
     */
    verbose?: boolean;
    /** Custom rate limiter function to control request throughput. */
    rateLimiter?: AxRateLimiterFunction;
    /** Custom fetch implementation (useful for proxies or custom HTTP handling). */
    fetch?: typeof fetch;
    /** Custom WebSocket constructor for providers that use realtime WebSocket transports. */
    webSocket?: any;
    /** OpenTelemetry tracer for distributed tracing. */
    tracer?: Tracer;
    /** OpenTelemetry meter for metrics collection. */
    meter?: Meter;
    /**
     * Request timeout in milliseconds.
     *
     * @default 300000 (5 minutes)
     */
    timeout?: number;
    /** Exclude message content from OpenTelemetry traces (for privacy). */
    excludeContentFromTrace?: boolean;
    /** AbortSignal for cancelling in-flight requests. */
    abortSignal?: AbortSignal;
    /** Custom logger function for debug output. */
    logger?: AxLoggerFunction;
    /** Session identifier for conversation tracking and memory isolation. */
    sessionId?: string;
    /**
     * Stable per-conversation key for OpenAI prompt caching.
     *
     * Routes the request to the shard its cache lives on, so it must stay the same
     * for every turn of a conversation and differ between unrelated ones. OpenAI
     * advises staying under roughly 15 requests/minute per key.
     *
     * Falls back to `sessionId` when unset.
     *
     * **Currently used by:** OpenAI GPT-5.6+ and Meta Responses/Chat Completions.
     */
    promptCacheKey?: string;
    /** Meta Responses prompt-cache retention policy. */
    promptCacheRetention?: 'in_memory' | '24h';
    /**
     * Request-scoped attribution included in normalized usage events.
     *
     * Per-call values override service defaults. Custom attributes are
     * shallow-merged with per-call keys taking precedence.
     */
    usageContext?: AxUsageContext;
    /** Hide system prompt in debug output (for cleaner logs). */
    debugHideSystemPrompt?: boolean;
    /** OpenTelemetry trace context for distributed tracing. */
    traceContext?: Context;
    /**
     * Enable streaming responses.
     *
     * When true, the AI returns responses as a stream of chunks, enabling
     * real-time display of generated text.
     */
    stream?: boolean;
    /**
     * How to handle function/tool calling.
     *
     * - `'auto'` - Let the provider decide the best approach (default)
     * - `'native'` - Use the provider's native function calling API. Fails if
     *   the model doesn't support it.
     * - `'prompt'` - Simulate function calling via prompt engineering. Works with
     *   any model but may be less reliable.
     *
     * @default 'auto'
     */
    functionCallMode?: 'auto' | 'native' | 'prompt';
    /**
     * Token budget for extended thinking (chain-of-thought reasoning).
     *
     * Extended thinking allows models to "think through" complex problems before
     * responding. Higher budgets allow deeper reasoning but cost more.
     *
     * **Approximate token allocations:**
     * - `'none'` - Disabled (default)
     * - `'minimal'` - ~1,000 tokens (~750 words of thinking)
     * - `'low'` - ~4,000 tokens
     * - `'medium'` - ~10,000 tokens
     * - `'high'` - ~20,000 tokens
     * - `'highest'` - ~32,000+ tokens (provider maximum)
     *
     * **Provider support:**
     * - Anthropic Claude: Full support with `claude-sonnet-4` and above
     * - OpenAI: Supported with o1/o3 models (uses `reasoning_effort`)
     * - Google: Supported with Gemini 2.0 Flash Thinking
     * - DeepSeek: Supported with DeepSeek V4 models
     *
     * @example
     * ```typescript
     * // Enable medium thinking for complex reasoning
     * await gen.forward(ai, values, { thinkingTokenBudget: 'medium' });
     * ```
     */
    thinkingTokenBudget?: 'minimal' | 'low' | 'medium' | 'high' | 'highest' | 'none';
    /**
     * Portable inference scheduling policy.
     *
     * `auto` delegates to provider routing when supported and otherwise omits
     * the provider field. Explicit tiers are rejected when the selected
     * provider/model has not verified them.
     */
    serviceTier?: AxServiceTier;
    /**
     * Include the model's thinking/reasoning in the output.
     *
     * When true and `thinkingTokenBudget` is set, the model's internal reasoning
     * is included in the response. Useful for debugging and understanding AI behavior.
     *
     * @default false
     */
    showThoughts?: boolean;
    /**
     * Confirms a request may use a model marked `isExpensive` in its model info.
     *
     * Requests for such a model are rejected unless this is `'yes'`. It does not
     * select a different model.
     */
    useExpensiveModel?: 'yes';
    /**
     * Provider-specific hint to opt in to beta API paths when available.
     *
     * Currently used by Google Gemini on Vertex AI to route requests through
     * `v1beta1` instead of the default stable `v1` endpoint.
     */
    beta?: boolean;
    /** Internal: Current step index for multi-step operations. */
    stepIndex?: number;
    /**
     * CORS proxy URL for browser environments.
     *
     * When running in a browser, API calls may be blocked by CORS. Specify a
     * proxy URL to route requests through.
     *
     * @example 'https://cors-anywhere.herokuapp.com/'
     */
    corsProxy?: string;
    /**
     * Retry configuration for failed requests.
     *
     * Controls automatic retry behavior for transient errors (rate limits,
     * timeouts, server errors).
     */
    retry?: Partial<RetryConfig>;
    /**
     * Context caching options for large prompt prefixes.
     *
     * When enabled, large prompt prefixes can be cached for cost savings and
     * lower latency on subsequent requests.
     *
     * **Currently supported by:** Google Gemini/Vertex AI
     */
    contextCache?: AxContextCacheOptions;
    /**
     * Custom labels for OpenTelemetry metrics.
     *
     * These labels are merged with `axGlobals.customLabels` (service-level
     * options override global settings).
     *
     * @example { environment: 'production', feature: 'search' }
     */
    customLabels?: Record<string, string>;
    /**
     * Whether to include the request body in `AxAIServiceError` messages.
     *
     * When `false`, the request body is omitted from thrown errors. Useful when
     * requests may contain sensitive data (API keys, PII) or large base64-encoded
     * content that would bloat error logs.
     *
     * @default true
     */
    includeRequestBodyInErrors?: boolean;
};
/** Non-serializable execution hooks shared by AI services and programs. */
type AxRuntimeHooks = Pick<AxAIServiceOptions, 'rateLimiter' | 'tracer' | 'meter'>;
interface AxAIService<TModel = unknown, TEmbedModel = unknown, TModelKey = string> {
    getId(): string;
    getName(): string;
    getFeatures(model?: TModel): AxAIFeatures;
    getModelList(): AxAIModelList<TModelKey> | undefined;
    getMetrics(): AxAIServiceMetrics;
    getLogger(): AxLoggerFunction;
    getLastUsedChatModel(): TModel | undefined;
    getLastUsedEmbedModel(): TEmbedModel | undefined;
    getLastUsedModelConfig(): AxModelConfig | undefined;
    /** Check request compatibility without network calls, credentials, or state changes. */
    validateChatRequest?(req: Readonly<AxChatRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): void;
    /** Resolve a provider before a controlled/tool run; the returned service is pinned. */
    resolveChatService?(req: Readonly<AxChatRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<{
        service: Readonly<AxAIService<unknown, unknown, any>>;
        model?: string;
    }>;
    openChatSession?(req: Readonly<AxChatRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatSession>;
    chat(req: Readonly<AxChatRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatResponse | ReadableStream<AxChatResponse>>;
    embed(req: Readonly<AxEmbedRequest<TEmbedModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxEmbedResponse>;
    transcribe(req: Readonly<AxTranscriptionRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
    getEstimatedCost(modelUsage?: AxModelUsage): number;
    setOptions(options: Readonly<AxAIServiceOptions>): void;
    getOptions(): Readonly<AxAIServiceOptions>;
}
/**
 * Context cache operation to be executed by the base AI service.
 * Providers define these operations; AxBaseAI executes them via apiCall().
 */
type AxContextCacheOperation = {
    /** Type of cache operation */
    type: 'create' | 'update' | 'delete' | 'get';
    /** API endpoint configuration */
    apiConfig: AxAPI;
    /** Request payload */
    request: unknown;
    /** Parse the response and return cache info */
    parseResponse: (response: unknown) => AxContextCacheInfo | undefined;
};
/**
 * Result of preparing a chat request with context cache support.
 */
type AxPreparedChatRequest<TChatRequest> = {
    /** API endpoint configuration */
    apiConfig: AxAPI;
    /** The prepared chat request */
    request: TChatRequest;
    /** Optional cache operations to execute before the main request */
    cacheOperations?: AxContextCacheOperation[];
    /** Cache name to use in the request (if using existing cache) */
    cachedContentName?: string;
};
interface AxAIServiceImpl<TModel, TEmbedModel, TChatRequest, TEmbedRequest, TChatResponse, TChatResponseDelta, TEmbedResponse> {
    /** Validate original tools/history before automatic prompt-mode emulation. */
    validateChatReq?(req: Readonly<AxInternalChatRequest<TModel>>): void;
    createChatReq(req: Readonly<AxInternalChatRequest<TModel>>, config?: Readonly<AxAIServiceOptions>): Promise<[AxAPI, TChatRequest]> | [AxAPI, TChatRequest];
    createChatResp(resp: Readonly<TChatResponse>, request?: Readonly<AxInternalChatRequest<TModel>>): AxChatResponse;
    createChatStreamResp?(resp: Readonly<TChatResponseDelta>, state: object): AxChatResponse;
    /**
     * Optional: classify a raw streaming delta that carries a transient error into the
     * HTTP status it corresponds to (e.g. Anthropic's HTTP-200 `overloaded_error` SSE event
     * → 529). The base layer applies the same retryable-status policy used for real HTTP
     * status errors, so a streaming overload is retried-with-backoff before any failover —
     * matching the non-streaming path. Return undefined for normal deltas (the common case).
     */
    classifyStreamErrorStatus?(resp: Readonly<TChatResponseDelta>): number | undefined;
    createEmbedReq?(req: Readonly<AxInternalEmbedRequest<TEmbedModel>>, config?: Readonly<AxAIServiceOptions>): Promise<[AxAPI, TEmbedRequest]> | [AxAPI, TEmbedRequest];
    createEmbedResp?(resp: Readonly<TEmbedResponse>): AxEmbedResponse;
    getModelConfig(): AxModelConfig;
    getTokenUsage(): AxTokenUsage | undefined;
    /**
     * Optional: Prepare a chat request with context cache support.
     * Providers implement this to support explicit context caching.
     * Returns cache operations to execute and the modified request.
     */
    prepareCachedChatReq?(req: Readonly<AxInternalChatRequest<TModel>>, options: Readonly<AxAIServiceOptions>, existingCacheName?: string): Promise<AxPreparedChatRequest<TChatRequest>>;
    /**
     * Optional: Return tool/function-call state that becomes part of the
     * provider's immutable explicit-cache prefix.
     *
     * This is used for cache identity and token estimation when a provider
     * treats tool state as cached prefix state even if the generic request does
     * not mark functions with `cache: true`.
     */
    getContextCacheToolState?(req: Readonly<AxInternalChatRequest<TModel>>, options: Readonly<AxAIServiceOptions>): {
        functions?: AxChatRequest['functions'];
        functionCall?: AxChatRequest['functionCall'];
    } | undefined;
    /**
     * Optional: Build a context cache creation operation.
     * Called when a new cache needs to be created from the request.
     */
    buildCacheCreateOp?(req: Readonly<AxInternalChatRequest<TModel>>, options: Readonly<AxAIServiceOptions>): AxContextCacheOperation | undefined;
    /**
     * Optional: Build a context cache TTL update operation.
     */
    buildCacheUpdateTTLOp?(cacheName: string, ttlSeconds: number): AxContextCacheOperation;
    /**
     * Optional: Build a context cache deletion operation.
     */
    buildCacheDeleteOp?(cacheName: string): AxContextCacheOperation;
    /**
     * Optional: Check if explicit context caching is supported (e.g., Gemini).
     * Explicit caching creates a separate cache resource with an ID.
     */
    supportsContextCache?(model: TModel): boolean;
    /**
     * Optional: Check if implicit context caching is supported (e.g., Anthropic).
     * Implicit caching marks content in the request; provider handles caching automatically.
     */
    supportsImplicitCaching?(model: TModel): boolean;
}

type AxMemoryMessageValue = Omit<AxChatRequest['chatPrompt'][number], 'role'> | Omit<AxChatResponseResult, 'index'>;
type AxMemoryData = {
    tags?: string[];
    role: AxChatRequest['chatPrompt'][number]['role'];
    updatable?: boolean;
    chat: {
        index: number;
        value: AxMemoryMessageValue;
    }[];
}[];
interface AxAIMemory {
    addRequest(result: AxChatRequest['chatPrompt'], sessionId?: string): void;
    addResponse(results: Readonly<AxChatResponseResult[]>, sessionId?: string): void;
    updateResult(results: Readonly<AxChatResponseResult> & {
        delta?: string;
    }, sessionId?: string): void;
    addFunctionResults(results: Readonly<AxFunctionResult[]>, sessionId?: string): void;
    history(index: number, sessionId?: string): AxChatRequest['chatPrompt'];
    reset(sessionId?: string): void;
    getLast(sessionId?: string): AxMemoryData[number] | undefined;
    addTag(name: string, sessionId?: string): void;
    rewindToTag(name: string, sessionId?: string): AxMemoryData;
    removeByTag(name: string, sessionId?: string): AxMemoryData;
}

interface AxAssertion<T = Record<string, unknown>> {
    fn(values: T): Promise<boolean | string | undefined> | boolean | string | undefined;
    message?: string;
}
interface AxStreamingAssertion {
    fieldName: string;
    fn(content: string, done?: boolean): Promise<boolean | string | undefined> | boolean | string | undefined;
    message?: string;
}
declare class AxAssertionError extends Error {
    constructor({ message, }: Readonly<{
        message: string;
    }>);
    getFixingInstructions: () => {
        name: string;
        title: string;
        description: string;
    }[];
    toString(): string;
}
declare class AxStreamingAssertionError extends Error {
    constructor({ message, }: Readonly<{
        message: string;
    }>);
    getFixingInstructions: () => {
        name: string;
        title: string;
        description: string;
    }[];
    toString(): string;
}

declare class AxMemory implements AxAIMemory {
    private memories;
    private defaultMemory;
    constructor();
    private getMemory;
    addRequest(value: AxChatRequest['chatPrompt'], sessionId?: string): void;
    addResponse(results: Readonly<AxChatResponseResult[]>, sessionId?: string): void;
    addFunctionResults(results: Readonly<AxFunctionResult[]>, sessionId?: string): void;
    updateResult(result: Readonly<AxChatResponseResult & {
        delta?: string;
    }>, sessionId?: string): void;
    addTag(name: string, sessionId?: string): void;
    rewindToTag(name: string, sessionId?: string): AxMemoryData;
    removeByTag(name: string, sessionId?: string): AxMemoryData;
    history(index: number, sessionId?: string): ({
        role: "system";
        content: string;
        cache?: boolean;
    } | {
        role: "user";
        name?: string;
        content: string | ({
            type: "text";
            text: string;
            cache?: boolean;
        } | {
            type: "image";
            mimeType: string;
            image: string;
            details?: "high" | "low" | "auto";
            cache?: boolean;
            optimize?: "quality" | "size" | "auto";
            altText?: string;
        } | {
            type: "audio";
            data: string;
            format?: AxAudioFormat;
            mimeType?: string;
            sampleRate?: number;
            channels?: number;
            cache?: boolean;
            transcription?: string;
            duration?: number;
        } | {
            type: "file";
            data: string;
            filename?: string;
            mimeType: string;
            cache?: boolean;
            extractedText?: string;
        } | {
            type: "file";
            fileUri: string;
            filename?: string;
            mimeType: string;
            cache?: boolean;
            extractedText?: string;
        } | {
            type: "url";
            url: string;
            cache?: boolean;
            cachedContent?: string;
            title?: string;
            description?: string;
        })[];
        cache?: boolean;
    } | {
        role: "assistant";
        content?: string;
        name?: string;
        functionCalls?: {
            id: string;
            type: "function";
            function: {
                name: string;
                params?: string | object;
            };
        }[];
        thought?: string;
        thoughtBlocks?: AxThoughtBlockItem[];
        audio?: {
            id: string;
            transcript?: string;
        };
        images?: AxChatImageOutput[];
        phase?: "commentary" | "final_answer";
        cache?: boolean;
    } | {
        role: "function";
        result: string;
        content?: AxFunctionResultContent;
        isError?: boolean;
        functionId: string;
        protocolResult?: {
            protocol: NonNullable<AxFunction["protocol"]>;
            value: unknown;
        };
        cache?: boolean;
    })[];
    getLast(sessionId?: string): {
        tags?: string[];
        role: AxChatRequest["chatPrompt"][number]["role"];
        updatable?: boolean;
        chat: {
            index: number;
            value: AxMemoryMessageValue;
        }[];
    } | undefined;
    reset(sessionId?: string): void;
}

/**
 * Internal implementation of AxStepContext.
 * Uses a pending mutations pattern: mutations are collected during a step
 * and consumed/applied at the next step boundary.
 */
declare class AxStepContextImpl implements AxStepContext {
    private _stepIndex;
    readonly maxSteps: number;
    private _functionsExecuted;
    private _lastFunctionCalls;
    private _usage;
    readonly state: Map<string, unknown>;
    private _pendingOptions;
    private _functionsToAdd;
    private _functionsToRemove;
    private _stopRequested;
    private _stopResultValues?;
    constructor(maxSteps: number);
    get stepIndex(): number;
    get isFirstStep(): boolean;
    get functionsExecuted(): ReadonlySet<string>;
    get lastFunctionCalls(): readonly AxFunctionCallRecord[];
    get usage(): Readonly<AxStepUsage>;
    setModel(model: string): void;
    setThinkingBudget(budget: AxAIServiceOptions['thinkingTokenBudget']): void;
    setTemperature(temperature: number): void;
    setMaxTokens(maxTokens: number): void;
    setOptions(options: Partial<AxAIServiceOptions & {
        modelConfig?: Partial<AxModelConfig>;
    }>): void;
    addFunctions(functions: AxInputFunctionType): void;
    removeFunctions(...names: string[]): void;
    stop(resultValues?: Record<string, unknown>): void;
    /** Reset per-step state at the beginning of a new step. */
    _beginStep(stepIndex: number): void;
    /** Record a function call that was executed during this step. */
    _recordFunctionCall(name: string, args: unknown, result: unknown): void;
    /** Accumulate token usage from a completed step. */
    _addUsage(promptTokens: number, completionTokens: number, totalTokens: number): void;
    /** Consume and clear pending options. Returns undefined if no pending options. */
    _consumePendingOptions(): Partial<AxAIServiceOptions & {
        modelConfig?: Partial<AxModelConfig>;
        model?: string;
    }> | undefined;
    /** Consume and clear pending functions to add. */
    _consumeFunctionsToAdd(): AxInputFunctionType | undefined;
    /** Consume and clear pending function names to remove. */
    _consumeFunctionsToRemove(): string[] | undefined;
    /** Check if stop was requested. */
    get _isStopRequested(): boolean;
    /** Get stop result values if any. */
    get _stopValues(): Record<string, unknown> | undefined;
}

declare class AxStopFunctionCallException extends Error {
    readonly calls: ReadonlyArray<{
        func: Readonly<AxFunction>;
        args: unknown;
        result: unknown;
    }>;
    constructor(calls: ReadonlyArray<{
        func: Readonly<AxFunction>;
        args: unknown;
        result: unknown;
    }>);
}
declare class AxFunctionError extends Error {
    private fields;
    constructor(fields: {
        field: string;
        message: string;
    }[]);
    getFields: () => {
        field: string;
        message: string;
    }[];
    toString(): string;
}
type AxChatResponseFunctionCall = {
    id: string;
    name: string;
    args: string;
};
declare class AxFunctionProcessor {
    private funcList;
    constructor(funcList: Readonly<AxFunction[]>);
    private executeFunction;
    executeWithDetails: <MODEL>(func: Readonly<AxChatResponseFunctionCall>, options?: Readonly<AxProgramForwardOptions<MODEL> & {
        traceId?: string;
        stopFunctionNames?: readonly string[];
        step?: AxStepContextImpl;
    }>) => Promise<{
        formatted: string;
        rawResult: unknown;
        parsedArgs: unknown;
    }>;
    execute: <MODEL>(func: Readonly<AxChatResponseFunctionCall>, options?: Readonly<AxProgramForwardOptions<MODEL> & {
        traceId?: string;
        stopFunctionNames?: readonly string[];
        step?: AxStepContextImpl;
    }>) => Promise<string>;
}
type AxInputFunctionType = (AxFunction | {
    toFunction: () => AxFunction | AxFunction[];
})[];

type AxPromptMetrics = {
    systemPromptCharacters: number;
    exampleChatContextCharacters: number;
    mutableChatContextCharacters: number;
    chatContextCharacters: number;
    totalPromptCharacters: number;
};

/**
 * Generic component-optimization surface that any AxProgrammable can implement.
 *
 * GEPA (and any future reflective optimizer) discovers what can be optimized by
 * calling `getOptimizableComponents()` on a program tree, mutates the returned
 * string values, and broadcasts the updates back via `applyOptimizedComponents()`.
 * The optimizer learns nothing about specific artifact kinds — each program owns
 * its own dispatch and tree traversal.
 */
type AxOptimizableValidator = (value: string) => true | string;
interface AxOptimizableComponent {
    /**
     * Globally-unique key within the program tree. Stable across calls.
     * Convention: `${programId}::${kind}` or `${programId}::${kind}:${subKey}`.
     */
    key: string;
    /**
     * Free-form hint for the reflection prompt. Not interpreted by the optimizer.
     * Examples: "instruction", "description", "fn-desc", "fn-name", "actor-tpl",
     * "primitive", or any user-defined kind.
     */
    kind: string;
    /** Current value snapshot. */
    current: string;
    /** Human-readable context shown to the reflection LLM. */
    description?: string;
    /** Free-form invariants the proposed value must respect. */
    constraints?: string;
    /** Stable identifier used to correlate runtime traces with this component. */
    traceId?: string;
    /** Other component keys that should be proposed and evaluated with this one. */
    dependsOn?: readonly string[];
    /** Literal tokens/placeholders that proposed values must preserve. */
    preserve?: readonly string[];
    /** Optional generic length hint for reflection and validation. */
    maxLength?: number;
    /** Optional generic format hint, e.g. "snake_case" or "handlebars-template". */
    format?: string;
    /**
     * Optional validator: returns `true` when the value is acceptable, or an
     * error message string the optimizer can show the LLM on re-roll.
     */
    validate?: AxOptimizableValidator;
}
/** Common validators reused by program-side component declarations. */
declare const axOptimizableValidators: {
    /** snake_case identifier, ≤ maxLen chars. */
    readonly snakeCaseIdentifier: (maxLen?: number) => AxOptimizableValidator;
    /** Must contain every placeholder in `required` (e.g. `['{{primitivesList}}']`). */
    readonly preservesPlaceholders: (required: readonly string[]) => AxOptimizableValidator;
    /** Non-empty after trim. */
    readonly nonEmpty: () => AxOptimizableValidator;
};

interface AxGEPAEvaluationBatch<Traj = any, Out = any> {
    outputs: Out[];
    scores: number[];
    scoreVectors?: Record<string, number>[];
    trajectories?: Traj[] | null;
}
interface AxGEPAAdapter<Datum = any, Traj = any, Out = any> {
    evaluate(batch: readonly Datum[], candidate: Readonly<Record<string, string>>, captureTraces?: boolean): Promise<AxGEPAEvaluationBatch<Traj, Out>> | AxGEPAEvaluationBatch<Traj, Out>;
    make_reflective_dataset(candidate: Readonly<Record<string, string>>, evalBatch: Readonly<AxGEPAEvaluationBatch<Traj, Out>>, componentsToUpdate: readonly string[]): Record<string, any[]>;
    propose_new_texts?: (candidate: Readonly<Record<string, string>>, reflectiveDataset: Readonly<Record<string, any[]>>, componentsToUpdate: readonly string[]) => Promise<Record<string, string>> | Record<string, string>;
}

type AxOptimizerLoggerData = {
    name: 'OptimizationStart';
    value: {
        optimizerType: string;
        config: Record<string, unknown>;
        exampleCount: number;
        validationCount: number;
    };
} | {
    name: 'RoundProgress';
    value: {
        round: number;
        totalRounds: number;
        currentScore: number;
        bestScore: number;
        configuration: Record<string, unknown>;
    };
} | {
    name: 'EarlyStopping';
    value: {
        reason: string;
        finalScore: number;
        round: number;
    };
} | {
    name: 'OptimizationComplete';
    value: {
        optimizerType?: string;
        bestScore: number;
        bestConfiguration: Record<string, unknown>;
        totalCalls?: number;
        successRate?: string;
        explanation?: string;
        recommendations?: string[];
        performanceAssessment?: string;
        stats: AxOptimizationStats;
    };
} | {
    name: 'ConfigurationProposal';
    value: {
        type: 'instructions' | 'demos' | 'general';
        proposals: string[] | Record<string, unknown>[];
        count: number;
    };
} | {
    name: 'BootstrappedDemos';
    value: {
        count: number;
        demos: unknown[];
    };
} | {
    name: 'BestConfigFound';
    value: {
        config: Record<string, unknown>;
        score: number;
    };
};
type AxOptimizerLoggerFunction = (data: AxOptimizerLoggerData) => void;

type AxExample$1 = Record<string, AxFieldValue>;
type AxTypedExample<IN = any> = IN & {
    [key: string]: AxFieldValue;
};
type AxMetricFn = <T = any>(arg0: Readonly<{
    prediction: T;
    example: AxExample$1;
}>) => number | Promise<number>;
type AxMetricFnArgs = Parameters<AxMetricFn>[0];
type AxMultiMetricFn = <T = any>(arg0: Readonly<{
    prediction: T;
    example: AxExample$1;
}>) => Record<string, number> | Promise<Record<string, number>>;
interface AxOptimizationProgress {
    round: number;
    totalRounds: number;
    currentScore: number;
    bestScore: number;
    tokensUsed: number;
    timeElapsed: number;
    successfulExamples: number;
    totalExamples: number;
    currentConfiguration?: Record<string, unknown>;
    bestConfiguration?: Record<string, unknown>;
    convergenceInfo?: {
        improvement: number;
        stagnationRounds: number;
        isConverging: boolean;
    };
}
interface AxCostTracker {
    trackTokens(count: number, model: string): void;
    getCurrentCost(): number;
    getTokenUsage(): Record<string, number>;
    getTotalTokens(): number;
    isLimitReached(): boolean;
    reset(): void;
}
interface AxCostTrackerOptions {
    costPerModel?: Record<string, number>;
    maxCost?: number;
    maxTokens?: number;
}
interface AxOptimizationCheckpoint {
    version: string;
    timestamp: number;
    optimizerType: string;
    optimizerConfig: Record<string, unknown>;
    currentRound: number;
    totalRounds: number;
    bestScore: number;
    bestConfiguration?: Record<string, unknown>;
    scoreHistory: number[];
    configurationHistory: Record<string, unknown>[];
    stats: AxOptimizationStats;
    optimizerState: Record<string, unknown>;
    examples: readonly AxExample$1[];
}
interface AxGEPABootstrapOptions {
    scoreThreshold?: number;
    maxBootstrapDemos?: number;
    maxBootstrapMetricCalls?: number;
}
type AxCheckpointSaveFn = (checkpoint: Readonly<AxOptimizationCheckpoint>) => Promise<string>;
type AxCheckpointLoadFn = (checkpointId: string) => Promise<AxOptimizationCheckpoint | null>;
interface AxOptimizationStats {
    totalCalls: number;
    successfulDemos: number;
    estimatedTokenUsage: number;
    earlyStopped: boolean;
    earlyStopping?: {
        bestScoreRound: number;
        patienceExhausted: boolean;
        reason: string;
    };
    bestScore: number;
    bestConfiguration?: Record<string, unknown>;
    resourceUsage: {
        totalTokens: number;
        totalTime: number;
        avgLatencyPerEval: number;
        peakMemoryUsage?: number;
        costByModel: Record<string, number>;
    };
    convergenceInfo: {
        converged: boolean;
        finalImprovement: number;
        stagnationRounds: number;
        convergenceThreshold: number;
    };
    evaluationBreakdown?: {
        trainingScore: number;
        validationScore: number;
        crossValidationScores?: number[];
        standardDeviation?: number;
    };
}
type AxOptimizerArgs = {
    studentAI: AxAIService;
    teacherAI?: AxAIService;
    /**
     * AI service options for the optimizer's teacher calls: GEPA feedback and
     * proposals, the ACE reflector and curator, and BootstrapFewShot demo runs.
     * They also apply when those calls fall back to `studentAI`. Set
     * `useExpensiveModel: 'yes'` to use a teacher model marked `isExpensive`.
     */
    teacherOptions?: AxAIServiceOptions;
    numCandidates?: number;
    initTemperature?: number;
    numTrials?: number;
    minibatch?: boolean;
    minibatchSize?: number;
    minibatchFullEvalSteps?: number;
    programAwareProposer?: boolean;
    dataAwareProposer?: boolean;
    viewDataBatchSize?: number;
    tipAwareProposer?: boolean;
    fewshotAwareProposer?: boolean;
    earlyStoppingTrials?: number;
    minImprovementThreshold?: number;
    sampleCount?: number;
    resultPicker?: AxResultPickerFunction<any>;
    optimizeTopP?: boolean;
    minSuccessRate?: number;
    targetScore?: number;
    onProgress?: (progress: Readonly<AxOptimizationProgress>) => void;
    onEarlyStop?: (reason: string, stats: Readonly<AxOptimizationStats>) => void;
    costTracker?: AxCostTracker;
    checkpointSave?: AxCheckpointSaveFn;
    checkpointLoad?: AxCheckpointLoadFn;
    checkpointInterval?: number;
    resumeFromCheckpoint?: string;
    logger?: AxLoggerFunction;
    verbose?: boolean;
    seed?: number;
    debugOptimizer?: boolean;
    optimizerLogger?: (data: AxOptimizerLoggerData) => void;
};
interface AxCompileOptions {
    maxIterations?: number;
    earlyStoppingPatience?: number;
    verbose?: boolean;
    maxDemos?: number;
    auto?: 'light' | 'medium' | 'heavy';
    overrideTargetScore?: number;
    overrideCostTracker?: AxCostTracker;
    overrideTeacherAI?: AxAIService;
    overrideOnProgress?: (progress: Readonly<AxOptimizationProgress>) => void;
    overrideOnEarlyStop?: (reason: string, stats: Readonly<AxOptimizationStats>) => void;
    overrideCheckpointSave?: AxCheckpointSaveFn;
    overrideCheckpointLoad?: AxCheckpointLoadFn;
    overrideCheckpointInterval?: number;
    saveCheckpointOnComplete?: boolean;
    gepaAdapter?: AxGEPAAdapter<any, any, any>;
    bootstrap?: boolean | AxGEPABootstrapOptions;
    validationExamples?: readonly AxTypedExample<any>[];
    feedbackExamples?: readonly AxTypedExample<any>[];
    feedbackFn?: (args: Readonly<{
        prediction: unknown;
        example: AxExample$1;
        componentId?: string;
    }>) => string | string[] | undefined;
    skipPerfectScore?: boolean;
    perfectScore?: number;
    maxMetricCalls?: number;
    /**
     * Custom labels to include in OpenTelemetry metrics.
     * These labels are merged with axGlobals.customLabels and AI service customLabels.
     */
    customLabels?: Record<string, string>;
}

type AxGEPAComponentTarget = {
    id: string;
    kind: string;
    current: string;
    description?: string;
    constraints?: string;
    traceId?: string;
    dependsOn?: readonly string[];
    preserve?: readonly string[];
    maxLength?: number;
    format?: string;
    validate?: (value: string) => true | string;
};

type AxGEPAComponentBanditState = {
    proposals: number;
    accepts: number;
    lastAcceptIter: number;
    stagnation: number;
};
declare class AxGEPAComponentSelector {
    private readonly targets;
    private readonly states;
    constructor(targets: readonly AxGEPAComponentTarget[], initialState?: Readonly<Record<string, AxGEPAComponentBanditState>>);
    getState(id: string): AxGEPAComponentBanditState | undefined;
    snapshot(): Record<string, AxGEPAComponentBanditState>;
    pick(iteration: number, rand: () => number): AxGEPAComponentTarget;
    recordProposal(id: string): void;
    recordResult(id: string, accepted: boolean, iteration: number): void;
}

interface AxOptimizerMetricsConfig {
    enabled: boolean;
    enabledCategories: ('optimization' | 'convergence' | 'resource_usage' | 'teacher_student' | 'checkpointing' | 'pareto')[];
    maxLabelLength: number;
    samplingRate: number;
}
declare const axDefaultOptimizerMetricsConfig: AxOptimizerMetricsConfig;
interface AxOptimizerMetricsInstruments {
    optimizationLatencyHistogram?: Histogram;
    optimizationRequestsCounter?: Counter;
    optimizationErrorsCounter?: Counter;
    convergenceRoundsHistogram?: Histogram;
    convergenceScoreGauge?: Gauge;
    convergenceImprovementGauge?: Gauge;
    stagnationRoundsGauge?: Gauge;
    earlyStoppingCounter?: Counter;
    tokenUsageCounter?: Counter;
    costUsageCounter?: Counter;
    memoryUsageGauge?: Gauge;
    optimizationDurationHistogram?: Histogram;
    teacherStudentUsageCounter?: Counter;
    teacherStudentLatencyHistogram?: Histogram;
    teacherStudentScoreImprovementGauge?: Gauge;
    checkpointSaveCounter?: Counter;
    checkpointLoadCounter?: Counter;
    checkpointSaveLatencyHistogram?: Histogram;
    checkpointLoadLatencyHistogram?: Histogram;
    paretoOptimizationsCounter?: Counter;
    paretoFrontSizeHistogram?: Histogram;
    paretoHypervolumeGauge?: Gauge;
    paretoSolutionsGeneratedHistogram?: Histogram;
    programInputFieldsGauge?: Gauge;
    programOutputFieldsGauge?: Gauge;
    examplesCountGauge?: Gauge;
    validationSetSizeGauge?: Gauge;
    evaluationLatencyHistogram?: Histogram;
    demoGenerationLatencyHistogram?: Histogram;
    metricComputationLatencyHistogram?: Histogram;
    optimizerTypeGauge?: Gauge;
    targetScoreGauge?: Gauge;
    maxRoundsGauge?: Gauge;
}
declare const axUpdateOptimizerMetricsConfig: (config: Readonly<Partial<AxOptimizerMetricsConfig>>) => void;
declare const axGetOptimizerMetricsConfig: () => AxOptimizerMetricsConfig;
interface AxOptimizerResult<OUT> {
    demos?: AxProgramDemos<any, OUT>[];
    stats: AxOptimizationStats;
    bestScore: number;
    finalConfiguration?: Record<string, unknown>;
    scoreHistory?: number[];
    configurationHistory?: Record<string, unknown>[];
    optimizedProgram?: AxOptimizedProgram<OUT>;
}
interface AxOptimizedProgram<OUT = any> {
    bestScore: number;
    stats: AxOptimizationStats;
    /**
     * Generic component map produced by reflective optimizers (e.g. GEPA).
     * Keys follow the `${programId}::${kind}[:${subKey}]` grammar from
     * `AxOptimizableComponent`. Applied via `program.applyOptimizedComponents`.
     */
    componentMap?: Record<string, string>;
    selectorState?: Record<string, AxGEPAComponentBanditState>;
    demos?: AxProgramDemos<any, OUT>[];
    modelConfig?: {
        temperature?: number;
        maxTokens?: number;
        topP?: number;
        topK?: number;
        frequencyPenalty?: number;
        presencePenalty?: number;
        stop?: string | string[];
        [key: string]: unknown;
    };
    optimizerType: string;
    optimizationTime: number;
    totalRounds: number;
    converged: boolean;
    scoreHistory?: number[];
    configurationHistory?: Record<string, unknown>[];
    artifactFormatVersion?: number;
    instructionSchema?: string;
    applyTo<IN, T extends AxGenOut>(program: AxGen<IN, T>): void;
}
type AxSerializedOptimizedProgram<OUT = any> = Omit<AxOptimizedProgram<OUT>, 'applyTo'>;
declare class AxOptimizedProgramImpl<OUT = any> implements AxOptimizedProgram<OUT> {
    readonly bestScore: number;
    readonly stats: AxOptimizationStats;
    readonly componentMap?: Record<string, string>;
    readonly selectorState?: Record<string, AxGEPAComponentBanditState>;
    readonly demos?: AxProgramDemos<any, OUT>[];
    readonly examples?: AxExample$1[];
    readonly modelConfig?: {
        temperature?: number;
        maxTokens?: number;
        topP?: number;
        topK?: number;
        frequencyPenalty?: number;
        presencePenalty?: number;
        stop?: string | string[];
        [key: string]: unknown;
    };
    readonly optimizerType: string;
    readonly optimizationTime: number;
    readonly totalRounds: number;
    readonly converged: boolean;
    readonly scoreHistory?: number[];
    readonly configurationHistory?: Record<string, unknown>[];
    readonly artifactFormatVersion?: number;
    readonly instructionSchema?: string;
    constructor(config: {
        bestScore: number;
        stats: AxOptimizationStats;
        componentMap?: Record<string, string>;
        selectorState?: Record<string, AxGEPAComponentBanditState>;
        demos?: AxProgramDemos<any, OUT>[];
        examples?: AxExample$1[];
        modelConfig?: AxOptimizedProgram<OUT>['modelConfig'];
        optimizerType: string;
        optimizationTime: number;
        totalRounds: number;
        converged: boolean;
        scoreHistory?: number[];
        configurationHistory?: Record<string, unknown>[];
        artifactFormatVersion?: number;
        instructionSchema?: string;
    });
    applyTo<IN, T extends AxGenOut>(program: AxGen<IN, T>): void;
}
declare function axSerializeOptimizedProgram<OUT = any>(optimizedProgram: Readonly<AxOptimizedProgram<OUT>>): AxSerializedOptimizedProgram<OUT>;
declare function axDeserializeOptimizedProgram<OUT = any>(serialized: Readonly<AxSerializedOptimizedProgram<OUT>>): AxOptimizedProgramImpl<OUT>;
interface AxParetoResult<OUT = any> extends AxOptimizerResult<OUT> {
    paretoFront: ReadonlyArray<{
        demos: readonly AxProgramDemos<any, OUT>[];
        scores: Readonly<Record<string, number>>;
        configuration: Readonly<Record<string, unknown>>;
        dominatedSolutions: number;
    }>;
    hypervolume?: number;
    paretoFrontSize: number;
    convergenceMetrics?: Record<string, number>;
}
/**
 * Interface for optimizing AI programs through automated prompt tuning.
 *
 * Optimizers improve program performance by finding optimal demonstrations (few-shot examples)
 * that guide the AI toward better outputs. The optimization process:
 *
 * 1. Runs the program on training examples
 * 2. Evaluates outputs using the metric function
 * 3. Selects high-scoring input/output pairs as demonstrations
 * 4. Iterates to find the best demonstration set
 *
 * @example Basic optimization
 * ```typescript
 * const optimizer = new AxBootstrapFewShot({ maxDemos: 4 });
 *
 * const result = await optimizer.compile(
 *   program,
 *   trainingExamples,
 *   ({ prediction, example }) => prediction.answer === example.expectedAnswer ? 1 : 0
 * );
 *
 * // Apply optimized demos to program
 * program.setDemos(result.demos);
 * ```
 */
interface AxOptimizer {
    /**
     * Optimize a program using the provided training examples and metric function.
     *
     * The optimizer runs the program on examples, scores the outputs, and builds
     * a set of demonstrations that improve program performance. The process is
     * automatic - you provide the data and metric, the optimizer does the rest.
     *
     * **Metric Function:**
     * The metric function evaluates how well the program's output matches expectations.
     * It receives the prediction and original example, and should return a score
     * between 0 (worst) and 1 (best).
     *
     * @param program - The AxGen program to optimize. The optimizer will call
     *   `.forward()` on this program during training.
     *
     * @param examples - Training examples with input values. Examples are automatically
     *   split into training and validation sets. Each example should have the input
     *   fields required by the program's signature.
     *
     * @param metricFn - Function that scores program outputs. Called with:
     *   - `prediction`: The program's output for this example
     *   - `example`: The original input example (useful if it contains expected outputs)
     *   - Returns: Number between 0 (bad) and 1 (perfect)
     *
     * @param options - Optional configuration:
     *   - `ai`: AI service to use (required if not set on program)
     *   - `valSet`: Custom validation set (otherwise auto-split from examples)
     *   - `trainSplit`: Fraction of examples for training (default: 0.8)
     *
     * @returns Promise resolving to optimization results including:
     *   - `demos`: Optimized demonstrations to use with the program
     *   - `stats`: Training/validation scores and iteration counts
     *
     * @example Exact match metric
     * ```typescript
     * const result = await optimizer.compile(
     *   qa,
     *   examples,
     *   ({ prediction, example }) => {
     *     return prediction.answer.toLowerCase() === example.expectedAnswer.toLowerCase() ? 1 : 0;
     *   }
     * );
     * ```
     *
     * @example Semantic similarity metric
     * ```typescript
     * const result = await optimizer.compile(
     *   summarizer,
     *   examples,
     *   async ({ prediction, example }) => {
     *     const similarity = await computeCosineSimilarity(
     *       await embed(prediction.summary),
     *       await embed(example.referenceSummary)
     *     );
     *     return similarity; // 0-1 based on embedding similarity
     *   }
     * );
     * ```
     *
     * @example Partial credit metric
     * ```typescript
     * const result = await optimizer.compile(
     *   extractor,
     *   examples,
     *   ({ prediction, example }) => {
     *     const expectedKeywords = example.keywords;
     *     const foundKeywords = prediction.keywords;
     *     const matches = expectedKeywords.filter(k => foundKeywords.includes(k));
     *     return matches.length / expectedKeywords.length; // Fraction found
     *   }
     * );
     * ```
     */
    compile<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise<AxOptimizerResult<OUT>>;
    /**
     * Optimize a program with real-time streaming updates
     * @param program The program to optimize
     * @param examples Training examples
     * @param metricFn Evaluation metric function
     * @param options Optional configuration options
     * @returns Async iterator yielding optimization progress
     */
    compileStream?<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn, options?: AxCompileOptions): AsyncIterableIterator<AxOptimizationProgress>;
    /**
     * Multi-objective optimization using Pareto frontier
     * @param program The program to optimize
     * @param examples Training examples
     * @param metricFn Multi-objective metric function
     * @param options Optional configuration options
     * @returns Pareto optimization result
     */
    compilePareto?<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMultiMetricFn, options?: AxCompileOptions): Promise<AxParetoResult<OUT>>;
    /**
     * Get current optimization statistics
     * @returns Current optimization statistics
     */
    getStats(): AxOptimizationStats;
    /**
     * Cancel ongoing optimization gracefully
     * @returns Promise that resolves when cancellation is complete
     */
    cancel?(): Promise<void>;
    /**
     * Reset optimizer state for reuse with different programs
     */
    reset?(): void;
    /**
     * Get optimizer-specific configuration
     * @returns Current optimizer configuration
     */
    getConfiguration?(): Record<string, unknown>;
    /**
     * Update optimizer configuration
     * @param config New configuration to merge with existing
     */
    updateConfiguration?(config: Readonly<Record<string, unknown>>): void;
    /**
     * Validate that the optimizer can handle the given program
     * @param program Program to validate
     * @returns Validation result with any issues found
     */
    validateProgram?<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>): {
        isValid: boolean;
        issues: string[];
        suggestions: string[];
    };
}
interface AxBootstrapOptimizerOptions {
    maxRounds?: number;
    maxExamples?: number;
    maxDemos?: number;
    batchSize?: number;
    earlyStoppingPatience?: number;
    teacherAI?: AxAIService;
    costMonitoring?: boolean;
    maxTokensPerGeneration?: number;
    verboseMode?: boolean;
    debugMode?: boolean;
    adaptiveBatching?: boolean;
    dynamicTemperature?: boolean;
    qualityThreshold?: number;
    diversityWeight?: number;
}
declare class AxDefaultCostTracker implements AxCostTracker {
    private tokenUsage;
    private totalTokens;
    private readonly costPerModel;
    private readonly maxCost?;
    private readonly maxTokens?;
    constructor(options?: AxCostTrackerOptions);
    trackTokens(count: number, model: string): void;
    getCurrentCost(): number;
    getTokenUsage(): Record<string, number>;
    getTotalTokens(): number;
    isLimitReached(): boolean;
    reset(): void;
}
/**
 * Abstract base class for optimizers that provides common functionality
 * and standardized handling of AxOptimizerArgs
 */
declare abstract class AxBaseOptimizer implements AxOptimizer {
    protected readonly studentAI: AxAIService;
    protected readonly teacherAI?: AxAIService;
    protected readonly teacherOptions?: AxAIServiceOptions;
    protected readonly targetScore?: number;
    protected readonly minSuccessRate?: number;
    protected readonly onProgress?: (progress: Readonly<AxOptimizationProgress>) => void;
    protected readonly onEarlyStop?: (reason: string, stats: Readonly<AxOptimizationStats>) => void;
    protected readonly costTracker?: AxCostTracker;
    protected readonly seed?: number;
    protected readonly checkpointSave?: AxCheckpointSaveFn;
    protected readonly checkpointLoad?: AxCheckpointLoadFn;
    protected readonly checkpointInterval?: number;
    protected readonly resumeFromCheckpoint?: string;
    protected readonly logger?: AxLoggerFunction;
    protected readonly verbose?: boolean;
    protected readonly debugOptimizer: boolean;
    protected readonly optimizerLogger?: AxOptimizerLoggerFunction;
    protected currentRound: number;
    private scoreHistory;
    private configurationHistory;
    protected stats: AxOptimizationStats;
    private resultExplainer?;
    constructor(args: Readonly<AxOptimizerArgs>);
    /**
     * Get merged custom labels from globals, AI services, and compile options.
     * Labels are merged with later sources overriding earlier ones.
     */
    protected getMergedCustomLabels(options?: AxCompileOptions): Record<string, string>;
    protected getMetricsInstruments(): AxOptimizerMetricsInstruments | undefined;
    /**
     * Initialize the result explanation generator
     * FIXME: Disabled due to circular dependency with ax() function
     */
    private initializeResultExplainer;
    /**
     * Initialize the optimization statistics structure
     */
    protected initializeStats(): AxOptimizationStats;
    /**
     * Set up reproducible random seed if provided
     */
    protected setupRandomSeed(): void;
    /**
     * Check if optimization should stop early due to cost limits
     */
    protected checkCostLimits(): boolean;
    /**
     * Check if target score has been reached
     */
    protected checkTargetScore(currentScore: number): boolean;
    /**
     * Update resource usage statistics
     */
    protected updateResourceUsage(startTime: number, tokensUsed?: number): void;
    /**
     * Trigger early stopping with appropriate callbacks
     */
    protected triggerEarlyStopping(reason: string, bestScoreRound: number, options?: AxCompileOptions): void;
    /**
     * Validate that examples meet minimum requirements for optimization
     * @param examples Examples to validate
     * @param requireSplit Whether this optimizer requires train/validation split (default: true)
     * @throws Error if examples don't meet minimum requirements
     */
    protected validateExamples<IN>(examples: readonly AxTypedExample<IN>[], requireSplit?: boolean): void;
    /**
     * Get the AI service to use for a specific task, preferring teacher when available
     * @param preferTeacher Whether to prefer teacher AI over student AI
     * @param options Optional compile options that may override teacher AI
     * @returns The appropriate AI service to use
     */
    protected getAIService(preferTeacher?: boolean, options?: AxCompileOptions): AxAIService;
    /**
     * Check if teacher AI is available (including overrides)
     * @param options Optional compile options that may override teacher AI
     * @returns True if teacher AI is configured or overridden
     */
    protected hasTeacherAI(options?: AxCompileOptions): boolean;
    /**
     * Get teacher AI if available, otherwise return student AI
     * @param options Optional compile options that may override teacher AI
     * @returns Teacher AI if available, otherwise student AI
     */
    protected getTeacherOrStudentAI(options?: AxCompileOptions): AxAIService;
    /**
     * Execute a task with teacher AI if available, otherwise use student AI
     * @param task Function that takes an AI service and returns a promise
     * @param preferTeacher Whether to prefer teacher AI (default: true)
     * @param options Optional compile options that may override teacher AI
     * @returns Result of the task execution
     */
    protected executeWithTeacher<T>(task: (ai: AxAIService) => Promise<T>, preferTeacher?: boolean, options?: AxCompileOptions): Promise<T>;
    /**
     * Abstract method that must be implemented by concrete optimizers
     */
    abstract compile<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise<AxOptimizerResult<OUT>>;
    /**
     * Optimize a program with real-time streaming updates
     * @param program The program to optimize
     * @param examples Training examples
     * @param metricFn Evaluation metric function
     * @param options Optional configuration options
     * @returns Async iterator yielding optimization progress
     */
    compileStream<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn, options?: AxCompileOptions): AsyncIterableIterator<AxOptimizationProgress>;
    /**
     * Multi-objective optimization using Pareto frontier
     * Default implementation that leverages the single-objective compile method
     * @param program The program to optimize
     * @param examples Training examples
     * @param metricFn Multi-objective metric function that returns multiple scores
     * @param options Optional configuration options
     * @returns Pareto optimization result with frontier of non-dominated solutions
     */
    compilePareto<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMultiMetricFn, options?: AxCompileOptions): Promise<AxParetoResult<OUT>>;
    /**
     * Generate solutions using different weighted combinations of objectives
     */
    private generateWeightedSolutions;
    /**
     * Generate solutions using constraint-based optimization
     */
    private generateConstraintSolutions;
    /**
     * Generate different weight combinations for objectives
     */
    private generateWeightCombinations;
    /**
     * Evaluate a single-objective result with multi-objective metrics
     */
    private evaluateWithMultiObjective;
    /**
     * Find the Pareto frontier from a set of solutions
     */
    private findParetoFrontier;
    /**
     * Check if solution A dominates solution B
     * A dominates B if A is better or equal in all objectives and strictly better in at least one
     */
    private dominates;
    /**
     * Calculate hypervolume of the Pareto frontier
     * Simplified implementation using reference point at origin
     */
    private calculateHypervolume;
    /**
     * Save current optimization state to checkpoint
     */
    protected saveCheckpoint(optimizerType: string, optimizerConfig: Record<string, unknown>, bestScore: number, bestConfiguration?: Record<string, unknown>, optimizerState?: Record<string, unknown>, options?: AxCompileOptions): Promise<string | undefined>;
    /**
     * Load optimization state from checkpoint
     */
    protected loadCheckpoint(checkpointId: string, options?: AxCompileOptions): Promise<AxOptimizationCheckpoint | null>;
    /**
     * Restore optimizer state from checkpoint
     */
    protected restoreFromCheckpoint(checkpoint: Readonly<AxOptimizationCheckpoint>): void;
    /**
     * Check if checkpoint should be saved
     */
    protected shouldSaveCheckpoint(round: number, options?: AxCompileOptions): boolean;
    /**
     * Update optimization progress and handle checkpointing
     */
    protected updateOptimizationProgress(round: number, score: number, configuration: Record<string, unknown>, optimizerType: string, optimizerConfig: Record<string, unknown>, bestScore: number, bestConfiguration?: Record<string, unknown>, optimizerState?: Record<string, unknown>, options?: AxCompileOptions): Promise<void>;
    /**
     * Save final checkpoint on completion
     */
    protected saveFinalCheckpoint(optimizerType: string, optimizerConfig: Record<string, unknown>, bestScore: number, bestConfiguration?: Record<string, unknown>, optimizerState?: Record<string, unknown>, options?: AxCompileOptions): Promise<void>;
    /**
     * Get the logger function with fallback hierarchy:
     * 1. Explicit logger passed to optimizer
     * 2. Logger from student AI service
     * 3. undefined if verbose is false
     */
    protected getLogger(options?: AxCompileOptions): AxLoggerFunction | undefined;
    /**
     * Check if logging is enabled based on verbose settings
     */
    protected isLoggingEnabled(options?: AxCompileOptions): boolean;
    /**
     * Record optimization start metrics
     */
    protected recordOptimizationStart(optimizerType: string, programSignature?: string, options?: AxCompileOptions): void;
    /**
     * Record optimization completion metrics
     */
    protected recordOptimizationComplete(duration: number, success: boolean, optimizerType: string, programSignature?: string, options?: AxCompileOptions): void;
    /**
     * Record convergence metrics
     */
    protected recordConvergenceMetrics(rounds: number, currentScore: number, improvement: number, stagnationRounds: number, optimizerType: string, options?: AxCompileOptions): void;
    /**
     * Record early stopping metrics
     */
    protected recordEarlyStoppingMetrics(reason: string, optimizerType: string, options?: AxCompileOptions): void;
    /**
     * Record teacher-student interaction metrics
     */
    protected recordTeacherStudentMetrics(latency: number, scoreImprovement: number, optimizerType: string, options?: AxCompileOptions): void;
    /**
     * Record checkpoint metrics
     */
    protected recordCheckpointMetrics(operation: 'save' | 'load', latency: number, success: boolean, optimizerType: string, options?: AxCompileOptions): void;
    /**
     * Record Pareto optimization metrics
     */
    protected recordParetoMetrics(frontSize: number, solutionsGenerated: number, optimizerType: string, hypervolume?: number, options?: AxCompileOptions): void;
    /**
     * Record performance metrics
     */
    protected recordPerformanceMetrics(metricType: 'evaluation' | 'demo_generation' | 'metric_computation', duration: number, optimizerType: string, options?: AxCompileOptions): void;
    protected isOptimizerLoggingEnabled(options?: AxCompileOptions): boolean;
    protected getOptimizerLogger(options?: AxCompileOptions): AxOptimizerLoggerFunction | undefined;
    getStats(): AxOptimizationStats;
    protected explainOptimizationResults(bestScore: number, bestConfiguration?: Record<string, unknown>, _options?: AxCompileOptions): Promise<{
        humanExplanation: string;
        recommendations: string[];
        performanceAssessment: string;
    } | undefined>;
    /**
     * Log human-readable optimization completion message
     */
    protected logOptimizationComplete(optimizerType: string, bestScore: number, bestConfiguration?: Record<string, unknown>, options?: AxCompileOptions, explanation?: {
        humanExplanation: string;
        recommendations: string[];
        performanceAssessment: string;
    }): Promise<void>;
    reset(): void;
}

declare class AxProgram<IN = any, OUT = any> implements AxUsable, AxTunable<IN, OUT> {
    protected signature: AxSignature;
    protected sigHash: string;
    protected examples?: OUT[];
    protected examplesOptions?: AxSetExamplesOptions;
    protected demos?: OUT[];
    protected trace?: OUT;
    protected usage: AxProgramUsage[];
    protected traceLabel?: string;
    private key;
    private children;
    private childNames;
    private childCount;
    constructor(signature: string | Readonly<AxSignatureConfig> | Readonly<AxSignature> | undefined, options?: Readonly<AxProgramOptions>);
    getSignature(): AxSignature;
    setSignature(signature: string | Readonly<AxSignatureConfig> | Readonly<AxSignature>): void;
    setDescription(description: string): void;
    private updateSignatureHash;
    getId(): string;
    register(prog: Readonly<AxTunable<IN, OUT> & AxUsable>, name?: string): void;
    setId(id: string): void;
    setExamples(examples: Readonly<AxProgramExamples<IN, OUT>>, options?: Readonly<AxSetExamplesOptions>): void;
    getTraces(): AxProgramTrace<IN, OUT>[];
    getUsage(): AxProgramUsage[];
    getChatLog(): readonly AxChatLogEntry[];
    resetUsage(): void;
    private static _propagating;
    setDemos(demos: readonly AxProgramDemos<IN, OUT>[], options?: {
        modelConfig?: Record<string, unknown>;
    }): void;
    /**
     * Returns all programs in the hierarchy with their IDs and signatures.
     * Use this to discover the IDs needed for `setDemos()`.
     *
     * Equivalent to DSPy's `named_parameters()`.
     *
     * @example
     * ```ts
     * agent.setId('qa');
     * console.log(agent.namedPrograms());
     * // [
     * //   { id: 'qa.actor', signature: '... -> javascriptCode' },
     * //   { id: 'qa.responder', signature: '... -> answer' },
     * // ]
     * ```
     */
    namedPrograms(): Array<{
        id: string;
        signature?: string;
    }>;
    namedProgramInstances(): AxNamedProgramInstance<IN, OUT>[];
    applyOptimization(optimizedProgram: AxOptimizedProgram<OUT>): void;
    /**
     * Walks the program tree and emits one `AxOptimizableComponent` per
     * string-valued artifact reachable from this node. Subclasses override
     * `localOptimizableComponents()` to add their own; tree traversal is
     * handled here so callers never need to recurse.
     */
    getOptimizableComponents(): readonly AxOptimizableComponent[];
    /**
     * Components owned directly by this node (excluding children). Subclasses
     * override this to append their own kinds (e.g. AxGen adds `fn-desc:*`).
     */
    protected localOptimizableComponents(): readonly AxOptimizableComponent[];
    /**
     * Broadcast component updates across this subtree. Each node filters keys
     * belonging to itself and dispatches via `applyLocalOptimizedComponents`.
     */
    applyOptimizedComponents(updates: Readonly<Record<string, string>>): void;
    /**
     * Apply only this node's own components. Subclasses override to add their
     * own dispatch (e.g. AxGen handles `fn-desc:*` and `fn-name:*`).
     */
    protected applyLocalOptimizedComponents(updates: Readonly<Record<string, string>>): void;
}

type AxFieldProcessorProcess = (value: AxFieldValue, context?: Readonly<{
    values?: AxGenOut;
    sessionId?: string;
    done?: boolean;
}>) => unknown | Promise<unknown>;
type AxStreamingFieldProcessorProcess = (value: string, context?: Readonly<{
    values?: AxGenOut;
    sessionId?: string;
    done?: boolean;
}>) => unknown | Promise<unknown>;
interface AxFieldProcessor {
    field: Readonly<AxField>;
    /**
     * Process the field value and return a new value (or undefined if no update is needed).
     * The returned value may be merged back into memory.
     * @param value - The current field value.
     * @param context - Additional context (e.g. memory and session id).
     */
    process: AxFieldProcessorProcess | AxStreamingFieldProcessorProcess;
}

type AxGenerateResult<OUT> = OUT & {
    thought?: string;
};
interface AxStreamingEvent<T> {
    event: 'delta' | 'done' | 'error';
    data: {
        contentDelta?: string;
        partialValues?: Partial<T>;
        error?: string;
        functions?: AxChatResponseFunctionCall[];
    };
}
declare class AxGen<IN = any, OUT extends AxGenOut = any> extends AxProgram<IN, OUT> implements AxProgrammable<IN, OUT> {
    clone: () => AxGen<IN, OUT>;
    private promptTemplate;
    private asserts;
    private streamingAsserts;
    private options?;
    private functions;
    private functionComponentIds;
    private fieldProcessors;
    private streamingFieldProcessors;
    private excludeContentFromTrace;
    private thoughtFieldName;
    private signatureToolCallingManager?;
    private structuredOutputFunctionFallback;
    private structuredOutputRung?;
    private activeAbortControllers;
    private _stopRequested;
    private chatLog;
    constructor(signature: string | Readonly<AxSignatureConfig> | Readonly<AxSignature<IN & Record<string, any>, OUT>>, options?: Readonly<AxProgramForwardOptions<any>>);
    /**
     * Stops an in-flight generation. Causes `forward()` / `streamingForward()`
     * to throw `AxAIServiceAbortedError`.
     */
    stop(): void;
    setInstruction(instruction: string): void;
    getInstruction(): string | undefined;
    clearInstruction(): void;
    private static stableFunctionComponentBase;
    private ensureFunctionComponentIds;
    private validateFunctionNameCandidate;
    protected localOptimizableComponents(): readonly AxOptimizableComponent[];
    protected applyLocalOptimizedComponents(updates: Readonly<Record<string, string>>): void;
    private getEffectiveContextCache;
    private renderPromptWithMetricsForInternalUse;
    private renderPromptForInternalUse;
    /** @internal */
    _measurePromptCharsForInternalUse(ai: Readonly<AxAIService>, values: IN, options?: Readonly<Partial<Omit<AxProgramForwardOptions<any>, 'functions'>>>): Promise<AxPromptMetrics>;
    private getSignatureName;
    private getMetricsInstruments;
    private getEffectiveMeter;
    private getMergedCustomLabels;
    updateMeter(meter?: Meter): void;
    private createStates;
    addAssert(fn: AxAssertion<OUT>['fn'], message?: string): void;
    addStreamingAssert(fieldName: keyof OUT, fn: AxStreamingAssertion['fn'], message?: string): void;
    private addFieldProcessorInternal;
    addStreamingFieldProcessor<K extends keyof OUT>(fieldName: K, fn: (value: string, context?: {
        values?: OUT;
        sessionId?: string;
        done?: boolean;
    }) => unknown | Promise<unknown>): void;
    addFieldProcessor<K extends keyof OUT>(fieldName: K, fn: (value: OUT[K], context?: {
        values?: OUT;
        sessionId?: string;
        done?: boolean;
    }) => unknown | Promise<unknown>): void;
    /**
     * Get the normalized chat log from the last forward() call.
     * One entry per AI chat round-trip, with roles normalized to
     * system/user/assistant/tool and inline XML for thinking and tool calls.
     */
    getChatLog(): readonly AxChatLogEntry[];
    private captureChatResponseLogMetadata;
    private applyChatResponseLogMetadata;
    /**
     * Normalize internal chatPrompt messages to standard training format.
     * If functions are provided, appends a <tools> JSON block to the system prompt.
     */
    private normalizeChatMessages;
    /**
     * Build an assistant AxChatLogMessage from a response result.
     */
    private buildAssistantLogMessage;
    private forwardSendRequest;
    private forwardCore;
    private _forward2;
    /**
     * Validate input values against field constraints
     * @throws ValidationError if any input value fails validation
     */
    private validateInputs;
    /**
     * Recursively validate object field values
     */
    private validateObjectFields;
    _forward1(ai: Readonly<AxAIService>, values: IN, options: Readonly<AxProgramForwardOptions<any>>): AxGenStreamingOut<OUT>;
    /**
     * Executes the generator with the given AI service and input values.
     *
     * This is the main entry point for running an AI generation. The execution pipeline:
     * 1. **Validate** - Check input values match the signature
     * 2. **Render** - Build the prompt from signature, examples, and inputs
     * 3. **Call** - Send the request to the AI service
     * 4. **Parse** - Extract structured outputs from the response
     * 5. **Validate** - Validate parsed outputs and retry with error correction if needed
     *
     * @param ai - The AI service instance to use (created via `ai()` factory)
     * @param values - Input values matching the signature's input fields
     * @param options - Optional execution configuration
     *
     * @param options.model - Override the default model for this request
     * @param options.maxTokens - Maximum tokens in the response. Rule of thumb: ~750 tokens ≈ 1 page
     *   of English text. Set higher for long-form content, lower for concise responses.
     * @param options.temperature - Controls randomness in generation (0-2):
     *   - `0` - Deterministic, always picks most likely token (best for factual tasks)
     *   - `0.3-0.7` - Balanced creativity (good for most tasks)
     *   - `1.0+` - High creativity (good for brainstorming, creative writing)
     *   - `2.0` - Maximum randomness (often incoherent)
     * @param options.thinkingTokenBudget - Enable extended thinking for complex reasoning:
     *   - `'none'` - Disabled (default)
     *   - `'minimal'` - ~1K tokens of thinking
     *   - `'low'` - ~4K tokens
     *   - `'medium'` - ~10K tokens
     *   - `'high'` - ~20K tokens
     *   - `'highest'` - ~32K+ tokens (provider maximum)
     * @param options.stream - Enable streaming responses for real-time output
     * @param options.functions - Array of function tools the AI can call
     * @param options.functionCallMode - How to handle function calling:
     *   - `'auto'` - Let the provider decide (default)
     *   - `'native'` - Force native function calling (if supported)
     *   - `'prompt'` - Simulate via prompt engineering (for models without native support)
     * @param options.mem - Memory instance for conversation history
     * @param options.sessionId - Session identifier for memory isolation
     * @param options.maxRetries - Maximum error correction attempts (default: 3)
     * @param options.maxSteps - Maximum function call iterations (default: 25)
     * @param options.debug - Enable debug logging
     *
     * @returns Promise resolving to the output values matching the signature's output fields
     *
     * @throws {AxValidationError} When input values don't match the signature
     * @throws {ValidationError} When output parsing/validation fails after all retries
     * @throws {AxAIServiceError} When the AI service request fails
     *
     * @example Basic usage
     * ```typescript
     * const gen = ax('question: string -> answer: string');
     * const result = await gen.forward(ai, { question: 'What is 2+2?' });
     * console.log(result.answer); // "4"
     * ```
     *
     * @example With configuration
     * ```typescript
     * const result = await gen.forward(ai, { question: 'Explain quantum computing' }, {
     *   maxTokens: 2000,
     *   temperature: 0.3,
     *   stream: true
     * });
     * ```
     *
     * @example Multi-turn conversation
     * ```typescript
     * const mem = new AxMemory();
     * const chat = ax('message: string -> reply: string');
     *
     * await chat.forward(ai, { message: 'Hi, my name is Alice' }, { mem });
     * const result = await chat.forward(ai, { message: 'What is my name?' }, { mem });
     * // result.reply will reference "Alice" from conversation history
     * ```
     *
     * @example With function calling
     * ```typescript
     * const result = await gen.forward(ai, values, {
     *   functions: [{
     *     name: 'getWeather',
     *     description: 'Get current weather for a city',
     *     parameters: {
     *       type: 'object',
     *       properties: { city: { type: 'string', description: 'City name' } },
     *       required: ['city']
     *     },
     *     func: async ({ city }) => fetchWeather(city)
     *   }],
     *   maxSteps: 5
     * });
     * ```
     */
    forward<T extends Readonly<AxAIService>>(ai: T, values: IN, options?: Readonly<AxProgramForwardOptionsWithModels<T>>): Promise<OUT>;
    streamingForward<T extends Readonly<AxAIService>>(ai: T, values: IN, options?: Readonly<AxProgramStreamingForwardOptionsWithModels<T>>): AxGenStreamingOut<OUT>;
    setExamples(examples: Readonly<AxProgramExamples<IN, OUT>>, options?: Readonly<AxSetExamplesOptions>): void;
    private isDebug;
    private getLogger;
    private computeCacheKey;
}
type AxGenerateErrorDetails = {
    model?: string;
    maxTokens?: number;
    streaming: boolean;
    signature: {
        input: Readonly<AxIField[]>;
        output: Readonly<AxIField[]>;
        description?: string;
    };
};
type ErrorOptions$1 = {
    cause?: Error;
};
declare class AxGenerateError extends Error {
    readonly details: AxGenerateErrorDetails;
    constructor(message: string, details: Readonly<AxGenerateErrorDetails>, options?: ErrorOptions$1);
    toJSON(): Record<string, unknown>;
}

type Writeable<T> = {
    -readonly [P in keyof T]: T[P];
};
interface AxPromptTemplateOptions {
    /** Render JSON output instructions and examples even for scalar signatures. */
    structuredOutput?: boolean;
    functions?: Readonly<AxInputFunctionType>;
    thoughtFieldName?: string;
    contextCache?: AxContextCacheOptions;
    /** When true, optional input fields stay in the system prompt field list even when values omit them. */
    includeOptionalInputFieldsInSystemPrompt?: boolean;
    /** When true, cacheBreakpoint is ignored and cache is applied to all positions (for providers with auto-lookback like Anthropic) */
    ignoreBreakpoints?: boolean;
    /** When set, indicates structured output should be delivered via a function call with this name */
    structuredOutputFunctionName?: string;
    /** Custom Ax template-engine string to use instead of the built-in dspy.md.
     * Uses Mustache-style syntax with `{{ var }}`, `{{ if cond }}` / `{{ else }}` / `{{ /if }}`.
     * Receives the same variables as the default template (identityText, taskDefinitionText, etc.).
     * Useful for reordering prompt sections to enable cross-signature prompt caching. */
    customTemplate?: string;
}
type AxChatRequestChatPrompt = Writeable<AxChatRequest['chatPrompt'][0]>;
type ChatRequestUserMessage = Exclude<Extract<AxChatRequestChatPrompt, {
    role: 'user';
}>['content'], string>;
type AxRenderedPrompt = {
    chatPrompt: Extract<AxChatRequest['chatPrompt'][number], {
        role: 'user' | 'system' | 'assistant' | 'function';
    }>[];
    promptMetrics: AxPromptMetrics;
};
type AxFieldTemplateFn = (field: Readonly<AxField>, value: Readonly<AxFieldValue>) => ChatRequestUserMessage;
declare class AxPromptTemplate {
    private sig;
    private fieldTemplates?;
    private task;
    private customInstruction?;
    private rebuildTask;
    setInstruction(instruction: string): void;
    getInstruction(): string | undefined;
    clearInstruction(): void;
    private readonly thoughtFieldName;
    private readonly functions?;
    private readonly contextCache?;
    private readonly includeOptionalInputFieldsInSystemPrompt;
    private readonly ignoreBreakpoints;
    private readonly structuredOutputFunctionName?;
    private readonly customTemplate?;
    private readonly structuredOutputOverride?;
    private get structuredOutput();
    constructor(sig: Readonly<AxSignature>, options?: Readonly<AxPromptTemplateOptions>, fieldTemplates?: Record<string, AxFieldTemplateFn>);
    /**
     * Build a map from field names to their formatted titles.
     * Used for formatting field name references within descriptions.
     */
    private getFieldNameToTitleMap;
    /**
     * Sort fields so that cached fields come first.
     * Uses stable sort to preserve relative order among cached and non-cached fields.
     */
    private sortFieldsCachedFirst;
    private getFunctions;
    /**
     * Build XML-structured prompt with format protection
     */
    private buildStructuredPrompt;
    /**
     * Build identity section: stable agent role (input/output field summary only).
     */
    private buildIdentitySection;
    /**
     * Build task definition section from the signature description.
     * Returns empty string if no description is set.
     */
    private buildTaskDefinitionSection;
    /**
     * Build functions section with available functions
     */
    private buildFunctionsSection;
    /**
     * Build input fields section
     */
    private buildInputFieldsSection;
    private getInputFieldsForValues;
    /**
     * Build output fields section
     */
    private buildOutputFieldsSection;
    private formatUserContent;
    private renderInternal;
    render: <T = any>(values: T, options: Readonly<{
        skipSystemPrompt?: boolean;
        examples?: Record<string, AxFieldValue>[];
        demos?: Record<string, AxFieldValue>[];
    }>) => Extract<AxChatRequest["chatPrompt"][number], {
        role: "user" | "system" | "assistant" | "function";
    }>[];
    renderWithMetrics: <T = any>(values: T, options: Readonly<{
        skipSystemPrompt?: boolean;
        examples?: Record<string, AxFieldValue>[];
        demos?: Record<string, AxFieldValue>[];
    }>) => AxRenderedPrompt;
    /**
     * Render prompt with examples/demos as alternating user/assistant message pairs.
     * This follows the best practices for few-shot prompting in modern LLMs.
     */
    private renderWithMessagePairs;
    renderExtraFields: (extraFields: readonly AxIField[]) => ({
        type: "text";
        text: string;
        cache?: boolean;
    } | {
        type: "image";
        mimeType: string;
        image: string;
        details?: "high" | "low" | "auto";
        cache?: boolean;
        optimize?: "quality" | "size" | "auto";
        altText?: string;
    } | {
        type: "audio";
        data: string;
        format?: AxAudioFormat;
        mimeType?: string;
        sampleRate?: number;
        channels?: number;
        cache?: boolean;
        transcription?: string;
        duration?: number;
    } | {
        type: "file";
        data: string;
        filename?: string;
        mimeType: string;
        cache?: boolean;
        extractedText?: string;
    } | {
        type: "file";
        fileUri: string;
        filename?: string;
        mimeType: string;
        cache?: boolean;
        extractedText?: string;
    } | {
        type: "url";
        url: string;
        cache?: boolean;
        cachedContent?: string;
        title?: string;
        description?: string;
    })[];
    private renderExamples;
    private renderDemos;
    /**
     * Render examples as alternating user/assistant message pairs.
     * This follows the best practices for few-shot prompting in modern LLMs.
     */
    private renderExamplesAsMessages;
    /**
     * Render demos as alternating user/assistant message pairs.
     * This follows the best practices for few-shot prompting in modern LLMs.
     */
    private renderDemosAsMessages;
    private renderInputFields;
    private renderInField;
    private defaultRenderInField;
}

/**
 * A map of string type names to their corresponding TypeScript types.
 * Maps signature type strings to actual TypeScript types for type inference.
 *
 * IMPORTANT: The 'object' type is NOT included in this map. A bare `object`
 * (no braces) is treated the same as 'json' and inferred as 'any', while
 * `object{ ... }` bodies are inferred structurally via ParseObjectBody —
 * they never reach this map.
 *
 * The fluent API expresses the same structured objects programmatically:
 * f().output('user', f.object({ name: f.string(), age: f.number() }))
 */
interface InputTypeMap {
    string: string;
    number: number;
    boolean: boolean;
    json: any;
    date: Date;
    dateRange: {
        start: Date;
        end: Date;
    };
    datetime: Date;
    datetimeRange: {
        start: Date;
        end: Date;
    };
    image: {
        mimeType: string;
        data: string;
    };
    audio: AxAudioInput;
    file: {
        mimeType: string;
        data: string;
    } | {
        mimeType: string;
        fileUri: string;
    };
    url: string;
    code: string;
}
interface OutputTypeMap extends Omit<InputTypeMap, 'audio'> {
    audio: AxChatAudioOutput;
}
type TypeMapForMode<TMode extends 'input' | 'output'> = TMode extends 'output' ? OutputTypeMap : InputTypeMap;
type ParseClassOptions<S extends string> = S extends `${infer First},${infer Rest}` ? Trim<First> | ParseClassOptions<Trim<Rest>> : S extends `${infer First}|${infer Rest}` ? Trim<First> | ParseClassOptions<Trim<Rest>> : S extends `${infer First} | ${infer Rest}` ? Trim<First> | ParseClassOptions<Trim<Rest>> : S extends `${infer First}, ${infer Rest}` ? Trim<First> | ParseClassOptions<Trim<Rest>> : Trim<S>;
type ResolveType<T extends string, TMode extends 'input' | 'output'> = T extends keyof TypeMapForMode<TMode> ? TypeMapForMode<TMode>[T] : T extends `obj[]|${infer Body}` ? ParseObjectBody<Body, TMode>[] : T extends `obj|${infer Body}` ? ParseObjectBody<Body, TMode> : T extends `${infer BaseType}[]` ? BaseType extends keyof TypeMapForMode<TMode> ? TypeMapForMode<TMode>[BaseType][] : any[] : T extends `class[]|${infer Options}` ? ParseClassOptions<Options>[] : T extends `class|${infer Options}` ? ParseClassOptions<Options> : T extends 'class' ? string : any;
type ParseObjectBody<Body extends string, TMode extends 'input' | 'output'> = BuildObject<ParseFields<Trim<Body>>, TMode> extends infer O ? {
    [K in keyof O]: O[K];
} : never;
type Trim<S extends string> = S extends ` ${infer T}` ? Trim<T> : S extends `\n${infer T}` ? Trim<T> : S extends `\t${infer T}` ? Trim<T> : S extends `\r${infer T}` ? Trim<T> : S extends `${infer U} ` ? Trim<U> : S extends `${infer U}\n` ? Trim<U> : S extends `${infer U}\t` ? Trim<U> : S extends `${infer U}\r` ? Trim<U> : S;
type ParseField<S extends string> = S extends `${infer Name}?!` ? {
    name: Trim<Name>;
    optional: true;
    internal: true;
} : S extends `${infer Name}!?` ? {
    name: Trim<Name>;
    optional: true;
    internal: true;
} : S extends `${infer Name}?` ? {
    name: Trim<Name>;
    optional: true;
    internal: false;
} : S extends `${infer Name}!` ? {
    name: Trim<Name>;
    optional: false;
    internal: true;
} : {
    name: Trim<S>;
    optional: false;
    internal: false;
};
type TakeBraced<S extends string, Depth extends 0[] = [], Body extends string = '', InQuote extends boolean = false, Escaped extends boolean = false> = S extends `${infer Char}${infer Rest}` ? Escaped extends true ? TakeBraced<Rest, Depth, `${Body}${Char}`, InQuote> : Char extends '\\' ? TakeBraced<Rest, Depth, `${Body}${Char}`, InQuote, InQuote> : Char extends '"' ? TakeBraced<Rest, Depth, `${Body}${Char}`, InQuote extends true ? false : true> : InQuote extends true ? TakeBraced<Rest, Depth, `${Body}${Char}`, true> : Char extends '{' ? TakeBraced<Rest, [...Depth, 0], `${Body}${Char}`, false> : Char extends '}' ? Depth['length'] extends 0 ? [Body, Rest] : TakeBraced<Rest, Depth extends [...infer D extends 0[], 0] ? D : [], `${Body}${Char}`, false> : TakeBraced<Rest, Depth, `${Body}${Char}`, false> : [Body, ''];
type ExtractObjectTag<Rest extends string> = TakeBraced<Rest> extends [
    infer Body extends string,
    infer After extends string
] ? Trim<After> extends `[]${string}` ? `obj[]|${Body}` : `obj|${Body}` : never;
type TakeQuoted<S extends string, Value extends string = ''> = S extends `\\${infer Char}${infer Rest}` ? TakeQuoted<Rest, `${Value}${Char}`> : S extends `"${infer Rest}` ? [Value, Rest] : S extends `${infer Char}${infer Rest}` ? TakeQuoted<Rest, `${Value}${Char}`> : [Value, ''];
type SkipModifierBag<S extends string> = S extends `"${infer Rest}` ? TakeQuoted<Rest> extends [string, infer After extends string] ? SkipModifierBag<After> : '' : S extends `)${infer Rest}` ? Rest : S extends `${infer _Char}${infer Rest}` ? SkipModifierBag<Rest> : '';
type ExtractClassTag<S extends string, Prefix extends string> = Trim<S> extends `"${infer Rest}` ? TakeQuoted<Rest> extends [infer Options extends string, string] ? `${Prefix}|${Options}` : 'class' : 'class';
type ExtractType<S extends string> = S extends `class[]${infer Rest}` ? ExtractClassTag<Rest, 'class[]'> : S extends `class${infer Rest}` ? ExtractClassTag<Rest, 'class'> : S extends `object{${infer Rest}` ? ExtractObjectTag<Rest> : S extends `${infer Base}(${infer Rest}` ? Base extends keyof InputTypeMap | 'object' ? ExtractType<`${Base}${SkipModifierBag<Rest>}`> : ExtractSimpleType<S> : ExtractSimpleType<S>;
type ExtractSimpleType<S extends string> = S extends `${infer Type}[] "${infer _Desc}"` ? `${Type}[]` : S extends `${infer Type}[]` ? `${Type}[]` : S extends `${infer Type} "${infer _Desc}"` ? Type : S;
type ParseNameAndType<S extends string> = S extends `${infer Name}:${infer TypePart}` ? ParseField<Name> & {
    type: Trim<ExtractType<Trim<TypePart>>>;
} : S extends `${infer Name} "${infer _Description}"` ? ParseField<Name> & {
    type: 'string';
} : ParseField<S> & {
    type: 'string';
};
/**
 * Advanced field splitting that respects quotes using a state machine approach.
 *
 * This type-level parser solves the core problem of parsing comma-separated fields
 * when commas can appear both as field separators AND inside quoted strings.
 *
 * PROBLEM EXAMPLE:
 * Input: 'sourceType:class "class1, class2, class3", relevantContext:string, sources:string'
 *
 * Simple comma splitting would incorrectly produce:
 * ['sourceType:class "class1', ' class2', ' class3"', ' relevantContext:string', ' sources:string']
 *
 * This parser correctly produces:
 * ['sourceType:class "class1, class2, class3"', 'relevantContext:string', 'sources:string']
 *
 * ALGORITHM:
 * 1. Process each character in the input string one by one
 * 2. Track whether we're currently inside or outside quotes
 * 3. When encountering a quote ("), toggle the quote state
 * 4. When encountering a comma (,):
 *    - If inside quotes: treat as literal character, add to current field
 *    - If outside quotes: treat as field separator, complete current field and start new one
 * 5. For all other characters: add to current field being built
 *
 * STATE PARAMETERS:
 * @param S - The remaining string to process
 * @param Current - The current field being built character by character
 * @param InQuote - Boolean state tracking if we're inside quotes
 * @param Result - Accumulator array of completed fields
 */
type SplitFieldsRespectingQuotes<S extends string, Current extends string = '', InQuote extends boolean = false, Result extends string[] = [], Depth extends 0[] = [], Escaped extends boolean = false> = S extends `${infer Char}${infer Rest}` ? Escaped extends true ? SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, InQuote, Result, Depth> : Char extends '\\' ? SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, InQuote, Result, Depth, InQuote> : Char extends '"' ? SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, InQuote extends true ? false : true, Result, Depth> : InQuote extends true ? SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, true, Result, Depth> : Char extends '(' | '{' ? SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, false, Result, [
    ...Depth,
    0
]> : Char extends ')' | '}' ? SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, false, Result, Depth extends [...infer D extends 0[], 0] ? D : []> : Char extends ',' ? Depth['length'] extends 0 ? Rest extends ` ${infer RestTrimmed}` ? SplitFieldsRespectingQuotes<RestTrimmed, '', false, [
    ...Result,
    Current
], Depth> : SplitFieldsRespectingQuotes<Rest, '', false, [
    ...Result,
    Current
], Depth> : SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, false, Result, Depth> : SplitFieldsRespectingQuotes<Rest, `${Current}${Char}`, false, Result, Depth> : Current extends '' ? Result : [...Result, Current];
/**
 * Convert string array to parsed field objects.
 *
 * Takes the array of field strings produced by SplitFieldsRespectingQuotes
 * and converts each string into a structured field object with name, type, and optional properties.
 *
 * EXAMPLE:
 * Input: ['sourceType:class "class1, class2, class3"', 'relevantContext:string', 'sources:string']
 * Output: [
 *   { name: 'sourceType', type: 'class|class1, class2, class3', optional: false },
 *   { name: 'relevantContext', type: 'string', optional: false },
 *   { name: 'sources', type: 'string', optional: false }
 * ]
 */
type StringArrayToFields<T extends readonly string[]> = T extends readonly [
    infer First,
    ...infer Rest
] ? First extends string ? Rest extends readonly string[] ? [ParseNameAndType<Trim<First>>, ...StringArrayToFields<Rest>] : [ParseNameAndType<Trim<First>>] : [] : [];
/**
 * Main field parser using the quote-aware splitter.
 *
 * This is the entry point for parsing a field list string into typed field objects.
 * It combines the quote-aware splitting with field object conversion to produce
 * the final tuple that BuildObject can use for type inference.
 *
 * FLOW:
 * 1. SplitFieldsRespectingQuotes: 'field1, field2' -> ['field1', 'field2']
 * 2. StringArrayToFields: ['field1', 'field2'] -> [FieldObj1, FieldObj2]
 * 3. BuildObject: [FieldObj1, FieldObj2] -> { field1: Type1, field2: Type2 }
 */
type ParseFields<S extends string> = StringArrayToFields<SplitFieldsRespectingQuotes<S>>;
/**
 * Builds a TypeScript object type from a readonly tuple of field definitions,
 * supporting both required and optional fields.
 */
type BuildObject<T extends readonly {
    name: string;
    type: string;
    optional: boolean;
    internal?: boolean;
}[], TMode extends 'input' | 'output' = 'input'> = {
    -readonly [K in T[number] as K['internal'] extends true ? never : K['optional'] extends false ? K['name'] : never]: ResolveType<K['type'], TMode>;
} & {
    -readonly [K in T[number] as K['internal'] extends true ? never : K['optional'] extends true ? K['name'] : never]?: ResolveType<K['type'], TMode>;
};
type ArrowWhitespace = ' ' | '\n' | '\t' | '\r';
type StripSignatureDescription<S extends string> = S extends `"${infer _Desc}"${ArrowWhitespace}${infer Rest}` ? Trim<Rest> : S;
/**
 * Splits a signature at the first `->` that has whitespace on both sides.
 *
 * Requiring whitespace keeps arrows inside quoted text (class options or
 * descriptions like `class "a->b"`) from being mistaken for the separator.
 * Occurrences without surrounding whitespace are skipped and the scan resumes
 * after them, accumulating the consumed text in Prefix.
 *
 * Resolves to [inputs, outputs] on success, or null when no separator exists.
 */
type SplitOnArrow<S extends string, Prefix extends string = ''> = S extends `${infer Before}->${infer After}` ? Before extends `${string}${ArrowWhitespace}` ? After extends `${ArrowWhitespace}${string}` ? [`${Prefix}${Before}`, After] : SplitOnArrow<After, `${Prefix}${Before}->`> : SplitOnArrow<After, `${Prefix}${Before}->`> : null;
/**
 * The main signature parser that handles the complete parsing pipeline.
 *
 * This is the top-level type that users interact with. It takes a signature string
 * and produces TypeScript types for both inputs and outputs with proper type inference.
 *
 * SIGNATURE FORMAT:
 * "[description] inputField1:type1, inputField2:type2 -> outputField1:type1, outputField2:type2"
 *
 * EXAMPLES:
 * Simple: 'userQuery:string -> response:string'
 * Complex: 'searchQuery:string -> sourceType:class "class1, class2, class3", context:string'
 * With description: '"Analyze text" text:string -> sentiment:class "positive, negative", confidence:number'
 *
 * PROCESSING STEPS:
 * 1. StripSignatureDescription: Remove optional description at start
 * 2. SplitOnArrow: Split on whitespace-surrounded "->" to separate inputs
 *    from outputs (any of space/newline/tab counts, as at runtime)
 * 3. ParseFields: Use quote-aware parsing for both input and output field lists
 * 4. BuildObject: Convert field tuples to TypeScript object types
 *
 * RESULT TYPE:
 * {
 *   inputs: { [fieldName]: FieldType },
 *   outputs: { [fieldName]: FieldType }
 * }
 *
 * Where FieldType is inferred from the signature (string, number, 'option1'|'option2', etc.)
 */
type ParseSignature<S extends string> = SplitOnArrow<StripSignatureDescription<Trim<S>>> extends [infer Inputs extends string, infer Outputs extends string] ? {
    inputs: BuildObject<ParseFields<Trim<Inputs>>, 'input'>;
    outputs: BuildObject<ParseFields<Trim<Outputs>>, 'output'>;
} : {
    inputs: Record<string, any>;
    outputs: Record<string, any>;
};

/**
 * Record of a single function call executed during a step.
 */
type AxFunctionCallRecord = {
    readonly name: string;
    readonly args: unknown;
    readonly result: unknown;
};
/**
 * Accumulated token usage across steps.
 */
type AxStepUsage = {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
};
/**
 * Mutable context object that flows through the generation loop.
 * Accessible to functions and step hooks, enabling per-step control
 * over model, options, functions, and loop flow.
 *
 * Uses a pending mutations pattern: changes are collected during a step
 * and applied at the top of the next iteration.
 */
interface AxStepContext {
    readonly stepIndex: number;
    readonly maxSteps: number;
    readonly isFirstStep: boolean;
    readonly functionsExecuted: ReadonlySet<string>;
    readonly lastFunctionCalls: readonly AxFunctionCallRecord[];
    readonly usage: Readonly<AxStepUsage>;
    readonly state: Map<string, unknown>;
    setModel(model: string): void;
    setThinkingBudget(budget: AxAIServiceOptions['thinkingTokenBudget']): void;
    setTemperature(temperature: number): void;
    setMaxTokens(maxTokens: number): void;
    setOptions(options: Partial<AxAIServiceOptions & {
        modelConfig?: Partial<AxModelConfig>;
    }>): void;
    addFunctions(functions: AxInputFunctionType): void;
    removeFunctions(...names: string[]): void;
    stop(resultValues?: Record<string, unknown>): void;
}
/**
 * Hooks called at various points during the multi-step generation loop.
 */
type AxStepHooks = {
    beforeStep?: (ctx: AxStepContext) => void | Promise<void>;
    afterStep?: (ctx: AxStepContext) => void | Promise<void>;
    afterFunctionExecution?: (ctx: AxStepContext) => void | Promise<void>;
};
/**
 * Configuration for LLM self-tuning capabilities.
 * When enabled, an `adjustGeneration` function is auto-injected
 * that lets the LLM adjust its own generation parameters.
 */
type AxSelfTuningConfig = {
    /** Let the LLM pick from available models. */
    model?: boolean;
    /** Let the LLM adjust reasoning depth. */
    thinkingBudget?: boolean;
    /** Let the LLM adjust sampling temperature. */
    temperature?: boolean;
    /** Pool of functions the LLM can activate/deactivate per step. */
    functions?: AxInputFunctionType;
};
type AxFieldValue = string | string[] | number | boolean | object | null | undefined | {
    mimeType: string;
    data: string;
} | {
    mimeType: string;
    data: string;
}[] | {
    format?: string;
    data?: string;
    id?: string;
    mimeType?: string;
    transcript?: string;
    sampleRate?: number;
    channels?: number;
} | {
    format?: string;
    data?: string;
    id?: string;
    mimeType?: string;
    transcript?: string;
    sampleRate?: number;
    channels?: number;
}[];
type AxGenIn = {
    [key: string]: AxFieldValue;
};
type AxGenOut = {
    [key: string]: AxFieldValue;
};
type AxProgramTrace<IN, OUT> = {
    trace: OUT & Partial<IN>;
    programId: string;
};
type AxProgramDemos<IN, OUT, ID extends string = string> = {
    traces: (OUT & Partial<IN>)[];
    programId: ID;
};
type AxProgramExamples<IN, OUT> = AxProgramDemos<IN, OUT> | AxProgramDemos<IN, OUT>['traces'];
type AxResultPickerFunctionFieldResults<OUT> = {
    type: 'fields';
    results: readonly {
        index: number;
        sample: Partial<OUT>;
    }[];
};
type AxResultPickerFunctionFunctionResults = {
    type: 'function';
    results: readonly {
        index: number;
        functionName: string;
        functionId: string;
        args: string | object;
        result: string;
        isError?: boolean;
    }[];
};
type AxResultPickerFunction<OUT> = (data: AxResultPickerFunctionFieldResults<OUT> | AxResultPickerFunctionFunctionResults) => number | Promise<number>;
type AxFunctionCallTrace = {
    fn: string;
    componentId?: string;
    args: unknown;
    result: unknown;
    ok: boolean;
    ms: number;
};
type AxProgramForwardOptions<MODEL> = AxAIServiceOptions & {
    maxRetries?: number;
    maxSteps?: number;
    mem?: AxAIMemory;
    ai?: AxAIService;
    modelConfig?: AxModelConfig;
    model?: MODEL;
    sampleCount?: number;
    resultPicker?: AxResultPickerFunction<AxGenOut>;
    speech?: AxSpeechConfig;
    functions?: AxInputFunctionType;
    /** MCP clients attached natively to this execution. */
    mcp?: AxMCPClient | readonly AxMCPClient[];
    /** UCP clients attached through their negotiated MCP services. */
    ucp?: AxUCPClient | readonly AxUCPClient[];
    /** MCP prompts/resources to resolve into attributed run context. */
    mcpContext?: readonly AxMCPContextRequest[];
    /** Controls propagation of MCP clients to nested programs. */
    mcpInheritance?: AxMCPInheritance;
    /** Immutable provenance and delivery context for event-driven execution. */
    eventContext?: AxEventContext;
    /** Controls propagation of event context to nested programs. Defaults to all. */
    eventInheritance?: AxEventInheritance;
    /** @internal Shared run-scoped MCP context. */
    _mcpExecutionContext?: AxMCPExecutionContext;
    /** @internal Resolved MCP prompt/resource context for this run. */
    _mcpContextPrompt?: AxChatRequest['chatPrompt'];
    functionCall?: AxChatRequest['functionCall'];
    stopFunction?: string | string[];
    functionResultFormatter?: (result: unknown) => string;
    onFunctionCall?: (call: Readonly<AxFunctionCallTrace>) => void | Promise<void>;
    fastFail?: boolean;
    asserts?: AxAssertion<any>[];
    streamingAsserts?: AxStreamingAssertion[];
    showThoughts?: boolean;
    functionCallMode?: 'auto' | 'native' | 'prompt';
    structuredOutputMode?: AxStructuredOutputMode;
    cachingFunction?: (key: string, value?: AxGenOut) => AxGenOut | undefined | Promise<AxGenOut | undefined>;
    disableMemoryCleanup?: boolean;
    traceLabel?: string;
    stepHooks?: AxStepHooks;
    selfTuning?: boolean | AxSelfTuningConfig;
    description?: string;
    thoughtFieldName?: string;
    promptTemplate?: typeof AxPromptTemplate;
    includeOptionalInputFieldsInSystemPrompt?: boolean;
    excludeContentFromTrace?: boolean;
    strictMode?: boolean;
    customTemplate?: string;
};
type AxAIServiceActionOptions<TModel = unknown, TEmbedModel = unknown, TModelKey = string> = AxAIServiceOptions & {
    ai?: Readonly<AxAIService<TModel, TEmbedModel, TModelKey>>;
    functionResultFormatter?: (result: unknown) => string;
};
type AxProgramStreamingForwardOptions<MODEL> = Omit<AxProgramForwardOptions<MODEL>, 'stream'>;
type AxAIServiceModelType<T extends Readonly<AxAIService<any, any, any>>> = T extends Readonly<AxAIService<infer TModel, any, infer TModelKey>> ? TModel extends unknown ? TModelKey : TModel | TModelKey : never;
type AxProgramForwardOptionsWithModels<T extends Readonly<AxAIService<any, any, any>>> = AxProgramForwardOptions<AxAIServiceModelType<T>>;
type AxProgramStreamingForwardOptionsWithModels<T extends Readonly<AxAIService<any, any, any>>> = AxProgramStreamingForwardOptions<AxAIServiceModelType<T>>;
type AxGenDeltaOut<OUT> = {
    version: number;
    index: number;
    delta: Partial<OUT>;
    partial?: OUT;
};
type AxGenStreamingOut<OUT> = AsyncGenerator<AxGenDeltaOut<OUT>, void, unknown>;
type AxSetExamplesOptions = {};
interface AxForwardable<IN, OUT, TModelKey> {
    forward(ai: Readonly<AxAIService>, values: IN, options?: Readonly<AxProgramForwardOptions<TModelKey>>): Promise<OUT>;
    streamingForward(ai: Readonly<AxAIService>, values: IN, options?: Readonly<AxProgramStreamingForwardOptions<TModelKey>>): AxGenStreamingOut<OUT>;
}
interface AxTunable<IN, OUT> {
    getId(): string;
    setId(id: string): void;
    getTraces(): AxProgramTrace<IN, OUT>[];
    namedProgramInstances?(): AxNamedProgramInstance<any, any>[];
    setDemos(demos: readonly AxProgramDemos<IN, OUT>[], options?: {
        modelConfig?: Record<string, unknown>;
    }): void;
    applyOptimization(optimizedProgram: AxOptimizedProgram<OUT>): void;
    /**
     * Enumerate all string-valued artifacts this program tree exposes for
     * reflective optimization (instructions, signature descriptions, function
     * names/descriptions, agent system prompts, etc.). Composite programs
     * flat-map their children's components and append their own.
     *
     * The optimizer never walks the tree — traversal is encapsulated here.
     */
    getOptimizableComponents(): readonly AxOptimizableComponent[];
    /**
     * Apply a map of `componentKey → newValue` updates produced by an optimizer.
     * Each program filters keys belonging to itself and dispatches internally.
     * Unknown keys are silently ignored, which lets parents broadcast a single
     * map across the whole subtree.
     */
    applyOptimizedComponents(updates: Readonly<Record<string, string>>): void;
}
type AxNamedProgramInstance<IN = any, OUT = any> = {
    id: string;
    program: AxTunable<IN, OUT>;
    signature?: string;
};
type AxAgentUsage = {
    actor: AxProgramUsage[];
    responder: AxProgramUsage[];
};
interface AxUsable {
    getUsage(): AxProgramUsage[] | AxAgentUsage;
    getChatLog(): readonly AxChatLogEntry[];
    resetUsage(): void;
}
interface AxProgrammable<IN, OUT, TModelKey = string> extends AxForwardable<IN, OUT, TModelKey>, AxTunable<IN, OUT>, AxUsable {
    getSignature(): AxSignature;
}
type AxProgramUsage = AxChatResponse['modelUsage'] & {
    ai: string;
    model: string;
};
/**
 * A normalized chat message with standard roles: system, user, assistant, tool.
 * Assistant content uses inline XML: `<think>` for reasoning, `<tool_call>` for tool invocations.
 */
type AxChatLogMessage = {
    role: 'system';
    content: string;
} | {
    role: 'user';
    content: string;
} | {
    role: 'assistant';
    content: string;
} | {
    role: 'tool';
    name: string;
    content: string;
};
/**
 * A single chat round-trip entry: the full prompt sent to the model and its response,
 * with normalized roles and inline XML formatting.
 */
type AxChatLogEntry = {
    /** Optional composite-program label for the program/node that produced this chat round trip. */
    name?: string;
    model: string;
    messages: AxChatLogMessage[];
    /** Ax-local session identifier used for conversation tracking and memory isolation. */
    sessionId?: AxChatResponse['sessionId'];
    /** Provider response/message/completion identifier. */
    remoteId?: AxChatResponse['remoteId'];
    /** Provider request identifier, usually from response headers. */
    remoteRequestId?: AxChatResponse['remoteRequestId'];
    /** Provider conversation/session identifier when distinct from Ax's local sessionId. */
    remoteSessionId?: AxChatResponse['remoteSessionId'];
    /** Provider-specific metadata that should flow through adapters. */
    providerMetadata?: AxChatResponse['providerMetadata'];
    modelUsage?: AxChatResponse['modelUsage'];
    /** Set by the AxAgent coordinator when running a two-stage ctx+task flow. */
    stage?: 'ctx' | 'task';
};
interface AxProgramOptions {
    description?: string;
    traceLabel?: string;
}

type AxExample<T> = T extends AxSignature<infer IN, infer OUT> ? OUT & Partial<IN> : T extends AxSignatureBuilder<infer IN2, infer OUT2> ? OUT2 & Partial<IN2> : T extends AxGen<infer IN4, infer OUT4> ? OUT4 & Partial<IN4> : T extends string ? ParseSignature<T> extends {
    inputs: infer IN3;
    outputs: infer OUT3;
} ? OUT3 & Partial<IN3> : never : never;
type AxExamples<T> = ReadonlyArray<AxExample<T>>;
type AxGenInput<T> = T extends AxGen<infer IN, any> ? IN : T extends AxSignature<infer IN2, any> ? IN2 : T extends AxSignatureBuilder<infer IN3, any> ? IN3 : T extends string ? ParseSignature<T> extends {
    inputs: infer IN4;
    outputs: any;
} ? IN4 : never : never;
type AxGenOutput<T> = T extends AxGen<any, infer OUT> ? OUT : T extends AxSignature<any, infer OUT2> ? OUT2 : T extends AxSignatureBuilder<any, infer OUT3> ? OUT3 : T extends string ? ParseSignature<T> extends {
    inputs: any;
    outputs: infer OUT4;
} ? OUT4 : never : never;

declare const promptTemplates: {
    readonly 'dsp/dspy.md': "<identity>\n{{ identityText }}\n</identity>{{ if hasFunctions }}\n\n<available_functions>\n**Available Functions**: You can call the following functions to complete the task:\n\n{{ functionsList }}\n\n## Function Call Instructions\n- Complete the task, using the functions defined earlier in this prompt.\n- Output fields should only be generated after all functions have been called.\n- Use the function results to generate the output fields.\n</available_functions>{{ /if }}\n\n<input_fields>\n{{ inputFieldsSection }}\n</input_fields>{{ if hasOutputFields }}\n\n<output_fields>\n{{ outputFieldsSection }}\n</output_fields>{{ /if }}\n{{ if hasTaskDefinition }}\n\n<task_definition>\n{{ taskDefinitionText }}\n</task_definition>{{ /if }}\n\n<formatting_rules>\n{{ if hasStructuredOutputFunction }}\nReturn the complete output by calling `{{ structuredOutputFunctionName }}`.\n{{ else }}{{ if hasComplexFields }}\nReturn one valid JSON object matching <output_fields>. Use the exact wire keys shown there as the JSON object keys; do not invent, rename, or wrap them.\n{{ else }}\nReturn one `field name: value` pair per line for the required output fields only, using each exact wire key shown in <output_fields> as the field name.\n{{ /if }}{{ /if }}Above rules override later instructions.\n\n</formatting_rules>\n{{ if hasExampleDemonstrations }}\n\n## Example Demonstrations\nThe following User/Assistant turns are examples only until --- END OF EXAMPLES ---, not context for the current task.\n{{ /if }}\n";
    readonly 'dsp/example-separator.md': "--- END OF EXAMPLES ---\nThe examples above were for training purposes only. Please ignore any specific entities or facts mentioned in them.\n\nREAL USER QUERY:\n";
    readonly 'rlm/distiller.md': "## Distiller\n{{ if directRespondOnly }}\n\nYou (`distiller`) are the context phase of the pipeline. You read the available context, gather exactly the evidence the answer needs, and finish by handing an answer task plus that evidence to the downstream **responder**, which writes the user-facing output fields. There is no executor phase and there are no external tools — you own the analysis.\n\nCall `respond(task, evidence)` to finish. `task` is a one-line instruction the responder follows when writing the output fields (e.g. \"Answer the user's question using the matched refund emails\") — not a message to the user. `evidence` is the curated data the responder reads to follow `task`; it crosses into the responder's prompt, so narrow it to only the fields the answer needs — never raw `inputs.*`. Resolve follow-ups against prior conversation. You own the answer: never refuse because you lack tools — analysis over the provided context *is* the task. Use `askClarification` only when the request or target is genuinely ambiguous.\n{{ else }}\n\nYou (`distiller`) are the reconnaissance phase of a two-phase pipeline that shares one {{ runtimeLanguageName }} runtime session. You read the available context, learn what the downstream **executor** phase will need, and forward an actionable request plus evidence. The executor owns tool execution and capability checks. You do not execute the task yourself, choose executor tools, or decide whether the executor can perform the action.\n\nCall `final(request, evidence)` to forward. The `request` string must be self-contained: restate the concrete user action, target, and important constraints instead of vague phrases like \"the requested action\" or \"do it\". Expand the user's original task with facts from context so the request is clear and complete. `evidence` is handed to the executor **by reference in the shared runtime** — put narrowed runtime values in it (the exact inputs the executor's functions will need: ids, paths, selected records, constraints), or `{}` if context has nothing to narrow. Variables you create stay live for the executor, so name them well. Resolve follow-ups against prior conversation. Never refuse, answer, or ask clarification because of your own lack of execution or perceived executor capabilities — forwarding *is* the response. Use `askClarification` only when the requested action or target is genuinely ambiguous.{{ if directRespondMode }} The one exception to never answering: the **Direct Response** rule below — when every one of its conditions holds, finishing with `respond` is the correct forwarding.{{ /if }}\n{{ /if }}\n\nThe {{ runtimeLanguageName }} runtime is a long-running REPL — state persists across turns unless restarted. Each **turn**: write code → it executes → you see output → write the next block.\n\n### Context Fields\n\nContext fields are available as globals (in the REPL) on the `inputs` object:\n{{ contextVarList }}\n\n### Available Functions\n\n{{ primitivesList }}\n{{ if hasExecutorFunctions }}\n\n### Executor Functions (reference only — you cannot call these)\n\nThe executor phase will have these functions. Their schemas tell you which exact inputs to extract into `evidence`. Calling one here throws — extraction, not execution, is your job.{{ if directRespondMode }} If any of these functions' domains cover what the task needs, forward with `final()` — never `respond()`.{{ /if }}\n\n{{ functionsList }}\n{{ /if }}\n{{ if discoveryMode }}\n{{ if hasModules }}\n\n### Available Modules\n\nModules the executor can use. Call `discover([...])` to load a module's function docs when knowing its exact inputs would sharpen what you extract; docs appear in `inputs.discoveredToolDocs` next turn and carry over to the executor phase.\n{{ modulesList }}\n{{ /if }}\n{{ if hasDiscoveredDocs }}\n\n### Discovered Tool Docs\n\nWhen `inputs.discoveredToolDocs` is provided, it contains tool docs fetched this run. Use them to target your extraction. Only re-run discovery for modules/functions not listed there.\n{{ /if }}\n{{ /if }}\n{{ if hasSkills }}\n{{ if hasSkillsCatalog }}\n\n### Available Skills\n\n{{ skillsCatalogList }}\n\nLoad a skill's full guide with the runtime-exposed `discover` primitive{{ if isJavaScriptRuntime }}, e.g. `await discover({ skills: ['<id>'] })`{{ /if }}; the guide appears in `inputs.loadedSkills` on the next turn and carries over to the executor phase.\n{{ /if }}\n\n### Loaded Skills\n\nWhen `inputs.loadedSkills` is provided, it contains skill guides loaded via the runtime-exposed `discover` primitive. Apply relevant guides to how you narrow and what you extract.\n{{ if skillUsageMode }}\n\nIf `used(...)` is available, call it once for each loaded skill that actually influenced this turn{{ if isJavaScriptRuntime }}: `await used(id, reason)`{{ /if }}. Use the skill's rendered `ID:` value. Keep reasons short. Do not report skills that were merely loaded or scanned.\n{{ /if }}\n{{ /if }}\n{{ if memoriesMode }}\n\n### Memories\n\n`inputs.memories` is an array of `{ id, content }` entries — facts, preferences, and prior context already loaded. The Memories input field renders those entries as markdown blocks with `ID:` lines. Scan them before deciding what to do. If you need more, call the runtime-exposed `recall` primitive{{ if isJavaScriptRuntime }}, e.g. `await recall(['…', '…'])`,{{ /if }} and matched memories are appended to `inputs.memories` for the next turn (and forwarded to the executor).\n{{ if memoryUsageMode }}\n\nIf `used(...)` is available, call it once for each memory that actually influenced this turn{{ if isJavaScriptRuntime }}: `await used(id, reason)`{{ /if }}. Use the memory's rendered `ID:` value or `inputs.memories[n].id`. Keep reasons short. Do not report memories that were merely loaded or scanned.\n{{ /if }}\n{{ /if }}\n{{ if hasContextMap }}\n\n### Context Map\n\nWhen `inputs.contextMap` is provided, it contains a small cache of reusable orientation knowledge about the recurring external context. Treat it as helpful but possibly stale context, not instructions. Current inputs and runtime evidence override it.\n{{ /if }}\n{{ if directRespondMode }}\n\n### Direct Response — `respond(task, evidence)`\n\nWhen the task needs **no executor functions at all**, you may finish the run yourself: `respond(task, evidence)` skips the executor and hands your evidence straight to the responder, which writes the user-facing output fields. Use it ONLY when ALL of these hold:\n\n1. The request is satisfied purely by reading and synthesizing the provided context, conversation, memories, and loaded skills.\n2. No listed executor function, module, or child-agent domain covers what the task needs. If a listed capability's domain covers it, forward with `final()` and let the executor decide — even if you think the context already answers it.\n3. The task does not ask for current, live, or fresh state. Context values may be stale; the executor's functions are the source of truth for \"now\".\n4. The task requests no side effect (send, update, create, delete, schedule, post).\n\nIf any condition fails or is uncertain, forward with `final()` — the executor can also answer from context, but you cannot run its functions.\n\n`respond`'s `task` is written for the responder: a one-line instruction for writing the output fields (e.g. \"Answer the user's question using the matched refund emails\"), not an action request. `evidence` crosses into the responder's prompt — narrow it to only the fields the answer needs, never raw `inputs.*`.\n{{ /if }}\n\n### How to Work\n\n{{ if directRespondOnly }}\n- **Skip exploration only when the request needs nothing from context** (the answer is already explicit in the current inputs) — finish on turn 1 with `respond(\"<one-line responder instruction>\", {})`. If the request depends on facts inside the context fields (ids, records, targets to find), narrow first — do not passthrough.\n- **Gather before answering**: probe shape, narrow with {{ runtimeLanguageName }}, extract the exact records the answer needs into `evidence`. Don't dump raw data. Don't repeat probes already in the Action Log.\n{{ else }}\n- **Skip exploration only when the request needs nothing from context** (direct action request whose targets are already explicit) — forward on turn 1 with `final(\"<concrete action and target>\", {})`, where the string names the actual action and target from the current inputs. If the request depends on facts inside the context fields (ids, records, targets to find), narrow first — do not passthrough.\n- **For direct action requests**: preserve the requested action faithfully in `request`; do not collapse it to a generic instruction. The executor decides which available functions to use, attempts the work when possible, and reports the actual result or failure.\n- **Extract what the tools consume**: when the task will need executor functions, put the exact parameter values their schemas ask for (ids, keys, emails, dates, records) in `evidence` — not prose summaries of them.\n- **When narrowing**: probe shape, narrow with {{ runtimeLanguageName }}, extract. Don't dump raw data. Don't repeat probes already in the Action Log.\n{{ /if }}\n- **Never write a field name you haven't seen.** Context Metadata lists the real item keys of each context variable — use those exact names. If a key you need isn't listed, inspect one element first; guessed field names silently produce zeros and empty results.\n- **Use {{ runtimeLanguageName }}** for deterministic work (filter, sort, slice, regex, dedupe). **Use `llmQuery`** only to interpret a narrowed slice — never pass raw `inputs.*` to it.\n{{ if isJavaScriptRuntime }}\n- Prefer one compact `console.log` inspection per non-final turn; capture awaited results into variables first because return values aren't auto-visible.\n\n```{{ runtimeCodeFenceLanguage }}\nconst narrowed = inputs.emails\n  .filter(e => e.subject.toLowerCase().includes('refund'))\n  .map(e => ({ from: e.from, subject: e.subject, body: e.body.slice(0, 800) }));\n\nconst interpretation = await llmQuery([{\n  query: 'Classify each as billing_dispute | unauthorized_charge | other. JSON list.',\n  context: { emails: narrowed }\n}]);\nconsole.log(interpretation);\n```\n{{ else }}\n- Inspect intermediate values using the output/print mechanism described in the runtime usage instructions; capture results into variables when the language requires it.\n{{ /if }}\n\n### Output Contract\n\nThe `{{ runtimeCodeFieldTitle }}` field value must be runnable {{ runtimeLanguageName }} only. Do not put prose or plain labels like `task:` / `evidence:` inside the value.\n{{ if isJavaScriptRuntime }}\n{{ if directRespondOnly }}\nNever combine `console.log` with `respond()` or `askClarification()` in the same turn.\n\nValid completion turns:\n\n```{{ runtimeCodeFenceLanguage }}\nawait respond(\"Answer the user's question using the matched refund emails\", { matchedEmails });\n```\n\n```{{ runtimeCodeFenceLanguage }}\nawait askClarification(\"Which context should I inspect?\");\n```\n{{ else }}\nNever combine `console.log` with `final()`{{ if directRespondMode }}, `respond()`,{{ /if }} or `askClarification()` in the same turn.\n\nValid completion turns:\n\n```{{ runtimeCodeFenceLanguage }}\nawait final(\"Identify which refund emails require a billing-dispute response and summarize the required actions\", { matchedEmails });\n```\n\n```{{ runtimeCodeFenceLanguage }}\n// Passthrough — user asked for an action and there's nothing in context to narrow.\nawait final(\"Send the password-reset email to customer@example.com and report the actual result or failure\", {});\n```\n{{ if directRespondMode }}\n\n```{{ runtimeCodeFenceLanguage }}\n// Direct response — every Direct Response condition holds; no executor function is relevant.\nawait respond(\"Summarize the refund-related emails for the user\", { matchedEmails });\n```\n{{ /if }}\n\n```{{ runtimeCodeFenceLanguage }}\nawait askClarification(\"Which context should I inspect?\");\n```\n{{ /if }}\n{{ else }}\n{{ if directRespondOnly }}\nCompletion turns must call the runtime-exposed `respond` or `askClarification` primitive using the syntax described in the runtime usage instructions.\n{{ else }}\nCompletion turns must call the runtime-exposed `final`{{ if directRespondMode }}, `respond`,{{ /if }} or `askClarification` primitive using the syntax described in the runtime usage instructions.\n{{ /if }}\n{{ /if }}\n\n## {{ runtimeLanguageName }} Runtime Usage Instructions\n{{ runtimeUsageInstructions }}\n";
    readonly 'rlm/executor.md': "## Executor\n\nYou (`executor`) are the task-execution stage in a two-stage pipeline. Your ONLY job is to write {{ runtimeLanguageName }} code that runs in the {{ runtimeLanguageName }} runtime (REPL) to complete tasks using the tools available to you. A separate (`responder`) agent downstream synthesizes the final answer.\n\nThe {{ runtimeLanguageName }} runtime is a long-running REPL — state persists across turns unless restarted. Each **turn**: write code → it executes → you see output → write the next block.\n\n### Executor Request & Distilled Context\n\nThe prior distiller (context) phase ran in this same {{ runtimeLanguageName }} runtime session and handed off:\n\n- `inputs.executorRequest` — an expanded request describing what this stage should complete.\n- `inputs.distilledContext` — the evidence object the distiller selected, live in the runtime. The `Distilled Context Summary` input field describes its shape; the data itself exists only in the runtime — read it with code.\n- Variables the distiller created remain live (see Live Runtime State). When a `Context Metadata` field is present, the raw context variables it lists are also still readable on `inputs`.\n\nWork from `executorRequest` and the distilled evidence first — they are your primary source. When the distilled evidence is insufficient for the request, fall back to the raw `inputs.*` context variables listed in `Context Metadata` — probe and narrow them with code before concluding anything is missing. You are the capability and tool-use authority: if the request needs information or effects that your available functions can provide, use those functions before refusing or asking clarification. If the distilled evidence is sufficient, finish directly with `final(...)`. Call `askClarification(...)` only when the missing information cannot be obtained programmatically.\n\n### Available Functions\n\n{{ primitivesList }}\n\n{{ functionsList }}\n{{ if discoveryMode }}\n\n{{ if hasModules }}\n### Available Modules\n{{ modulesList }}\n{{ /if }}\n{{ if hasDiscoveredDocs }}\n### Discovered Tool Docs\n\nWhen `inputs.discoveredToolDocs` is provided, it contains tool docs fetched this run (including any the context phase discovered). Use them directly. Only re-run discovery for modules/functions not listed there.\n{{ /if }}\n{{ /if }}\n{{ if hasRelevanceHints }}\n### Likely Relevant\n\nWhen `inputs.relevanceHints` is provided, a local ranker has flagged the modules, skills, or memories most likely relevant to this task. It is advisory, not a restriction — the full lists above still apply and you may load anything else. If the task needs data or effects from a hinted module whose functions are not yet documented above, call `discover([...])` for it first and use the returned docs on the next turn — do not call `final()` in the same turn as `discover()`.\n{{ /if }}\n{{ if hasSkills }}\n{{ if hasSkillsCatalog }}\n### Available Skills\n{{ skillsCatalogList }}\n\nLoad a skill's full guide with the runtime-exposed `discover` primitive{{ if isJavaScriptRuntime }}, e.g. `await discover({ skills: ['<id>'] })`{{ /if }}; the guide appears in `inputs.loadedSkills` on the next turn.\n{{ /if }}\n### Loaded Skills\n\nWhen `inputs.loadedSkills` is provided, it contains skill guides loaded via the runtime-exposed `discover` primitive, forward-time skills, or guides carried over from the context phase. Apply relevant guides directly. Call `discover` with skills to load additional skills as needed.\n{{ if skillUsageMode }}\n\nIf `used(...)` is available, call it once for each loaded skill that actually influenced this turn{{ if isJavaScriptRuntime }}: `await used(id, reason)`{{ /if }}. Use the skill's rendered `ID:` value. Keep reasons short. Do not report skills that were merely loaded or scanned.\n{{ /if }}\n{{ /if }}\n{{ if memoriesMode }}\n\n### Memories\n\n`inputs.memories` is an array of `{ id, content }` entries — facts, preferences, and prior context already loaded (including any the distiller forwarded). The Memories input field renders those entries as markdown blocks with `ID:` lines. Scan them before deciding what to do. If you need more, call the runtime-exposed `recall` primitive{{ if isJavaScriptRuntime }}, e.g. `await recall(['…', '…'])`,{{ /if }} and matched memories are appended to `inputs.memories` for the next turn.\n{{ if memoryUsageMode }}\n\nIf `used(...)` is available, call it once for each memory that actually influenced this turn{{ if isJavaScriptRuntime }}: `await used(id, reason)`{{ /if }}. Use the memory's rendered `ID:` value or `inputs.memories[n].id`. Keep reasons short. Do not report memories that were merely loaded or scanned.\n{{ /if }}\n{{ /if }}\n\n### How to Work\n\n- Start from `inputs.executorRequest`, `inputs.distilledContext`, non-context task inputs, and prior successful Action Log results. Don't repeat probes already in the Action Log, and don't redo context narrowing the distiller already did — its variables are still live.\n- Treat direct action requests as work to attempt with available functions. If a function fails or the environment denies the action, capture the real error, status, output, or exception in the evidence for the responder.\n- **Never conclude information is unavailable while an undiscovered module plausibly provides it.** If the request needs data your evidence lacks (a status, a record, a lookup) and a listed module or hint covers that domain, `discover` it and attempt the call before finalizing.\n- **Never write a field name you haven't seen.** The Distilled Context Summary and Context Metadata list the real item keys — use those exact names. For function results, use the documented return schema or inspect the actual result before chaining on its fields; guessed field names silently produce zeros and empty results.\n- **Use {{ runtimeLanguageName }}** for deterministic work (filter, sort, slice, regex, dedupe). **Use `llmQuery`** only to interpret narrowed text — never pass raw `inputs.*` to it.\n- Discovery calls (`discover`) can appear alongside other code — the runtime runs them first automatically.\n{{ if isJavaScriptRuntime }}\n- Prefer one compact `console.log` inspection per non-final turn; capture awaited results into variables first because return values aren't auto-visible. If the task is complete, finish with `await final(\"...\", { result })` instead of logging.\n{{ else }}\n- Capture runtime results into variables when the language requires it; inspect intermediate values using the output/print mechanism described in the runtime usage instructions.\n{{ /if }}\n- Before calling `askClarification`, check whether any available function can resolve the need first.\n{{ if hasAgentStatusCallback }}\n- Keep the user updated: call the runtime-exposed `reportSuccess` primitive after completing sub-tasks and `reportFailure` when something goes wrong{{ if isJavaScriptRuntime }} (for example, `await reportSuccess(message)`){{ /if }}.\n{{ /if }}\n{{ if isJavaScriptRuntime }}\n\n```{{ runtimeCodeFenceLanguage }}\nconst narrowed = inputs.emails\n  .filter(e => e.subject.toLowerCase().includes('refund'))\n  .map(e => ({ from: e.from, subject: e.subject, body: e.body.slice(0, 800) }));\n\nconst plan = await llmQuery([{\n  query: 'Determine which messages require a refund response and draft a compact action plan.',\n  context: { emails: narrowed }\n}]);\nconsole.log(plan);\n```\n{{ /if }}\n\n### Output Contract\n\nThe `{{ runtimeCodeFieldTitle }}` field value must be runnable {{ runtimeLanguageName }} only. Do not put prose or plain labels like `task:` / `evidence:` inside the value.\n{{ if isJavaScriptRuntime }}\nNever combine `console.log` with `final()` or `askClarification()` in the same turn.\n{{ /if }}\n\n{{ if isJavaScriptRuntime }}\nWhen done, call `await final(task, evidence)`:\n{{ else }}\nWhen done, call the runtime-exposed `final(task, evidence)` primitive:\n{{ /if }}\n\n- `task` — a one-line instruction the **responder** will follow when writing the user-facing output fields (e.g. \"Answer the user's question using the matched emails\").\n- `evidence` — the curated data the responder will read to follow `task`. Pass narrowed runtime values with only the fields that matter, not raw `inputs.*`. Use plain keys (for example, `matchedEmails`) — don't wrap under the output field name.\n\nDo not pre-format the answer; the responder writes the output fields.\n\nValid completion turns:\n\n{{ if isJavaScriptRuntime }}\n```{{ runtimeCodeFenceLanguage }}\nawait final(\"Answer the user's question using the gathered evidence\", { evidence });\n```\n\n```{{ runtimeCodeFenceLanguage }}\nawait askClarification(\"Which file should I analyze?\");\n```\n{{ else }}\nCompletion turns must call the runtime-exposed `final` or `askClarification` primitive using the syntax described in the runtime usage instructions.\n{{ /if }}\n\n## {{ runtimeLanguageName }} Runtime Usage Instructions\n{{ runtimeUsageInstructions }}\n";
    readonly 'rlm/responder.md': "## Answer Synthesis Agent\n\nYou synthesize the final answer from the evidence the actor gathered. You do not run code, call tools, or invoke agents — you read input fields and write the output fields.\n\n### Reading the actor's payload\n\n`Context Data` has two keys:\n\n- `task` — a one-line instruction telling you what to write into the output fields.\n- `evidence` — the data the actor curated for you to follow that instruction.\n\n### Rules\n\n1. Follow `Context Data.task` using `Context Data.evidence` and any other input fields provided.\n2. When emitting a JSON output field, write the value flat — do **not** wrap it under a key matching the field's title. The field is already named.\n3. If `evidence` lacks sufficient information, give the best possible answer from what's available across all input fields.\n4. Do not contradict actor evidence. If evidence contains a tool result, failure, status, output, or exception, report that result rather than inventing a capability limit.\n\n### Context variables that were analyzed (metadata only)\n{{ contextVarSummary }}\n{{ if hasAgentIdentity }}\n\n### Agent Identity\n\nUser-facing identity:\n{{ agentIdentityText }}\n{{ /if }}\n";
};
type TemplateId = keyof typeof promptTemplates;

type AxAgentContextStage = 'distiller' | 'executor';
type AxAgentContextPressure = 'ok' | 'watch' | 'critical';
type AxAgentContextEvent = {
    kind: 'budget_check';
    stage: AxAgentContextStage;
    turn: number;
    pressure: AxAgentContextPressure;
    mutablePromptChars: number;
    fixedPromptChars: number;
    effectiveBudgetChars: number;
    targetPromptChars: number;
    checkpointActive: boolean;
    actionLogEntryCount: number;
    guidanceLogEntryCount: number;
} | {
    kind: 'checkpoint_created' | 'checkpoint_cleared';
    stage: AxAgentContextStage;
    turn: number;
    coveredTurns: number[];
    summaryChars?: number;
    reason: 'over_budget' | 'under_budget' | 'disabled';
} | {
    kind: 'tombstone_created';
    stage: AxAgentContextStage;
    turn: number;
    resolvedByTurn: number;
    source: 'deterministic' | 'model';
    summaryChars: number;
} | {
    kind: 'action_compacted';
    stage: AxAgentContextStage;
    turn: number;
    mode: 'distill' | 'compact';
    reason: 'structured_output' | 'superseded' | 'pressure' | 'proactive' | 'lean';
    originalChars: number;
    renderedChars: number;
}
/**
 * Emitted once per ranked domain per forward when the advisory relevance
 * ranker runs (`relevanceRanking` plus the domain's prerequisite: modules
 * need `functionDiscovery`; skills/memories need their catalogs). Records
 * the shortlist actually surfaced to the model.
 *
 * To measure whether the hint helps, an observer joins per forward:
 * `shortlist.map((s) => s.id)` against what the model then loaded — for
 * modules the internal `discover` calls (`onFunctionCall` with
 * `kind:'internal'`, `name:'discover'`, `args.request`) and the module part
 * of external `qualifiedName`s; for skills `onLoadedSkills`/`used(id)`; for
 * memories `onLoadedMemories`/`used(id)`.
 */
 | {
    kind: 'relevance_ranking';
    stage: AxAgentContextStage;
    domain: 'modules' | 'skills' | 'memories';
    /** Length of the ranked task string (not the text — avoids log bloat). */
    taskChars: number;
    /** Items surfaced to the model, most relevant first ([] if suppressed). */
    shortlist: {
        id: string;
        score: number;
    }[];
    /** True when the low-confidence guard emitted nothing. */
    suppressed: boolean;
}
/**
 * Emitted once per field per run when `autoUpgrade.contextFields` keeps an
 * oversized undeclared input value runtime-only. The value stays available
 * in the code runtime as `inputs.<fieldName>`; the prompt carries a
 * truncated preview (or nothing when `promptPreviewChars` is undefined)
 * plus a `contextMetadata` entry.
 */
 | {
    kind: 'field_auto_promoted';
    stage: AxAgentContextStage;
    turn: number;
    fieldName: string;
    originalChars: number;
    /** Chars kept inline as a preview; undefined => runtime-only. */
    promptPreviewChars?: number;
};
type AxAgentOnContextEvent = (event: Readonly<AxAgentContextEvent>) => void | Promise<void>;

type AxAgentGuidancePayload = {
    type: 'guide_agent';
    guidance: string;
    triggeredBy?: string;
};
type AxAgentInternalCompletionPayload = AxAgentExecutorResultPayload | AxAgentGuidancePayload;
declare class AxAgentProtocolCompletionSignal extends Error {
    readonly type: AxAgentInternalCompletionPayload['type'];
    constructor(type: AxAgentInternalCompletionPayload['type']);
}

/**
 * Semantic Context Management for the AxAgent RLM loop.
 *
 * Manages the action log by evaluating step importance via hindsight heuristics,
 * generating compact tombstones for resolved errors, and pruning low-value entries
 * to maximize context window utility.
 */

type ActionLogTag = 'error' | 'dead-end' | 'foundational' | 'pivot' | 'superseded';
type ActionLogStepKind = 'explore' | 'transform' | 'query' | 'finalize' | 'error';
type ActionReplayMode = 'full' | 'distill' | 'compact' | 'omit';
type ActionLogHygieneMode = 'none' | 'pressure' | 'proactive' | 'aggressive';
type ActionLogFunctionCall = {
    qualifiedName: string;
    name?: string;
    arguments?: unknown;
    result?: unknown;
    error?: string;
};
type ActionLogEntry = {
    turn: number;
    code: string;
    output: string;
    tags: ActionLogTag[];
    summary?: string;
    producedVars?: string[];
    referencedVars?: string[];
    stateDelta?: string;
    stepKind?: ActionLogStepKind;
    replayMode?: ActionReplayMode;
    /** 0-5 importance score set by hindsight evaluation. */
    rank?: number;
    /** Compact summary replacing full code+output when rendered. */
    tombstone?: string;
    /** @internal Pending tombstone generation. */
    _tombstonePromise?: Promise<string>;
    /** @internal Direct qualified callable usages like `db.search(...)`. */
    _directQualifiedCalls?: readonly string[];
    /** @internal Runtime-recorded function calls made during this turn. */
    _functionCalls?: readonly ActionLogFunctionCall[];
    /** @internal Durable runtime values written during this turn. */
    _durableWrites?: readonly string[];
    /** @internal Runtime values read during this turn. */
    _durableReads?: readonly string[];
    /** @internal Retry hazards inferred from errors in this turn. */
    _failureHazards?: readonly string[];
};
type CheckpointSummaryState = {
    fingerprint: string;
    summary: string;
    turns: number[];
};
type RuntimeStateVariableProvenance = {
    createdTurn: number;
    lastReadTurn?: number;
    stepKind?: ActionLogStepKind;
    source?: string;
    code?: string;
};

/**
 * Interface for agents that can be used as child agents.
 * Provides methods to get the agent's function definition and features.
 */
interface AxAgentic<IN extends AxGenIn, OUT extends AxGenOut> extends AxProgrammable<IN, OUT> {
    getFunction(): AxFunction;
}
type AxAnyAgentic = AxAgentic<any, any>;
type AxFunctionProvider = {
    toFunction(): AxFunction | readonly AxFunction[];
};
type AxAgentIdentity = {
    name: string;
    description: string;
    namespace?: string;
};
type AxAgentFunctionModuleMeta = {
    namespace: string;
    title: string;
    selectionCriteria?: string;
    description?: string;
    alwaysInclude?: boolean;
};
type AxAgentFunctionExample = {
    code: string;
    title?: string;
    description?: string;
    language?: string;
};
type AxAgentFunction = Omit<AxFunction, 'description'> & {
    description?: string;
    examples?: readonly AxAgentFunctionExample[];
    /**
     * Marks the function's origin so the runtime can distinguish user-registered
     * tools (`'external'`, default) from agent-derived ones (`'internal'`) when
     * dispatching `onFunctionCall` observers. Set automatically when an
     * `AxAgentic` is supplied through `functions: [...]`.
     */
    _kind?: 'internal' | 'external';
    /** Internal marker copied from an `AxAgentFunctionGroup` with alwaysInclude. */
    _alwaysInclude?: boolean;
};
type AxAgentFunctionGroup = AxAgentFunctionModuleMeta & {
    functions: readonly (Omit<AxAgentFunction, 'namespace'> | AxFunctionProvider)[];
};
type AxAgentTestCompletionPayload = {
    type: 'final' | 'askClarification' | 'respond';
    args: unknown[];
};
type AxAgentTestResult = string | AxAgentTestCompletionPayload;
type AxAgentClarificationKind = 'text' | 'number' | 'date' | 'single_choice' | 'multiple_choice';
type AxAgentClarificationChoice = string | {
    label: string;
    value?: string;
};
type AxAgentClarification = string | AxAgentStructuredClarification;
type AxAgentStructuredClarification = {
    question: string;
    type?: AxAgentClarificationKind;
    choices?: AxAgentClarificationChoice[];
    [key: string]: unknown;
};
type AxAgentGuidanceLogEntry = {
    turn: number;
    guidance: string;
    triggeredBy?: string;
};
type AxAgentStateActionLogEntry = Pick<ActionLogEntry, 'turn' | 'code' | 'output' | 'tags' | 'summary' | 'producedVars' | 'referencedVars' | 'stateDelta' | 'stepKind' | 'replayMode' | 'rank' | 'tombstone'>;
type AxAgentStateCheckpointState = CheckpointSummaryState;
type AxAgentStateRuntimeEntry = AxCodeSessionSnapshotEntry;
type AxExecutorModelPolicyEntryBase = {
    model: string;
    namespaces?: readonly string[];
    aboveErrorTurns?: number;
};
type AxExecutorModelPolicyEntry = (AxExecutorModelPolicyEntryBase & {
    aboveErrorTurns: number;
}) | (AxExecutorModelPolicyEntryBase & {
    namespaces: readonly string[];
});
type AxAgentStateExecutorModelState = {
    consecutiveErrorTurns: number;
    matchedNamespaces?: string[];
};
type AxAgentDiscoveryPromptState = {
    modules?: Array<{
        module: string;
        text: string;
    }>;
    functions?: Array<{
        qualifiedName: string;
        text: string;
    }>;
};
type AxAgentSkillsPromptState = {
    loaded?: Array<{
        id?: string;
        name: string;
        content: string;
    }>;
};
type AxExecutorModelPolicy = readonly [
    AxExecutorModelPolicyEntry,
    ...AxExecutorModelPolicyEntry[]
];
type AxAgentState = {
    version: 1;
    runtimeBindings: Record<string, unknown>;
    runtimeEntries: AxAgentStateRuntimeEntry[];
    actionLogEntries: AxAgentStateActionLogEntry[];
    guidanceLogEntries?: AxAgentGuidanceLogEntry[];
    discoveryPromptState?: AxAgentDiscoveryPromptState;
    skillsPromptState?: AxAgentSkillsPromptState;
    checkpointState?: AxAgentStateCheckpointState;
    provenance: Record<string, RuntimeStateVariableProvenance>;
    actorModelState?: AxAgentStateExecutorModelState;
    /** Logical MCP references only; never credentials, sessions, or transports. */
    mcp?: AxMCPContinuationState;
};
declare class AxAgentClarificationError extends Error {
    readonly question: string;
    readonly clarification: AxAgentStructuredClarification;
    private readonly stateSnapshot;
    private readonly stateErrorMessage;
    constructor(clarification: AxAgentClarification, options?: Readonly<{
        state?: AxAgentState;
        stateError?: string;
    }>);
    getState(): AxAgentState | undefined;
}
type AxAgentFunctionCollection = readonly (AxAgentFunction | AxAnyAgentic | AxFunctionProvider)[] | readonly AxAgentFunctionGroup[];
type AxContextFieldInput = string | {
    field: string;
    promptMaxChars?: number;
    keepInPromptChars?: number;
    reverseTruncate?: boolean;
};
type AxContextFieldPromptConfig = {
    kind: 'threshold';
    promptMaxChars: number;
} | {
    kind: 'truncate';
    keepInPromptChars: number;
    reverseTruncate: boolean;
};
type AxAgentInputUpdateCallback<IN extends AxGenIn> = (currentInputs: Readonly<IN>) => Promise<Partial<IN> | undefined> | Partial<IN> | undefined;
type AxAgentActorTurnCallbackArgs = {
    /** Actor stage that produced this turn. */
    stage: AxAgentContextStage;
    /** 1-based actor turn number. */
    turn: number;
    /** Number of action log entries recorded after processing this turn. */
    actionLogEntryCount: number;
    /** Number of guidance log entries recorded after processing this turn. */
    guidanceLogEntryCount: number;
    /** Full actor AxGen output for the turn, including the runtime code field and any actor fields. */
    executorResult: Record<string, unknown>;
    /** Normalized runtime code that was executed for this turn. */
    code: string;
    /**
     * Raw runtime execution result before formatting or truncation.
     * For policy-violation turns and completion-signal turns, this is undefined.
     */
    result: unknown;
    /** Action-log-safe runtime output string after formatting/truncation. */
    output: string;
    /** True when the turn recorded an error output. */
    isError: boolean;
    /** Thought text returned by the actor AxGen when available. */
    thought?: string;
    /** Token usage for this turn only. */
    usage?: AxProgramUsage[];
    /** Model used for this turn, when explicitly set via executorModelPolicy. */
    model?: string;
    /** Raw ChatML conversation for this turn (system, user, assistant). Only populated when an actor turn callback is set. */
    chatLogMessages?: ReadonlyArray<{
        role: string;
        content: string;
    }>;
};
type AxAgentActorTurnCallback = (args: AxAgentActorTurnCallbackArgs) => void | Promise<void>;

/**
 * RLM (Recursive Language Model) interfaces and prompt builder.
 *
 * Pluggable interpreter interface — anyone can implement for any runtime.
 * No Node.js-specific imports; browser-safe.
 */

type AgentIdentityPrompt = Readonly<{
    name: string;
    description: string;
}>;
type AxRuntimeCallableFormatArgs = Readonly<{
    qualifiedName: string;
    description?: string;
    parameters?: AxFunctionJSONSchema;
    returns?: AxFunctionJSONSchema;
}>;
type AxRuntimePrimitiveOverrideMap = ReadonlyMap<string, readonly string[]> | Readonly<Record<string, readonly string[]>>;
type AxRuntimeLanguageInfo = Readonly<{
    languageName: string;
    codeFieldName: string;
    codeFieldTitle: string;
    codeFenceLanguage: string;
    isJavaScript: boolean;
}>;
/**
 * A code runtime that can create persistent sessions.
 * Implement this interface for your target runtime (Node.js, browser, WASM, etc.).
 */
interface AxCodeRuntime {
    /**
     * Human-readable language name for generated actor code.
     * Defaults to JavaScript when omitted for backwards compatibility.
     */
    readonly language?: string;
    createSession(globals?: Record<string, unknown>, options?: {
        shouldBubbleError?: (err: unknown) => boolean;
    }): AxCodeSession;
    /**
     * Optional runtime-specific usage guidance injected into the RLM system prompt.
     * Use this for execution semantics that differ by runtime/language.
     */
    getUsageInstructions(): string;
    /**
     * Optional language-native prompt text for built-in actor primitives such as
     * final, askClarification, discover, and recall.
     */
    getPrimitiveOverrides?(): AxRuntimePrimitiveOverrideMap | undefined;
    /**
     * Optional language-native formatter for callable tools exposed in the
     * runtime. Execution still happens inside the runtime session.
     */
    formatCallable?(args: AxRuntimeCallableFormatArgs): string;
}
type AxCodeSessionSnapshotEntry = {
    name: string;
    type: string;
    ctor?: string;
    size?: string;
    preview?: string;
    restorable?: boolean;
};
type AxCodeSessionSnapshot = {
    version: 1;
    entries: AxCodeSessionSnapshotEntry[];
    bindings: Record<string, unknown>;
};
/**
 * Result of {@link AxCodeSession.executeWithStatus}.
 */
type AxCodeExecutionResult = {
    /** The value `execute()` resolves with for the same code. */
    value: unknown;
    /**
     * True when `value` is the runtime's report of an error in the code (for
     * example `ReferenceError: x is not defined`) rather than a normal result.
     */
    isError: boolean;
};
/**
 * A persistent code execution session. Variables persist across `execute()` calls.
 */
interface AxCodeSession {
    execute(code: string, options?: {
        signal?: AbortSignal;
        reservedNames?: readonly string[];
    }): Promise<unknown>;
    /**
     * Optional variant of `execute()` that also reports whether the resolved
     * value describes an error in the code. Implement it when the runtime
     * returns errors as readable text instead of rejecting (as `AxJSRuntime`
     * does for `ReferenceError`, `TypeError`, `SyntaxError`, …) so AxAgent tags
     * those turns as errors while the actor still reads the same text. Without
     * it, only rejected executions count as errors.
     */
    executeWithStatus?(code: string, options?: {
        signal?: AbortSignal;
        reservedNames?: readonly string[];
    }): Promise<AxCodeExecutionResult>;
    inspectGlobals?(options?: {
        signal?: AbortSignal;
        reservedNames?: readonly string[];
    }): Promise<string>;
    snapshotGlobals?(options?: {
        signal?: AbortSignal;
        reservedNames?: readonly string[];
    }): Promise<AxCodeSessionSnapshot>;
    patchGlobals(globals: Record<string, unknown>, options?: {
        signal?: AbortSignal;
    }): Promise<void>;
    close(): void;
}
/**
 * Opinionated context replay presets for the Actor loop.
 *
 * - `full`: Keep prior actions fully replayed with minimal compression.
 *   Best for debugging or short tasks where the actor should reread exact old code/output.
 * - `adaptive`: Keep live runtime state visible, preserve recent or dependency-relevant
 *   actions in full, keep discovery docs available by default, and collapse older successful work
 *   into checkpoint summaries as context grows. Reliability-first defaults favor
 *   summaries before deletion. Best default for long multi-turn tasks.
 * - `lean`: Most aggressive compression. Keep live runtime state visible, checkpoint
 *   older successful work, and summarize replay-pruned successful turns instead of
 *   replaying their full code blocks. Reliability-first
 *   defaults still preserve recent evidence before deleting older low-value steps.
 *   Best when character-based prompt pressure matters more than raw replay detail.
 * - `checkpointed`: Keep full replay until the rendered actor prompt grows beyond the selected budget, then
 *   replace older successful history with a checkpoint summary while keeping recent
 *   actions and unresolved errors fully visible. Best when you want conservative,
 *   debugging-friendly replay until prompt pressure becomes real.
 */
type AxContextPolicyPreset = 'full' | 'adaptive' | 'lean' | 'checkpointed';
type AxContextPolicyBudget = 'compact' | 'balanced' | 'expanded';
/**
 * Public context policy for the Actor loop.
 * Users choose replay style via `preset` and overall prompt budget via `budget`.
 */
interface AxContextPolicyConfig {
    /**
     * Opinionated preset for how the agent should replay and compress context.
     *
     * - `full`: prefer raw replay of earlier actions
     * - `adaptive`: balance replay detail with checkpoint compression while keeping more recent evidence visible
     * - `lean`: prefer live state + compact summaries over raw replay detail
     * - `checkpointed`: keep full replay until the rendered actor prompt grows beyond the selected budget, then replace older successful turns with a checkpoint summary
     */
    preset?: AxContextPolicyPreset;
    /** Overall prompt budget and compression aggressiveness. */
    budget?: AxContextPolicyBudget;
}
/**
 * RLM configuration for AxAgent.
 */
interface AxRLMConfig {
    /** Input fields holding long context (will be removed from the LLM prompt). */
    contextFields: string[];
    /** Actor prompt verbosity and scaffolding level (default: 'default'). */
    promptLevel?: 'default' | 'detailed';
    /** Code runtime for the REPL loop (default: AxJSRuntime). */
    runtime?: AxCodeRuntime;
    /** Global cap on recursive sub-agent calls across all descendants (default: 100). */
    maxSubAgentCalls?: number;
    /** Maximum parallel llmQuery calls in batched mode (default: 8). */
    maxBatchedLlmQueryConcurrency?: number;
    /** Maximum Actor turns before forcing Responder (default: 10). */
    maxTurns?: number;
    /** Maximum characters to keep from runtime output and console/log replay (default: 3000). */
    maxRuntimeChars?: number;
    /**
     * Maximum serialized characters for a `final(task, evidence)` evidence
     * object crossing the host boundary (default: 50000). Oversized evidence
     * throws inside the actor turn so the model narrows and retries; in-worker
     * evidence handoffs in shared-session mode are exempt.
     */
    maxEvidenceChars?: number;
    /** Context replay, checkpointing, and runtime-state policy. */
    contextPolicy?: AxContextPolicyConfig;
    /** Default options for the internal checkpoint summarizer. */
    summarizerOptions?: Omit<AxProgramForwardOptions<string>, 'functions'>;
    /**
     * Called after each Actor turn is recorded with both raw runtime output and
     * the formatted action-log output.
     */
    actorTurnCallback?: AxAgentActorTurnCallback;
    /**
     * Called when AxAgent measures context pressure or changes compacted context state.
     * Intended for observability; callback failures are ignored.
     */
    onContextEvent?: AxAgentOnContextEvent;
    /**
     * Called when the actor signals task progress via `reportSuccess(message)` or `reportFailure(message)`.
     */
    agentStatusCallback?: (message: string, status: 'success' | 'failed') => void | Promise<void>;
}
/**
 * Builds the context-understanding actor system prompt (the distiller).
 * The distiller is the pipeline's reconnaissance phase: it explores
 * long-context inputs AND the executor's capability surface (function
 * schemas, module catalog, skills index, discovery) so its evidence is shaped
 * to what the executor's tools will actually consume. It cannot execute
 * tools — its callables are throwing stubs.
 */
declare function axBuildDistillerDefinition(baseDefinition: string | undefined, contextFields: readonly AxIField[], options: Readonly<{
    runtimeUsageInstructions?: string;
    runtimeLanguageName?: string;
    runtimeCodeFieldTitle?: string;
    runtimeCodeFenceLanguage?: string;
    isJavaScriptRuntime?: boolean;
    formatCallable?: AxCodeRuntime['formatCallable'];
    promptLevel?: 'default' | 'detailed';
    hasInspectRuntime?: boolean;
    hasLiveRuntimeState?: boolean;
    hasCompressedActionReplay?: boolean;
    /** Enables tool discovery (`discover`) in the prompt. */
    discoveryMode?: boolean;
    /** Enables `discover({ skills })` runtime overload in the prompt. */
    skillsMode?: boolean;
    /** Static skill catalog rendered as an `### Available Skills` index. */
    skillsCatalog?: ReadonlyArray<{
        id: string;
        name: string;
        description?: string;
    }>;
    /** Enables `recall` runtime primitive in the prompt. */
    memoriesMode?: boolean;
    /** Enables the generic `used` runtime primitive in the prompt. */
    usageTrackingMode?: boolean;
    /** Enables actor-declared memory usage instructions. */
    memoryUsageMode?: boolean;
    /** Enables actor-declared skill usage instructions. */
    skillUsageMode?: boolean;
    /**
     * Dynamic direct-respond: offers `respond(task, evidence)` alongside
     * `final` under the conservative direct-response covenant.
     */
    directRespondMode?: boolean;
    /**
     * Static direct-respond (agent has no functions/child agents): `respond`
     * replaces `final` as the completion primitive and the prompt drops the
     * executor-forwarding covenant. Mutually exclusive with
     * `directRespondMode`.
     */
    directRespondOnly?: boolean;
    /** Optional prompt-resident orientation cache for recurring long context. */
    contextMapText?: string;
    availableModules?: ReadonlyArray<{
        namespace: string;
        selectionCriteria?: string;
    }>;
    agentFunctions?: ReadonlyArray<{
        name: string;
        description?: string;
        parameters?: AxFunctionJSONSchema;
        returns?: AxFunctionJSONSchema;
        namespace: string;
        alwaysInclude?: boolean;
    }>;
    /** Optional override for the `rlm/distiller.md` template source. */
    templateOverride?: string;
    /** Optional per-primitive override map keyed by primitive id. */
    primitiveOverrides?: ReadonlyMap<string, readonly string[]>;
}>): string;
/**
 * Builds the executor system prompt. The executor consumes
 * `inputs.executorRequest` and `inputs.distilledContext` from the prior
 * distiller stage and runs tools / discovery to complete the task.
 */
declare function axBuildExecutorDefinition(baseDefinition: string | undefined, contextFields: readonly AxIField[], responderOutputFields: readonly AxIField[], options: Readonly<{
    runtimeUsageInstructions?: string;
    runtimeLanguageName?: string;
    runtimeCodeFieldTitle?: string;
    runtimeCodeFenceLanguage?: string;
    isJavaScriptRuntime?: boolean;
    formatCallable?: AxCodeRuntime['formatCallable'];
    promptLevel?: 'default' | 'detailed';
    hasInspectRuntime?: boolean;
    hasLiveRuntimeState?: boolean;
    hasCompressedActionReplay?: boolean;
    llmQueryPromptMode?: 'simple';
    enforceIncrementalConsoleTurns?: boolean;
    hasAgentStatusCallback?: boolean;
    discoveryMode?: boolean;
    /** Renders the advisory "Likely Relevant" instruction section. */
    relevanceHintsMode?: boolean;
    /** Enables `discover({ skills })` runtime overload in the prompt. */
    skillsMode?: boolean;
    /**
     * Static skill catalog rendered as an `### Available Skills` index so
     * skill discovery is targeted instead of blind. Construction-stable, so
     * it is safe inside the cached system prompt.
     */
    skillsCatalog?: ReadonlyArray<{
        id: string;
        name: string;
        description?: string;
    }>;
    /** Enables `recall` runtime primitive in the prompt. */
    memoriesMode?: boolean;
    /** Enables the generic `used` runtime primitive in the prompt. */
    usageTrackingMode?: boolean;
    /** Enables actor-declared memory usage instructions. */
    memoryUsageMode?: boolean;
    /** Enables actor-declared skill usage instructions. */
    skillUsageMode?: boolean;
    /** Distiller-prompt concern (dynamic direct-respond); ignored here. */
    directRespondMode?: boolean;
    /** Distiller-prompt concern (static direct-respond); ignored here. */
    directRespondOnly?: boolean;
    /** Optional prompt-resident orientation cache for recurring long context. */
    contextMapText?: string;
    availableModules?: ReadonlyArray<{
        namespace: string;
        selectionCriteria?: string;
    }>;
    discoveredDocsMarkdown?: string;
    /** Skill bodies accumulated during the current run (sorted by id). */
    skillsMarkdown?: string;
    agentFunctions?: ReadonlyArray<{
        name: string;
        description?: string;
        parameters?: AxFunctionJSONSchema;
        returns?: AxFunctionJSONSchema;
        namespace: string;
        alwaysInclude?: boolean;
    }>;
    /** Optional override for the `rlm/executor.md` template source. */
    templateOverride?: string;
    /** Optional per-primitive override map keyed by primitive id. */
    primitiveOverrides?: ReadonlyMap<string, readonly string[]>;
}>): string;
/**
 * Builds the Responder system prompt. The Responder synthesizes a final answer
 * from the action log produced by the Actor. It NEVER generates code.
 */
declare function axBuildResponderDefinition(baseDefinition: string | undefined, contextFields: readonly AxIField[], options?: Readonly<{
    /** User-facing agent identity from `agentIdentity`. */
    agentIdentity?: AgentIdentityPrompt;
    /** Optional override for the `rlm/responder.md` template source. */
    templateOverride?: string;
}>): string;

type AxAgentMemoryResult = {
    /** Stable identifier — dedup key and label in `inputs.memories`. */
    id: string;
    /** Opaque markdown body (frontmatter, if any, is not parsed). */
    content: string;
};
type AxAgentUsedMemory = {
    /** Stable identifier of a memory present in `inputs.memories`. */
    id: string;
    /** Short actor-declared explanation of how the memory influenced the run. */
    reason?: string;
    /** Actor stage that declared this memory as used. */
    stage: AxAgentContextStage;
};
type AxAgentUsedMemoriesCallback = (usedMemories: readonly AxAgentUsedMemory[]) => void | Promise<void>;
/**
 * Memories search callback. Receives the raw search strings and the
 * snapshot of `inputs.memories` already loaded for the current run
 * (deduped by id, sorted). Use the second argument to skip work for
 * entries that are already in scope — for example, filter your vector
 * search by `id NOT IN alreadyLoaded` so you don't re-fetch and the
 * actor doesn't pay tokens for duplicates. Returning already-loaded
 * entries is still safe (the runtime dedupes by id) but wastes work.
 */
type AxAgentMemoriesSearchFn = (searches: readonly string[], alreadyLoaded: readonly AxAgentMemoryResult[]) => readonly AxAgentMemoryResult[] | Promise<readonly AxAgentMemoryResult[]>;

type AxAgentSkillResult = {
    /** Stable identifier — dedup key, prompt label, and usage telemetry key. */
    id?: string;
    /** Human-readable title rendered in the Loaded Skills prompt section. */
    name: string;
    /** Opaque markdown body (frontmatter, if any, is not parsed). */
    content: string;
};
/**
 * A skill in a host-provided static catalog (`skillsCatalog` option). Unlike
 * `skills` (which preloads full content into the prompt), a catalog entry is
 * only loaded when matched — by the built-in local search that backs
 * `discover({ skills })` when no `onSkillsSearch` callback is provided, and by
 * the advisory relevance hint.
 */
type AxAgentCatalogSkill = {
    /** Stable identifier — dedup key, prompt label, and usage telemetry key. */
    id: string;
    /** Human-readable title. */
    name: string;
    /** Optional short "when to use" description (high-signal for matching). */
    description?: string;
    /** Full markdown body returned when the skill is loaded. */
    content: string;
};
type AxAgentSkillsSearchFn = (searches: readonly string[]) => readonly AxAgentSkillResult[] | Promise<readonly AxAgentSkillResult[]>;
type AxAgentUsedSkill = {
    /** Stable skill id present in the Loaded Skills prompt state. */
    id: string;
    /** Human-readable skill title. */
    name: string;
    /** Optional actor-declared explanation of how the skill influenced the run. */
    reason?: string;
    /** Actor stage that declared this skill as used. */
    stage: AxAgentContextStage;
};
type AxAgentUsedSkillsCallback = (usedSkills: readonly AxAgentUsedSkill[]) => void | Promise<void>;

/**
 * Smart-defaults knob: `true`/`false` toggles both upgrades; an object tunes
 * each independently (an object value implies enabled for that domain).
 */
type AxAgentAutoUpgrade = boolean | {
    /** Auto-enable runtime callable discovery for large tool catalogs. */
    functionDiscovery?: boolean | {
        aboveFunctionDocChars?: number;
    };
    /** Auto-keep oversized undeclared input values runtime-only. */
    contextFields?: boolean | {
        promoteAboveChars?: number;
        previewChars?: number;
    };
};
type AxResolvedAutoUpgrade = {
    functionDiscovery: {
        enabled: boolean;
        aboveFunctionDocChars: number;
    };
    contextFields: {
        enabled: boolean;
        promoteAboveChars: number;
        previewChars: number;
    };
};
/**
 * Direct-respond knob: lets the distiller end the run with
 * `respond(task, evidence)` and skip the executor stage entirely (zero
 * executor model calls) when the task needs no user-provided functions.
 *
 * - `'auto'` (default): agents with zero functions/child agents run
 *   respond-only (the skip is deterministic — `final` is not offered);
 *   agents WITH functions offer `respond` alongside `final` under a
 *   conservative covenant (no live/fresh-state asks, no side effects, no
 *   task covered by a listed function/module domain).
 * - `'off'`: the primitive is absent from the prompt and the runtime, and a
 *   respond payload reaching the pipeline is rejected.
 */
type AxAgentDirectResponse = 'auto' | 'off';
/**
 * Chain-of-evidence citations knob: when enabled, the responder gains an
 * optional string-array output field whose entries must be evidence ids the
 * answer actually relies on — the top-level keys of the `final(task,
 * evidence)` / `respond(task, evidence)` evidence object, plus (by default)
 * the `id` of any id-bearing records one level deep inside it, e.g. loaded
 * memories. Citations are validated subset-only against those ids; a
 * violation re-prompts the responder through the standard validation-retry
 * loop. Runs without evidence skip validation entirely.
 */
type AxAgentCitations = boolean | {
    /** Responder output field name. Default 'evidenceCitations'. */
    field?: string;
    /**
     * Where validated citations land. `'output'` (default) keeps the field
     * on the returned result; `'hidden'` strips it after validation so the
     * result matches the user signature exactly — read citations via
     * `onCitations`.
     */
    surface?: 'output' | 'hidden';
    /**
     * Also accept `id` values of record arrays one level deep in the
     * evidence object (the shape `recall(...)` memories arrive in).
     * Default true.
     */
    includeMemoryIds?: boolean;
    /** Observer for validated citations; failures are swallowed. */
    onCitations?: (citations: readonly string[]) => void | Promise<void>;
};
/** Convenience result intersection for reading citations off a forward result. */
type AxAgentCitationsOutput = {
    evidenceCitations?: string[];
};
type AxResolvedCitations = {
    enabled: boolean;
    field: string;
    surface: 'output' | 'hidden';
    includeMemoryIds: boolean;
    onCitations?: (citations: readonly string[]) => void | Promise<void>;
};

/**
 * Deterministic failure harvesting for the AxAgent RLM loop.
 *
 * Builds a structured report of failure signals from the live action-log
 * entries at the end of a stage run — while the internal per-turn metadata
 * (`_functionCalls`) is still present — so run-end consumers (playbook
 * learning) never need the internal fields to survive state serialization.
 * Zero LLM calls; every heuristic here is pure and synchronous.
 */

type AxAgentFailureSignalKind = 
/** A turn errored and was neither resolved nor a repeat of the prior turn. */
'error_turn'
/** A turn errored, a later turn succeeded, and the signature never recurred. */
 | 'resolved_error'
/** A turn repeated the previous turn's failure (same error signature). */
 | 'dead_end'
/** A registered tool/function call returned an error during a turn. */
 | 'tool_error';
type AxAgentFailureSignal = {
    kind: AxAgentFailureSignalKind;
    /** Turn the failing action ran in. */
    turn: number;
    /** Normalized fingerprint (`extractErrorSignature`) used for deduping. */
    signature: string;
    /** Human-readable failure line (error message / `tool: error`). */
    detail: string;
    /** `resolved_error` only: turn whose action resolved the failure. */
    resolvedByTurn?: number;
    /** Truncated offending actor code (or tool arguments digest). */
    code?: string;
    /** Number of merged occurrences of this (kind, signature) pair. */
    occurrences: number;
};
type AxAgentFailureReport = {
    stage: 'distiller' | 'executor';
    signals: readonly AxAgentFailureSignal[];
};
/** Playbook section that curated failure-avoidance rules land in. */
declare const axPlaybookFailureSection = "failures_to_avoid";

type AxJudgeForwardOptions = Omit<AxProgramForwardOptions<string>, 'functions' | 'description'>;
interface AxJudgeOptions extends AxJudgeForwardOptions {
    ai: AxAIService;
    criteria?: string;
    description?: string;
    randomizeOrder?: boolean;
}

/**
 * Individual playbook bullet with metadata used for incremental updates.
 * Mirrors the structure described in the ACE paper (Section 3.1).
 */
interface AxACEBullet extends Record<string, unknown> {
    id: string;
    section: string;
    content: string;
    helpfulCount: number;
    harmfulCount: number;
    createdAt: string;
    updatedAt: string;
    tags?: string[];
    metadata?: Record<string, unknown>;
}
/**
 * Aggregated ACE playbook structure grouped by sections.
 */
interface AxACEPlaybook {
    version: number;
    sections: Record<string, AxACEBullet[]>;
    stats: {
        bulletCount: number;
        helpfulCount: number;
        harmfulCount: number;
        tokenEstimate: number;
    };
    updatedAt: string;
    description?: string;
}
/**
 * Generator output format (Appendix B of the paper) distilled to core fields.
 */
interface AxACEGeneratorOutput extends Record<string, unknown> {
    reasoning: string;
    answer: unknown;
    bulletIds: string[];
    trajectory?: string;
    metadata?: Record<string, unknown>;
}
/**
 * Reflection payload, mapping to the Reflector JSON schema in the paper.
 */
interface AxACEReflectionOutput extends Record<string, unknown> {
    reasoning: string;
    errorIdentification: string;
    rootCauseAnalysis: string;
    correctApproach: string;
    keyInsight: string;
    bulletTags: {
        id: string;
        tag: 'helpful' | 'harmful' | 'neutral';
    }[];
    metadata?: Record<string, unknown>;
}
/**
 * Curator operations emitted as deltas (Section 3.1).
 */
type AxACECuratorOperationType = 'ADD' | 'UPDATE' | 'REMOVE';
interface AxACECuratorOperation {
    type: AxACECuratorOperationType;
    section: string;
    bulletId?: string;
    content?: string;
    metadata?: Record<string, unknown>;
}
interface AxACECuratorOutput extends Record<string, unknown> {
    reasoning: string;
    operations: AxACECuratorOperation[];
    metadata?: Record<string, unknown>;
}
/**
 * Runtime feedback captured after each generator rollout for online updates.
 */
interface AxACEFeedbackEvent {
    example: AxExample$1;
    prediction: unknown;
    score: number;
    generatorOutput: AxACEGeneratorOutput;
    reflection?: AxACEReflectionOutput;
    curator?: AxACECuratorOutput;
    timestamp: string;
}
/**
 * Configuration options specific to ACE inside Ax.
 */
interface AxACEOptions {
    /**
     * Maximum number of epochs for offline adaptation.
     */
    maxEpochs?: number;
    /**
     * Maximum reflector refinement rounds (paper uses up to 5).
     */
    maxReflectorRounds?: number;
    /**
     * Maximum bullets allowed in any section before triggering pruning.
     */
    maxSectionSize?: number;
    /**
     * Reserved threshold value; current dedupe uses normalized exact-content match.
     */
    similarityThreshold?: number;
    /**
     * Whether to automatically create sections when curator emits new ones.
     */
    allowDynamicSections?: boolean;
    /**
     * Initial playbook supplied by the caller.
     */
    initialPlaybook?: AxACEPlaybook;
    /**
     * Maximum serialized characters per field stored in ACE trajectories.
     */
    maxSerializedFieldChars?: number;
}
/**
 * Serialized artifact saved after optimization for future reuse.
 */
interface AxACEOptimizationArtifact {
    playbook: AxACEPlaybook;
    feedback: AxACEFeedbackEvent[];
    history: {
        source?: 'compile' | 'online';
        epoch: number;
        exampleIndex: number;
        operations: AxACECuratorOperation[];
        /**
         * Ids of the bullets this delta created or updated. ADD operations get
         * their ids assigned at apply time, so the operations alone cannot be
         * mapped back to surviving bullets — this field can.
         */
        updatedBulletIds?: string[];
    }[];
}

/**
 * Options for {@link playbook}.
 *
 * A playbook grows an evolving body of task knowledge ("context engineering")
 * and renders it into a program's context. The underlying evolution engine is
 * an implementation detail (currently ACE — the Agentic Context Engineering
 * loop) and is intentionally absent from this surface, mirroring how
 * {@link optimize} hides its optimizer.
 */
type AxPlaybookOptions = {
    /** Model that runs the program while the playbook is grown. */
    studentAI: AxAIService;
    /** Model used to reflect on rollouts and curate the playbook. Defaults to studentAI. */
    teacherAI?: AxAIService;
    /**
     * AI service options for the reflection and curation calls, including when
     * they fall back to `studentAI`. Set `useExpensiveModel: 'yes'` to use a
     * teacher model marked `isExpensive`.
     */
    teacherOptions?: AxAIServiceOptions;
    verbose?: boolean;
    seed?: number;
    /** Max passes over the dataset during {@link AxPlaybook.evolve}. */
    maxEpochs?: number;
    /** Max reflection refinement rounds per example. */
    maxReflectorRounds?: number;
    /** Max bullets per section before pruning kicks in. */
    maxSectionSize?: number;
    /** Allow the playbook to grow new sections on its own. */
    allowDynamicSections?: boolean;
    /** Seed the playbook with existing content. */
    initialPlaybook?: AxACEPlaybook;
    /** Intensity preset applied at construction. */
    auto?: 'light' | 'medium' | 'heavy';
};
/**
 * A serializable snapshot of a playbook's content and history. Persist with
 * {@link AxPlaybook.toJSON} and restore with {@link AxPlaybook.load}.
 */
type AxPlaybookSnapshot = {
    playbook: AxACEPlaybook;
    artifact: AxACEOptimizationArtifact;
};
/** Result of {@link AxPlaybook.evolve}: the best score reached and the resulting playbook. */
type AxPlaybookEvolveResult = {
    bestScore: number;
    playbook: AxACEPlaybook;
};
/** Per-run overrides for a single {@link AxPlaybook.evolve} call. */
type AxPlaybookEvolveOptions = {
    maxEpochs?: number;
    auto?: 'light' | 'medium' | 'heavy';
};
/**
 * A live, evolving context playbook bound to a program.
 *
 * Grow it offline from examples ({@link evolve}), keep it growing online from
 * live feedback ({@link update}), render it into the program's context
 * ({@link applyTo}), and persist/restore it ({@link toJSON}/{@link load}).
 *
 * Construct via the {@link playbook} factory.
 */
declare class AxPlaybook<IN = any, OUT extends AxGenOut = AxGenOut> {
    private readonly program;
    private readonly engine;
    private readonly baseInstruction;
    private started;
    private applyHook?;
    constructor(program: Readonly<AxGen<IN, OUT>>, options: Readonly<AxPlaybookOptions>);
    /**
     * Grow the playbook offline from labeled examples, scoring each rollout with
     * `metricFn`, then render the result into the bound program.
     */
    evolve(examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn, options?: Readonly<AxPlaybookEvolveOptions>): Promise<AxPlaybookEvolveResult>;
    /**
     * Refine the playbook online from a single live interaction. Safe to call
     * without a prior {@link evolve}/{@link load} — the bound program is hydrated
     * lazily on first use.
     */
    update(args: Readonly<{
        example: AxExample$1;
        prediction: unknown;
        feedback?: string;
    }>): Promise<void>;
    /** Render the current playbook into a program's context (defaults to the bound program). */
    applyTo(program?: Readonly<AxGen<IN, OUT>>): void;
    /** The current playbook rendered as a markdown block. */
    render(): string;
    /** A serializable snapshot of the current playbook and its history. */
    getState(): AxPlaybookSnapshot;
    /** Alias of {@link getState} so `JSON.stringify(handle)` yields a snapshot. */
    toJSON(): AxPlaybookSnapshot;
    /** Restore a snapshot into this handle and render it into the bound program. */
    load(snapshot: Readonly<AxPlaybookSnapshot>): this;
    /** Set the evolution intensity preset. */
    configureAuto(level: 'light' | 'medium' | 'heavy'): void;
    /** Clear the playbook back to its initial state. */
    reset(): void;
    /**
     * @internal Redirect playbook injection. Used by `agent.playbook()` to push
     * the rendered playbook into a pipeline stage instead of a bare program.
     */
    _setApplyHook(hook: (rendered: string) => void): void;
    private inject;
}
/**
 * Create an evolving context {@link AxPlaybook} for a program.
 *
 * A playbook accumulates task knowledge and renders it into the program's
 * context: grow it offline from examples ({@link AxPlaybook.evolve}), keep it
 * growing online from live feedback ({@link AxPlaybook.update}), and
 * persist/restore it ({@link AxPlaybook.toJSON}/{@link AxPlaybook.load}). The
 * evolution engine is an implementation detail and never appears on this
 * surface.
 */
declare function playbook<IN = any, OUT extends AxGenOut = AxGenOut>(program: Readonly<AxGen<IN, OUT>>, options: Readonly<AxPlaybookOptions>): AxPlaybook<IN, OUT>;

type AxAgentRecursiveTargetId = 'root.actor.shared' | 'root.actor.root' | 'root.actor.recursive' | 'root.actor.terminal' | 'root.responder';
type AxAgentRecursiveNodeRole = 'root' | 'recursive' | 'terminal';
type AxAgentRecursiveUsage = {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
};
type AxAgentRecursiveTurn = {
    turn: number;
    code: string;
    output: string;
    isError: boolean;
    thought?: string;
};
type AxAgentRecursiveFunctionCall = {
    qualifiedName: string;
    name?: string;
    error?: string;
};
type AxAgentRecursiveTraceNode = {
    nodeId: string;
    parentId?: string;
    depth: number;
    role: AxAgentRecursiveNodeRole;
    taskDigest?: string;
    contextDigest?: string;
    completionType?: 'final' | 'askClarification';
    turnCount: number;
    childCount: number;
    actorTurns: AxAgentRecursiveTurn[];
    functionCalls: AxAgentRecursiveFunctionCall[];
    toolErrors: string[];
    localUsage: AxAgentRecursiveUsage;
    cumulativeUsage: AxAgentRecursiveUsage;
    children: AxAgentRecursiveTraceNode[];
};
type AxAgentRecursiveExpensiveNode = {
    nodeId: string;
    role: AxAgentRecursiveNodeRole;
    depth: number;
    taskDigest?: string;
    totalTokens: number;
};
type AxAgentRecursiveStats = {
    nodeCount: number;
    leafCount: number;
    maxDepth: number;
    recursiveCallCount: number;
    batchedFanOutCount: number;
    clarificationCount: number;
    errorCount: number;
    directAnswerCount: number;
    delegatedAnswerCount: number;
    rootLocalUsage: AxAgentRecursiveUsage;
    rootCumulativeUsage: AxAgentRecursiveUsage;
    topExpensiveNodes: AxAgentRecursiveExpensiveNode[];
};

type AxAgentContextMapSnapshot = {
    version: 1;
    text: string;
    scores?: Record<string, number>;
    steps?: number;
    maxChars?: number;
    infiniteEvolve?: boolean;
    evolveSteps?: number;
};
type AxAgentContextMapOptions = {
    maxChars?: number;
    infiniteEvolve?: boolean;
    evolveSteps?: number;
};
type AxAgentContextMapOperation = {
    type: 'ADD';
    section: string;
    content: string;
} | {
    type: 'DELETE';
    itemId: string;
} | {
    type: 'REPLACE';
    itemId: string;
    content: string;
};
type AxAgentContextMapUpdateResult = {
    map: AxAgentContextMap;
    mapText: string;
    status: 'updated' | 'unchanged' | 'skipped';
    step: number;
    skipReason?: 'evolve_steps';
    diagnosis?: string;
    operations: AxAgentContextMapOperation[];
    changed: boolean;
};
type AxAgentContextMapConfig = {
    map?: AxAgentContextMap | AxAgentContextMapSnapshot | string;
    onUpdate?: (result: AxAgentContextMapUpdateResult) => void | Promise<void>;
};
type ContextMapUpdaterOutput = {
    diagnosis?: string;
    itemTags?: Record<string, unknown>;
    cacheCandidates?: unknown;
    operations?: unknown;
};
declare class AxAgentContextMap {
    private maxChars;
    private infiniteEvolve;
    private evolveSteps?;
    private scores;
    private steps;
    text: string;
    constructor(input?: AxAgentContextMapSnapshot | string, options?: AxAgentContextMapOptions);
    static fromSnapshot(snapshot: AxAgentContextMapSnapshot, options?: AxAgentContextMapOptions): AxAgentContextMap;
    static fromText(text: string, options?: AxAgentContextMapOptions): AxAgentContextMap;
    snapshot(): AxAgentContextMapSnapshot;
    tag(itemId: string, tag: string): boolean;
    private shouldEvolve;
    private skippedUpdateResult;
    applyUpdatePayload(payload: ContextMapUpdaterOutput): AxAgentContextMapUpdateResult;
    update(ai: Readonly<AxAIService>, args: Readonly<{
        task: string;
        trajectory: string;
        options?: Readonly<Omit<AxProgramForwardOptions<string>, 'functions'>>;
    }>): Promise<AxAgentContextMapUpdateResult>;
}

/**
 * Construction-time playbook configuration for AxAgent.
 *
 * Mirrors the `contextMap` config precedent: attach an evolving
 * {@link AxPlaybook} to an agent at construction, keep it rendered into the
 * live stage prompt, and (by default) let the agent learn from its own
 * failures — a run-end hook harvests the run's failure signals and curates
 * durable avoidance rules into the playbook so later runs stop repeating
 * them. Persistence is caller-driven via `onUpdate`.
 */

type AxAgentPlaybookLearnOptions = {
    /**
     * Failure signals a run must produce before spending LLM calls on a
     * playbook update. Default 1.
     */
    minSignals?: number;
    /**
     * Skip signals whose signature was already curated into this playbook —
     * recorded on the snapshot artifact's update events, so the check is
     * deterministic and survives save/restore. Coverage lapses when every
     * bullet that update produced has since been pruned from the playbook, so
     * a lost lesson can be re-learned; an update the curator explicitly
     * answered with no operations stays covered. Default true.
     */
    dedupe?: boolean;
};
type AxAgentPlaybookUpdateStatus = 'updated' | 'unchanged' | 'skipped';
type AxAgentPlaybookSkipReason = 'learning_disabled' | 'no_failures' | 'below_min_signals' | 'all_duplicates';
type AxAgentPlaybookUpdateResult = {
    /** Snapshot of the playbook after this run (persist via `onUpdate`). */
    snapshot: AxPlaybookSnapshot;
    status: AxAgentPlaybookUpdateStatus;
    skipReason?: AxAgentPlaybookSkipReason;
    /** Failure signals this update was fed (fresh signals only when deduping). */
    signals: readonly AxAgentFailureSignal[];
    /** Digest text sent to the playbook curator. Absent on skips. */
    feedback?: string;
};
type AxAgentPlaybookConfig = {
    /**
     * Seed content: a persisted {@link AxPlaybookSnapshot} (from `onUpdate` /
     * `handle.getState()`) or a bare playbook object.
     */
    playbook?: AxPlaybookSnapshot | AxACEPlaybook;
    /** Stage whose live prompt receives the rendered playbook. Default 'actor'. */
    target?: 'actor' | 'responder';
    /** Render the playbook into the live stage prompt. Default true. */
    apply?: boolean;
    /**
     * Run-end failure learning — ON by default (the config block itself is the
     * opt-in). After each completed run that produced failure signals (error
     * turns, repeated dead-ends, tool errors), one bounded playbook update
     * (default: 1 reflector + 1 curator call) curates avoidance rules into the
     * `failures_to_avoid` section. Clean runs cost zero extra calls. Pass an
     * object to tune gating, or `false` for a render-only playbook.
     */
    learn?: boolean | AxAgentPlaybookLearnOptions;
    /**
     * Persistence hook — fires after a run-end update actually ran
     * (`status !== 'skipped'`). Failures in the hook are swallowed; playbook
     * upkeep never breaks the completed user-facing run.
     */
    onUpdate?: (result: AxAgentPlaybookUpdateResult) => void | Promise<void>;
    /** AI running reflection/curation. Defaults to the agent's `ai`. */
    studentAI?: Readonly<AxAIService>;
    /** Stronger model for reflection/curation. Defaults to the agent's `judgeAI`. */
    teacherAI?: Readonly<AxAIService>;
    /**
     * AI service options for the reflection and curation calls. Set
     * `useExpensiveModel: 'yes'` for a teacher marked `isExpensive`; without
     * it those calls are rejected before any request is sent, and updates
     * curate nothing.
     */
    teacherOptions?: AxAIServiceOptions;
} & Pick<AxPlaybookOptions, 'maxReflectorRounds' | 'maxSectionSize' | 'allowDynamicSections' | 'seed' | 'verbose'>;
type AxResolvedAgentPlaybookLearn = {
    enabled: boolean;
    minSignals: number;
    dedupe: boolean;
};
type AxResolvedAgentPlaybookConfig = {
    seedPlaybook?: AxPlaybookSnapshot | AxACEPlaybook;
    target: 'actor' | 'responder';
    apply: boolean;
    learn: AxResolvedAgentPlaybookLearn;
    onUpdate?: (result: AxAgentPlaybookUpdateResult) => void | Promise<void>;
    studentAI?: Readonly<AxAIService>;
    teacherAI?: Readonly<AxAIService>;
    teacherOptions?: AxAIServiceOptions;
    playbookOptions: Pick<AxPlaybookOptions, 'maxReflectorRounds' | 'maxSectionSize' | 'allowDynamicSections' | 'seed' | 'verbose'>;
};

/**
 * Demo traces for AxAgent's split architecture.
 * Actor demos use the runtime code field (`javascriptCode` for JavaScript,
 * `<language>Code` for other runtimes such as `pythonCode`).
 * Responder demos use the agent's output type + optional input fields.
 */
type AxAgentDemos<IN extends AxGenIn, OUT extends AxGenOut, PREFIX extends string = string> = {
    programId: `${PREFIX}.actor`;
    traces: Record<string, AxFieldValue>[];
} | {
    programId: `${PREFIX}.responder`;
    traces: (OUT & Partial<IN>)[];
};
type AxAgentJudgeOptions = Partial<Omit<AxJudgeOptions, 'ai'>>;
type AxAgentOptimizeTarget = 'actor' | 'responder' | 'all' | readonly string[];
type AxAgentEvalFunctionCall = {
    qualifiedName: string;
    name: string;
    arguments: AxFieldValue;
    result?: AxFieldValue;
    error?: string;
};
type AxAgentEvalPredictionShared = {
    actionLog: string;
    guidanceLog?: string;
    functionCalls: AxAgentEvalFunctionCall[];
    toolErrors: string[];
    turnCount: number;
    usage?: AxProgramUsage[];
    /**
     * Deterministic failure signals harvested from the run's stages (merged
     * distiller + executor), when the run produced any. Structured input for
     * failure clustering in `agent.playbook().evolve()`.
     */
    failureSignals?: readonly AxAgentFailureSignal[];
    recursiveTrace?: AxAgentRecursiveTraceNode;
    recursiveStats?: AxAgentRecursiveStats;
    recursiveSummary?: string;
};
type AxAgentEvalPrediction<OUT = any> = (AxAgentEvalPredictionShared & {
    completionType: 'final';
    output: OUT;
    clarification?: undefined;
}) | (AxAgentEvalPredictionShared & {
    completionType: 'askClarification';
    output?: undefined;
    clarification: AxAgentStructuredClarification;
});
type AxAgentEvalTask<IN = any> = {
    input: IN;
    criteria: string;
    id?: string;
    expectedOutput?: AxFieldValue;
    expectedActions?: string[];
    forbiddenActions?: string[];
    weight?: number;
    metadata?: AxFieldValue;
};
type AxAgentEvalDataset<IN = any> = readonly AxAgentEvalTask<IN>[] | {
    train: readonly AxAgentEvalTask<IN>[];
    validation?: readonly AxAgentEvalTask<IN>[];
};
type AxAgentOptimizeOptions<_IN extends AxGenIn = AxGenIn, _OUT extends AxGenOut = AxGenOut> = {
    studentAI?: Readonly<AxAIService>;
    /** Optional separate judge model. Defaults to the agent's `judgeAI`, then `teacherAI`, then the student model. */
    judgeAI?: Readonly<AxAIService>;
    teacherAI?: Readonly<AxAIService>;
    /**
     * AI service options for GEPA's teacher calls, which use `teacherAI` or,
     * without it, the judge model. Set `useExpensiveModel: 'yes'` for a teacher
     * marked `isExpensive`.
     */
    teacherOptions?: AxAIServiceOptions;
    judgeOptions?: AxAgentJudgeOptions;
    /** Optional optimization scope. Defaults to `'actor'`. */
    target?: AxAgentOptimizeTarget;
    apply?: boolean;
    maxMetricCalls?: number;
    bootstrap?: boolean | AxGEPABootstrapOptions;
    /** Optional deterministic scorer. If omitted, optimize() uses the built-in LLM judge. */
    metric?: AxMetricFn;
    verbose?: boolean;
    debugOptimizer?: boolean;
    optimizerLogger?: AxOptimizerLoggerFunction;
    onProgress?: (progress: Readonly<AxOptimizationProgress>) => void;
    onEarlyStop?: (reason: string, stats: Readonly<AxOptimizationStats>) => void;
    /**
     * Evaluation defaults to replay/sandbox clients. Live mode must be explicit
     * because optimizers evaluate the same task repeatedly.
     */
    mcpEvaluation?: Readonly<{
        mode: 'replay';
        mcp?: AxMCPClient | readonly AxMCPClient[];
        ucp?: AxUCPClient | readonly AxUCPClient[];
    }> | Readonly<{
        mode: 'live';
        mcp?: AxMCPClient | readonly AxMCPClient[];
        ucp?: AxUCPClient | readonly AxUCPClient[];
    }>;
} & Pick<AxOptimizerArgs, 'numTrials' | 'minibatch' | 'minibatchSize' | 'earlyStoppingTrials' | 'minImprovementThreshold' | 'sampleCount' | 'seed'>;
type AxAgentOptimizeResult<OUT extends AxGenOut = AxGenOut> = AxParetoResult<OUT>;
/**
 * Options for `AxAgent.playbook()`. Builds an `AxPlaybook` bound to an agent
 * stage (the actor by default). The evolution engine (ACE) is hidden, exactly
 * as in the standalone `playbook()` factory.
 */
type AxAgentPlaybookOptions = {
    studentAI?: Readonly<AxAIService>;
    teacherAI?: Readonly<AxAIService>;
    /**
     * AI service options for the playbook's reflection and curation calls,
     * which use `teacherAI`, then the agent's `judgeAI`, then the student
     * model. Set `useExpensiveModel: 'yes'` for a teacher marked `isExpensive`.
     */
    teacherOptions?: AxAIServiceOptions;
    /** Which agent stage to evolve a playbook for. Defaults to `'actor'`. */
    target?: 'actor' | 'responder';
    /** Render the evolving playbook into the live stage. Defaults to `true`. */
    apply?: boolean;
} & Pick<AxPlaybookOptions, 'verbose' | 'seed' | 'maxEpochs' | 'maxReflectorRounds' | 'maxSectionSize' | 'allowDynamicSections' | 'initialPlaybook' | 'auto'>;
type AxAgentOptions<IN extends AxGenIn = AxGenIn> = Omit<AxProgramForwardOptions<string>, 'functions' | 'description' | 'onFunctionCall'> & {
    debug?: boolean;
    /**
     * Input fields used as context.
     * - `string`: runtime-only (legacy behavior)
     * - `{ field, promptMaxChars }`: runtime + conditionally inlined into the distiller prompt
     * - `{ field, keepInPromptChars, reverseTruncate? }`: runtime + truncated string excerpt in the distiller prompt
     */
    contextFields?: readonly AxContextFieldInput[];
    /**
     * Optional persistent context map for recurring long-context work.
     * When configured, Ax injects the map into the distiller prompt and updates
     * it once after each successful completed run. Use `onUpdate` to persist the
     * updated snapshot.
     */
    contextMap?: AxAgentContextMapConfig;
    /**
     * Optional evolving playbook attached at construction. The rendered
     * playbook is injected into the chosen stage's live prompt (the actor by
     * default), and — unless `learn: false` — the agent learns from its own
     * failures: after each completed run that produced failure signals (error
     * turns, repeated dead-ends, tool errors), one bounded playbook update
     * (default 1 reflection + 1 curation call, zero on clean runs) curates
     * durable avoidance rules into a `failures_to_avoid` section so later runs
     * stop repeating them. Seed it with a persisted snapshot and use `onUpdate`
     * to persist new snapshots; read the live handle via `getPlaybook()`.
     */
    playbook?: AxAgentPlaybookConfig;
    /**
     * Chain-of-evidence citations — opt-in (default off). When enabled, the
     * responder gains an optional string-array output field (default
     * `evidenceCitations`) that must list the evidence ids the answer actually
     * relies on: the top-level keys of the `final(task, evidence)` /
     * `respond(task, evidence)` evidence object, plus the `id` of id-bearing
     * records inside it (e.g. loaded memories). Citations are validated
     * subset-only against those ids — a violation re-prompts the responder via
     * the standard validation-retry loop; runs without evidence skip
     * validation. Pass an object to rename the field, hide it from the result
     * (`surface: 'hidden'`), or observe citations via `onCitations`. Valid ids
     * are the evidence object's top-level keys plus (with `includeMemoryIds`,
     * default on) the `id` of records nested inside it — arrays of records,
     * keyed maps of records, or single records, with string or numeric ids. A
     * run whose evidence object is empty rejects any citation; a run with no
     * evidence object at all skips validation. The guarantee is existence, not
     * entailment: the model cannot cite evidence it never collected, but
     * validation does not check that the answer's claims match the cited
     * evidence's content.
     */
    citations?: AxAgentCitations;
    /**
     * Tools registered under their configured namespace globals. May contain
     * `AxFunction` / `AxAgentFunction` entries, grouped function modules, or
     * `AxAgentic` instances — agents are auto-converted via `.getFunction()` and
     * land under their `agentIdentity.namespace` (or `utils` if unset), exactly
     * like a plain function. Pass an `AxAgent` here to use it as a child tool.
     */
    functions?: AxAgentFunctionCollection;
    /** Enables runtime callable discovery (modules + on-demand definitions). */
    functionDiscovery?: boolean;
    /**
     * Smart defaults — ON by default (set `false` to opt out). Two upgrades,
     * both driven by character counts so callers don't have to remember the
     * underlying knobs:
     *
     * - `functionDiscovery`: when the option is left unset and the estimated
     *   inline docs of discoverable functions exceed `aboveFunctionDocChars`
     *   (default 10_000), discovery is enabled automatically. An explicit
     *   `functionDiscovery: true | false` always wins.
     * - `contextFields`: per run, an undeclared input value whose serialized
     *   size exceeds `promoteAboveChars` (default 8_000, strictly greater) is
     *   kept runtime-only like a declared context field: the prompt gets a
     *   truncated preview (`previewChars`, default 1_200) plus a
     *   `contextMetadata` entry, while the full value stays addressable in the
     *   code runtime as `inputs.<field>`. Fields declared in `contextFields`
     *   keep their declared config. Values in required non-string fields
     *   (arrays, objects, numbers, media) are left inline — declare those in
     *   `contextFields` explicitly. Each promotion emits a
     *   `field_auto_promoted` context event for observability.
     *
     * Pass an object to tune or disable each side independently.
     */
    autoUpgrade?: AxAgentAutoUpgrade;
    /**
     * Direct-respond — ON by default (`'auto'`; set `'off'` to opt out). Lets
     * the distiller end the run with `respond(task, evidence)` and skip the
     * executor stage entirely (zero executor model calls) when the task needs
     * no user-provided functions.
     *
     * - Agents with zero `functions`/child agents run respond-only: the skip is
     *   deterministic and every run is distiller → responder.
     * - Agents WITH functions additionally offer `respond` under a conservative
     *   covenant: only for tasks answered purely by reading/synthesizing the
     *   provided context, never when a listed function/module domain covers the
     *   need, never for live/fresh-state asks (context may be stale — tools are
     *   the source of truth for "now"), never for side effects.
     *
     * On skip, the distiller's evidence crosses into the responder prompt
     * (subject to `maxEvidenceChars`) and its runtime variables are exported as
     * the cross-run state exactly as the executor's would have been.
     */
    directResponse?: AxAgentDirectResponse;
    /**
     * Advisory local relevance ranker — ON by default (set `false` to opt out).
     * Enabled by default since its A/B gate passed (substance-judged,
     * n=49/variant/model: small model discover-precision 24%->90% and answer
     * substance 14%->29%; frontier-model control substance 63%->88% with fewer
     * turns).
     *
     * When enabled, a cheap deterministic token-overlap ranker scores this
     * agent's discoverable capabilities against the task and injects a
     * non-authoritative "Likely Relevant" hint into the executor turn. Ranked
     * domains light up with their prerequisites: modules require
     * `functionDiscovery`; skills/memories require their catalogs. The hint
     * lands in a dynamic, non-cached field, so it does not affect the prompt
     * cache; the full lists and the `discover()`/`recall()` flows are unchanged
     * and the model may still choose anything. Pass an object to tune `topK`
     * (default 3) / `minScore` (default 0.08).
     */
    relevanceRanking?: boolean | {
        topK?: number;
        minScore?: number;
    };
    /**
     * Optional skills search callback. When set, the executor runtime gains a
     * `discover({ skills })` path. The callback receives the raw search strings
     * and returns matched skills (`{ id?, name, content }`); each returned skill's
     * content is rendered into the executor system prompt for subsequent turns
     * (sorted by id to keep the prefix cache stable). `discover(...)` itself
     * returns nothing — the actor inspects the **Loaded Skills** section of the
     * next turn's prompt to see what landed.
     */
    onSkillsSearch?: AxAgentSkillsSearchFn;
    /**
     * Static skill catalog. When set and no `onSkillsSearch` callback is
     * provided, ax backs `discover({ skills })` with a built-in deterministic
     * local search over the catalog — skills work batteries-included with zero
     * host search code. A host `onSkillsSearch` always takes precedence for
     * search; the catalog still powers the advisory relevance hint (with
     * `relevanceRanking`). Unlike `skills`, catalog content is NOT preloaded
     * into the prompt — entries load only when matched.
     */
    skillsCatalog?: readonly AxAgentCatalogSkill[];
    /**
     * Skills to preload into the executor prompt at startup, in the same
     * shape returned by `onSkillsSearch` ({ id?, name, content }). Useful when
     * the caller already knows which skills are relevant and wants to
     * skip the actor's `discover({ skills })` round-trip. Merged with skills
     * passed at forward()-time (forward overrides by id). Does NOT
     * fire `onLoadedSkills` — that callback is for runtime-loaded skills.
     */
    skills?: readonly AxAgentSkillResult[];
    /**
     * Optional callback fired whenever `discover({ skills })` loads skills. Receives
     * the matched `{ id?, name, content }[]` from `onSkillsSearch`. Use this for
     * analytics, telemetry, or feedback loops on skill relevance — it does
     * not affect runtime behaviour.
     */
    onLoadedSkills?: (results: readonly AxAgentSkillResult[]) => void | Promise<void>;
    /**
     * Optional callback fired once per agent forward when skill usage tracking
     * is enabled. Receives actor-declared skills that actually influenced the
     * executor (`{ id, name, reason?, stage }`). Unknown ids are dropped.
     */
    onUsedSkills?: AxAgentUsedSkillsCallback;
    /**
     * Optional memories search callback. When set, the distiller and executor
     * stages gain a `recall(searches: string[]): void` global, and both
     * stages get a `memories` input field. The callback receives the raw
     * search strings plus a snapshot of `inputs.memories` already loaded
     * for the current run (`alreadyLoaded`), and returns matched memories
     * (`{ id, content }`); the runtime appends matched entries to
     * `inputs.memories` (deduped by id, sorted) so the next turn's prompt
     * includes them. Use `alreadyLoaded` to skip work for entries the
     * actor already has — e.g. filter your vector search by `id NOT IN
     * alreadyLoaded`. `recall()` itself returns nothing — the actor reads
     * `inputs.memories` next turn to see what landed. Memories loaded by
     * the distiller thread to the executor automatically; the responder
     * does not receive the memories field. Memories live for one
     * `.forward()` call; persist them externally to carry across calls.
     */
    onMemoriesSearch?: AxAgentMemoriesSearchFn;
    /**
     * Static memory catalog. When set and no `onMemoriesSearch` callback is
     * provided, ax backs `recall(...)` with a built-in deterministic local
     * search over the catalog — memories work batteries-included with zero host
     * search code. A host `onMemoriesSearch` always takes precedence for
     * search; the catalog still powers the advisory relevance hint (with
     * `relevanceRanking`). Catalog content is NOT preloaded into the prompt —
     * entries load only when recalled. To preload specific memories for a run,
     * pass them as the `memories` input value at forward time:
     * `forward(ai, { ..., memories: [{ id, content }] })`.
     */
    memoriesCatalog?: readonly AxAgentMemoryResult[];
    /**
     * Optional callback fired whenever `recall(...)` loads memories. Receives
     * the matched `{ id, content }[]` from `onMemoriesSearch`. Use this for
     * load telemetry, cache warming, or feedback loops on retrieval relevance —
     * it does not mean the actor used every memory in its final reasoning.
     */
    onLoadedMemories?: (results: readonly AxAgentMemoryResult[]) => void | Promise<void>;
    /**
     * Optional callback fired once per agent forward when memory usage tracking
     * is enabled. Receives actor-declared memories that actually influenced the
     * distiller or executor (`{ id, reason?, stage }`). Unknown ids are dropped.
     */
    onUsedMemories?: AxAgentUsedMemoriesCallback;
    /** Code runtime for the REPL loop (default: AxJSRuntime). */
    runtime?: AxCodeRuntime;
    /** Actor prompt verbosity and scaffolding level (default: 'default'). */
    promptLevel?: 'default' | 'detailed';
    /** Global cap on recursive sub-agent calls across all descendants (default: 100). */
    maxSubAgentCalls?: number;
    /** Maximum parallel llmQuery calls in batched mode (default: 8). */
    maxBatchedLlmQueryConcurrency?: number;
    /** Maximum Actor turns before forcing Responder (default: 10). */
    maxTurns?: number;
    /** Maximum characters to keep from runtime output and console/log replay. */
    maxRuntimeChars?: number;
    /**
     * Maximum serialized characters for a `final(task, evidence)` evidence
     * object crossing the host boundary (default: 50000). Oversized evidence
     * throws inside the actor turn so the model narrows and retries.
     */
    maxEvidenceChars?: number;
    /** Context replay, checkpointing, and runtime-state policy. */
    contextPolicy?: AxContextPolicyConfig;
    /** Default options for the internal checkpoint summarizer. */
    summarizerOptions?: Omit<AxProgramForwardOptions<string>, 'functions'>;
    /**
     * Called after each actor turn is recorded with both the raw runtime
     * result and the formatted action-log output.
     */
    actorTurnCallback?: AxAgentActorTurnCallback;
    /**
     * Called when AxAgent measures context pressure or creates/clears compacted
     * context. Use for observability and evaluation; failures are ignored.
     */
    onContextEvent?: AxAgentOnContextEvent;
    /**
     * Called when the executor signals task progress via `reportSuccess(message)` or `reportFailure(message)`.
     */
    agentStatusCallback?: (message: string, status: 'success' | 'failed') => void | Promise<void>;
    /**
     * Called before each executor turn with current input values. Return a
     * partial patch to update in-flight inputs for subsequent executor/responder
     * steps.
     */
    inputUpdateCallback?: AxAgentInputUpdateCallback<IN>;
    /**
     * Fired whenever any function registered on the agent is invoked from the
     * runtime. `kind` is `'external'` for user-registered functions, `'internal'`
     * for agent-injected ones (child agents, skills/memories loaders, discovery globals).
     */
    onFunctionCall?: AxAgentOnFunctionCall;
    /**
     * Ordered executor-model overrides keyed by consecutive error turns or
     * namespace matches. Later entries take precedence over earlier ones.
     */
    executorModelPolicy?: AxExecutorModelPolicy;
    /**
     * Default forward options for recursive llmQuery sub-agent calls.
     * Set `ai` to route recursive sub-agent calls to a different AI service
     * than the one used for the parent agent. Falls back to the parent
     * `forward(ai, ...)` argument when `ai` is not set.
     */
    recursionOptions?: AxAgentRecursionOptions;
    /**
     * Forward options for the **context distiller** stage. Configures the
     * REPL/turn loop and forward-to-LLM options for the context-understanding
     * stage that runs before the executor. Set `ai` to override the AI service
     * for this stage only — falls back to `forward(ai, ...)` when not set.
     */
    contextOptions?: AxStageOptions;
    /**
     * Forward options for the **task executor** stage. Set `ai` to override
     * the AI service for this stage only — falls back to `forward(ai, ...)`
     * when not set.
     */
    executorOptions?: AxStageOptions;
    /**
     * Forward options for the **final responder** stage. Set `ai` to override
     * the AI service for this stage only — falls back to `forward(ai, ...)`
     * when not set.
     */
    responderOptions?: AxStageOptions;
    /** Default options for the built-in judge used by optimize(). */
    judgeOptions?: AxAgentJudgeOptions;
    /** Error classes that should bubble up instead of being caught and returned to the LLM. */
    bubbleErrors?: ReadonlyArray<new (...args: any[]) => Error>;
};
/**
 * Per-stage forward options. Used by `contextOptions`, `executorOptions`, and
 * `responderOptions` — one shape, three peers, one per pipeline stage.
 */
/**
 * Forward options for `AxAgent.forward(...)`. Extends the dsp-layer
 * `AxProgramForwardOptionsWithModels` with agent-specific knobs that only
 * make sense at the agent boundary (currently `skills` for one-shot
 * preloading). Forward-time `skills` merge on top of init-time `skills`
 * (forward overrides by id).
 */
type AxAgentForwardOptions<T extends Readonly<AxAIService>> = AxProgramForwardOptionsWithModels<T> & {
    skills?: readonly AxAgentSkillResult[];
    onUsedMemories?: AxAgentUsedMemoriesCallback;
    onUsedSkills?: AxAgentUsedSkillsCallback;
};
type AxAgentStreamingForwardOptions<T extends Readonly<AxAIService>> = AxProgramStreamingForwardOptionsWithModels<T> & {
    skills?: readonly AxAgentSkillResult[];
    onUsedMemories?: AxAgentUsedMemoriesCallback;
    onUsedSkills?: AxAgentUsedSkillsCallback;
};
type AxStageOptions = Partial<Omit<AxProgramForwardOptions<string>, 'functions'> & {
    description?: string;
    /** Input field names to strip before passing values to this stage. */
    excludeFields?: readonly string[];
}>;
type AxAgentJudgeInput = {
    taskInput: AxFieldValue;
    criteria: string;
    expectedOutput?: AxFieldValue;
    expectedActions?: string[];
    forbiddenActions?: string[];
    metadata?: AxFieldValue;
};
type AxAgentJudgeOutput = {
    completionType: 'final' | 'askClarification';
    clarification?: AxFieldValue;
    finalOutput?: AxFieldValue;
    actionLog: string;
    guidanceLog?: string;
    functionCalls: AxFieldValue;
    toolErrors: string[];
    turnCount: number;
    usage: AxFieldValue;
    recursiveTrace?: AxFieldValue;
    recursiveStats?: AxFieldValue;
};
type AxAgentJudgeEvalInput = AxAgentJudgeInput & AxAgentJudgeOutput;
type AxAgentJudgeEvalOutput = {
    reasoning: string;
    quality: string;
};
/** Forward options forwarded to the `AxGen` spawned by each `llmQuery(...)` call. */
type AxAgentRecursionOptions = Partial<Omit<AxProgramForwardOptions<string>, 'functions'>>;

/** Outcome of running one actor turn's code in the runtime session. */
type ActorCodeExecutionResult = {
    result: unknown;
    output: string;
    /** The turn failed; the action log tags it `error`. */
    isError: boolean;
    /**
     * The failure is an error in the code that the live session reported as
     * its result (`AxCodeSession.executeWithStatus()`) instead of rejecting, so
     * `output` is still the runtime's own text.
     */
    isCodeError?: boolean;
};

type AxAgentExecutorResultPayload = AxAgentTestCompletionPayload;
type AxAgentFunctionCallRecorder = (call: AxAgentEvalFunctionCall) => void;
type AxAgentFunctionCall = {
    name: string;
    qualifiedName: string;
    args: Record<string, unknown>;
    kind: 'internal' | 'external';
};
type AxAgentOnFunctionCall = (call: Readonly<AxAgentFunctionCall>) => void | Promise<void>;
/**
 * Budget state for llmQuery calls. Uses a shared global object for cross-tree
 * tracking plus per-agent local counters to prevent any single child from
 * starving siblings.
 */
type AxLlmQueryBudgetState = {
    /** Global usage counter shared across all descendants (by reference). */
    global: {
        used: number;
    };
    /** Global maximum across the entire agent tree. */
    globalMax: number;
    /** Local usage counter for this specific agent. */
    localUsed: number;
    /** Per-agent maximum. */
    localMax: number;
};
type AxLlmQueryPromptMode = 'simple';
type AxResolvedContextPolicy = {
    preset: AxContextPolicyPreset;
    budget: AxContextPolicyBudget;
    summarizerOptions?: Omit<AxProgramForwardOptions<string>, 'functions'>;
    actionReplay: 'full' | 'adaptive' | 'minimal' | 'checkpointed';
    recentFullActions: number;
    contextHygiene: {
        defaultMode: ActionLogHygieneMode;
        pressureMode?: ActionLogHygieneMode;
    };
    errorPruning: boolean;
    hindsightEvaluation: boolean;
    pruneRank: number;
    rankPruneGraceTurns: number;
    tombstoning: boolean | Omit<AxProgramForwardOptions<string>, 'functions'> | undefined;
    stateSummary: {
        enabled: boolean;
        maxEntries?: number;
        maxChars?: number;
    };
    stateInspection: {
        enabled: boolean;
        contextThreshold?: number;
    };
    checkpoints: {
        enabled: boolean;
        triggerChars?: number;
    };
    targetPromptChars: number;
    maxRuntimeChars: number;
};
type AxResolvedExecutorModelPolicyEntry = {
    model: string;
    aboveErrorTurns?: number;
    namespaces?: string[];
};
type AxResolvedExecutorModelPolicy = readonly AxResolvedExecutorModelPolicyEntry[];
/** One auto-upgrade context promotion, pending `field_auto_promoted` emission. */
type AxAgentAutoPromotionRecord = {
    fieldName: string;
    originalChars: number;
    /** Chars kept inline as a preview; undefined => runtime-only. */
    promptPreviewChars?: number;
};
type AxAgentRuntimeInputState = {
    currentInputs: Record<string, unknown>;
    signatureInputFieldNames: Set<string>;
    recomputeTurnInputs: (validateRequiredContext: boolean) => void;
    getNonContextValues: () => Record<string, unknown>;
    getActorInlineContextValues: () => Record<string, unknown>;
    getContextMetadata: () => string | undefined;
    /** Returns promotions recorded since the last drain (each field once per run). */
    drainAutoPromotionEvents: () => readonly AxAgentAutoPromotionRecord[];
};
type AxAgentRuntimeCompletionState = {
    payload: AxAgentInternalCompletionPayload | undefined;
};
type AxStageDefinitionBuildOptions = Parameters<typeof axBuildExecutorDefinition>[3];
type AxPreparedRestoredState = {
    runtimeBindings: Record<string, unknown>;
    runtimeEntries: AxAgentStateRuntimeEntry[];
    actionLogEntries: ActionLogEntry[];
    guidanceLogEntries: AxAgentGuidanceLogEntry[];
    discoveryPromptState?: AxAgentDiscoveryPromptState;
    skillsPromptState?: AxAgentSkillsPromptState;
    checkpointState?: AxAgentStateCheckpointState;
    provenance: Record<string, RuntimeStateVariableProvenance>;
    actorModelState?: AxAgentStateExecutorModelState;
};
type AxAgentGuidanceState = {
    entries: AxAgentGuidanceLogEntry[];
};
type AxAgentRuntimeExecutionContext = {
    consumeNativeToolActivity?: () => readonly string[];
    getNativeFunctions?: (options: AxProgramForwardOptions<string>) => AxFunction[];
    effectiveContextConfig: AxResolvedContextPolicy;
    bootstrapContextSummary?: string;
    applyBootstrapRuntimeContext: () => Promise<string | undefined>;
    captureRuntimeStateSummary: () => Promise<string | undefined>;
    consumeDiscoveryTurnArtifacts: () => {
        summary?: string;
        texts: string[];
    };
    getActorModelMatchedNamespaces: () => readonly string[];
    exportRuntimeState: (options?: Readonly<{
        includeBindings?: boolean;
    }>) => Promise<AxAgentState>;
    restoreRuntimeState: (state: Readonly<AxAgentState>, options?: Readonly<{
        skipBindings?: boolean;
    }>) => Promise<AxPreparedRestoredState>;
    syncRuntimeInputsToSession: () => Promise<void>;
    executeActorCode: (code: string) => Promise<ActorCodeExecutionResult>;
    executeTestCode: (code: string) => Promise<AxAgentTestResult>;
    /**
     * Present only when the run participates in a pipeline-owned shared runtime
     * session. The actor loop awaits it before the first turn: the distiller
     * phase adopts the fresh session, the executor phase patches its bindings
     * over the inherited one and runs the phase-boundary snippet.
     */
    prepareSharedSession?: () => Promise<void>;
    close: () => void;
};
type AxDiscoveryTurnSummary = {
    modules: Set<string>;
    functions: Set<string>;
    texts: Set<string>;
};
type AxAgentOptimizationTargetDescriptor = {
    id: string;
    signature?: string;
    program: AxNamedProgramInstance<any, any>['program'] & {
        getInstruction?: () => string | undefined;
        setInstruction?: (instruction: string) => void;
        getSignature?: () => {
            getDescription?: () => string | undefined;
        };
    };
};

type AxSynthesizerRole = 'final';
interface AxSynthesizerInit {
    /** Pre-built signature: `{ ...nonContextInputs, contextData } -> OUT`. */
    signature: AxSignature;
    /** Inline context-field metadata used by the responder template (titles/descriptions). */
    contextFieldMeta: readonly AxIField[];
    /** Stage role. Currently only the `responder` uses this class. */
    role: AxSynthesizerRole;
    /** Optional human-authored instruction prepended to the responder template. */
    description?: string;
    /** Optional agent identity rendered into the prompt. */
    agentIdentity?: {
        name: string;
        description: string;
        namespace?: string;
    };
    /**
     * Resolved chain-of-evidence citations config. When enabled, the caller has
     * already appended the citations output field to the signature; this class
     * validates the model's citations against the per-call evidence ids and
     * surfaces/strips the field per `surface`.
     */
    citations?: AxResolvedCitations;
}
interface AxSynthesizerOptions {
    /** Forward options merged onto every responder call (debug, model choice, etc.). */
    forwardOptions?: Partial<AxProgramForwardOptions<string>>;
    /** Stable id used in `namedPrograms()` (e.g. `responder`). */
    id?: string;
}
/**
 * The responder synthesis stage. Wraps an `AxGen` whose signature is
 * `{ ...nonContextInputs, contextData } -> outputFields`, rendered with
 * `rlm/responder.md`.
 *
 * Callers hand it the upstream actor's payload via `forward({ executorResult, ... })`;
 * the contextData reshape (`buildResponderContextData`) happens here, not at the
 * call site.
 */
declare class Synthesizer<OUT extends AxGenOut = AxGenOut> {
    private readonly init;
    private readonly options;
    private program;
    private templateOverride;
    private _stopRequested;
    /**
     * Evidence ids valid for the in-flight call; `undefined` disables the
     * citations assert (no evidence this call). Per-call mutable state on a
     * shared stage — same accepted non-reentrancy class as the agent's
     * discovery/skills prompt state.
     */
    private _validCitationKeys;
    constructor(init: Readonly<AxSynthesizerInit>, options?: Readonly<AxSynthesizerOptions>);
    /**
     * Registered once — the underlying AxGen instance survives description
     * rebuilds and signature swaps, so the assert stays attached. Violations
     * return a dynamic message enumerating the invalid and valid ids, which
     * drives the standard validation-retry loop.
     */
    private _registerCitationsAssert;
    /**
     * Ids the responder may cite this call: the evidence object's top-level
     * keys plus (when `includeMemoryIds`) the `id` of any records nested inside
     * it — arrays of records (the `recall()` memories shape), keyed maps of
     * records, or single records — with string OR numeric ids (DB keys are
     * commonly numeric). Returns `undefined` only when the payload carries no
     * evidence contract at all (absent / non-object / array); a plain object —
     * even empty `{}` — returns its (possibly empty) key set so the assert
     * rejects citations fabricated on an evidence-less run.
     */
    private _computeCitationKeys;
    /**
     * Collect every `id` (string or number, stringified) reachable within
     * `depth` levels of `node`, descending through arrays and plain objects.
     * Bounded so a deeply nested / cyclic evidence object can't spin.
     */
    private _collectNestedIds;
    private _normalizeCitations;
    /** Fire the observer and strip the field for `surface: 'hidden'`. */
    private _finalizeCitations;
    private _buildProgram;
    private _templateId;
    getRole(): AxSynthesizerRole;
    getId(): string;
    setId(id: string): void;
    getSignature(): AxSignature;
    getProgram(): AxGen<any, OUT>;
    asTunableUsable(): Readonly<AxTunable<any, any> & AxUsable>;
    stop(): void;
    resetUsage(): void;
    getUsage(): readonly AxProgramUsage[];
    getChatLog(): readonly AxChatLogEntry[];
    getTraces(): readonly AxProgramTrace<any, OUT>[];
    namedPrograms(): Array<{
        id: string;
        signature?: string;
    }>;
    namedProgramInstances(): AxNamedProgramInstance<any, OUT>[];
    setDemos(demos: readonly AxProgramDemos<any, OUT>[], options?: {
        modelConfig?: Record<string, unknown>;
    }): void;
    getOptimizableComponents(): readonly any[];
    applyOptimization(optimizedProgram: any): void;
    applyOptimizedComponents(updates: Readonly<Record<string, string>>): void;
    /**
     * Run the synthesizer non-streaming. Reshapes the upstream actor result into
     * `contextData` and merges it with `nonContextValues`.
     */
    forward(ai: AxAIService, args: Readonly<{
        nonContextValues: Record<string, unknown>;
        executorResult: AxAgentExecutorResultPayload;
        options?: Readonly<AxProgramForwardOptions<string>>;
    }>): Promise<OUT>;
    /**
     * Streaming variant — only the responder uses this. Yields the
     * AxGen deltas; the pipeline appends `actorFieldValues` as a final delta
     * if any are present.
     */
    streamingForward(ai: AxAIService, args: Readonly<{
        nonContextValues: Record<string, unknown>;
        executorResult: AxAgentExecutorResultPayload;
        options?: Readonly<AxProgramForwardOptions<string>>;
    }>): AxGenStreamingOut<OUT>;
}

/**
 * Public types for `agent.playbook().evolve(dataset, options)` — verified (or
 * trust-batch) playbook learning. The engine (batch eval → failure clustering
 * → grounded weakness mining → bounded playbook proposal → regression-gated
 * accept) is hidden behind the method, exactly as `optimize()` hides GEPA.
 * Verified learning produces only playbook bullets.
 */

/** One executed (task, prediction, score) triple from the batch harness. */
type AxAgentPlaybookEvolveRunRecord<IN extends AxGenIn = AxGenIn, OUT extends AxGenOut = AxGenOut> = {
    task: AxAgentEvalTask<IN>;
    /** Absent when the run threw before producing a prediction. */
    prediction?: AxAgentEvalPrediction<OUT>;
    score: number;
    /** `score >= scoreThreshold` and the run neither threw nor stalled. */
    passed: boolean;
    /** Message of a thrown (non-clarification) run error. */
    error?: string;
};
/** A verifier-grounded weakness mined from one failure cluster. */
type AxAgentPlaybookWeakness = {
    id: string;
    /** Deterministic cluster fingerprint the weakness was mined from. */
    clusterSignature: string;
    description: string;
    rootCause: string;
    /** The avoidance rule/lesson the proposal carries into the playbook. */
    proposedGuidance: string;
    /**
     * Quotes from the actual failure excerpts that ground this weakness. Only
     * quotes that substring-match the real excerpts survive; a weakness with
     * zero surviving quotes is discarded.
     */
    evidenceQuotes: readonly string[];
    /** Tasks in the cluster (by id or index). */
    taskIds: readonly string[];
    /** Report-only configuration suggestions; never auto-applied. */
    configRecommendations: readonly string[];
};
/** A bounded proposal: one curated playbook update per mined weakness. */
type AxAgentPlaybookEvolveProposal = {
    weaknessId: string;
    /** Cluster signature recorded on the update event (dedupe ledger). */
    clusterSignature: string;
    /** Digest handed to the playbook update (curator input). */
    feedback: string;
};
type AxAgentPlaybookEvolveOutcome = {
    proposal: AxAgentPlaybookEvolveProposal;
    accepted: boolean;
    reason: string;
    heldIn: {
        before: number;
        after: number;
    };
    heldOut?: {
        before: number;
        after: number;
    };
};
type AxAgentPlaybookEvolveProgressEvent = {
    phase: 'baseline' | 'mining' | 'proposal' | 'validation' | 'done';
    message: string;
    metricCallsUsed: number;
};
type AxAgentPlaybookEvolveOptions = {
    /**
     * Keep only proposals that provably help — re-score train + held-out after
     * each candidate bullet and accept only on a held-in gain without a
     * held-out regression, else roll it back. Default true. With `false`,
     * mined lessons are applied without the gate (fast trust-batch).
     */
    verify?: boolean;
    /** Runs the agent during evaluation. Defaults to the agent's `ai`. */
    studentAI?: Readonly<AxAIService>;
    /** Mines weaknesses. Defaults to `judgeAI`, then the student. */
    teacherAI?: Readonly<AxAIService>;
    /**
     * AI service options for the weakness miner's calls. Set
     * `useExpensiveModel: 'yes'` for a teacher marked `isExpensive`. The
     * reflection and curation calls that apply each proposal use the
     * playbook's own `teacherOptions` (from `agent.playbook(...)` or the
     * `playbook` config).
     */
    teacherOptions?: AxAIServiceOptions;
    /** Scores runs via the built-in judge. Resolution mirrors `optimize()`. */
    judgeAI?: Readonly<AxAIService>;
    judgeOptions?: AxAgentJudgeOptions;
    /** Optional deterministic scorer replacing the LLM judge. */
    metric?: AxMetricFn;
    /** Maximum weaknesses mined / proposals evaluated. Default 4. */
    maxProposals?: number;
    /**
     * Budget counting (agent run + judge) pairs across baseline and
     * re-evaluations. Default `max(100, (maxProposals + 1) * (train + validation)
     * * runsPerTask)`.
     */
    maxMetricCalls?: number;
    /**
     * Times each task runs per evaluation, with scores averaged. Default 1.
     * Use 2-3 when the dataset is small: accept/reject compares mean scores,
     * and on a handful of tasks a single lucky or unlucky run can otherwise
     * decide the gate. Each repeat spends budget.
     */
    runsPerTask?: number;
    /** Tolerated held-out drop when accepting a proposal (verify). Default 0.01. */
    epsilon?: number;
    /** Required held-in improvement to accept a proposal (verify). Default 0.05. */
    minHeldInGain?: number;
    /** Records scoring below this count as failures for mining. Default 0.7. */
    scoreThreshold?: number;
    /**
     * Keep accepted bullets on the live playbook (default). With `false`, the
     * playbook is rolled back at the end and the result's `playbookSnapshot`
     * carries the accepted state for a later `getPlaybook()?.load(...)`.
     */
    apply?: boolean;
    verbose?: boolean;
    onProgress?: (event: Readonly<AxAgentPlaybookEvolveProgressEvent>) => void;
    abortSignal?: AbortSignal;
};
type AxAgentPlaybookEvolveResult<OUT extends AxGenOut = AxGenOut> = {
    baseline: {
        heldIn: number;
        heldOut?: number;
    };
    final: {
        heldIn: number;
        heldOut?: number;
    };
    weaknesses: readonly AxAgentPlaybookWeakness[];
    outcomes: readonly AxAgentPlaybookEvolveOutcome[];
    /** Config suggestions collected from mined weaknesses; never auto-applied. */
    recommendations: readonly string[];
    /** Playbook state after the accepted bullets. */
    playbookSnapshot?: AxPlaybookSnapshot;
    metricCallsUsed: number;
    /** The baseline corpus (post-run records with scores). */
    records: readonly AxAgentPlaybookEvolveRunRecord<any, OUT>[];
};

/**
 * `AxAgentPlaybook` — the agent-facing playbook handle returned by
 * `agent.playbook()` / `agent.getPlaybook()`.
 *
 * It is one thing (the agent's learned playbook) that grows three ways:
 *  - continuously, from each run (the `playbook` construction config);
 *  - on demand from one interaction, via {@link update} (trust);
 *  - from a task set, via {@link evolve} (verified by default, or trust-batch).
 *
 * The generic program-level `AxPlaybook` (from the `playbook(program, …)`
 * factory) is unchanged; this wraps one bound to an agent stage and adds the
 * agent-level `evolve(dataset, options)`. The shared handle methods delegate
 * to the inner `AxPlaybook`.
 */

declare class AxAgentPlaybook<IN extends AxGenIn = AxGenIn, OUT extends AxGenOut = AxGenOut> {
    /** The owning agent coordinator (used by `evolve`). */
    private readonly agent;
    /** The inner stage-bound playbook the handle methods delegate to. */
    private readonly handle;
    constructor(
    /** The owning agent coordinator (used by `evolve`). */
    agent: unknown, 
    /** The inner stage-bound playbook the handle methods delegate to. */
    handle: AxPlaybook<IN, OUT>);
    /**
     * Grow the playbook from a task set. `verify` (default) keeps only bullets
     * that provably help — re-scoring train + held-out after each candidate and
     * rolling back regressions. `verify: false` applies mined lessons without
     * the gate (trust-batch). Produces only playbook bullets. Must not run
     * concurrently with `forward()` on the same agent instance.
     */
    evolve(dataset: Readonly<AxAgentEvalDataset<IN>>, options?: Readonly<AxAgentPlaybookEvolveOptions>): Promise<AxAgentPlaybookEvolveResult<OUT>>;
    /** Refine the playbook from a single live interaction (trust). */
    update(args: Readonly<{
        example: unknown;
        prediction: unknown;
        feedback?: string;
    }>): Promise<void>;
    /** The current playbook rendered as a markdown block. */
    render(): string;
    /** A serializable snapshot of the current playbook and its history. */
    getState(): AxPlaybookSnapshot;
    /** Alias of {@link getState} so `JSON.stringify(handle)` yields a snapshot. */
    toJSON(): AxPlaybookSnapshot;
    /** Restore a snapshot and render it into the live stage. */
    load(snapshot: Readonly<AxPlaybookSnapshot>): this;
    /** Clear the playbook back to its initial state. */
    reset(): void;
    /** Set the evolution intensity preset. */
    configureAuto(level: 'light' | 'medium' | 'heavy'): void;
    /** The inner program-level playbook handle (for advanced use). */
    get inner(): AxPlaybook<IN, OUT>;
}

/**
 * Pipeline-based coordinator. Every run walks the same static sequence:
 *
 *   distiller (RLM actor)  →  executor (RLM actor)
 *                          ↓
 *                    responder (Synthesizer)
 *
 * The distiller's `final(request, evidence)` payload feeds the executor as
 * `{executorRequest, distilledContext}`. When no `contextFields` are declared,
 * the distiller still acts as the context-understanding/request-normalization
 * stage over the original inputs.
 *
 * This is the primary user-facing class. `ActorAgentRLM` and `Synthesizer`
 * are exported for callers that need direct per-instance control.
 */
declare class AxAgent<IN extends AxGenIn, OUT extends AxGenOut> implements AxAgentic<IN, OUT> {
    /** RLM actor that normalizes the request and distils context evidence. */
    readonly distiller: ActorAgentRLM<any, any>;
    /** RLM actor that runs tools / discovery with the pre-distilled context. */
    readonly executor: ActorAgentRLM<any, any>;
    /** Synthesizer that produces the user's output signature. Always present. */
    readonly responder: Synthesizer<OUT>;
    /**
     * Backward-compat handle used by legacy access patterns: returns the actor
     * stage that "owns" the run-time forward — always the `executor` in
     * current pipeline shapes. Tests reach in via
     * `agent.primaryAgent.actorProgram` etc.
     */
    get primaryAgent(): ActorAgentRLM<any, any>;
    private readonly contextFieldNames;
    /** Resolved auto-upgrade config; also read by the responder-input helpers. */
    readonly autoUpgradeResolved: AxResolvedAutoUpgrade;
    /** Field names stripped from executor inputs (from executorOptions.excludeFields). */
    readonly executorExcludeFields: Set<string>;
    /** Field names stripped from responder inputs (from responderOptions.excludeFields). */
    readonly responderExcludeFields: Set<string>;
    /**
     * Per-stage AI service overrides. When set, the corresponding stage uses
     * this AI service instead of the one passed positionally to `forward()`.
     * `forward(ai, ...)` is the fallback when the stage-specific override is
     * not defined.
     */
    readonly distillerAi?: Readonly<AxAIService>;
    readonly executorAi?: Readonly<AxAIService>;
    readonly responderAi?: Readonly<AxAIService>;
    private readonly fullSignature;
    private readonly pipelineFlow;
    private readonly init;
    private readonly options;
    private readonly contextMapConfig?;
    private contextMap?;
    private readonly playbookConfigResolved?;
    private playbookHandle?;
    private _agentPlaybook?;
    private readonly citationsResolved;
    private func?;
    constructor(init: Readonly<{
        ai?: Readonly<AxAIService>;
        judgeAI?: Readonly<AxAIService>;
        agentIdentity?: Readonly<AxAgentIdentity>;
        agentModuleNamespace?: string;
        signature: string | Readonly<AxSignatureConfig> | Readonly<AxSignature<IN, OUT>>;
    }>, options: Readonly<AxAgentOptions<IN>>);
    /**
     * Run the agent once.
     *
     * @param values Signature inputs plus an optional `memories` array. Forward
     * memories are visible from the first actor turn, merge with recalled
     * entries by ID, and reset before the next call.
     */
    forward<T extends Readonly<AxAIService>>(ai: T, values: IN & {
        /**
         * Memories to expose from the first actor turn of this forward call.
         * They merge with recalled entries by ID and reset before the next call.
         */
        memories?: readonly AxAgentMemoryResult[];
    }, options?: Readonly<AxAgentForwardOptions<T>>): Promise<OUT>;
    /**
     * Run the agent once and stream its output.
     *
     * @param values Signature inputs plus an optional `memories` array with the
     * same per-forward merge and reset semantics as `forward()`.
     */
    streamingForward<T extends Readonly<AxAIService>>(ai: T, values: IN & {
        /**
         * Memories to expose from the first actor turn of this forward call.
         * They merge with recalled entries by ID and reset before the next call.
         */
        memories?: readonly AxAgentMemoryResult[];
    }, options?: Readonly<AxAgentStreamingForwardOptions<T>>): AxGenStreamingOut<OUT>;
    getFunction(): AxFunction;
    getSignature(): AxSignature;
    stop(): void;
    getId(): string;
    setId(id: string): void;
    /**
     * The distiller is reported under `ctx.*` and the executor / responder
     * pair under `task.*` so optimizer demo IDs and template-overrides keep
     * stable stage ownership.
     */
    namedPrograms(): Array<{
        id: string;
        signature?: string;
    }>;
    namedProgramInstances(): AxNamedProgramInstance<IN, OUT>[];
    getTraces(): AxProgramTrace<IN, OUT>[];
    setDemos(demos: readonly (AxAgentDemos<IN, OUT> | AxProgramDemos<IN, OUT>)[], options?: {
        modelConfig?: Record<string, unknown>;
    }): void;
    getUsage(): AxAgentUsage;
    getStagedUsage(): {
        ctx?: AxAgentUsage;
        task: AxAgentUsage;
    };
    getChatLog(): readonly AxChatLogEntry[];
    resetUsage(): void;
    getState(): AxAgentState | undefined;
    setState(state?: AxAgentState): void;
    getContextMap(): AxAgentContextMap | undefined;
    setContextMap(map?: AxAgentContextMap | AxAgentContextMapSnapshot | string): void;
    _syncContextMapPrompt(): void;
    _updateContextMapFromPipelineState(ai: Readonly<AxAIService>, state: Readonly<Record<string, any>>, finalOutput?: unknown): Promise<void>;
    setSignature(signature: AxSignatureInput): void;
    applyOptimization(optimizedProgram: any): void;
    getOptimizableComponents(): readonly any[];
    applyOptimizedComponents(updates: Readonly<Record<string, string>>): void;
    optimize(dataset: Readonly<AxAgentEvalDataset<IN>>, options?: Readonly<AxAgentOptimizeOptions<IN, OUT>>): Promise<AxAgentOptimizeResult<OUT>>;
    /**
     * Append a standing instruction addendum to the executor actor's prompt.
     * A separate additive channel from `executorOptions.description` and the
     * playbook injection, so the three never clobber each other. Process-local —
     * not serialized into `AxAgentState`.
     */
    addActorInstruction(addendum: string): void;
    /**
     * The agent's learned playbook — one evolving body of task knowledge bound
     * to an agent stage (the actor/task stage by default). It grows three ways:
     * continuously from each run (the `playbook` construction config),
     * on demand via `.update(...)`, or from a task set via
     * `.evolve(dataset, options)` (verified by default). Unless `apply` is
     * `false`, the rendered playbook is injected into the live stage prompt.
     * Memoized — one playbook per agent. The evolution engine (ACE) is an
     * implementation detail.
     */
    playbook(options?: Readonly<AxAgentPlaybookOptions>): AxAgentPlaybook<any, any>;
    /** The agent's playbook handle, or `undefined` if none has been created. */
    getPlaybook(): AxAgentPlaybook<any, any> | undefined;
    private _agentPlaybookWrapper;
    private _buildStagePlaybook;
    /**
     * Build and seed the construction-time playbook handle (`options.playbook`).
     * Reuses the `playbook()` stage-binding path; a snapshot seed is restored
     * via `load()`, a bare playbook seeds the engine directly. Either way the
     * seeded content is rendered into the live stage prompt (unless
     * `apply: false`).
     */
    private _createPlaybookHandle;
    /**
     * Run-end failure learning for the attached playbook (see
     * `AxAgentPlaybookConfig.learn`): merge the stages' deterministic failure
     * reports, gate on volume and signature novelty, then feed one bounded
     * playbook update whose curated rules land in the `failures_to_avoid`
     * section. Non-fatal by construction — playbook upkeep must never break the
     * completed user-facing run.
     *
     * @internal Public for the pipeline flow node and tests.
     */
    _updatePlaybookFromPipelineState(state: Readonly<Record<string, any>>): Promise<AxAgentPlaybookUpdateResult | undefined>;
    private _listOptimizationTargetDescriptors;
    private _createOptimizationProgram;
    private _createAgentOptimizeMetric;
    /** @internal Used by the optimizer to evaluate a single dataset task end-to-end. */
    _forwardForEvaluation<T extends Readonly<AxAIService>>(parentAi: T, task: Readonly<AxAgentEvalTask<IN>>, options?: Readonly<AxProgramForwardOptionsWithModels<T>>): Promise<AxAgentEvalPrediction<OUT>>;
    test(code: string, values?: Partial<IN>, options?: Readonly<{
        ai?: AxAIService;
        abortSignal?: AbortSignal;
        debug?: boolean;
    }>): Promise<AxAgentTestResult>;
}
interface AxAgentConfig<_IN extends AxGenIn, _OUT extends AxGenOut> extends AxAgentOptions<_IN> {
    ai?: AxAIService;
    judgeAI?: AxAIService;
    agentIdentity?: AxAgentIdentity;
}
declare function agent<const T extends string, const CF extends readonly AxContextFieldInput[] = []>(signature: T, config: Omit<AxAgentConfig<ParseSignature<T>['inputs'], ParseSignature<T>['outputs']>, 'contextFields'> & {
    contextFields?: CF;
}): AxAgent<ParseSignature<T>['inputs'], ParseSignature<T>['outputs']>;
declare function agent<TInput extends Record<string, any>, TOutput extends Record<string, any>, const CF extends readonly AxContextFieldInput[] = []>(signature: AxSignature<TInput, TOutput>, config: Omit<AxAgentConfig<TInput, TOutput>, 'contextFields'> & {
    contextFields?: CF;
}): AxAgent<TInput, TOutput>;
declare function agent(signature: Readonly<AxSignatureConfig>, config: AxAgentConfig<AxGenIn, AxGenOut>): AxAgent<AxGenIn, AxGenOut>;

/**
 * RLM actor stage: a single AxGen program driven in a code-runtime loop.
 *
 * The actor generates runtime-language code, the TypeScript loop executes it in a
 * pluggable `AxCodeRuntime`, the result is appended to an action log, and the
 * loop continues until the actor terminates with `final(...)` /
 * `askClarification(...)` (or hits `maxTurns`).
 *
 * Synthesis (turning the actor's `{task, evidence}` payload into structured
 * output fields) is **not** done here — it lives in a `Synthesizer` stage
 * that the pipeline (`AxAgent`) composes after the actor loop.
 *
 * The pipeline owns up to two of these (one for context distillation, one
 * for task execution). Use `ActorAgentRLM` directly only when you need
 * precise per-instance configuration outside the standard pipeline.
 */
/**
 * Note: this no longer implements `AxAgentic` because synthesis (responder)
 * is owned by the pipeline `AxAgent`. Use `AxAgent` (or the `agent()` factory)
 * for the user-facing surface; `ActorAgentRLM` is the building block.
 */
declare class ActorAgentRLM<IN extends AxGenIn = AxGenIn, OUT extends AxGenOut = AxGenOut> {
    private ai?;
    private judgeAI?;
    private program;
    private actorProgram;
    /**
     * Child agents that arrived through `options.functions` and were inlined as
     * tools. Tracked here so the optimizer can still walk into them via
     * `getOptimizableComponents`.
     */
    private agents?;
    private agentFunctions;
    private agentFunctionModuleMetadata;
    private debug?;
    private options?;
    private rlmConfig;
    private runtime;
    private executorDescription?;
    /**
     * Stage-owned optimizable instruction, rendered at the top of the actor
     * definition. This is the live backing for the stage's `::instruction`
     * component: it survives `_buildSplitPrograms()` rebuilds (unlike an
     * instruction set on the inner split programs, which are recreated) and
     * setting it triggers a rebuild so it takes effect immediately.
     */
    private stageInstruction?;
    /**
     * Standing instruction addenda appended after `executorDescription` in the
     * actor definition (set via `agent.addActorInstruction(...)`). A separate
     * additive channel so manual standing rules and the playbook apply-hook
     * (which recomposes `executorDescription` from a captured base) never
     * clobber each other. Process-local: not serialized into `AxAgentState`.
     */
    private instructionAddenda?;
    private executorModelPolicy?;
    private judgeOptions?;
    private recursionForwardOptions?;
    private executorForwardOptions?;
    private inputUpdateCallback?;
    private agentStatusCallback?;
    private onFunctionCall?;
    private onContextEvent?;
    private contextPromptConfigByField;
    private functionDiscoveryEnabled;
    private relevanceHintsEnabled;
    private moduleHintEnabled;
    private skillsHintEnabled;
    private memoriesHintEnabled;
    private _relevanceRankingChoice;
    private relevanceRankingOptions;
    private skillsCatalog?;
    private memoriesCatalog?;
    private runtimeLanguageName;
    private runtimeCodeFieldName;
    private runtimeCodeFieldTitle;
    private runtimeCodeFenceLanguage;
    private isJavaScriptRuntime;
    private runtimeUsageInstructions;
    private enforceIncrementalConsoleTurns;
    private bubbleErrors?;
    private agentIdentity?;
    private activeAbortControllers;
    private _stopRequested;
    /** Stage behavioral policy, resolved once at init — see stagePolicy.ts. */
    private stagePolicy;
    state: AxAgentState | undefined;
    stateError: string | undefined;
    private runtimeBootstrapContext;
    private llmQueryBudgetState;
    private baseActorDefinition;
    private currentDiscoveryPromptState;
    private actorDefinitionBaseDescription;
    private actorDefinitionContextFields;
    private actorDefinitionResponderOutputFields;
    private actorDefinitionBuildOptions;
    private func;
    /** Per-instance overrides for shipped RLM template sources, keyed by TemplateId. */
    _actorTemplateOverrides: Map<TemplateId, string> | undefined;
    /** Per-instance overrides for primitive bullet line(s), keyed by primitive id. */
    _primitiveOverrides: Map<string, readonly string[]> | undefined;
    /** Returns the actor template id this agent's variant renders. */
    _actorTemplateId(): TemplateId;
    private _actorPrimitiveStage;
    private _primitiveFlags;
    /**
     * Components owned by this actor agent: the actor template plus each
     * runtime primitive that would be rendered for the current variant + flag
     * set. The Synthesizer stage owns the responder template separately.
     */
    private _localOptimizableComponents;
    /** Apply this agent's own override updates and return whether any changed. */
    private _applyLocalOptimizedComponents;
    private shouldBubbleUserError;
    private _reservedAgentFunctionNamespaces;
    private _mergeAgentFunctionModuleMetadata;
    private _validateConfiguredSignature;
    private _validateAgentFunctionNamespaces;
    private _supportsRecursiveActorSlotOptimization;
    private _renderActorDefinition;
    private _buildActorInstruction;
    constructor(init: Readonly<{
        ai?: Readonly<AxAIService>;
        judgeAI?: Readonly<AxAIService>;
        agentIdentity?: Readonly<AxAgentIdentity>;
        signature: string | Readonly<AxSignatureConfig> | Readonly<AxSignature<IN, OUT>>;
    }>, options: Readonly<AxAgentOptions<IN>>);
    /** Builds (or rebuilds) the Actor program from the current base signature. */
    private _buildSplitPrograms;
    /**
     * Stops an in-flight forward call. Causes the call to throw
     * `AxAIServiceAbortedError`.
     */
    stop(): void;
    getId(): string;
    setId(id: string): void;
    namedPrograms(): Array<{
        id: string;
        signature?: string;
    }>;
    namedProgramInstances(): AxNamedProgramInstance<IN, OUT>[];
    getTraces(): AxProgramTrace<IN, OUT>[];
    setDemos(demos: readonly (AxAgentDemos<IN, OUT> | AxProgramDemos<IN, OUT>)[], options?: {
        modelConfig?: Record<string, unknown>;
    }): void;
    getUsage(): readonly AxProgramUsage[];
    getChatLog(): readonly AxChatLogEntry[];
    resetUsage(): void;
    getState(): AxAgentState | undefined;
    setState(state?: AxAgentState): void;
    /**
     * Provided for the optimizer's `createOptimizationProgram` so the
     * pipeline can iterate every named program (actor + synthesizer) when
     * scoring component edits.
     */
    _listOptimizationTargetDescriptors(): AxAgentOptimizationTargetDescriptor[];
    getFunction(): AxFunction;
    private _createRuntimeInputState;
    private _ensureLlmQueryBudgetState;
    private _createRuntimeExecutionContext;
    getSignature(): AxSignature;
    test(code: string, values?: Partial<IN>, options?: Readonly<{
        ai?: AxAIService;
        abortSignal?: AbortSignal;
        debug?: boolean;
    }>): Promise<AxAgentTestResult>;
    setSignature(signature: AxSignatureInput): void;
    applyOptimization(optimizedProgram: any): void;
    /**
     * The stage's optimizable instruction. Backed by the stage itself (not the
     * inner split programs, which are recreated on every rebuild and would
     * silently drop it) and rendered at the top of the actor definition.
     */
    getInstruction(): string | undefined;
    setInstruction(instruction: string): void;
    getOptimizableComponents(): readonly any[];
    applyOptimizedComponents(updates: Readonly<Record<string, string>>): void;
    /**
     * Runs the Actor loop: sets up the runtime session, executes code iteratively,
     * and returns the actor result + non-context input values + any actor-produced
     * field values. The pipeline (or external callers) feed this into a
     * `Synthesizer` stage to produce structured output.
     *
     * Closes the runtime session before returning.
     */
    _runActorLoop(parentAi: Readonly<AxAIService>, values: IN, options?: Readonly<AxProgramForwardOptions<string>>, effectiveAbortSignal?: AbortSignal, functionCallRecords?: AxAgentEvalFunctionCall[]): Promise<{
        nonContextValues: Record<string, unknown>;
        contextMetadata: string | undefined;
        guidanceLog: string | undefined;
        actionLog: string;
        executorResult: AxAgentExecutorResultPayload;
        actorFieldValues: Record<string, unknown>;
        usedMemories: AxAgentUsedMemory[];
        usedSkills: AxAgentUsedSkill[];
        turnCount: number;
    }>;
    private _withDefaultExecutorRequest;
    /**
     * Public alias for `_runActorLoop` — preferred name in new code.
     * Manages its own AbortController and budget state.
     */
    run<T extends Readonly<AxAIService>>(parentAi: T, values: IN, options?: Readonly<AxProgramForwardOptions<string>>): Promise<{
        nonContextValues: Record<string, unknown>;
        executorResult: AxAgentExecutorResultPayload;
        actorFieldValues: Record<string, unknown>;
        usedMemories: AxAgentUsedMemory[];
        usedSkills: AxAgentUsedSkill[];
        turnCount: number;
        guidanceLog: string | undefined;
        actionLog: string;
    }>;
    /**
     * Wraps an AxFunction as an async callable that handles both
     * named ({ key: val }) and positional (val1, val2) argument styles.
     */
    private static wrapFunction;
    private buildRuntimeGlobals;
    /**
     * Returns options compatible with AxGen (strips agent-specific grouped options).
     */
    private get _genOptions();
    /**
     * Builds the clean AxFunction parameters schema from input fields only.
     */
    private _buildFuncParameters;
}

type AxAgentMemoryEntry = {
    id: string;
    content: string;
};

/**
 * Sequential agent-layer batch evaluation for `agent.playbook().evolve()`.
 *
 * Strictly sequential by design: `_forwardForEvaluation` saves/clears/
 * restores the primary actor's state, discovery state, and llmQuery budget
 * around each call — concurrent calls on one agent instance would interleave
 * those save/restore pairs and corrupt state.
 */

/** Mutable (run + judge) pair budget shared across all improve() batches. */
type AxAgentEvalBudget = {
    remaining: number;
};
type AxAgentEvalBatchResult<IN extends AxGenIn = AxGenIn, OUT extends AxGenOut = AxGenOut> = {
    records: AxAgentPlaybookEvolveRunRecord<IN, OUT>[];
    /** Weighted mean score over executed records (0 when none ran). */
    mean: number;
    /** True when the budget ran out before every task executed. */
    exhausted: boolean;
};

/**
 * Deterministic failure clustering for `agent.playbook().evolve()` — zero LLM calls.
 *
 * Failures group by a stable signature so the miner sees one cluster per
 * failure mode. Key resolution order per record: majority signature among the
 * run's structured failure signals (P1 harvest) → first tool-error line →
 * first `XxxError:` line in the action log → `'behavioral:no_error'` (the
 * judge failed an error-free run: wrong output, forbidden actions, stalls).
 */

type AxAgentFailureCluster = {
    signature: string;
    records: AxAgentPlaybookEvolveRunRecord[];
    /** count x mean(1 - score): frequent, badly-scored clusters rank first. */
    severity: number;
    taskIds: readonly string[];
};

/**
 * Local, deterministic relevance ranker for agent discovery and recall.
 *
 * The domain-neutral core is `rankDocuments`: given a query and a small set of
 * documents (each a bag of weighted text fields), it scores every document
 * with a lightweight BM25-style overlap and returns a shortlist — or nothing
 * when it has no confident signal. Domain adapters (`rankModules` for tool
 * modules; skills/memories catalog searchers) build their documents from the
 * metadata each domain has.
 *
 * It is intentionally pure and dependency-free (only `stopwords` is reused):
 * identical inputs always produce identical output, so it is trivially
 * unit-testable and produces stable telemetry for `agent.optimize()`.
 */
/** One searchable text field of a document. */
interface AxRankableField {
    text: string;
    /** Term-frequency multiplier (default 1). Use >1 for high-signal fields. */
    weight?: number;
    /** Tokenize as a code identifier (camelCase/snake/kebab) instead of prose. */
    identifier?: boolean;
}
/** A document the ranker can score. */
interface AxRankableDocument {
    id: string;
    fields: readonly AxRankableField[];
}
/** A single ranked document. */
interface AxRankedDocument {
    id: string;
    /** Score normalized to 0..1 relative to the top match (top is always 1). */
    score: number;
    /** Query terms that matched this document (for telemetry/debugging). */
    matchedTerms: string[];
}
interface AxRankDocumentsOptions {
    /** Max documents to return. Default 3. */
    topK?: number;
    /**
     * Absolute floor on the top match's idf-weighted query coverage (0..1).
     * Below this the ranker emits nothing. Default 0.08.
     */
    minScore?: number;
    /**
     * Discrimination guard. If every document scores within this ratio of the
     * top, the ranker can't discriminate and emits nothing. Default 0.15.
     */
    marginRatio?: number;
    /**
     * Minimum catalog size to rank at all (a hint over a 1-item catalog is
     * noise). Default 2. Explicit-search adapters pass 1 for best-effort mode.
     */
    minDocs?: number;
}
/** A module the ranker can score, flattened from agent function-group metadata. */
interface AxModuleRankInput {
    namespace: string;
    title?: string;
    selectionCriteria?: string;
    description?: string;
    /** Bare function names in the module, e.g. `['search', 'read']`. */
    functionNames?: readonly string[];
    /** Union of parameter property names across the module's functions. */
    argNames?: readonly string[];
}
/** A single ranked module. */
interface AxRankedModule {
    namespace: string;
    /** Score normalized to 0..1 relative to the top match (top is always 1). */
    score: number;
    /** Query terms that matched this module (for telemetry/debugging). */
    matchedTerms: string[];
}
interface AxRankModulesOptions {
    /** Max modules to return. Default 3. */
    topK?: number;
    /** Absolute floor on the top match's coverage (0..1). Default 0.08. */
    minScore?: number;
    /** Discrimination guard ratio. Default 0.15. */
    marginRatio?: number;
}
/** Per-domain shortlists for the advisory `relevanceHints` prompt field. */
interface AxRelevanceHints {
    modules?: readonly {
        namespace: string;
    }[];
    skills?: readonly {
        id: string;
        name: string;
    }[];
    memories?: readonly {
        id: string;
        snippet?: string;
    }[];
}

/**
 * Shape summary of the distiller's evidence object. Built in-worker (shared
 * mode) or host-side (fallback mode) and rendered into the executor's
 * `distilledContextSummary` prompt field; the data itself never enters a
 * prompt.
 */
type AxEvidenceDescriptor = {
    kind: 'axEvidenceDescriptor';
    totalChars: number;
    entries: {
        key: string;
        type: string;
        size: number;
        length?: number;
        /** Field names of the first element (arrays of objects). */
        itemKeys?: string[];
        /** Top-level keys (plain-object values). */
        keys?: string[];
    }[];
};
type AxSharedSessionPhase = 'distiller' | 'executor';
/**
 * Coordinates one runtime session across the pipeline's distiller and
 * executor phases. Created per `AxAgent.forward()` by the pipeline, handed to
 * both actor runs, closed by the pipeline.
 *
 * Shared mode requires a JavaScript-capable runtime (the phase boundary is an
 * in-session snippet). For other runtimes the pipeline keeps `mode:
 * 'fallback'`: each stage runs in its own session exactly as before, and the
 * evidence value crosses through the host into the executor's runtime
 * globals — correctness preserved, zero-copy lost.
 */
declare class AxAgentSharedRuntimeSession {
    readonly mode: 'shared' | 'fallback';
    phase: AxSharedSessionPhase;
    session: AxCodeSession | undefined;
    /**
     * Cross-run state (from the coordinator's canonical executor-held
     * `AxAgentState`). Variable bindings are applied once when the phase-1
     * session is adopted; stage-level prompt state stays with each stage.
     */
    restoreState: AxAgentState | undefined;
    /** Executor-stage field deletions applied at the phase boundary. */
    excludeFieldDeletions: readonly string[];
    /**
     * Phase-1 system/alias names, excluded from the executor phase's runtime
     * inspection so inherited context aliases don't render as user variables.
     */
    phase1ReservedNames: readonly string[];
    /** Fallback mode only: the real evidence value held host-side. */
    fallbackEvidence: Record<string, unknown> | undefined;
    /**
     * Entries actually restored into the phase-1 session from `restoreState`,
     * kept for the distiller's restore notice / live-state rendering.
     */
    restoredEntries: AxAgentState['runtimeEntries'] | undefined;
    private closed;
    constructor(options?: Readonly<{
        mode?: 'shared' | 'fallback';
    }>);
    get isShared(): boolean;
    /**
     * Adopt the freshly created phase-1 session: apply cross-run variable
     * bindings, install the in-worker `final` wrapper, remember reserved names.
     */
    adoptDistillerSession(session: AxCodeSession, options: Readonly<{
        reservedNames: readonly string[];
        signal?: AbortSignal;
    }>): Promise<void>;
    /**
     * Transition the adopted session into the executor phase. `phaseGlobals`
     * are the executor run's host closures (final/askClarification/llmQuery/
     * tools/…) patched over the phase-1 bindings; `inputs` are the executor's
     * input values merged per key.
     */
    beginExecutorPhase(options: Readonly<{
        phaseGlobals: Record<string, unknown>;
        inputs: Record<string, unknown>;
        aliasNames: readonly string[];
        signal?: AbortSignal;
    }>): Promise<void>;
    /** Mid-phase per-key input sync (replaces wholesale `inputs` patches). */
    mergeInputs(inputs: Record<string, unknown>, options?: Readonly<{
        signal?: AbortSignal;
    }>): Promise<void>;
    /**
     * Session-death recovery mid-phase: the runtime context recreated a fresh
     * session; track it so `close()` targets the live one. Inherited state is
     * gone, which matches the existing per-stage restart semantics.
     */
    replaceSession(session: AxCodeSession): void;
    close(): void;
}

/**
 * The pipeline's two actor stages are the same `ActorAgentRLM` running under
 * different policies. This table is the single answer to "what does being
 * the distiller/executor mean" — every stage-conditional in the codebase
 * reads a named capability from here instead of branching on the variant
 * string, so the full behavioral difference between the stages fits on one
 * screen.
 */
type AxAgentStageVariant = 'distiller' | 'executor';
interface AxAgentStagePolicy {
    readonly variant: AxAgentStageVariant;
    /** Actor system-prompt template (and primitive-registry stage). */
    readonly templateId: 'rlm/distiller.md' | 'rlm/executor.md';
    /**
     * Tool callables execute. The distiller sees the full tool surface
     * (schemas, catalogs, discovery — its extraction guide) but its callables
     * are throwing stubs; execution authority stays with the executor.
     */
    readonly executesTools: boolean;
    /**
     * Child agents (arriving via `options.functions`) register as optimizer
     * sub-programs. Only the executor owns them — the distiller shares the
     * function metadata without duplicating optimizer ownership.
     */
    readonly ownsChildAgents: boolean;
    /** Receives the prompt-resident `contextMap` orientation cache. */
    readonly seesContextMap: boolean;
    /** Receives advisory relevance hints (ranked toward task execution). */
    readonly seesRelevanceHints: boolean;
    /** Ingests forward-time preset skills passed on the forward call. */
    readonly ingestsForwardSkills: boolean;
    /**
     * Enables `used(...)` skill-usage attribution for this stage. Currently
     * executor-only (pre-reconnaissance behavior); candidate to enable for the
     * distiller now that it loads skill guides too.
     */
    readonly tracksSkillUsage: boolean;
    /**
     * May declare the coordinator-wired `contextMetadata` input (the shared
     * runtime's raw-context inventory). User signatures are still guarded —
     * they validate through the distiller, which carries every user input.
     */
    readonly allowsContextMetadataInput: boolean;
    /** Synthesizes a mechanical `executorRequest` when the handoff lacks one. */
    readonly synthesizesDefaultExecutorRequest: boolean;
    /**
     * Shared session: this stage creates the session (phase 1). The other
     * stage adopts the live session and patches its phase bindings over it.
     */
    readonly createsSharedSession: boolean;
    /**
     * Shared session: exports variable bindings at end of run — the pipeline's
     * canonical cross-run state. The phase-1 stage exports bindings-free
     * (its variables live on in the session) — except when its run ends in
     * `respond()`, which skips the executor: the actor loop then exports WITH
     * bindings and the pipeline copies them onto the executor's cross-run slot.
     */
    readonly exportsSharedBindings: boolean;
    /**
     * Shared session: excludes phase-1 system/alias names from runtime
     * inspection so inherited context aliases don't render as user variables.
     */
    readonly inheritsPhase1ReservedNames: boolean;
    /**
     * Fallback mode (non-JS runtime): receives the host-carried evidence as a
     * runtime-only input value plus bare alias.
     */
    readonly receivesFallbackEvidence: boolean;
}

/**
 * Context-engineering measurement aggregator (benchmark/spike helper).
 *
 * Subscribes to AxAgent `onContextEvent` telemetry and `getUsage()` to compute
 * the headline context-compression metrics for a single agent run:
 *   - peak mutable prompt size (chars)
 *   - compaction ratio (chars removed / chars seen)
 *   - cumulative tokens
 *   - pressure distribution, checkpoint/tombstone counts
 *
 * This is policy-agnostic: it only reads the public event stream, so it measures
 * any `contextPolicy` (today's hindsight presets) unchanged. A future
 * plan-aware "foresight" retention strategy would surface through the same
 * events and be measured here without modification.
 *
 * Internal benchmark helper — intentionally NOT exported from `src/ax/index.ts`.
 */

type AxContextTurnSample = {
    stage: AxAgentContextStage;
    turn: number;
    pressure: AxAgentContextPressure;
    mutablePromptChars: number;
    effectiveBudgetChars: number;
    actionLogEntryCount: number;
};
type AxContextMetricsSummary = {
    /** Number of `budget_check` events observed (one per actor turn). */
    turns: number;
    peakMutablePromptChars: number;
    finalMutablePromptChars: number;
    checkpoints: number;
    tombstones: number;
    compactions: number;
    totalOriginalChars: number;
    totalRenderedChars: number;
    /** (originalChars - renderedChars) / originalChars across all compactions; 0 when nothing compacted. */
    compactionRatio: number;
    pressureCounts: Record<AxAgentContextPressure, number>;
    cumulativeTokens: number;
    promptTokens: number;
    completionTokens: number;
    series: AxContextTurnSample[];
};
/**
 * Accumulates context telemetry for one agent run. Pass {@link onEvent} directly
 * as the agent's `onContextEvent` handler, then call {@link summarize} with
 * `agent.getUsage()` once `forward()` resolves.
 */
declare class AxContextMetricsCollector {
    private readonly series;
    private checkpoints;
    private tombstones;
    private compactions;
    private totalOriginalChars;
    private totalRenderedChars;
    private peakMutablePromptChars;
    private finalMutablePromptChars;
    private readonly pressureCounts;
    readonly onEvent: (event: Readonly<AxAgentContextEvent>) => void;
    summarize(usage?: readonly AxProgramUsage[] | AxAgentUsage | undefined): AxContextMetricsSummary;
}
type AxContextMetricsRow = {
    scenario: string;
    preset: string;
    summary: AxContextMetricsSummary;
    /** Wall-clock time for the run, in ms (live runs only; omit for mock). */
    elapsedMs?: number;
};

/**
 * Deterministic, offline scenarios + harness for the context-compression spike.
 *
 * Drives AxAgent with a scripted `AxMockAIService` + stub `AxCodeRuntime` (the
 * pattern from `ctx-vs-task.test.ts`) so a sweep runs with zero API keys and is
 * fully deterministic. Shared by the regression test
 * (`context-compression.test.ts`) and the runnable demo
 * (`src/examples/context-compression-spike.ts`).
 *
 * Forward-compat seam: the comparison axis is `contextPolicy.preset`
 * ({@link AX_CONTEXT_PRESETS}). A future plan-aware "foresight" retention
 * strategy becomes a new preset value (or `contextPolicy` field); adding it to
 * that array is the only change needed to A/B it against today's four presets.
 * The aggregator (`AxContextMetricsCollector`) is policy-agnostic and measures
 * it unchanged. Do NOT add foresight logic here — this file only measures the
 * existing (hindsight) baseline.
 *
 * Internal benchmark helper — NOT exported from `src/ax/index.ts`.
 */

type AxScriptedTurn = {
    kind: 'log';
    chars: number;
} | {
    kind: 'error';
    message: string;
} | {
    kind: 'final';
    answer: string;
};
type AxContextScenario = {
    name: string;
    description: string;
    signature: string;
    contextFields: string[];
    input: Record<string, unknown>;
    maxTurns: number;
    /** Ordered code payloads the mock returns for each EXECUTOR turn. */
    executorTurns: AxScriptedTurn[];
};

type AxAgentMetricsInstruments = Readonly<{
    requests: Counter;
    errors: Counter;
    duration: Histogram;
}>;

/**
 * Runtime primitive registry.
 *
 * The RLM stage templates (distiller.md, executor.md) advertise a small
 * set of built-in async functions to the LLM: `final`, `askClarification`,
 * `llmQuery`, `inspectRuntime`, `reportSuccess`/`reportFailure`,
 * `discover`, etc.
 *
 * Historically these were hand-written into each template as bullet lists,
 * which drifted apart as primitives were added. This module is the single
 * source of truth: each primitive is declared once with its stages and
 * gating flag, and the templates render the filtered list via a
 * `{{ primitivesList }}` variable.
 */
type AxRuntimePrimitiveStage = 'distiller' | 'executor';
interface AxRuntimePrimitive {
    /** Stable id; used for testing / debugging. */
    readonly id: string;
    /** Which actor stages advertise this primitive. */
    readonly stages: readonly AxRuntimePrimitiveStage[];
    /** Optional required flag name. */
    readonly enabledBy?: string;
    /** Optional flag names where at least one must be truthy. */
    readonly enabledByAny?: readonly string[];
    /** Optional flag name that hides the primitive when truthy. */
    readonly disabledBy?: string;
    /** Short purpose statement rendered above the overloads. */
    readonly description: string;
    /** Signature overloads rendered as separate backticked lines. */
    readonly signatures: readonly AxRuntimePrimitiveSignature[];
    /** Optional examples rendered under the overload list. */
    readonly examples?: readonly AxRuntimePrimitiveExample[];
}
type AxRuntimePrimitiveSignature = {
    readonly code: string;
    readonly enabledBy?: string;
    readonly enabledByAny?: readonly string[];
    readonly disabledBy?: string;
};
type AxRuntimePrimitiveExample = {
    readonly code: string;
    readonly enabledBy?: string;
    readonly enabledByAny?: readonly string[];
    readonly disabledBy?: string;
};
/**
 * Canonical, ordered registry of RLM actor primitives. Order here is the
 * order rendered into the prompt.
 */
declare const axRuntimePrimitives: readonly AxRuntimePrimitive[];

declare enum AxAIAnthropicModel {
    Claude55Opus = "claude-opus-5-5",
    Claude51Fable = "claude-fable-5-1",
    Claude5Opus = "claude-opus-5",
    Claude5Fable = "claude-fable-5",
    Claude5Sonnet = "claude-sonnet-5",
    Claude48Opus = "claude-opus-4-8",
    Claude47Opus = "claude-opus-4-7",
    Claude46Opus = "claude-opus-4-6",
    Claude46Sonnet = "claude-sonnet-4-6",
    Claude45Opus = "claude-opus-4-5-20251101",
    /** @deprecated Retired by Anthropic on 2026-08-05; use `Claude55Opus`. */
    Claude41Opus = "claude-opus-4-1-20250805",
    /** @deprecated Retired by Anthropic on 2026-06-15; use `Claude55Opus`. */
    Claude4Opus = "claude-opus-4-20250514",
    /** @deprecated Retired by Anthropic on 2026-06-15; use `Claude5Sonnet`. */
    Claude4Sonnet = "claude-sonnet-4-20250514",
    Claude45Sonnet = "claude-sonnet-4-5-20250929",
    Claude45Haiku = "claude-haiku-4-5",
    /** @deprecated Retired by Anthropic on 2026-02-19; use `Claude5Sonnet`. */
    Claude37Sonnet = "claude-3-7-sonnet-latest",
    /** @deprecated Retired by Anthropic on 2025-10-28; use `Claude5Sonnet`. */
    Claude35Sonnet = "claude-3-5-sonnet-latest",
    /** @deprecated Retired by Anthropic on 2026-02-19; use `Claude45Haiku`. */
    Claude35Haiku = "claude-3-5-haiku-latest",
    /** @deprecated Retired by Anthropic on 2026-01-05; use `Claude55Opus`. */
    Claude3Opus = "claude-3-opus-latest",
    /** @deprecated Retired by Anthropic on 2025-07-21; use `Claude5Sonnet`. */
    Claude3Sonnet = "claude-3-sonnet-20240229",
    /** @deprecated Retired by Anthropic on 2026-04-20; use `Claude45Haiku`. */
    Claude3Haiku = "claude-3-haiku-20240307",
    /** @deprecated Retired by Anthropic on 2025-07-21; use `Claude55Opus`. */
    Claude21 = "claude-2.1",
    /** @deprecated Retired by Anthropic on 2024-11-06; use `Claude45Haiku`. */
    ClaudeInstant12 = "claude-instant-1.2"
}
declare enum AxAIAnthropicVertexModel {
    Claude55Opus = "claude-opus-5-5",
    Claude51Fable = "claude-fable-5-1",
    Claude5Opus = "claude-opus-5",
    Claude5Fable = "claude-fable-5",
    Claude5Sonnet = "claude-sonnet-5",
    Claude48Opus = "claude-opus-4-8",
    Claude47Opus = "claude-opus-4-7",
    Claude46Opus = "claude-opus-4-6",
    Claude46Sonnet = "claude-sonnet-4-6",
    Claude45Opus = "claude-opus-4-5@20251101",
    Claude41Opus = "claude-opus-4-1@20250805",
    Claude4Opus = "claude-opus-4@20250514",
    Claude45Sonnet = "claude-sonnet-4-5@20250929",
    Claude4Sonnet = "claude-sonnet-4@20250514",
    Claude37Sonnet = "claude-3-7-sonnet@20250219",
    Claude35SonnetV2 = "claude-3-5-sonnet-v2@20241022",
    Claude45Haiku = "claude-haiku-4-5@20251001",
    Claude35Haiku = "claude-3-5-haiku@20241022",
    Claude35Sonnet = "claude-3-5-sonnet@20240620",
    Claude3Opus = "claude-3-opus@20240229",
    Claude3Haiku = "claude-3-haiku@20240307"
}
type AxAIAnthropicThinkingConfig = {
    /** Optional: numeric budget hint used in config normalization */
    thinkingTokenBudget?: number;
    /** Optional: include provider thinking content in outputs */
    includeThoughts?: boolean;
};
type AxAIAnthropicThinkingWire = {
    type: 'enabled';
    budget_tokens: number;
} | {
    type: 'adaptive';
    display?: 'summarized' | 'omitted';
} | {
    type: 'disabled';
};
type AxAIAnthropicEffortLevel = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
type AxAIAnthropicTaskBudget = {
    type: 'tokens';
    total: number;
    remaining?: number;
};
type AxAIAnthropicOutputConfig = {
    effort?: AxAIAnthropicEffortLevel;
    format?: {
        type: 'json_schema';
        schema: object;
    };
    task_budget?: AxAIAnthropicTaskBudget;
};
type AxAIAnthropicEffortLevelMapping = {
    minimal?: AxAIAnthropicEffortLevel;
    low?: AxAIAnthropicEffortLevel;
    medium?: AxAIAnthropicEffortLevel;
    high?: AxAIAnthropicEffortLevel;
    highest?: AxAIAnthropicEffortLevel;
};
type AxAIAnthropicThinkingTokenBudgetLevels = {
    minimal?: number;
    low?: number;
    medium?: number;
    high?: number;
    highest?: number;
};
type AxAIAnthropicFunctionTool = {
    name: string;
    description: string;
    input_schema?: object;
} & AxAIAnthropicChatRequestCacheParam;
type AxAIAnthropicWebSearchTool = {
    type: 'web_search_20250305';
    name: string;
    max_uses?: number;
    allowed_domains?: string[];
    blocked_domains?: string[];
    user_location?: {
        type: 'approximate';
        city?: string;
        region?: string;
        country?: string;
        timezone?: string;
    };
};
type AxAIAnthropicRequestTool = AxAIAnthropicFunctionTool | AxAIAnthropicWebSearchTool;
type AxAIAnthropicConfig = AxModelConfig & {
    model: AxAIAnthropicModel | AxAIAnthropicVertexModel;
    thinking?: AxAIAnthropicThinkingConfig;
    thinkingTokenBudgetLevels?: AxAIAnthropicThinkingTokenBudgetLevels;
    effortLevelMapping?: AxAIAnthropicEffortLevelMapping;
    tools?: ReadonlyArray<AxAIAnthropicRequestTool>;
};
type AxAIAnthropicChatRequestCacheParam = {
    cache_control?: {
        type: 'ephemeral';
    };
};
type AxAIAnthropicChatRequest = {
    model?: string;
    anthropic_version?: string;
    messages: ({
        role: 'system';
        content: string | ({
            type: 'text';
            text: string;
        } & AxAIAnthropicChatRequestCacheParam)[];
    } | {
        role: 'user';
        content: string | (({
            type: 'text';
            text: string;
        } & AxAIAnthropicChatRequestCacheParam) | ({
            type: 'image';
            source: {
                type: 'base64';
                media_type: string;
                data: string;
            };
        } & AxAIAnthropicChatRequestCacheParam) | ({
            type: 'audio' | 'document' | 'video' | 'image';
            source: {
                type: 'base64';
                media_type: string;
                data: string;
            } | {
                type: 'url';
                url: string;
            };
        } & AxAIAnthropicChatRequestCacheParam) | ({
            type: 'tool_result';
            is_error?: boolean;
            tool_use_id: string;
            content: string | (({
                type: 'text';
                text: string;
            } & AxAIAnthropicChatRequestCacheParam) | ({
                type: 'image';
                source: {
                    type: 'base64';
                    media_type: string;
                    data: string;
                };
            } & AxAIAnthropicChatRequestCacheParam))[];
        } & AxAIAnthropicChatRequestCacheParam))[];
    } | {
        role: 'assistant';
        content: string | (({
            type: 'text';
            text: string;
        } & AxAIAnthropicChatRequestCacheParam) | {
            type: 'thinking';
            thinking: string;
            signature?: string;
        } | {
            type: 'redacted_thinking';
            data: string;
            signature?: string;
        } | ({
            type: 'tool_use';
            id: string;
            name: string;
            input: object;
        } & AxAIAnthropicChatRequestCacheParam))[];
    })[];
    tools?: AxAIAnthropicRequestTool[];
    tool_choice?: {
        type: 'auto' | 'any' | 'none';
    } | {
        type: 'tool';
        name?: string;
    };
    max_tokens?: number;
    stop_sequences?: string[];
    stream?: boolean;
    system?: string | ({
        type: 'text';
        text: string;
    } & AxAIAnthropicChatRequestCacheParam)[];
    temperature?: number;
    top_p?: number;
    top_k?: number;
    thinking?: AxAIAnthropicThinkingWire;
    output_config?: AxAIAnthropicOutputConfig;
    speed?: 'fast';
    metadata?: {
        user_id: string;
    };
};
type AxAIAnthropicStopDetails = {
    type: 'refusal';
    category?: 'cyber' | 'bio' | string | null;
    explanation?: string | null;
};
type AxAIAnthropicChatResponse = {
    id: string;
    type: 'message';
    role: 'assistant';
    content: ({
        type: 'text';
        text: string;
    } | {
        id: string;
        name: string;
        type: 'tool_use';
        input?: string;
    } | {
        type: 'thinking';
        thinking: string;
        signature?: string;
    } | {
        type: 'redacted_thinking';
        thinking?: string;
        data?: string;
        signature?: string;
    })[];
    model: string;
    stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'refusal' | 'pause_turn' | 'model_context_window_exceeded';
    stop_details?: AxAIAnthropicStopDetails | null;
    stop_sequence?: string;
    usage: {
        input_tokens: number;
        output_tokens: number;
        cache_creation_input_tokens?: number;
        cache_read_input_tokens?: number;
        speed?: 'fast' | 'standard';
    };
};
type AxAIAnthropicChatError = {
    type: 'error';
    error: {
        type: 'overloaded_error' | 'api_error' | 'rate_limit_error' | 'invalid_request_error' | 'authentication_error' | 'permission_error' | 'not_found_error' | 'request_too_large';
        message: string;
    };
};
interface AxAIAnthropicMessageStartEvent {
    type: 'message_start';
    message: {
        id: string;
        type: 'message';
        role: 'assistant';
        content: [];
        model: string;
        stop_reason: null | string;
        stop_sequence: null | string;
        usage: {
            input_tokens: number;
            output_tokens: number;
            cache_creation_input_tokens?: number;
            cache_read_input_tokens?: number;
            speed?: 'fast' | 'standard';
        };
    };
}
interface AxAIAnthropicContentBlockStartEvent {
    index: number;
    type: 'content_block_start';
    content_block: {
        type: 'text';
        text: string;
    } | {
        type: 'tool_use';
        id: string;
        name: string;
        input: object;
    } | {
        type: 'server_tool_use';
        id: string;
        name: string;
        input: object;
    } | {
        type: 'web_search_tool_result';
        tool_use_id: string;
        content: unknown[];
    } | {
        type: 'thinking';
        thinking: string;
    };
}
interface AxAIAnthropicContentBlockDeltaEvent {
    index: number;
    type: 'content_block_delta';
    delta: {
        type: 'text_delta';
        text: string;
    } | {
        type: 'input_json_delta';
        partial_json: string;
    } | {
        type: 'thinking_delta';
        thinking: string;
    } | {
        type: 'signature_delta';
        signature: string;
    };
}
interface AxAIAnthropicContentBlockStopEvent {
    type: 'content_block_stop';
    index: number;
}
interface AxAIAnthropicMessageDeltaEvent {
    type: 'message_delta';
    delta: {
        stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'refusal' | 'pause_turn' | 'model_context_window_exceeded' | null;
        stop_sequence: string | null;
        stop_details?: AxAIAnthropicStopDetails | null;
    };
    usage: {
        output_tokens: number;
        speed?: 'fast' | 'standard';
    };
}
interface AxAIAnthropicMessageStopEvent {
    type: 'message_stop';
}
interface AxAIAnthropicPingEvent {
    type: 'ping';
}
interface AxAIAnthropicErrorEvent {
    type: 'error';
    error: {
        type: 'overloaded_error' | 'api_error' | 'rate_limit_error' | 'invalid_request_error' | 'authentication_error' | 'permission_error' | 'not_found_error' | 'request_too_large';
        message: string;
    };
}
type AxAIAnthropicChatResponseDelta = AxAIAnthropicMessageStartEvent | AxAIAnthropicContentBlockStartEvent | AxAIAnthropicContentBlockDeltaEvent | AxAIAnthropicContentBlockStopEvent | AxAIAnthropicMessageDeltaEvent | AxAIAnthropicMessageStopEvent | AxAIAnthropicPingEvent | AxAIAnthropicErrorEvent;

declare const axAIAnthropicDefaultConfig: () => AxAIAnthropicConfig;
declare const axAIAnthropicVertexDefaultConfig: () => AxAIAnthropicConfig;
type ExtractModelKeys$1<T> = T extends readonly {
    key: infer K;
}[] ? K : never;
interface AxAIAnthropicArgs<TModelKey = string> {
    name: 'anthropic';
    apiKey?: string | (() => Promise<string>);
    credentialProvider?: AxAICredentialProvider;
    projectId?: string;
    region?: string;
    config?: Readonly<Partial<AxAIAnthropicConfig>>;
    options?: Readonly<AxAIServiceOptions>;
    models?: AxAIInputModelList<AxAIAnthropicModel | AxAIAnthropicVertexModel, undefined, TModelKey>;
}
declare class AxAIAnthropic<TModelKey = string> extends AxBaseAI<AxAIAnthropicModel | AxAIAnthropicVertexModel, unknown, AxAIAnthropicChatRequest, never, AxAIAnthropicChatResponse, AxAIAnthropicChatResponseDelta, never, TModelKey> {
    static create<const T extends AxAIAnthropicArgs<any>>(options: T): T extends {
        models: infer M;
    } ? AxAIAnthropic<ExtractModelKeys$1<M>> : AxAIAnthropic<string>;
    constructor({ apiKey, credentialProvider, projectId, region, config, options, models, _profile, }: Readonly<Omit<AxAIAnthropicArgs<TModelKey>, 'name'> & {
        _profile?: {
            id: string;
            name: string;
            apiURL: string;
            headers: () => Promise<Record<string, string>>;
            defaultModel: string;
            modelInfo: ReadonlyArray<AxModelInfo>;
            supportFor: (model: string) => AxAIFeatures;
            requestUpdater?: (request: AxAIAnthropicChatRequest, options: Readonly<AxAIServiceOptions>) => AxAIAnthropicChatRequest;
            supportsToolChoiceNone?: boolean;
        };
    }>);
}

declare const axModelInfoAnthropic: AxModelInfo[];

type FetchLike = typeof fetch;
type JsonRecord = Record<string, any>;
declare const axAudioInputToBlob: (audio: Readonly<AxAudioInput>, fallbackFormat?: AxAudioFormat) => Blob;
declare const axAudioInputFilename: (audio: Readonly<AxAudioInput>, fallbackFormat?: AxAudioFormat) => string;
declare const axNormalizeTranscriptionResponse: (value: unknown) => AxTranscriptionResponse;
declare const axFetchMultipartTranscription: ({ url, headers, audio, fields, fetch, abortSignal, }: Readonly<{
    url: string;
    headers: Record<string, string>;
    audio: AxAudioInput;
    fields: Record<string, string | number | boolean | undefined>;
    fetch?: FetchLike;
    abortSignal?: AbortSignal;
}>) => Promise<AxTranscriptionResponse>;
declare const axFetchJsonSpeech: ({ url, headers, body, format, transcript, fetch, abortSignal, }: Readonly<{
    url: string;
    headers: Record<string, string>;
    body: JsonRecord;
    format?: AxAudioFormat;
    transcript: string;
    fetch?: FetchLike;
    abortSignal?: AbortSignal;
}>) => Promise<AxSpeechResponse>;

declare const axOpenAIChatAudioDefaults: () => AxChatAudioConfig;
declare const axGoogleGeminiLiveAudioDefaults: () => AxChatAudioConfig;
declare const axMergeChatAudioConfig: (base?: Readonly<AxChatAudioConfig>, override?: Readonly<AxChatAudioConfig>) => AxChatAudioConfig | undefined;
declare const axIsAudioOutputEnabled: (audio?: Readonly<AxChatAudioConfig>) => boolean;

declare const axAudioMimeType: (format?: AxAudioFormat, sampleRate?: number, fallback?: string) => string;
declare const axAudioFormatFromMimeType: (mimeType?: string) => AxAudioFormat | undefined;
/**
 * Read the `rate=` and `channels=` parameters that raw-PCM mime types such as
 * `audio/l16; rate=24000; channels=1` carry, since the bytes themselves don't.
 */
declare const axAudioParamsFromMimeType: (mimeType?: string) => {
    sampleRate?: number;
    channels?: number;
};
declare const axConcatBase64: (chunks: readonly string[]) => string;

/**
 * Expected token counts used to compare route costs before a request runs.
 * Omitted prompt or completion counts are treated as zero.
 */
type AxBalancerExpectedTokens = Readonly<Partial<Pick<AxTokenUsage, 'promptTokens' | 'completionTokens'>>>;
/** Stable address for one adaptive route's learned statistics. */
type AxBalancerStatsKey = Readonly<{
    /** Application-level partition for independently deployed routing policies. */
    namespace: string;
    /** Request-level partition, such as workflow or traffic class. */
    slice: string;
    /** Model alias requested from the balancer. */
    logicalModel: string;
    /** Stable provider route identity supplied by the application. */
    routeKey: string;
}>;
/**
 * Versioned route state used by adaptive balancing.
 *
 * Successful latency is stored in log space using Welford's online mean and
 * M2. The balancer combines those values with a Normal-Inverse-Gamma prior at
 * selection time.
 */
type AxBalancerRouteStats = Readonly<{
    /** Serialized state format version. */
    version: 1;
    /** Total successful and failed observations. */
    observations: number;
    /** Successful observations included in the latency model. */
    successes: number;
    /** Exponentially weighted probability of a transient provider failure. */
    failureEwma: number;
    /** Online mean of the natural logarithm of successful latency. */
    logLatencyMean: number;
    /** Welford M2 accumulator for natural-log successful latency. */
    logLatencyM2: number;
}>;
/** One provider-health observation recorded after an adaptive attempt. */
type AxBalancerStatsObservation = Readonly<{
    outcome: 'success';
    latencyMs: number;
}> | Readonly<{
    outcome: 'failure';
}>;
/**
 * Storage contract for adaptive routing state.
 *
 * `observe` must update a key atomically. Remote implementations can use
 * {@link axUpdateBalancerRouteStats} inside a transaction or server-side
 * script. Store failures are isolated from model requests by `AxBalancer`.
 */
interface AxBalancerStatsStore {
    /** Read the latest route state, or return `undefined` for a cold route. */
    get(key: AxBalancerStatsKey): Promise<AxBalancerRouteStats | undefined>;
    /** Atomically reduce one observation into the state stored at `key`. */
    observe(key: AxBalancerStatsKey, observation: AxBalancerStatsObservation): Promise<void>;
}
/** Public, prompt-free context supplied to adaptive routing callbacks. */
type AxBalancerRoutingContext<TModelKey = string> = Readonly<{
    /** Logical model alias on the chat request. */
    model: TModelKey | undefined;
    /** Prompt-free service options associated with the request. */
    options: Readonly<AxAIServiceOptions> | undefined;
}>;
/** Context supplied when overriding a route's estimated request cost. */
type AxBalancerCostContext<TModelKey = string> = Readonly<{
    /** Candidate service whose request cost is being estimated. */
    service: AxAIService<unknown, unknown, TModelKey>;
    /** Stable position of the service in the balancer's original input list. */
    serviceIndex: number;
    /** Stable route identity used by the adaptive stats store. */
    routeKey: string;
    /** Logical model alias requested from the balancer. */
    logicalModel: string;
    /** Concrete provider model selected by the service's model mapping. */
    resolvedModel: string;
    /** Optional pre-request token estimate configured on the strategy. */
    expectedTokens: AxBalancerExpectedTokens | undefined;
}>;
/** Sanitized candidate score exposed by the routing event hook. */
type AxBalancerCandidateScore = Readonly<{
    /** Stable route identity used by the stats store. */
    routeKey: string;
    /** Public service name returned by the candidate. */
    serviceName: string;
    /** Final value used to rank this candidate; lower is better. */
    score: number;
    /** Pre-request cost estimate in the strategy's chosen currency or unit. */
    estimatedCost: number;
    /** Learned EWMA probability of a transient provider failure. */
    failureProbability: number;
    /** Sampled probability that a successful response misses the deadline. */
    deadlineMissProbability: number;
}>;
/** Classification of a transient provider failure used for failover. */
type AxBalancerFailureReason = 'status' | 'network' | 'response' | 'stream-terminated' | 'timeout';
/**
 * Prompt-free adaptive routing telemetry.
 *
 * Events intentionally contain no chat request, response, or raw provider
 * error. Callback failures never affect routing.
 */
type AxBalancerRoutingEvent = Readonly<{
    /** Application namespace used by the stats key. */
    namespace: string;
    /** Request partition used by the stats key. */
    slice: string;
    /** Logical model alias requested from the balancer. */
    logicalModel: string;
}> & (Readonly<{
    /** Candidate ranking was computed once for this request. */
    type: 'ranked';
    /** Candidates in attempt order with prompt-free score components. */
    candidates: readonly AxBalancerCandidateScore[];
}> | Readonly<{
    /** One candidate was selected for an attempt. */
    type: 'selected';
    routeKey: string;
    serviceName: string;
    /** One-based position in this request's ranked attempt sequence. */
    attempt: number;
}> | Readonly<{
    /** A transient provider failure caused failover to the next route. */
    type: 'fallback';
    fromRouteKey: string;
    toRouteKey: string | undefined;
    reason: AxBalancerFailureReason;
    status: number | undefined;
}> | Readonly<{
    /** A success or eligible transient failure was sent to the store. */
    type: 'observation';
    routeKey: string;
    serviceName: string;
    outcome: AxBalancerStatsObservation['outcome'];
    latencyMs: number | undefined;
    streaming: boolean;
    reason: AxBalancerFailureReason | undefined;
    status: number | undefined;
}> | Readonly<{
    /** A best-effort stats-store operation failed. */
    type: 'store-error';
    operation: 'get' | 'observe';
    routeKey: string;
    errorType: string;
}>);
/** Opt-in adaptive provider-routing strategy for {@link AxBalancer}. */
type AxBalancerAdaptiveStrategy<TModelKey = string> = Readonly<{
    /** Selects adaptive routing while leaving the default strategy unchanged. */
    type: 'adaptive';
    /** Target response latency in milliseconds; streaming uses first-chunk latency. */
    deadlineMs: number;
    /**
     * Cost assigned to a provider failure or deadline miss, in the same currency
     * or unit returned by `estimateCost` or the service pricing catalog.
     */
    badOutcomeCost: number;
    /** Expected tokens used with each service's built-in model pricing. */
    expectedTokens?: AxBalancerExpectedTokens;
    /** Override route pricing. Values must be finite and non-negative. */
    estimateCost?: (context: AxBalancerCostContext<TModelKey>) => number;
    /** Namespace used to isolate applications sharing a stats store. @default "default" */
    namespace?: string;
    /** Prompt-free application partition such as a workflow or tenant class. */
    slice?: (context: AxBalancerRoutingContext<TModelKey>) => string;
    /**
     * Stable route identity. Required when `statsStore` is supplied. The index
     * is the service's position in the balancer's original input list.
     */
    routeKey?: (service: AxAIService<unknown, unknown, TModelKey>, serviceIndex: number) => string;
    /** Shared decision-state store. Defaults to one in-memory store per balancer. */
    statsStore?: AxBalancerStatsStore;
    /** Best-effort prompt-free telemetry hook. */
    onRoutingEvent?: (event: AxBalancerRoutingEvent) => void | Promise<void>;
}>;
/**
 * Pure reducer for an adaptive route observation.
 *
 * External stores should apply this update atomically for each stats key.
 */
declare function axUpdateBalancerRouteStats(current: AxBalancerRouteStats | undefined, observation: AxBalancerStatsObservation): AxBalancerRouteStats;
/** Browser-compatible in-memory adaptive routing store. */
declare class AxInMemoryBalancerStatsStore implements AxBalancerStatsStore {
    private readonly stats;
    get(key: AxBalancerStatsKey): Promise<AxBalancerRouteStats | undefined>;
    observe(key: AxBalancerStatsKey, observation: AxBalancerStatsObservation): Promise<void>;
}

type ExtractServiceModelKeys$1<T> = T extends AxAIService<any, any, infer K> ? K : never;
type ExtractAllModelKeys$1<T extends readonly any[]> = T extends readonly [
    infer First,
    ...infer Rest
] ? ExtractServiceModelKeys$1<First> | ExtractAllModelKeys$1<Rest> : never;
/**
 * Options for the balancer.
 */
type AxBalancerOptions<TModelKey = string> = {
    comparator?: (a: AxAIService<unknown, unknown, TModelKey>, b: AxAIService<unknown, unknown, TModelKey>) => number;
    debug?: boolean;
    initialBackoffMs?: number;
    maxBackoffMs?: number;
    maxRetries?: number;
    /**
     * Opt into request-time provider selection using learned failure rate,
     * successful latency, and estimated cost. When omitted, the existing
     * comparator-ordered behavior is unchanged.
     */
    strategy?: AxBalancerAdaptiveStrategy<TModelKey>;
};
/**
 * Provider balancer with ordered failover by default and opt-in adaptive
 * routing for chat requests.
 */
declare class AxBalancer<TServices extends readonly AxAIService<any, any, any>[] = readonly AxAIService[], TModelKey = ExtractAllModelKeys$1<TServices>> implements AxAIService<unknown, unknown, TModelKey> {
    private services;
    private currentServiceIndex;
    private currentService;
    private debug;
    private initialBackoffMs;
    private maxBackoffMs;
    private maxRetries;
    private readonly adaptive;
    private serviceFailures;
    private static readonly RETRYABLE_STATUS_CODES;
    constructor(services: TServices, options?: AxBalancerOptions<TModelKey>);
    /**
     * Static factory method for type-safe balancer creation with automatic model key inference.
     */
    static create<const TServices extends readonly AxAIService<any, any, any>[]>(services: TServices, options?: AxBalancerOptions<ExtractAllModelKeys$1<TServices>>): AxBalancer<TServices, ExtractAllModelKeys$1<TServices>>;
    getLastUsedChatModel(): unknown;
    getLastUsedEmbedModel(): unknown;
    getLastUsedModelConfig(): AxModelConfig | undefined;
    /**
     * Service comparator that respects the input order of services.
     */
    static inputOrderComparator: () => number;
    /**
     * Service comparator that sorts services by cost.
     */
    static metricComparator: <TModelKey_1 = string>(a: AxAIService<unknown, unknown, TModelKey_1>, b: AxAIService<unknown, unknown, TModelKey_1>) => number;
    getModelList(): AxAIModelList<TModelKey> | undefined;
    private getNextService;
    private reset;
    getName(): string;
    getId(): string;
    getFeatures(model?: string): AxAIFeatures;
    getMetrics(): AxAIServiceMetrics;
    getEstimatedCost(modelUsage?: AxModelUsage): number;
    private canRetryService;
    private handleFailure;
    private handleSuccess;
    /**
     * Whether an error should route to another service rather than fail the request.
     * Mirrors the decisions made in chat()'s catch block so the streaming peek path and
     * the synchronous path agree on what "retryable" means.
     */
    private isRetryableServiceError;
    validateChatRequest(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): void;
    private getCandidateServices;
    /**
     * Wraps a streaming response to make it participate in failover. Two responsibilities:
     *
     * 1. Pre-content errors: eagerly reads the first chunk so a provider error thrown while
     *    reading (e.g. Anthropic's HTTP-200 `overloaded_error` SSE) rejects here, where
     *    {@link chat}'s try/catch can route it through the normal failover path. On success it
     *    returns a new stream that re-emits the buffered first chunk then pumps the rest.
     * 2. Mid-stream errors: a retryable error *after* the first chunk can't fail over
     *    transparently (partial output is already committed), so it is surfaced via
     *    `controller.error`. But we record the failure first (see {@link handleFailure}) —
     *    otherwise the failed service stays out of backoff and an app-level retry via chat()
     *    (which restarts at index 0 and doesn't reset()) would route straight back to it.
     */
    private peekStreamForFailover;
    private executeChatAttempt;
    private chatAdaptive;
    private rankAdaptiveCandidates;
    private estimateAdaptiveCost;
    private getAdaptiveStats;
    private recordAdaptiveObservation;
    private emitRoutingEvent;
    resolveChatService(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<{
        service: Readonly<AxAIService<unknown, unknown, any>>;
        model?: string;
    }>;
    openChatSession(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatSession>;
    chat(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatResponse | ReadableStream<AxChatResponse>>;
    embed(req: Readonly<AxEmbedRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxEmbedResponse>;
    transcribe(req: Readonly<AxTranscriptionRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
    setOptions(options: Readonly<AxAIServiceOptions>): void;
    getOptions(): Readonly<AxAIServiceOptions>;
    getLogger(): AxLoggerFunction;
}

type AxUserMessage = Extract<AxChatRequest['chatPrompt'][number], {
    role: 'user';
}>;
type AxUserContentItem = Exclude<AxUserMessage['content'], string>[number];
type AxUserImageContent = Extract<AxUserContentItem, {
    type: 'image';
}>;
type AxUserFileContent = Extract<AxUserContentItem, {
    type: 'file';
}>;
/**
 * Configuration options for content processing and fallback behavior
 */
interface ProcessingOptions {
    /** How to handle unsupported content types: 'error' throws, 'degrade' converts to text, 'skip' omits */
    fallbackBehavior?: 'error' | 'degrade' | 'skip';
    /** Service to convert images to text descriptions */
    imageToText?: (imageData: string) => Promise<string>;
    /** Service to convert audio to text transcriptions */
    audioToText?: (audioData: string, format?: string) => Promise<string>;
    /** Service to extract text from files */
    fileToText?: (fileData: string, mimeType: string) => Promise<string>;
    /** Service to fetch and extract text from URLs */
    urlToText?: (url: string) => Promise<string>;
}
/**
 * Represents content after provider-specific processing. Native image and file
 * content is retained when the provider advertises support.
 */
type ProcessedContent = {
    type: 'text';
    text: string;
} | AxUserImageContent | AxUserFileContent;
/**
 * Indicates what types of media content are present in a request
 */
interface MediaRequirements {
    /** Whether the content includes images */
    hasImages: boolean;
    /** Whether the content includes audio */
    hasAudio: boolean;
    /** Whether the content includes files */
    hasFiles: boolean;
    /** Whether the content includes URLs */
    hasUrls: boolean;
}
/**
 * Processes content for a specific AI provider, handling unsupported media types.
 *
 * This function takes mixed content (text, images, audio, files, URLs) and transforms
 * it to formats supported by the target provider. Unsupported content types are
 * handled according to the fallback behavior:
 * - 'error': Throws AxMediaNotSupportedError
 * - 'degrade': Converts to text using fallback services or alt text
 * - 'skip': Omits the unsupported content
 *
 * @param content - The content to process (string, object, or array of content items)
 * @param provider - The target AI service provider
 * @param options - Processing options including fallback behavior and conversion services
 * @returns Promise resolving to processed text and supported native media items
 * @throws AxMediaNotSupportedError when fallbackBehavior is 'error' and content is unsupported
 * @throws AxContentProcessingError when a conversion service fails
 *
 * @example
 * ```typescript
 * const processed = await axProcessContentForProvider(
 *   [
 *     { type: 'text', text: 'Analyze this:' },
 *     { type: 'image', image: 'base64...', altText: 'Chart showing sales data' }
 *   ],
 *   textOnlyProvider,
 *   {
 *     fallbackBehavior: 'degrade',
 *     imageToText: async (data) => await visionService.describe(data)
 *   }
 * );
 * // Result for a text-only provider: [{ type: 'text', text: 'Analyze this:' }, { type: 'text', text: 'Chart showing sales data' }]
 * ```
 */
declare function axProcessContentForProvider(content: any, provider: AxAIService, options?: ProcessingOptions): Promise<ProcessedContent[]>;
/**
 * Analyzes a chat prompt to determine what media types it contains.
 *
 * Scans through chat messages to identify the types of media content present,
 * which can be used for provider capability matching and routing decisions.
 *
 * @param chatPrompt - Array of chat messages to analyze
 * @returns Object indicating which media types are present in the chat prompt
 *
 * @example
 * ```typescript
 * const requirements = axAnalyzeChatPromptRequirements([
 *   {
 *     role: 'user',
 *     content: [
 *       { type: 'text', text: 'Analyze this:' },
 *       { type: 'image', image: 'base64...' },
 *       { type: 'file', filename: 'report.pdf' }
 *     ]
 *   }
 * ]);
 * // Result: { hasImages: true, hasAudio: false, hasFiles: true, hasUrls: false }
 * ```
 */
declare function axAnalyzeChatPromptRequirements(chatPrompt: any[]): MediaRequirements;

/**
 * Represents a provider's compatibility score for a specific request
 */
interface ProviderCapabilityScore {
    /** The AI service provider */
    provider: AxAIService;
    /** Numerical score based on capability match (higher is better) */
    score: number;
    /** List of capabilities the provider is missing for this request */
    missingCapabilities: string[];
    /** List of capabilities the provider supports for this request */
    supportedCapabilities: string[];
}
/**
 * Result of validating whether a provider can handle a request
 */
interface CapabilityValidationResult {
    /** Whether the provider fully supports the request */
    isSupported: boolean;
    /** List of capabilities the provider is missing */
    missingCapabilities: string[];
    /** Non-critical issues or limitations */
    warnings: string[];
    /** Suggested alternatives for missing capabilities */
    alternatives: string[];
}
/**
 * Analyzes a chat request to determine what capabilities it requires from AI providers.
 *
 * This function examines the request content to identify:
 * - Media types (images, audio, files, URLs)
 * - Function calling requirements
 * - Streaming requirements
 * - Caching requirements
 * - Token usage estimation
 *
 * @param request - The chat request to analyze
 * @returns Object containing detailed capability requirements and token estimation
 *
 * @example
 * ```typescript
 * const requirements = axAnalyzeRequestRequirements({
 *   chatPrompt: [{
 *     role: 'user',
 *     content: [
 *       { type: 'text', text: 'Analyze this image:' },
 *       { type: 'image', image: 'base64...', details: 'high' }
 *     ]
 *   }]
 * });
 *
 * console.log(requirements.hasImages); // true
 * console.log(requirements.estimatedTokens); // ~95
 * ```
 */
declare function axAnalyzeRequestRequirements(request: AxChatRequest): MediaRequirements & {
    hasAudioOutput: boolean;
    requiresFunctions: boolean;
    requiresStreaming: boolean;
    requiresCaching: boolean;
    contentTypes: Set<string>;
    estimatedTokens: number;
};
/**
 * Validates whether an AI provider can handle a request with specific requirements.
 *
 * Compares the provider's feature set against the analyzed request requirements
 * to determine compatibility, missing capabilities, and potential issues.
 *
 * @param provider - The AI service provider to validate
 * @param requirements - Requirements object from axAnalyzeRequestRequirements()
 * @returns Validation result with support status, missing capabilities, and alternatives
 *
 * @example
 * ```typescript
 * const requirements = axAnalyzeRequestRequirements(request);
 * const validation = axValidateProviderCapabilities(openaiProvider, requirements);
 *
 * if (!validation.isSupported) {
 *   console.log('Missing:', validation.missingCapabilities);
 *   console.log('Try:', validation.alternatives);
 * }
 * ```
 */
declare function axValidateProviderCapabilities(provider: AxAIService, requirements: ReturnType<typeof axAnalyzeRequestRequirements>, request?: Readonly<AxChatRequest>, options?: Readonly<AxAIServiceOptions>): CapabilityValidationResult;
/**
 * Scores multiple AI providers based on how well they meet request requirements.
 *
 * Uses a weighted scoring system where providers earn points for supported capabilities:
 * - Base functionality: +10 points
 * - Media support (images/audio/files/URLs): +25 points each
 * - Core features (functions/streaming/caching): +8-15 points each
 * - Missing critical capabilities: -10 points each
 * - Bonus points for advanced features (large file support, persistent caching, etc.)
 *
 * @param providers - Array of AI service providers to score
 * @param requirements - Requirements object from axAnalyzeRequestRequirements()
 * @returns Array of scored providers sorted by score (highest first)
 *
 * @example
 * ```typescript
 * const requirements = axAnalyzeRequestRequirements(request);
 * const scores = axScoreProvidersForRequest([openai, gemini, cohere], requirements);
 *
 * console.log(`Best: ${scores[0].provider.getName()} (${scores[0].score} points)`);
 * console.log(`Supports: ${scores[0].supportedCapabilities.join(', ')}`);
 * ```
 */
declare function axScoreProvidersForRequest(providers: AxAIService[], requirements: ReturnType<typeof axAnalyzeRequestRequirements>, request?: Readonly<AxChatRequest>, options?: Readonly<AxAIServiceOptions>): ProviderCapabilityScore[];
/**
 * Automatically selects the optimal AI provider for a given request.
 *
 * Analyzes the request requirements, scores available providers, and returns
 * the best match based on capability compatibility and scoring algorithm.
 *
 * @param request - The chat request to find a provider for
 * @param availableProviders - Array of available AI service providers
 * @param options - Selection options
 * @param options.requireExactMatch - Only return providers with full capability support
 * @param options.allowDegradation - Allow providers that require content processing fallbacks
 * @returns The optimal AI service provider
 * @throws Error if no suitable provider found or requirements not met
 *
 * @example
 * ```typescript
 * // Automatic selection with degradation allowed
 * const provider = axSelectOptimalProvider(
 *   multiModalRequest,
 *   [openai, gemini, cohere],
 *   { allowDegradation: true }
 * );
 *
 * // Strict matching - must support all features natively
 * const provider = axSelectOptimalProvider(
 *   imageRequest,
 *   [openai, gemini],
 *   { requireExactMatch: true }
 * );
 * ```
 */
declare function axSelectOptimalProvider(request: AxChatRequest, availableProviders: AxAIService[], options?: {
    requireExactMatch?: boolean;
    allowDegradation?: boolean;
}, serviceOptions?: Readonly<AxAIServiceOptions>): AxAIService;
/**
 * Generates a comprehensive compatibility report for a request across all providers.
 *
 * Provides detailed analysis including requirement breakdown, provider scoring,
 * recommendations, and human-readable compatibility summary.
 *
 * @param request - The chat request to analyze
 * @param availableProviders - Array of available AI service providers
 * @returns Comprehensive compatibility report with analysis and recommendations
 *
 * @example
 * ```typescript
 * const report = axGetCompatibilityReport(request, [openai, gemini, cohere]);
 *
 * console.log(report.summary); // "OpenAI supports 4/4 requirements (100% compatibility)"
 * console.log('Requirements:', report.requirements);
 *
 * for (const score of report.providerScores) {
 *   console.log(`${score.provider.getName()}: ${score.score} points`);
 *   console.log(`  Missing: ${score.missingCapabilities.join(', ')}`);
 * }
 * ```
 */
declare function axGetCompatibilityReport(request: AxChatRequest, availableProviders: AxAIService[]): {
    requirements: ReturnType<typeof axAnalyzeRequestRequirements>;
    providerScores: ProviderCapabilityScore[];
    recommendedProvider: AxAIService | null;
    summary: string;
};
/**
 * Filters providers that support a specific media type.
 *
 * @param providers - Array of AI service providers to filter
 * @param mediaType - The media type to check support for
 * @returns Array of providers that support the specified media type
 *
 * @example
 * ```typescript
 * const imageProviders = axGetProvidersWithMediaSupport(allProviders, 'images');
 * console.log(`${imageProviders.length} providers support images`);
 * ```
 */
declare function axGetProvidersWithMediaSupport(providers: AxAIService[], mediaType: 'images' | 'audio' | 'files' | 'urls'): AxAIService[];
/**
 * Analyzes format compatibility across providers for a specific media type.
 *
 * @param providers - Array of AI service providers to analyze
 * @param mediaType - The media type to check format support for
 * @returns Object mapping each supported format to the providers that support it
 *
 * @example
 * ```typescript
 * const compatibility = axGetFormatCompatibility(allProviders, 'images');
 * console.log('JPEG support:', compatibility['image/jpeg']?.map(p => p.getName()));
 * console.log('PNG support:', compatibility['image/png']?.map(p => p.getName()));
 * ```
 */
declare function axGetFormatCompatibility(providers: AxAIService[], mediaType: 'images' | 'audio' | 'files'): {
    [format: string]: AxAIService[];
};

/** JSON values accepted in native Typesafe state and criteria. */
type AxAITypesafeJsonValue = string | number | boolean | null | readonly AxAITypesafeJsonValue[] | {
    readonly [key: string]: AxAITypesafeJsonValue;
};
/** Native state, instructions, or a criterion description. */
type AxAITypesafeEntry = string | null | readonly AxAITypesafeJsonValue[] | {
    readonly [key: string]: AxAITypesafeJsonValue;
};
type AxAITypesafeNoulQuestion = {
    readonly type: 'noul';
    readonly instructions?: AxAITypesafeEntry;
    readonly criteria?: {
        readonly true?: AxAITypesafeEntry;
        readonly false?: AxAITypesafeEntry;
    } | null;
};
type AxAITypesafeChoiceQuestion = {
    readonly type: 'choice';
    readonly instructions?: AxAITypesafeEntry;
    readonly criteria: Readonly<Record<string, AxAITypesafeEntry>>;
};
type AxAITypesafeScoreQuestion = {
    readonly type: 'score';
    readonly instructions?: AxAITypesafeEntry;
    /** Two to ten descriptions, ordered from lowest to highest. */
    readonly criteria: readonly [
        AxAITypesafeEntry,
        AxAITypesafeEntry,
        ...AxAITypesafeEntry[]
    ];
};
type AxAITypesafeQuestion = AxAITypesafeNoulQuestion | AxAITypesafeChoiceQuestion | AxAITypesafeScoreQuestion;
type AxAITypesafeQuestions = Readonly<Record<string, AxAITypesafeQuestion>>;
type AxAITypesafeAnswer<Q extends AxAITypesafeQuestion> = Q extends AxAITypesafeNoulQuestion ? {
    readonly type: 'noul';
    readonly noul: number;
} : Q extends AxAITypesafeChoiceQuestion ? {
    readonly type: 'choice';
    readonly choice: keyof Q['criteria'] & string;
    readonly probabilities: {
        readonly [K in keyof Q['criteria']]: number;
    };
    readonly confidence: number;
} : Q extends AxAITypesafeScoreQuestion ? {
    readonly type: 'score';
    /** Fractional expected rubric index, starting at zero. */
    readonly score: number;
    readonly probabilities: Readonly<Record<string, number>>;
    readonly legend: Readonly<Record<string, AxAITypesafeEntry>>;
    readonly confidence: number;
} : never;
type AxAITypesafeRequest<Q extends AxAITypesafeQuestions = AxAITypesafeQuestions> = {
    readonly state: AxAITypesafeEntry;
    readonly questions: Q;
    readonly model?: string;
};
type AxAITypesafeResponse<Q extends AxAITypesafeQuestions = AxAITypesafeQuestions> = {
    readonly model: string;
    readonly answers: {
        readonly [K in keyof Q]: AxAITypesafeAnswer<Q[K]>;
    };
    readonly usage: {
        readonly input_tokens: number;
        readonly output_tokens: number;
    };
};
type AxAITypesafeModelCard = {
    readonly name: string;
    readonly description: string;
    readonly release_date: string;
};

/** Typesafe evaluates typed questions; it does not generate freeform text. */
type AxAITypesafeArgs<TModelKey = string> = {
    name: 'typesafe';
    apiKey?: string;
    credentialProvider?: AxAICredentialProvider;
    apiURL?: string;
    config?: {
        model?: string;
    };
    options?: Readonly<AxAIServiceOptions>;
    models?: AxAIInputModelList<string, never, TModelKey>;
    modelInfo?: AxModelInfo[];
    /** Convert a Noul probability to true at or above this value. Default: 0.5. */
    trueThreshold?: number;
};
type Request$1 = AxAITypesafeRequest & {
    model: string;
};
/** Native Typesafe System One transport, with Ax retries, cancellation and usage. */
declare class AxAITypesafe<TModelKey = string> extends AxBaseAI<string, never, Request$1, never, unknown, never, never, TModelKey> {
    constructor(args: Readonly<AxAITypesafeArgs<TModelKey>>);
}

/**
 * Cohere: Models for text generation
 */
declare enum AxAICohereModel {
    CommandRPlus = "command-r-plus",
    CommandR = "command-r",
    Command = "command",
    CommandLight = "command-light"
}
/**
 * Cohere: Models for use in embeddings
 */
declare enum AxAICohereEmbedModel {
    EmbedEnglishV30 = "embed-english-v3.0",
    EmbedEnglishLightV30 = "embed-english-light-v3.0",
    EmbedMultiLingualV30 = "embed-multilingual-v3.0",
    EmbedMultiLingualLightV30 = "embed-multilingual-light-v3.0"
}

/**
 * DeepSeek: Models for text generation
 */
declare enum AxAIDeepSeekModel {
    DeepSeekV4Flash = "deepseek-v4-flash",
    DeepSeekV4Pro = "deepseek-v4-pro",
    /** @deprecated Use DeepSeekV4Flash. DeepSeek will remove this alias on 2026-07-24. */
    DeepSeekChat = "deepseek-chat",
    /** @deprecated Use DeepSeekV4Flash or DeepSeekV4Pro. */
    DeepSeekCoder = "deepseek-coder",
    /** @deprecated Use DeepSeekV4Flash with thinking enabled. DeepSeek will remove this alias on 2026-07-24. */
    DeepSeekReasoner = "deepseek-reasoner"
}

declare enum AxAIGoogleGeminiModel {
    Gemini38Flash = "gemini-3.8-flash",
    Gemini37Flash = "gemini-3.7-flash",
    Gemini36Flash = "gemini-3.6-flash",
    Gemini35Flash = "gemini-3.5-flash",
    Gemini35FlashLite = "gemini-3.5-flash-lite",
    Gemini31Pro = "gemini-3.1-pro-preview",
    Gemini31FlashLite = "gemini-3.1-flash-lite",
    /** @deprecated Shut down by Google on 2026-05-25; use `Gemini31FlashLite`. */
    Gemini3FlashLite = "gemini-3.1-flash-lite-preview",
    Gemini3Flash = "gemini-3-flash-preview",
    Gemini3Pro = "gemini-3.1-pro-preview",
    Gemini3ProImage = "gemini-3-pro-image",
    Gemini31FlashImage = "gemini-3.1-flash-image",
    Gemini31FlashLiteImage = "gemini-3.1-flash-lite-image",
    Gemini38Live = "gemini-3.8-live",
    Gemini38LiveExtendedThinking = "gemini-3.8-live-extended-thinking",
    Gemini31FlashLive = "gemini-3.1-flash-live-preview",
    Gemini38FlashTTS = "gemini-3.8-flash-tts",
    Gemini38FlashLiteTTS = "gemini-3.8-flash-lite-tts",
    Gemini31FlashTTS = "gemini-3.1-flash-tts-preview",
    Gemini35Transcribe = "gemini-3.5-transcribe",
    NanoBanana2 = "nano-banana-2",
    /** @deprecated Shut down by Google on 2026-08-31; use `gemini-robotics-er-2-preview`. */
    GeminiRoboticsER16 = "gemini-robotics-er-1.6-preview",
    Gemini25Pro = "gemini-2.5-pro",
    Gemini25Flash = "gemini-2.5-flash",
    Gemini25FlashNativeAudio = "gemini-2.5-flash-native-audio-preview-12-2025",
    Gemini25FlashLite = "gemini-2.5-flash-lite",
    /** @deprecated Shut down by Google on 2026-06-01; use `Gemini36Flash`. */
    Gemini20Flash = "gemini-2.0-flash",
    /** @deprecated Shut down by Google on 2026-06-01; use `Gemini31FlashLite`. */
    Gemini20FlashLite = "gemini-2.0-flash-lite",
    /** @deprecated Shut down by Google; use `Gemini36Flash`. */
    Gemini20ProExp = "gemini-2.0-pro-exp-02-05",
    /** @deprecated Shut down by Google; use `Gemini36Flash`. */
    Gemini20FlashThinkingExp = "gemini-2.0-flash-thinking-exp-01-21",
    /** @deprecated Shut down by Google; use `Gemini36Flash`. */
    Gemini1Pro = "gemini-1.0-pro",
    /** @deprecated Shut down by Google; use `Gemini36Flash`. */
    Gemini15Flash = "gemini-1.5-flash",
    /** @deprecated Shut down by Google; use `Gemini36Flash`. */
    Gemini15Flash002 = "gemini-1.5-flash-002",
    /** @deprecated Shut down by Google; use `Gemini31FlashLite`. */
    Gemini15Flash8B = "gemini-1.5-flash-8b",
    /** @deprecated Shut down by Google; use `Gemini31Pro`. */
    Gemini15Pro = "gemini-1.5-pro",
    GeminiFlashLatest = "gemini-flash-latest",
    GeminiFlashLiteLatest = "gemini-flash-lite-latest",
    GeminiProLatest = "gemini-pro-latest"
}
declare enum AxAIGoogleGeminiEmbedModel {
    GeminiEmbedding2 = "gemini-embedding-2",
    GeminiEmbedding001 = "gemini-embedding-001",
    /** @deprecated Shut down by Google on 2025-10-30; use `GeminiEmbedding2`. */
    GeminiEmbedding = "gemini-embedding-exp",
    TextEmbeddingLarge = "text-embedding-large-exp-03-07",
    TextEmbedding005 = "text-embedding-005"
}
declare enum AxAIGoogleGeminiSafetyCategory {
    HarmCategoryHarassment = "HARM_CATEGORY_HARASSMENT",
    HarmCategoryHateSpeech = "HARM_CATEGORY_HATE_SPEECH",
    HarmCategorySexuallyExplicit = "HARM_CATEGORY_SEXUALLY_EXPLICIT",
    HarmCategoryDangerousContent = "HARM_CATEGORY_DANGEROUS_CONTENT"
}
declare enum AxAIGoogleGeminiSafetyThreshold {
    BlockNone = "BLOCK_NONE",
    BlockOnlyHigh = "BLOCK_ONLY_HIGH",
    BlockMediumAndAbove = "BLOCK_MEDIUM_AND_ABOVE",
    BlockLowAndAbove = "BLOCK_LOW_AND_ABOVE",
    BlockDefault = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"
}
declare enum AxAIGoogleGeminiEmbedTypes {
    SemanticSimilarity = "SEMANTIC_SIMILARITY",
    Classification = "CLASSIFICATION",
    Clustering = "CLUSTERING",
    RetrievalDocument = "RETRIEVAL_DOCUMENT",
    RetrievalQuery = "RETRIEVAL_QUERY",
    QuestionAnswering = "QUESTION_ANSWERING",
    FactVerification = "FACT_VERIFICATION",
    CodeRetrievalQuery = "CODE_RETRIEVAL_QUERY"
}
type AxAIGoogleGeminiContent = {
    role: 'user' | 'model';
    parts: AxAIGoogleGeminiContentPart[];
};
type AxAIGoogleGeminiContentPart = {
    thought?: boolean;
    thought_signature?: string;
    metadata?: {
        videoMetadata: object;
    };
} & ({
    text: string;
    thought?: boolean;
} | {
    thought: string;
} | {
    inlineData: {
        mimeType: string;
        data: string;
    };
} | {
    functionCall: {
        id?: string;
        name: string;
        args: object;
    };
} | {
    functionResponse: {
        id?: string;
        name: string;
        response: object;
    };
} | {
    fileData: {
        mimeType: string;
        fileUri: string;
    };
} | {
    audioTranscription: {
        text: string;
    };
} | {
    executableCode: object;
} | {
    codeExecutionResult: object;
});
type AxAIGoogleGeminiToolFunctionDeclaration = {
    name: string;
    description?: string;
    /** OpenAPI Schema subset: rejects `additionalProperties` and type unions. */
    parameters?: object;
    /** Full JSON Schema. Mutually exclusive with `parameters`. */
    parametersJsonSchema?: object;
};
type AxAIGoogleGeminiToolGoogleSearchRetrieval = {
    dynamic_retrieval_config: {
        mode?: 'MODE_DYNAMIC';
        dynamic_threshold?: number;
    };
};
type AxAIGoogleGeminiToolGoogleMaps = {
    enableWidget?: boolean;
};
type AxAIGoogleGeminiTool = {
    function_declarations?: AxAIGoogleGeminiToolFunctionDeclaration[];
    code_execution?: object;
    google_search_retrieval?: AxAIGoogleGeminiToolGoogleSearchRetrieval;
    google_search?: object;
    url_context?: object;
    google_maps?: AxAIGoogleGeminiToolGoogleMaps;
};
type AxAIGoogleGeminiToolConfig = {
    function_calling_config: {
        mode: 'ANY' | 'NONE' | 'AUTO';
        allowed_function_names?: string[];
    };
    retrievalConfig?: AxAIGoogleGeminiRetrievalConfig;
};
type AxAIGoogleGeminiThinkingLevel = 'minimal' | 'low' | 'medium' | 'high';
type AxAIGoogleGeminiGenerationConfig = {
    temperature?: number;
    topP?: number;
    topK?: number;
    frequencyPenalty?: number;
    candidateCount?: number;
    maxOutputTokens?: number;
    stopSequences?: readonly string[];
    responseMimeType?: string;
    responseSchema?: object;
    responseJsonSchema?: object;
    thinkingConfig?: {
        thinkingBudget?: number;
        thinkingLevel?: AxAIGoogleGeminiThinkingLevel;
        includeThoughts?: boolean;
    };
};
type AxAIGoogleGeminiRetrievalConfig = {
    latLng?: {
        latitude: number;
        longitude: number;
    };
};
type AxAIGoogleGeminiSafetySettings = {
    category: AxAIGoogleGeminiSafetyCategory;
    threshold: AxAIGoogleGeminiSafetyThreshold;
}[];
type AxAIGoogleGeminiChatRequest = {
    contents: AxAIGoogleGeminiContent[];
    tools?: AxAIGoogleGeminiTool[];
    toolConfig?: AxAIGoogleGeminiToolConfig;
    systemInstruction?: AxAIGoogleGeminiContent;
    generationConfig: AxAIGoogleGeminiGenerationConfig;
    safetySettings?: AxAIGoogleGeminiSafetySettings;
    /** Reference to a cached content resource (for explicit context caching) */
    cachedContent?: string;
    service_tier?: 'standard' | 'flex' | 'priority';
};
type AxAIGoogleGeminiChatResponse = {
    responseId?: string;
    modelVersion?: string;
    candidates: {
        content: AxAIGoogleGeminiContent;
        finishReason: 'STOP' | 'MAX_TOKENS' | 'SAFETY' | 'RECITATION' | 'OTHER' | 'BLOCKLIST' | 'PROHIBITED_CONTENT' | 'SPII' | 'MALFORMED_FUNCTION_CALL' | 'UNEXPECTED_TOOL_CALL' | 'FINISH_REASON_UNSPECIFIED';
        citationMetadata: {
            citations: {
                startIndex: number;
                endIndex: number;
                uri: string;
                title: string;
                license: string;
                publicationDate: {
                    year: number;
                    month: number;
                    day: number;
                };
            }[];
        };
        groundingMetadata?: {
            groundingChunks?: {
                maps?: {
                    title?: string;
                    uri?: string;
                };
                retrievedContext?: {
                    title?: string;
                    uri?: string;
                    /** File Search multimodal (May 2026): id of the file/media chunk. */
                    media_id?: string;
                    /** File Search multimodal (May 2026): page numbers cited within the source. */
                    page_numbers?: number[];
                };
            }[];
            googleMapsWidgetContextToken?: string;
        };
    }[];
    usageMetadata: {
        promptTokenCount: number;
        candidatesTokenCount: number;
        totalTokenCount: number;
        thoughtsTokenCount: number;
        /** Number of tokens in the cached content (from explicit caching) */
        cachedContentTokenCount?: number;
        /** Service tier that actually handled the request. */
        serviceTier?: 'unspecified' | 'standard' | 'flex' | 'priority';
    };
};
type AxAIGoogleGeminiChatResponseDelta = AxAIGoogleGeminiChatResponse;
type AxAIGoogleGeminiThinkingConfig = {
    thinkingTokenBudget?: number;
    thinkingLevel?: AxAIGoogleGeminiThinkingLevel;
    includeThoughts?: boolean;
};
type AxAIGoogleGeminiThinkingTokenBudgetLevels = {
    minimal?: number;
    low?: number;
    medium?: number;
    high?: number;
    highest?: number;
};
/**
 * Maps thinkingTokenBudget string levels to Gemini 3 thinkingLevel values.
 * The mapped result is clamped to the levels supported by the resolved model.
 */
type AxAIGoogleGeminiThinkingLevelMapping = {
    minimal?: AxAIGoogleGeminiThinkingLevel;
    low?: AxAIGoogleGeminiThinkingLevel;
    medium?: AxAIGoogleGeminiThinkingLevel;
    high?: AxAIGoogleGeminiThinkingLevel;
    highest?: AxAIGoogleGeminiThinkingLevel;
};
/**
 * AxAIGoogleGeminiConfig: Configuration options for Google Gemini API
 */
type AxAIGoogleGeminiConfig = AxModelConfig & {
    model: AxAIGoogleGeminiModel;
    embedModel?: AxAIGoogleGeminiEmbedModel;
    safetySettings?: AxAIGoogleGeminiSafetySettings;
    embedType?: AxAIGoogleGeminiEmbedTypes;
    dimensions?: number;
    autoTruncate?: boolean;
    thinking?: AxAIGoogleGeminiThinkingConfig;
    thinkingTokenBudgetLevels?: AxAIGoogleGeminiThinkingTokenBudgetLevels;
    /** Maps thinkingTokenBudget levels to Gemini 3+ thinkingLevel values */
    thinkingLevelMapping?: AxAIGoogleGeminiThinkingLevelMapping;
    urlContext?: string;
    responseFormat?: 'json_object';
    /** Inference service tier used by the Gemini API. */
    serviceTier?: AxServiceTier;
};
/**
 * AxAIGoogleGeminiEmbedRequest: Structure for making an embedding request to the Google Gemini API.
 */
type AxAIGoogleGeminiBatchEmbedRequest = {
    requests: {
        model: string;
        content: {
            parts: {
                text: string;
            }[];
        };
    }[];
};
/**
 * AxAIGoogleGeminiEmbedResponse: Structure for handling responses from the Google Gemini API embedding requests.
 */
type AxAIGoogleGeminiBatchEmbedResponse = {
    embeddings: {
        values: number[];
    }[];
};
/**
 * AxAIGoogleVertexBatchEmbedRequest: Structure for making an embedding request to the Google Vertex API.
 */
type AxAIGoogleVertexBatchEmbedRequest = {
    instances: {
        content: string;
        task_type?: AxAIGoogleGeminiEmbedTypes;
    }[];
    parameters: {
        autoTruncate?: boolean;
        outputDimensionality?: number;
    };
};
/**
 * AxAIGoogleVertexBatchEmbedResponse: Structure for handling responses from the Google Vertex API embedding requests.
 */
type AxAIGoogleVertexBatchEmbedResponse = {
    predictions: {
        embeddings: {
            values: number[];
        };
    }[];
};
/**
 * AxAIGoogleVertexEmbedContentRequest: Structure for a single-text Vertex `:embedContent` request.
 */
type AxAIGoogleVertexEmbedContentRequest = {
    content: {
        parts: {
            text: string;
        }[];
    };
    autoTruncate?: boolean;
    outputDimensionality?: number;
};
/**
 * AxAIGoogleVertexEmbedContentResponse: Structure for handling a Vertex `:embedContent` response.
 */
type AxAIGoogleVertexEmbedContentResponse = {
    embedding: {
        values: number[];
    };
    usageMetadata?: {
        promptTokenCount?: number;
        totalTokenCount?: number;
    };
};
/**
 * Request to create a context cache in Vertex AI / Gemini API.
 */
type AxAIGoogleGeminiCacheCreateRequest = {
    /** The model to associate with the cache */
    model: string;
    /** Display name for the cache (optional) */
    displayName?: string;
    /** System instruction to cache */
    systemInstruction?: AxAIGoogleGeminiContent;
    /** Content parts to cache */
    contents?: AxAIGoogleGeminiContent[];
    /** Tools to cache */
    tools?: AxAIGoogleGeminiTool[];
    /** Tool configuration to cache */
    toolConfig?: AxAIGoogleGeminiToolConfig;
    /** TTL duration string (e.g., "3600s" for 1 hour) */
    ttl?: string;
    /** Absolute expiration time (ISO 8601) */
    expireTime?: string;
};
/**
 * Response from creating/getting a context cache.
 */
type AxAIGoogleGeminiCacheResponse = {
    /** Resource name of the cached content (e.g., "projects/.../locations/.../cachedContents/...") */
    name: string;
    /** Display name */
    displayName?: string;
    /** Model associated with the cache */
    model: string;
    /** When the cache was created (ISO 8601) */
    createTime: string;
    /** When the cache was last updated (ISO 8601) */
    updateTime: string;
    /** When the cache expires (ISO 8601) */
    expireTime: string;
    /** Token count of cached content */
    usageMetadata?: {
        totalTokenCount: number;
    };
};
/**
 * Request to update a context cache (e.g., extend TTL).
 */
type AxAIGoogleGeminiCacheUpdateRequest = {
    /** TTL duration string (e.g., "3600s" for 1 hour) */
    ttl?: string;
    /** Absolute expiration time (ISO 8601) */
    expireTime?: string;
};

type GeminiLiveRequest = {
    model: AxAIGoogleGeminiModel;
    request: AxAIGoogleGeminiChatRequest;
    apiKey: string;
    audio: AxChatAudioConfig;
};
declare const axAIGoogleGeminiLiveAudioDefaultConfig: () => AxAIGoogleGeminiConfig;
declare const axIsGeminiLiveAudioModel: (model: string) => boolean;
declare const axResolveGeminiLiveAudioConfig: (providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => AxChatAudioConfig | undefined;
declare const axShouldUseGeminiLiveAudio: (model: string, providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => boolean;
declare const axValidateGeminiLiveAudioInput: (part: Readonly<AxAIGoogleGeminiContentPart>) => void;
declare const axMapGeminiLiveAudioPart: (part: Readonly<AxAIGoogleGeminiContentPart>) => AxChatAudioOutput | undefined;
declare const axCreateGeminiLiveAudioApi: (liveRequest: GeminiLiveRequest) => AxAPI;

/**
 * AxAIGoogleGemini: Default Model options for text generation
 */
declare const axAIGoogleGeminiDefaultConfig: () => AxAIGoogleGeminiConfig;
declare const axAIGoogleGeminiDefaultCreativeConfig: () => AxAIGoogleGeminiConfig;
interface AxAIGoogleGeminiOptionsTools {
    codeExecution?: boolean;
    googleSearchRetrieval?: {
        mode?: 'MODE_DYNAMIC';
        dynamicThreshold?: number;
    };
    googleSearch?: boolean;
    urlContext?: boolean;
    googleMaps?: AxAIGoogleGeminiToolGoogleMaps;
    retrievalConfig?: AxAIGoogleGeminiRetrievalConfig;
}
interface AxAIGoogleGeminiArgs<TModelKey> {
    name: 'google-gemini';
    apiKey?: string | (() => Promise<string>);
    credentialProvider?: AxAICredentialProvider;
    projectId?: string;
    region?: string;
    endpointId?: string;
    config?: Readonly<Partial<AxAIGoogleGeminiConfig>>;
    options?: Readonly<AxAIServiceOptions & AxAIGoogleGeminiOptionsTools>;
    models?: AxAIInputModelList<AxAIGoogleGeminiModel, AxAIGoogleGeminiEmbedModel, TModelKey>;
    modelInfo?: AxModelInfo[];
}
type ExtractModelKeys<T> = T extends readonly {
    key: infer K;
}[] ? K : never;
declare class AxAIGoogleGemini<TModelKey = string> extends AxBaseAI<AxAIGoogleGeminiModel, AxAIGoogleGeminiEmbedModel, AxAIGoogleGeminiChatRequest, AxAIGoogleGeminiBatchEmbedRequest | AxAIGoogleVertexBatchEmbedRequest | AxAIGoogleVertexEmbedContentRequest, AxAIGoogleGeminiChatResponse, AxAIGoogleGeminiChatResponseDelta, AxAIGoogleGeminiBatchEmbedResponse | AxAIGoogleVertexBatchEmbedResponse | AxAIGoogleVertexEmbedContentResponse, TModelKey> {
    static create<const T extends AxAIGoogleGeminiArgs<any>>(options: T): T extends {
        models: infer M;
    } ? AxAIGoogleGemini<ExtractModelKeys<M>> : AxAIGoogleGemini<string>;
    constructor({ apiKey, credentialProvider, projectId, region, endpointId, config, options, models, modelInfo, }: Readonly<Omit<AxAIGoogleGeminiArgs<TModelKey>, 'name'>>);
}

declare enum AxAIOpenAIModel {
    GPT4 = "gpt-4",
    GPT41 = "gpt-4.1",
    GPT41Mini = "gpt-4.1-mini",
    GPT41Nano = "gpt-4.1-nano",
    GPT4O = "gpt-4o",
    GPT4OMini = "gpt-4o-mini",
    GPTAudio = "gpt-audio",
    GPTAudioMini = "gpt-audio-mini",
    GPTAudio15 = "gpt-audio-1.5",
    GPTRealtime15 = "gpt-realtime-1.5",
    GPTRealtime2 = "gpt-realtime-2",
    GPTRealtime21 = "gpt-realtime-2.1",
    GPTRealtime21Mini = "gpt-realtime-2.1-mini",
    GPTRealtimeWhisper = "gpt-realtime-whisper",
    GPTRealtimeTranslate = "gpt-realtime-translate",
    GPTTranscribe = "gpt-transcribe",
    GPT4ChatGPT4O = "chatgpt-4o-latest",
    GPT4Turbo = "gpt-4-turbo",
    GPT35Turbo = "gpt-3.5-turbo",
    GPT35TurboInstruct = "gpt-3.5-turbo-instruct",
    GPT35TextDavinci002 = "text-davinci-002",
    GPT3TextBabbage002 = "text-babbage-002",
    GPT3TextAda001 = "text-ada-001",
    GPT5 = "gpt-5",
    GPT5Nano = "gpt-5-nano",
    GPT5Mini = "gpt-5-mini",
    GPT5Chat = "gpt-5-chat",
    GPT5ChatLatest = "gpt-5-chat-latest",
    GPT5Codex = "gpt-5-codex",
    GPT5Pro = "gpt-5-pro",
    GPT51 = "gpt-5.1",
    GPT51ChatLatest = "gpt-5.1-chat-latest",
    GPT51Codex = "gpt-5.1-codex",
    GPT51CodexMini = "gpt-5.1-codex-mini",
    GPT51CodexMax = "gpt-5.1-codex-max",
    GPT52 = "gpt-5.2",
    GPT52ChatLatest = "gpt-5.2-chat-latest",
    GPT52Codex = "gpt-5.2-codex",
    GPT52Pro = "gpt-5.2-pro",
    GPT54 = "gpt-5.4",
    GPT54Mini = "gpt-5.4-mini",
    GPT54Nano = "gpt-5.4-nano",
    GPT55 = "gpt-5.5",
    GPT55Pro = "gpt-5.5-pro",
    GPT56 = "gpt-5.6",
    GPT56Sol = "gpt-5.6-sol",
    GPT56Terra = "gpt-5.6-terra",
    GPT56Luna = "gpt-5.6-luna",
    GPT6Astra = "gpt-6-astra",
    GPT6Sol = "gpt-6-sol",
    GPT6Luna = "gpt-6-luna",
    O1 = "o1",
    O1Mini = "o1-mini",
    O3 = "o3",
    O3Mini = "o3-mini",
    O4Mini = "o4-mini"
}
declare enum AxAIOpenAIEmbedModel {
    TextEmbeddingAda002 = "text-embedding-ada-002",
    TextEmbedding3Small = "text-embedding-3-small",
    TextEmbedding3Large = "text-embedding-3-large"
}
type AxAIOpenAIUrlCitation = {
    url: string;
    title?: string;
    description?: string;
};
type AxAIOpenAIAnnotation = {
    type: 'url_citation';
    url_citation: AxAIOpenAIUrlCitation;
};
type AxAIOpenAIConfig<TModel, TEmbedModel> = Omit<AxModelConfig, 'topK'> & {
    model: TModel;
    embedModel?: TEmbedModel;
    user?: string;
    responseFormat?: 'json_object';
    bestOf?: number;
    logitBias?: Map<string, number>;
    suffix?: string | null;
    stop?: string[];
    logprobs?: number;
    echo?: boolean;
    dimensions?: number;
    reasoningEffort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
    store?: boolean;
    /** Portable values plus the legacy OpenAI `default` alias. */
    serviceTier?: AxServiceTier | 'default';
    webSearchOptions?: {
        searchContextSize?: 'low' | 'medium' | 'high';
        userLocation?: {
            approximate: {
                type: 'approximate';
                city?: string;
                country?: string;
                region?: string;
                timezone?: string;
            };
        } | null;
    };
};
type AxAIOpenAILogprob = {
    tokens: string[];
    token_logprobs: number[];
    top_logprobs: Map<string, number>;
    text_offset: number[];
};
type AxAIOpenAIUsage = {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
    service_tier?: string;
    prompt_tokens_details?: {
        cached_tokens?: number;
        /**
         * Prompt tokens written to the cache on this request, billed at a premium
         * over uncached input. Sits alongside `cached_tokens`, and `prompt_tokens`
         * includes both — see usage.ts, which subtracts them back out.
         */
        cache_write_tokens?: number;
    };
    completion_tokens_details?: {
        reasoning_tokens?: number;
    };
};
/**
 * Marks a cache breakpoint on the content block that carries it. The marker is
 * part of the block, so moving it between requests changes the serialized
 * prefix and voids the entry it wrote — see caching.ts.
 */
type AxAIOpenAIPromptCacheBreakpoint = {
    mode: 'explicit';
};
/**
 * A content block in a Chat Completions message. Chat Completions accepts a
 * `prompt_cache_breakpoint` on `text`, `image_url`, `input_audio`, `file` and
 * `refusal` blocks; Ax never emits `refusal` on a request, so it is absent here.
 */
type AxAIOpenAIChatContentPart = ({
    type: string;
    text: string;
} | {
    type: 'image_url';
    image_url: {
        url: string;
        detail?: 'high' | 'low' | 'auto';
        details?: 'high' | 'low' | 'auto';
    };
} | {
    type: 'input_audio';
    input_audio: {
        data: string;
        format: 'wav' | 'mp3' | 'pcm16';
        mimeType?: string;
        sampleRate?: number;
        channels?: number;
    };
} | {
    type: 'file';
    file: {
        file_data?: string;
        file_url?: string;
        filename?: string;
    };
} | {
    type: 'video_url';
    video_url: {
        url: string;
    };
}) & {
    prompt_cache_breakpoint?: AxAIOpenAIPromptCacheBreakpoint;
};
interface AxAIOpenAIResponseDelta<T> {
    id: string;
    object: string;
    created: number;
    model: string;
    choices: {
        index: number;
        delta: T;
        finish_reason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null;
    }[];
    usage?: AxAIOpenAIUsage;
    service_tier?: string;
    service_tier_used?: string;
    system_fingerprint: string;
}
type AxAIOpenAIChatRequest<TModel> = {
    model: TModel;
    service_tier?: string;
    reasoning_effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
    /**
     * Stable per-conversation key that routes the request to the shard its cache
     * lives on. GPT-5.6+ requires it for reliable matching; earlier families
     * predate it and reject it with a 400.
     */
    prompt_cache_key?: string;
    /**
     * `implicit` (the default) also places a breakpoint at the newest user or tool
     * message; `explicit` uses only caller-provided breakpoints.
     */
    prompt_cache_options?: {
        mode?: 'implicit' | 'explicit';
        ttl?: '30m';
    };
    store?: boolean;
    modalities?: readonly ('text' | 'audio')[];
    audio?: {
        format: 'wav' | 'mp3' | 'flac' | 'opus' | 'aac' | 'pcm16';
        voice: string | {
            id: string;
        };
    };
    messages: ({
        role: 'system';
        content: string | AxAIOpenAIChatContentPart[];
    } | {
        role: 'user';
        content: string | AxAIOpenAIChatContentPart[];
        name?: string;
    } | {
        role: 'assistant';
        content?: string | {
            type: string;
            text: string;
        } | AxAIOpenAIChatContentPart[];
        name?: string;
        reasoning_content?: string;
        audio?: {
            id: string;
        };
    } | {
        role: 'assistant';
        content?: string | {
            type: string;
            text: string;
        } | AxAIOpenAIChatContentPart[];
        name?: string;
        reasoning_content?: string;
        tool_calls: {
            type: 'function';
            function: {
                name: string;
                arguments?: string;
            };
        }[];
    } | {
        role: 'tool';
        content: string | AxAIOpenAIChatContentPart[];
        tool_call_id: string;
    })[];
    tools?: {
        type: 'function';
        function: {
            name: string;
            description: string;
            parameters?: object;
        };
    }[];
    tool_choice?: 'none' | 'auto' | 'required' | {
        type: 'function';
        function: {
            name: string;
        };
    };
    response_format?: {
        type: string;
    } | {
        type: 'json_schema';
        json_schema: any;
    };
    max_completion_tokens?: number;
    temperature?: number;
    top_p?: number;
    n?: number;
    stream?: boolean;
    stop?: readonly string[];
    presence_penalty?: number;
    frequency_penalty?: number;
    logit_bias?: Map<string, number>;
    user?: string;
    organization?: string;
    web_search_options?: {
        search_context_size?: 'low' | 'medium' | 'high';
        user_location?: {
            approximate: {
                type: 'approximate';
                city?: string;
                country?: string;
                region?: string;
                timezone?: string;
            };
        } | null;
    };
};
type AxAIOpenAIChatResponse = {
    id: string;
    object: 'chat.completion';
    created: number;
    model: string;
    service_tier?: string;
    service_tier_used?: string;
    choices: {
        index: number;
        message: {
            role: string;
            content: string | null;
            refusal: string | null;
            audio?: {
                id: string;
                data?: string;
                expires_at?: number;
                transcript?: string;
            } | null;
            reasoning_content?: string;
            annotations?: AxAIOpenAIAnnotation[];
            tool_calls?: {
                id: string;
                type: 'function';
                function: {
                    name: string;
                    arguments: string;
                };
            }[];
        };
        finish_reason: 'stop' | 'length' | 'content_filter' | 'tool_calls';
    }[];
    usage?: AxAIOpenAIUsage;
    error?: {
        message: string;
        type: string;
        param: string;
        code: number;
    };
    system_fingerprint: string;
};
type AxAIOpenAIChatResponseDelta = AxAIOpenAIResponseDelta<{
    content: string | null;
    refusal?: string | null;
    audio?: {
        id?: string;
        data?: string;
        delta?: string;
        expires_at?: number;
        transcript?: string;
    } | null;
    reasoning_content?: string;
    role?: string;
    annotations?: AxAIOpenAIAnnotation[];
    tool_calls?: (NonNullable<AxAIOpenAIChatResponse['choices'][0]['message']['tool_calls']>[0] & {
        index: number;
    })[];
}>;
type AxAIOpenAIEmbedRequest<TEmbedModel> = {
    input: readonly string[];
    model: TEmbedModel;
    dimensions?: number;
    user?: string;
};
type AxAIOpenAIEmbedResponse = {
    model: string;
    data: {
        embedding: readonly number[];
        index: number;
    }[];
    usage: AxAIOpenAIUsage;
};

type AxOpenAIInputAudioFormat = 'wav' | 'mp3';
type AxOpenAIRealtimeInputAudioFormat = AxOpenAIInputAudioFormat | 'pcm16';
type AxOpenAIAudioPart = {
    type: 'audio';
    data: string;
    format?: AxAudioFormat;
    mimeType?: string;
    sampleRate?: number;
    channels?: number;
};
declare const axAIOpenAIAudioDefaultConfig: () => AxAIOpenAIConfig<AxAIOpenAIModel, AxAIOpenAIEmbedModel>;
declare const axIsOpenAIChatAudioModel: (model: string) => boolean;
declare const axResolveOpenAIChatAudioConfig: (providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => AxChatAudioConfig | undefined;
declare const axMapOpenAIInputAudioPart: (part: Readonly<AxOpenAIAudioPart>, options?: Readonly<{
    allowPcm16?: boolean;
}>) => {
    type: "input_audio";
    input_audio: {
        data: string;
        format: AxOpenAIRealtimeInputAudioFormat;
        mimeType?: string;
        sampleRate?: number;
        channels?: number;
    };
};
declare const axApplyOpenAIChatAudioRequest: <TModel>(reqValue: AxAIOpenAIChatRequest<TModel>, req: Readonly<AxInternalChatRequest<TModel>>, providerAudio?: Readonly<AxChatAudioConfig>) => AxAIOpenAIChatRequest<TModel>;
declare const axMapOpenAIChatAudioResponse: (audio: NonNullable<AxAIOpenAIChatResponse["choices"][number]["message"]["audio"]> | null | undefined) => AxChatAudioOutput | undefined;
declare const axMapOpenAIChatAudioDelta: (audio: NonNullable<AxAIOpenAIChatResponseDelta["choices"][number]["delta"]["audio"]> | null | undefined) => AxChatAudioOutput | undefined;

type OpenAIRealtimeRequest<TModel> = {
    model: TModel;
    request: AxAIOpenAIChatRequest<TModel>;
    apiKey: string;
    audio: AxChatAudioConfig;
    webSocket?: any;
    debug?: boolean;
    apiName?: string;
    providerName?: string;
    wsURL?: (model: string) => string;
    createSessionUpdate?: (request: Readonly<OpenAIRealtimeRequest<TModel>>) => object;
};
declare const axAIOpenAIRealtimeDefaultConfig: () => AxAIOpenAIConfig<AxAIOpenAIModel, AxAIOpenAIEmbedModel>;
declare const axAIOpenAIRealtimeTranscriptionDefaultConfig: () => AxAIOpenAIConfig<AxAIOpenAIModel, AxAIOpenAIEmbedModel>;
declare const axIsOpenAIRealtimeModel: (model: string) => boolean;
declare const axIsOpenAIRealtimeTranscriptionModel: (model: string) => boolean;
declare const axResolveOpenAIRealtimeAudioConfig: (providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => AxChatAudioConfig;
declare const axShouldUseOpenAIRealtime: (model: string, providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => boolean;
declare const axCreateOpenAIRealtimeApi: <TModel>(realtimeRequest: OpenAIRealtimeRequest<TModel>) => AxAPI;

declare const axAIOpenAIDefaultConfig: () => AxAIOpenAIConfig<AxAIOpenAIModel, AxAIOpenAIEmbedModel>;
declare const axAIOpenAIBestConfig: () => AxAIOpenAIConfig<AxAIOpenAIModel, AxAIOpenAIEmbedModel>;
declare const axAIOpenAICreativeConfig: () => AxAIOpenAIConfig<AxAIOpenAIModel, AxAIOpenAIEmbedModel>;
declare const axAIOpenAIFastConfig: () => AxAIOpenAIConfig<AxAIOpenAIModel, AxAIOpenAIEmbedModel>;
interface AxAIOpenAIArgs<TName = 'openai', TModel = AxAIOpenAIModel, TEmbedModel = AxAIOpenAIEmbedModel, TModelKey = string, TChatReq extends AxAIOpenAIChatRequest<TModel> = AxAIOpenAIChatRequest<TModel>> extends Omit<AxAIOpenAIBaseArgs<TModel, TEmbedModel, TModelKey, TChatReq>, 'config' | 'supportFor' | 'modelInfo'> {
    name: TName;
    modelInfo?: AxModelInfo[];
    config?: Partial<AxAIOpenAIBaseArgs<TModel, TEmbedModel, TModelKey, TChatReq>['config']>;
}
type ChatReqUpdater<TModel, TChatReq extends AxAIOpenAIChatRequest<TModel>> = (req: Readonly<TChatReq>, config: Readonly<AxAIServiceOptions>) => TChatReq;
type ChatRespProcessor = (resp: AxChatResponse) => AxChatResponse;
type ChatStreamRespProcessor = (resp: AxChatResponse, state: object) => AxChatResponse;
type RealtimeAdapter<TModel> = {
    apiName: string;
    shouldUse: (model: string, providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => boolean;
    resolveAudioConfig: (providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => AxChatAudioConfig;
    createApi: (request: OpenAIRealtimeRequest<TModel>) => AxAPI;
};
type AxOpenAIBatchAudioConfig = {
    transcriptionModel?: string;
    speechModel?: string;
    speechVoice?: string;
    speechFormat?: AxAudioFormat;
};
type AxOpenAIReasoningContentMode = 'none' | 'deepseek' | {
    assistantField?: string;
    responseFields: readonly string[];
    assistantDetailsField?: string;
    responseDetailsFields?: readonly string[];
};
type AxAIOpenAIBaseInternalArgs<TModel, TEmbedModel, TModelKey, TChatReq extends AxAIOpenAIChatRequest<TModel>> = Omit<AxAIOpenAIBaseArgs<TModel, TEmbedModel, TModelKey, TChatReq>, 'name'> & {
    /** @internal OpenAI-compatible reasoning trace wire format. */
    reasoningContentMode?: AxOpenAIReasoningContentMode;
};
interface AxAIOpenAIBaseArgs<TModel, TEmbedModel, TModelKey, TChatReq extends AxAIOpenAIChatRequest<TModel>> {
    apiKey?: string;
    credentialProvider?: AxAICredentialProvider;
    credentialProfile?: string;
    apiURL?: string;
    config: Readonly<AxAIOpenAIConfig<TModel, TEmbedModel>>;
    options?: Readonly<AxAIServiceOptions & {
        streamingUsage?: boolean;
    }>;
    modelInfo: Readonly<AxModelInfo[]>;
    models?: AxAIInputModelList<TModel, TEmbedModel, TModelKey>;
    chatReqUpdater?: ChatReqUpdater<TModel, TChatReq>;
    chatRespProcessor?: ChatRespProcessor;
    chatStreamRespProcessor?: ChatStreamRespProcessor;
    realtime?: RealtimeAdapter<TModel>;
    /**
     * Opt in to OpenAI prompt caching on GPT-5.6+ models. Off by default because
     * this request builder is shared: Azure OpenAI is typed on the same model
     * enum, so a `gpt-5.6-*` deployment would otherwise pick up parameters its API
     * version may reject. Official OpenAI and explicitly compatible named
     * profiles opt in deliberately.
     */
    promptCaching?: boolean;
    /** Apply the compatible prompt-cache wire format without OpenAI model-family gating. */
    promptCachingAllModels?: boolean;
    /** Whether the compatible API accepts explicit per-content cache breakpoints. */
    promptCacheBreakpoints?: boolean;
    supportFor: AxAIFeatures | ((model: TModel) => AxAIFeatures);
}
declare class AxAIOpenAIBase<TModel, TEmbedModel, TModelKey, TChatReq extends AxAIOpenAIChatRequest<TModel> = AxAIOpenAIChatRequest<TModel>> extends AxBaseAI<TModel, TEmbedModel, AxAIOpenAIChatRequest<TModel>, AxAIOpenAIEmbedRequest<TEmbedModel>, AxAIOpenAIChatResponse, AxAIOpenAIChatResponseDelta, AxAIOpenAIEmbedResponse, TModelKey> {
    protected batchAudioConfig: AxOpenAIBatchAudioConfig;
    protected readonly openAICompatibleApiKey: string;
    protected readonly openAICompatibleApiURL: string;
    constructor({ apiKey, credentialProvider, credentialProfile, config, options, apiURL, modelInfo, models, chatReqUpdater, chatRespProcessor, chatStreamRespProcessor, realtime, promptCaching, promptCachingAllModels, promptCacheBreakpoints, reasoningContentMode, supportFor, }: Readonly<AxAIOpenAIBaseInternalArgs<TModel, TEmbedModel, TModelKey, TChatReq>>);
    protected setBatchAudioConfig(config: Readonly<AxOpenAIBatchAudioConfig>): void;
    transcribe(req: Readonly<AxTranscriptionRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<TModel | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
}
declare class AxAIOpenAI<TModelKey = string> extends AxAIOpenAIBase<AxAIOpenAIModel, AxAIOpenAIEmbedModel, TModelKey> {
    constructor({ apiKey, credentialProvider, apiURL, config, options, models, modelInfo, }: Readonly<Omit<AxAIOpenAIArgs<'openai', AxAIOpenAIModel, AxAIOpenAIEmbedModel, TModelKey>, 'name'>>);
}

declare enum AxAIOpenAIResponsesModel {
    GPT4 = "gpt-4",
    GPT41 = "gpt-4.1",
    GPT41Mini = "gpt-4.1-mini",
    GPT41Nano = "gpt-4.1-nano",
    GPT4O = "gpt-4o",
    GPT4OMini = "gpt-4o-mini",
    GPT4ChatGPT4O = "chatgpt-4o-latest",
    GPT4Turbo = "gpt-4-turbo",
    GPT35Turbo = "gpt-3.5-turbo",
    GPT35TurboInstruct = "gpt-3.5-turbo-instruct",
    GPT35TextDavinci002 = "text-davinci-002",
    GPT3TextBabbage002 = "text-babbage-002",
    GPT3TextAda001 = "text-ada-001",
    GPT5 = "gpt-5",
    GPT5Nano = "gpt-5-nano",
    GPT5Mini = "gpt-5-mini",
    GPT5Chat = "gpt-5-chat",
    GPT5ChatLatest = "gpt-5-chat-latest",
    GPT5Codex = "gpt-5-codex",
    GPT5Pro = "gpt-5-pro",
    GPT51 = "gpt-5.1",
    GPT51ChatLatest = "gpt-5.1-chat-latest",
    GPT51Codex = "gpt-5.1-codex",
    GPT51CodexMini = "gpt-5.1-codex-mini",
    GPT51CodexMax = "gpt-5.1-codex-max",
    GPT52 = "gpt-5.2",
    GPT52ChatLatest = "gpt-5.2-chat-latest",
    GPT52Codex = "gpt-5.2-codex",
    GPT52Pro = "gpt-5.2-pro",
    GPT54 = "gpt-5.4",
    GPT54Mini = "gpt-5.4-mini",
    GPT54Nano = "gpt-5.4-nano",
    GPT55 = "gpt-5.5",
    GPT55Pro = "gpt-5.5-pro",
    GPT56 = "gpt-5.6",
    GPT56Sol = "gpt-5.6-sol",
    GPT56Terra = "gpt-5.6-terra",
    GPT56Luna = "gpt-5.6-luna",
    GPT6Astra = "gpt-6-astra",
    GPT6Sol = "gpt-6-sol",
    GPT6Luna = "gpt-6-luna",
    O1Pro = "o1-pro",
    O1 = "o1",
    O1Mini = "o1-mini",
    O3Pro = "o3-pro",
    O3 = "o3",
    O3Mini = "o3-mini",
    O4Mini = "o4-mini"
}
interface AxAIOpenAIResponsesInputTextContentPart {
    readonly type: 'input_text';
    readonly prompt_cache_breakpoint?: {
        readonly mode: 'explicit';
    };
    text: string;
    readonly cache_control?: {
        readonly type: 'ephemeral';
    };
}
interface AxAIOpenAIResponsesInputImageUrlContentPart {
    readonly type: 'input_image';
    readonly image_url: string;
    readonly detail?: 'low' | 'high' | 'auto';
    readonly cache_control?: {
        readonly type: 'ephemeral';
    };
}
interface AxAIOpenAIResponsesInputAudioContentPart {
    readonly type: 'input_audio';
    readonly input_audio: {
        readonly data: string;
        readonly format?: string;
    };
    readonly cache_control?: {
        readonly type: 'ephemeral';
    };
}
interface AxAIOpenAIResponsesInputFileContentPart {
    readonly type: 'input_file';
    readonly file_data?: string;
    readonly file_url?: string;
    readonly filename?: string;
    readonly cache_control?: {
        readonly type: 'ephemeral';
    };
}
interface AxAIOpenAIResponsesInputVideoContentPart {
    readonly type: 'input_video';
    readonly video_url: string;
    readonly cache_control?: {
        readonly type: 'ephemeral';
    };
}
type AxAIOpenAIResponsesInputContentPart = AxAIOpenAIResponsesInputTextContentPart | AxAIOpenAIResponsesInputImageUrlContentPart | AxAIOpenAIResponsesInputAudioContentPart | AxAIOpenAIResponsesInputFileContentPart | AxAIOpenAIResponsesInputVideoContentPart | AxAIOpenAIResponsesOutputTextContentPart;
interface AxAIOpenAIResponsesInputMessageItem {
    readonly type: 'message';
    readonly role: 'system' | 'user' | 'assistant' | 'developer';
    readonly content: string | ReadonlyArray<AxAIOpenAIResponsesInputContentPart>;
    readonly name?: string;
    readonly phase?: 'commentary' | 'final_answer';
}
interface AxAIOpenAIResponsesInputFunctionCallItem {
    readonly type: 'function_call';
    readonly async?: boolean;
    readonly id?: string;
    readonly call_id: string;
    readonly name: string;
    readonly arguments: string;
}
interface AxAIOpenAIResponsesInputFunctionCallOutputItem {
    readonly type: 'function_call_output';
    readonly id?: string;
    readonly call_id: string;
    readonly output: string | ReadonlyArray<AxAIOpenAIResponsesInputContentPart>;
}
interface AxAIOpenAIResponsesInputReasoningItem {
    readonly type: 'reasoning';
    readonly id?: string;
    readonly content?: string | ReadonlyArray<AxAIOpenAIResponsesInputTextContentPart>;
    readonly summary?: ReadonlyArray<{
        readonly type: 'summary_text';
        readonly text: string;
    }>;
    readonly encrypted_content?: string;
}
interface AxAIOpenAIResponsesInputImageGenerationCallItem {
    readonly type: 'image_generation_call';
    readonly id: string;
    readonly status?: 'completed';
    readonly result?: string | null;
}
type AxAIOpenAIResponsesInputItem = string | AxAIOpenAIResponsesInputMessageItem | AxAIOpenAIResponsesInputFunctionCallItem | AxAIOpenAIResponsesInputFunctionCallOutputItem | AxAIOpenAIResponsesOutputItem | AxAIOpenAIResponsesInputReasoningItem | AxAIOpenAIResponsesReasoningItem | AxAIOpenAIResponsesConfigurationUpdate | AxAIOpenAIResponsesCustomToolCall | AxAIOpenAIResponsesCustomToolOutput | AxAIOpenAIResponsesInputImageGenerationCallItem;
interface AxAIOpenAIResponsesDefineFunctionTool {
    readonly type: 'function';
    readonly async?: boolean;
    readonly name: string;
    readonly description?: string;
    readonly parameters: object;
    readonly strict?: boolean;
}
interface AxAIOpenAIResponsesDefineImageGenerationTool {
    readonly type: 'image_generation';
    readonly size?: `${number}x${number}` | 'auto';
    readonly output_format?: 'png' | 'jpeg' | 'webp';
    readonly enable_image_search?: boolean;
    readonly enable_web_search?: boolean;
    readonly enable_shell?: boolean;
    readonly reasoning_strength?: 'low' | 'high';
}
type AxAIOpenAIResponsesToolDefinition = AxAIOpenAIResponsesDefineFunctionTool | AxAIOpenAIResponsesDefineCustomTool | AxAIOpenAIResponsesDefineImageGenerationTool;
type AxAIOpenAIResponsesToolChoice = 'none' | 'auto' | 'required' | {
    readonly type: 'function' | 'custom';
    readonly name: string;
} | {
    readonly type: 'file_search';
};
interface AxAIOpenAIResponsesRequest<TModel = AxAIOpenAIResponsesModel> {
    readonly input: string | ReadonlyArray<AxAIOpenAIResponsesInputItem>;
    readonly model: TModel;
    readonly prompt_cache_options?: {
        readonly ttl?: '30m';
        readonly mode?: 'implicit' | 'explicit';
    };
    readonly background?: boolean | null;
    readonly include?: ReadonlyArray<'file_search_call.results' | 'message.input_image.image_url' | 'computer_call_output.output.image_url' | 'reasoning.encrypted_content' | 'code_interpreter_call.outputs' | 'web_search_call.action.return_token_budget'> | null;
    readonly instructions?: string | null;
    readonly max_output_tokens?: number | null;
    readonly metadata?: Readonly<Record<string, string>> | null;
    readonly parallel_tool_calls?: boolean | null;
    readonly previous_response_id?: string | null;
    readonly reasoning?: {
        readonly effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null;
        readonly summary?: 'auto' | 'concise' | 'detailed' | null;
    } | null;
    readonly service_tier?: string | null;
    readonly store?: boolean | null;
    readonly stream?: boolean | null;
    readonly temperature?: number | null;
    readonly text?: {
        readonly format?: {
            readonly type: 'text';
        } | {
            readonly type: 'json_object';
        } | {
            readonly type: 'json_schema';
            readonly name?: string;
            readonly schema?: object;
            readonly strict?: boolean;
            readonly description?: string;
            readonly json_schema?: object;
        } | null;
    } | null;
    readonly tool_choice?: AxAIOpenAIResponsesToolChoice | null;
    readonly tools?: ReadonlyArray<AxAIOpenAIResponsesToolDefinition> | null;
    readonly top_p?: number | null;
    readonly truncation?: 'auto' | 'disabled' | null;
    readonly user?: string | null;
    readonly seed?: number | null;
    readonly prompt_cache_key?: string;
    readonly prompt_cache_retention?: 'in_memory' | '24h';
}
interface AxAIOpenAIResponsesOutputMessageItem {
    type: 'message';
    id: string;
    role: 'assistant';
    content: ReadonlyArray<AxAIOpenAIResponsesOutputTextContentPart | AxAIOpenAIResponsesOutputRefusalContentPart>;
    status: 'in_progress' | 'completed' | 'incomplete';
    phase?: 'commentary' | 'final_answer';
}
interface AxAIOpenAIResponsesFunctionCallItem {
    async?: boolean;
    type: 'function_call';
    id: string;
    call_id: string;
    name: string;
    arguments: string;
    status?: 'in_progress' | 'completed' | 'incomplete' | 'searching' | 'failed';
}
interface AxAIOpenAIResponsesReasoningItem {
    readonly type: 'reasoning';
    readonly id: string;
    readonly content?: string | ReadonlyArray<AxAIOpenAIResponsesInputTextContentPart>;
    readonly summary?: ReadonlyArray<{
        type: 'summary_text';
        text: string;
    }>;
    readonly encrypted_content?: string | null;
    readonly status?: 'in_progress' | 'completed' | 'incomplete';
}
interface AxAIOpenAIResponsesOutputTextContentPart {
    readonly type: 'output_text';
    readonly text: string;
    readonly annotations?: ReadonlyArray<unknown>;
}
interface AxAIOpenAIResponsesOutputRefusalContentPart {
    readonly type: 'refusal';
    readonly refusal: string;
}
interface AxAIOpenAIResponsesReasoningSummaryPart {
    readonly type: 'summary_text';
    readonly text: string;
}
type AxAIOpenAIResponsesOutputItem = AxAIOpenAIResponsesOutputMessageItem | AxAIOpenAIResponsesFunctionCallItem | AxAIOpenAIResponsesReasoningItem | AxAIOpenAIResponsesFileSearchToolCall | AxAIOpenAIResponsesWebSearchToolCall | AxAIOpenAIResponsesComputerToolCall | AxAIOpenAIResponsesCodeInterpreterToolCall | AxAIOpenAIResponsesImageGenerationToolCall | AxAIOpenAIResponsesLocalShellToolCall | AxAIOpenAIResponsesMCPToolCall | AxAIOpenAIResponsesCustomToolCall;
interface AxAIOpenAIResponsesResponse {
    readonly id: string;
    readonly object: string;
    readonly status?: 'queued' | 'in_progress' | 'completed' | 'incomplete' | 'failed' | 'cancelled';
    readonly incomplete_details?: {
        readonly reason: string;
    };
    readonly error?: {
        readonly code: string;
        readonly message: string;
    } | null;
    readonly created_at?: number;
    readonly created?: number;
    readonly model: string;
    readonly service_tier?: string;
    readonly service_tier_used?: string;
    readonly output: ReadonlyArray<AxAIOpenAIResponsesOutputItem>;
    readonly usage?: {
        readonly prompt_tokens?: number;
        readonly input_tokens?: number;
        readonly completion_tokens?: number;
        readonly output_tokens?: number;
        readonly total_tokens?: number;
        readonly service_tier?: string;
        readonly prompt_tokens_details?: {
            readonly cached_tokens?: number;
            readonly cache_write_tokens?: number;
        };
        readonly input_tokens_details?: {
            readonly cached_tokens?: number;
            readonly cache_write_tokens?: number;
        };
        readonly completion_tokens_details?: {
            readonly reasoning_tokens?: number;
        };
        readonly output_tokens_details?: {
            readonly reasoning_tokens?: number;
        };
    } | null;
}
interface AxAIOpenAIResponsesStreamEventBase {
    readonly type: string;
    readonly sequence_number: number;
}
interface AxAIOpenAIResponsesResponseCreatedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.created';
    readonly response: Readonly<AxAIOpenAIResponsesResponse>;
}
interface AxAIOpenAIResponsesResponseInProgressEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.in_progress';
    readonly response: Readonly<AxAIOpenAIResponsesResponse>;
}
interface AxAIOpenAIResponsesResponseCompletedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.completed';
    readonly response: Readonly<AxAIOpenAIResponsesResponse>;
}
interface AxAIOpenAIResponsesResponseFailedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.failed';
    readonly response: Readonly<AxAIOpenAIResponsesResponse>;
}
interface AxAIOpenAIResponsesResponseIncompleteEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.incomplete';
    readonly response: Readonly<AxAIOpenAIResponsesResponse>;
}
interface AxAIOpenAIResponsesResponseQueuedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.queued';
    readonly response: Readonly<AxAIOpenAIResponsesResponse>;
}
interface AxAIOpenAIResponsesOutputItemAddedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.output_item.added';
    readonly output_index: number;
    readonly item: Readonly<AxAIOpenAIResponsesOutputItem>;
}
interface AxAIOpenAIResponsesOutputItemDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.output_item.done';
    readonly output_index: number;
    readonly item: Readonly<AxAIOpenAIResponsesOutputItem>;
}
interface AxAIOpenAIResponsesContentPartAddedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.content_part.added';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly part: Readonly<AxAIOpenAIResponsesOutputTextContentPart | AxAIOpenAIResponsesOutputRefusalContentPart>;
}
interface AxAIOpenAIResponsesContentPartDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.content_part.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly part: Readonly<AxAIOpenAIResponsesOutputTextContentPart | AxAIOpenAIResponsesOutputRefusalContentPart>;
}
interface AxAIOpenAIResponsesOutputTextDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.output_text.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly delta: string;
}
interface AxAIOpenAIResponsesOutputTextDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.output_text.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly text: string;
}
interface AxAIOpenAIResponsesRefusalDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.refusal.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly delta: string;
}
interface AxAIOpenAIResponsesRefusalDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.refusal.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly refusal: string;
}
interface AxAIOpenAIResponsesFunctionCallArgumentsDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.function_call_arguments.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly delta: string;
}
interface AxAIOpenAIResponsesFunctionCallArgumentsDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.function_call_arguments.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly arguments: string;
}
interface AxAIOpenAIResponsesFileSearchCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.file_search_call.in_progress';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesFileSearchCallSearchingEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.file_search_call.searching';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesFileSearchCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.file_search_call.completed';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesWebSearchCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.web_search_call.in_progress';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesWebSearchCallSearchingEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.web_search_call.searching';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesWebSearchCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.web_search_call.completed';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesReasoningDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly delta: object;
}
interface AxAIOpenAIResponsesReasoningDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly text: string;
}
interface AxAIOpenAIResponsesReasoningTextDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_text.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly delta: string;
}
interface AxAIOpenAIResponsesReasoningTextDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_text.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly text: string;
}
interface AxAIOpenAIResponsesReasoningSummaryPartAddedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_summary_part.added';
    readonly item_id: string;
    readonly output_index: number;
    readonly summary_index: number;
    readonly part: Readonly<AxAIOpenAIResponsesReasoningSummaryPart>;
}
interface AxAIOpenAIResponsesReasoningSummaryPartDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_summary_part.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly summary_index: number;
    readonly part: Readonly<AxAIOpenAIResponsesReasoningSummaryPart>;
}
interface AxAIOpenAIResponsesReasoningSummaryTextDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_summary_text.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly summary_index: number;
    readonly delta: string;
}
interface AxAIOpenAIResponsesReasoningSummaryTextDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_summary_text.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly summary_index: number;
    readonly text: string;
}
interface AxAIOpenAIResponsesReasoningSummaryDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_summary.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly summary_index: number;
    readonly delta: object;
}
interface AxAIOpenAIResponsesReasoningSummaryDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.reasoning_summary.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly summary_index: number;
    readonly text: string;
}
interface AxAIOpenAIResponsesImageGenerationCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.image_generation_call.in_progress';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesImageGenerationCallGeneratingEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.image_generation_call.generating';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesImageGenerationCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.image_generation_call.completed';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesImageGenerationCallPartialImageEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.image_generation_call.partial_image';
    readonly item_id: string;
    readonly output_index: number;
    readonly partial_image_index: number;
    readonly partial_image_b64: string;
}
interface AxAIOpenAIResponsesMCPCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_call.in_progress';
    readonly item_id: string;
    readonly output_index: number;
}
interface AxAIOpenAIResponsesMCPCallArgumentsDeltaEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_call.arguments.delta';
    readonly item_id: string;
    readonly output_index: number;
    readonly delta: object;
}
interface AxAIOpenAIResponsesMCPCallArgumentsDoneEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_call.arguments.done';
    readonly item_id: string;
    readonly output_index: number;
    readonly arguments: object;
}
interface AxAIOpenAIResponsesMCPCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_call.completed';
}
interface AxAIOpenAIResponsesMCPCallFailedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_call.failed';
}
interface AxAIOpenAIResponsesMCPListToolsInProgressEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_list_tools.in_progress';
}
interface AxAIOpenAIResponsesMCPListToolsCompletedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_list_tools.completed';
}
interface AxAIOpenAIResponsesMCPListToolsFailedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.mcp_list_tools.failed';
}
interface AxAIOpenAIResponsesOutputTextAnnotationAddedEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'response.output_text_annotation.added';
    readonly item_id: string;
    readonly output_index: number;
    readonly content_index: number;
    readonly annotation_index: number;
    readonly annotation: object;
}
interface AxAIOpenAIResponsesErrorEvent extends AxAIOpenAIResponsesStreamEventBase {
    readonly type: 'error';
    readonly code: string | null;
    readonly message: string;
    readonly param: string | null;
}
type AxAIOpenAIResponsesStreamEvent = AxAIOpenAIResponsesResponseCreatedEvent | AxAIOpenAIResponsesResponseInProgressEvent | AxAIOpenAIResponsesResponseCompletedEvent | AxAIOpenAIResponsesResponseFailedEvent | AxAIOpenAIResponsesResponseIncompleteEvent | AxAIOpenAIResponsesResponseQueuedEvent | AxAIOpenAIResponsesOutputItemAddedEvent | AxAIOpenAIResponsesOutputItemDoneEvent | AxAIOpenAIResponsesContentPartAddedEvent | AxAIOpenAIResponsesContentPartDoneEvent | AxAIOpenAIResponsesOutputTextDeltaEvent | AxAIOpenAIResponsesOutputTextDoneEvent | AxAIOpenAIResponsesRefusalDeltaEvent | AxAIOpenAIResponsesRefusalDoneEvent | AxAIOpenAIResponsesFunctionCallArgumentsDeltaEvent | AxAIOpenAIResponsesFunctionCallArgumentsDoneEvent | AxAIOpenAIResponsesFileSearchCallInProgressEvent | AxAIOpenAIResponsesFileSearchCallSearchingEvent | AxAIOpenAIResponsesFileSearchCallCompletedEvent | AxAIOpenAIResponsesWebSearchCallInProgressEvent | AxAIOpenAIResponsesWebSearchCallSearchingEvent | AxAIOpenAIResponsesWebSearchCallCompletedEvent | AxAIOpenAIResponsesReasoningDeltaEvent | AxAIOpenAIResponsesReasoningDoneEvent | AxAIOpenAIResponsesReasoningTextDeltaEvent | AxAIOpenAIResponsesReasoningTextDoneEvent | AxAIOpenAIResponsesReasoningSummaryPartAddedEvent | AxAIOpenAIResponsesReasoningSummaryPartDoneEvent | AxAIOpenAIResponsesReasoningSummaryTextDeltaEvent | AxAIOpenAIResponsesReasoningSummaryTextDoneEvent | AxAIOpenAIResponsesReasoningSummaryDeltaEvent | AxAIOpenAIResponsesReasoningSummaryDoneEvent | AxAIOpenAIResponsesImageGenerationCallInProgressEvent | AxAIOpenAIResponsesImageGenerationCallGeneratingEvent | AxAIOpenAIResponsesImageGenerationCallCompletedEvent | AxAIOpenAIResponsesImageGenerationCallPartialImageEvent | AxAIOpenAIResponsesMCPCallInProgressEvent | AxAIOpenAIResponsesMCPCallArgumentsDeltaEvent | AxAIOpenAIResponsesMCPCallArgumentsDoneEvent | AxAIOpenAIResponsesMCPCallCompletedEvent | AxAIOpenAIResponsesMCPCallFailedEvent | AxAIOpenAIResponsesMCPListToolsInProgressEvent | AxAIOpenAIResponsesMCPListToolsCompletedEvent | AxAIOpenAIResponsesMCPListToolsFailedEvent | AxAIOpenAIResponsesOutputTextAnnotationAddedEvent | AxAIOpenAIResponsesErrorEvent;
interface OpenAIResponsesResponseDelta {
    readonly id?: string;
    readonly model?: string;
    readonly event?: string;
    /** Provider-supplied speaker label for realtime transcription deltas. */
    readonly speaker?: string;
    readonly audioProcessedMs?: number;
    readonly transcript?: {
        text: string;
        isFinal: boolean;
    };
    readonly delta?: {
        readonly content?: string;
        readonly arguments?: string;
    };
    readonly item_index?: number;
    readonly item?: Partial<Readonly<AxAIOpenAIResponsesOutputItem>>;
    readonly response?: Readonly<AxAIOpenAIResponsesResponse>;
    readonly usage?: {
        readonly prompt_tokens?: number;
        readonly input_tokens?: number;
        readonly completion_tokens?: number;
        readonly output_tokens?: number;
        readonly total_tokens?: number;
        readonly prompt_tokens_details?: {
            readonly cached_tokens?: number;
            readonly cache_write_tokens?: number;
        };
        readonly input_tokens_details?: {
            readonly cached_tokens?: number;
            readonly cache_write_tokens?: number;
        };
        readonly completion_tokens_details?: {
            readonly reasoning_tokens?: number;
        };
        readonly output_tokens_details?: {
            readonly reasoning_tokens?: number;
        };
    } | null;
}
type AxAIOpenAIResponsesConfig<TModel, TEmbedModel> = Omit<AxModelConfig, 'topK'> & {
    model: TModel;
    embedModel?: TEmbedModel;
    user?: string;
    bestOf?: number;
    logitBias?: Map<string, number>;
    suffix?: string | null;
    stop?: string[];
    logprobs?: number;
    echo?: boolean;
    dimensions?: number;
    reasoningEffort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
    reasoningSummary?: 'auto' | 'concise' | 'detailed';
    store?: boolean;
    systemPrompt?: string;
    parallelToolCalls?: boolean;
    seed?: number;
    responseFormat?: 'text' | 'json_object' | 'json_schema';
    /** Built-in image generation invoked through the Responses transport. */
    imageGeneration?: {
        size?: `${number}x${number}` | 'auto';
        outputFormat?: 'png' | 'jpeg' | 'webp';
        enableImageSearch?: boolean;
        enableWebSearch?: boolean;
        enableShell?: boolean;
        reasoningStrength?: 'low' | 'high';
    };
    /** @internal Default image encoding for a named Responses adapter. */
    defaultImageOutputFormat?: 'png' | 'jpeg' | 'webp';
    /** Ask the provider to return opaque reasoning state for stateless replay. */
    includeEncryptedReasoning?: boolean;
    /** Reject rather than silently omit an explicit `none` reasoning request. */
    rejectReasoningNone?: boolean;
    /** Provider ceiling for portable `highest` reasoning. */
    highestReasoningEffort?: 'xhigh' | 'max';
    /** Provider-specific portable reasoning ladder. */
    reasoningEffortMap?: Partial<Record<'minimal' | 'low' | 'medium' | 'high' | 'highest', 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'>>;
    /** Provider performs prefix caching for compatible Responses inputs. */
    promptCaching?: boolean;
    /** Optional provider cache retention policy for compatible Responses APIs. */
    promptCacheRetention?: 'in_memory' | '24h';
    /** Realtime speech-recognition controls for compatible Responses profiles. */
    realtimeTranscription?: {
        mode?: 'push_to_talk' | 'endpointing' | 'diarization';
        languageBias?: string[];
        keywords?: string[];
        partialMode?: 'cumulative' | 'delta';
        emitAudioProgress?: boolean;
        zdrOverride?: boolean;
    };
    /** Portable values plus the legacy OpenAI `default` alias. */
    serviceTier?: AxServiceTier | 'default';
};
interface AxAIOpenAIResponsesToolCallBase {
    id: string;
    type: string;
    status?: string;
}
type AxAIOpenAIResponsesRealtimeRequest<TModel> = {
    model: TModel;
    request: AxAIOpenAIResponsesRequest<TModel>;
    apiKey: string;
    audio?: AxChatAudioConfig;
    webSocket?: unknown;
    abortSignal?: AbortSignal;
    turnTimeoutMs?: number;
    sessionId?: string;
};
type AxAIOpenAIResponsesRealtimeAdapter<TModel> = {
    shouldUse: (model: string) => boolean;
    createApi: (request: Readonly<AxAIOpenAIResponsesRealtimeRequest<TModel>>) => AxAPI;
};
interface AxAIOpenAIResponsesFileSearchToolCall extends AxAIOpenAIResponsesToolCallBase {
    type: 'file_search_call';
    queries: string[];
    results?: {
        file_id: string;
        filename: string;
        score: number;
        text: string;
        attributes?: Record<string, string | boolean | number>;
    }[];
}
interface AxAIOpenAIResponsesWebSearchToolCall extends AxAIOpenAIResponsesToolCallBase {
    type: 'web_search_call';
    queries: string[];
}
interface AxAIOpenAIResponsesComputerToolCall extends AxAIOpenAIResponsesToolCallBase {
    type: 'computer_call';
    action: object;
}
interface AxAIOpenAIResponsesCodeInterpreterToolCall extends AxAIOpenAIResponsesToolCallBase {
    type: 'code_interpreter_call';
    code: string;
    results?: unknown[];
}
interface AxAIOpenAIResponsesImageGenerationToolCall extends AxAIOpenAIResponsesToolCallBase {
    type: 'image_generation_call';
    result?: string;
}
interface AxAIOpenAIResponsesLocalShellToolCall extends AxAIOpenAIResponsesToolCallBase {
    type: 'local_shell_call';
    action: object;
}
interface AxAIOpenAIResponsesMCPToolCall extends AxAIOpenAIResponsesToolCallBase {
    type: 'mcp_call';
    name: string;
    args: string;
    server_label: string;
    output?: string;
    error?: string;
}
type AxAIOpenAIResponsesToolCall = AxAIOpenAIResponsesFunctionCallItem | AxAIOpenAIResponsesFileSearchToolCall | AxAIOpenAIResponsesWebSearchToolCall | AxAIOpenAIResponsesComputerToolCall | AxAIOpenAIResponsesCodeInterpreterToolCall | AxAIOpenAIResponsesImageGenerationToolCall | AxAIOpenAIResponsesLocalShellToolCall | AxAIOpenAIResponsesMCPToolCall | AxAIOpenAIResponsesCustomToolCall;
/** Reasoning efforts accepted by Astra's native Responses API. */
type AxAIOpenAIAstraReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
interface AxAIOpenAIResponsesConfigurationUpdate {
    readonly type: 'configuration_update';
    readonly reasoning: {
        readonly effort: AxAIOpenAIAstraReasoningEffort;
    };
}
interface AxAIOpenAIResponsesDefineCustomTool {
    readonly type: 'custom';
    readonly name: string;
    readonly description?: string;
    readonly async?: boolean;
    readonly format?: {
        readonly type: 'text';
    } | {
        readonly type: 'grammar';
        readonly syntax: 'lark' | 'regex';
        readonly definition: string;
    };
}
interface AxAIOpenAIResponsesCustomToolCall {
    readonly type: 'custom_tool_call';
    readonly id?: string;
    readonly call_id: string;
    readonly name: string;
    readonly input: string;
    readonly async?: boolean;
}
interface AxAIOpenAIResponsesCustomToolOutput {
    readonly type: 'custom_tool_call_output';
    readonly call_id: string;
    readonly output: string | ReadonlyArray<AxAIOpenAIResponsesInputContentPart>;
}

declare const axAIOpenAIResponsesDefaultConfig: () => AxAIOpenAIResponsesConfig<AxAIOpenAIResponsesModel, AxAIOpenAIEmbedModel>;
declare const axAIOpenAIResponsesBestConfig: () => AxAIOpenAIResponsesConfig<AxAIOpenAIResponsesModel, AxAIOpenAIEmbedModel>;
declare const axAIOpenAIResponsesCreativeConfig: () => AxAIOpenAIResponsesConfig<AxAIOpenAIResponsesModel, AxAIOpenAIEmbedModel>;
interface AxAIOpenAIResponsesBaseArgs<TModel, TEmbedModel, TModelKey, TResponsesReq extends AxAIOpenAIResponsesRequest<TModel>> {
    apiKey?: string;
    credentialProvider?: AxAICredentialProvider;
    credentialProfile?: string;
    config: AxAIOpenAIResponsesConfig<TModel, TEmbedModel>;
    options?: {
        streamingUsage?: boolean;
    } & AxAIServiceOptions;
    apiURL?: string;
    modelInfo?: ReadonlyArray<AxModelInfo>;
    models?: AxAIInputModelList<TModel, TEmbedModel, TModelKey>;
    responsesReqUpdater?: (req: Readonly<TResponsesReq>, options: Readonly<AxAIServiceOptions>) => Readonly<TResponsesReq>;
    supportFor?: AxAIFeatures | ((model: TModel) => AxAIFeatures);
    realtime?: AxAIOpenAIResponsesRealtimeAdapter<TModel>;
}
/**
 * Base class for OpenAI AI services using the /v1/responses API endpoint
 */
declare class AxAIOpenAIResponsesBase<TModel, TEmbedModel, TModelKey, TResponsesReq extends AxAIOpenAIResponsesRequest<TModel>> extends AxBaseAI<TModel, TEmbedModel, AxAIOpenAIResponsesRequest<TModel>, AxAIOpenAIEmbedRequest<TEmbedModel>, AxAIOpenAIResponsesResponse, OpenAIResponsesResponseDelta, AxAIOpenAIEmbedResponse, TModelKey> {
    constructor({ apiKey, credentialProvider, credentialProfile, config, options, apiURL, modelInfo, models, responsesReqUpdater, supportFor, realtime, }: Readonly<AxAIOpenAIResponsesBaseArgs<TModel, TEmbedModel, TModelKey, TResponsesReq>>);
}
/**
 * Ready-to-use implementation of the OpenAI Responses API client
 * This class uses OpenAI's /v1/responses API endpoint which supports text, image, and audio inputs
 */
interface AxAIOpenAIResponsesArgs<TName = 'openai-responses', TModel = AxAIOpenAIResponsesModel, TEmbedModel = AxAIOpenAIEmbedModel, TModelKey = string, TChatReq extends AxAIOpenAIResponsesRequest<TModel> = AxAIOpenAIResponsesRequest<TModel>> extends Omit<AxAIOpenAIResponsesBaseArgs<TModel, TEmbedModel, TModelKey, TChatReq>, 'config' | 'supportFor' | 'modelInfo'> {
    name: TName;
    modelInfo?: AxModelInfo[];
    config?: Partial<AxAIOpenAIResponsesBaseArgs<TModel, TEmbedModel, TModelKey, TChatReq>['config']>;
}
declare class AxAIOpenAIResponses<TModelKey = string> extends AxAIOpenAIResponsesBase<AxAIOpenAIResponsesModel, AxAIOpenAIEmbedModel, TModelKey, AxAIOpenAIResponsesRequest<AxAIOpenAIResponsesModel>> {
    constructor({ apiKey, credentialProvider, apiURL, config, options, models, modelInfo, }: Readonly<Omit<AxAIOpenAIResponsesArgs<'openai-responses', AxAIOpenAIResponsesModel, AxAIOpenAIEmbedModel, TModelKey>, 'name'>>);
}

declare enum AxAIMetaModel {
    MuseSpark13 = "muse-spark-1.3",
    MuseSpark13Contributor = "muse-spark-1.3-contributor",
    MuseSpark12 = "muse-spark-1.2",
    MuseSpark12Contributor = "muse-spark-1.2-contributor",
    MuseSpark11 = "muse-spark-1.1",
    MuseImage10 = "muse-image-1.0",
    MuseVoiceTranscribe10 = "muse-voice-transcribe-1.0"
}
type AxAIMetaSparkModel = AxAIMetaModel.MuseSpark13 | AxAIMetaModel.MuseSpark13Contributor | AxAIMetaModel.MuseSpark12 | AxAIMetaModel.MuseSpark12Contributor | AxAIMetaModel.MuseSpark11;
type AxAIMetaResponsesConfig = Omit<AxAIOpenAIResponsesConfig<AxAIMetaModel, never>, 'promptCaching' | 'defaultImageOutputFormat'>;
type AxAIMetaChatConfig = AxAIOpenAIConfig<AxAIMetaSparkModel, never>;
type AxAIMetaMessagesConfig = Omit<AxAIAnthropicConfig, 'model'> & {
    model: AxAIMetaSparkModel;
};
type AxAIMetaResponsesArgs<TModelKey = string> = Omit<AxAIOpenAIResponsesArgs<'meta', AxAIMetaModel, never, TModelKey>, 'config'> & {
    config?: Readonly<Partial<AxAIMetaResponsesConfig>>;
};
type AxAIMetaChatArgs<TModelKey = string> = AxAIOpenAIArgs<'meta-chat', AxAIMetaSparkModel, never, TModelKey>;
interface AxAIMetaMessagesArgs<TModelKey = string> {
    name: 'meta-messages';
    apiKey?: string;
    credentialProvider?: AxAICredentialProvider;
    apiURL?: string;
    config?: Readonly<Partial<AxAIMetaMessagesConfig>>;
    options?: Readonly<AxAIServiceOptions>;
    modelInfo?: AxModelInfo[];
    models?: AxAIInputModelList<AxAIMetaSparkModel, undefined, TModelKey>;
}
type AxAIMetaArgs<TModelKey = string> = AxAIMetaResponsesArgs<TModelKey> | AxAIMetaChatArgs<TModelKey> | AxAIMetaMessagesArgs<TModelKey>;

declare enum AxAIMistralModel {
    Mistral7B = "open-mistral-7b",
    Mistral8x7B = "open-mixtral-8x7b",
    MistralSmall = "mistral-small-latest",
    MistralNemo = "mistral-nemo-latest",
    MistralLarge = "mistral-large-latest",
    Codestral = "codestral-latest",
    OpenCodestralMamba = "open-codestral-mamba",
    OpenMistralNemo = "open-mistral-nemo-latest"
}
declare enum AxAIMistralEmbedModels {
    MistralEmbed = "mistral-embed"
}

declare const axAIProviderProfiles: {
    readonly openai: {
        readonly id: "openai";
        readonly name: "OpenAI";
        readonly aliases: readonly ["openai"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.openai.com/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "gpt-5-mini";
            readonly embedModel: "text-embedding-3-small";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly audioOutput: true;
            readonly structuredOutputModes: readonly ["native", "function", "json_object"];
            readonly files: {
                readonly uploadMethod: "upload";
            };
            readonly serviceTiers: readonly ["standard", "flex", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
            readonly transcribe: {
                readonly path: "/audio/transcriptions";
                readonly dialect: "openai-transcription";
            };
            readonly speak: {
                readonly path: "/audio/speech";
                readonly dialect: "openai-speech";
            };
            readonly realtime: {
                readonly path: "/realtime";
                readonly dialect: "openai-realtime";
                readonly modelMatch: {
                    readonly prefix: readonly ["gpt-realtime"];
                };
                readonly url: "wss://api.openai.com/v1/realtime";
                readonly grammar: "openai_realtime_compatible";
                readonly audio: {
                    readonly input: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                    };
                    readonly output: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                        readonly voices: readonly ["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"];
                        readonly defaultVoice: "alloy";
                    };
                };
                readonly validation: {
                    readonly structuredOutputWithAudio: false;
                };
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly prefix: readonly ["gpt-6-astra"];
            };
            readonly request: {
                readonly unsupportedThinkingLevels: {
                    readonly none: "GPT-6 Astra requires reasoning; use low or higher";
                };
            };
            readonly capabilities: {
                readonly audio: false;
                readonly audioOutput: false;
                readonly functions: true;
                readonly structuredOutputModes: readonly ["native", "json_object"];
            };
        }, {
            readonly match: {
                readonly prefix: readonly ["gpt-6-sol", "gpt-6-luna"];
            };
            readonly capabilities: {
                readonly audio: false;
                readonly audioOutput: false;
                readonly functions: true;
                readonly structuredOutputModes: readonly ["native", "json_object"];
            };
        }];
        readonly sources: readonly ["https://platform.openai.com/docs/api-reference/chat"];
        readonly reviewedAt: "2026-09-23";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: "auto";
                readonly standard: "default";
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly "openai-compatible": {
        readonly id: "openai-compatible";
        readonly name: "OpenAI Compatible";
        readonly aliases: readonly ["openai-compatible", "openai_compatible", "compatible"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://platform.openai.com/docs/api-reference/chat"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "openai-responses": {
        readonly id: "openai-responses";
        readonly name: "OpenAI Responses";
        readonly aliases: readonly ["openai-responses", "openai_responses", "responses"];
        readonly transport: "openai-responses";
        readonly baseURL: "https://api.openai.com/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "gpt-5-mini";
            readonly embedModel: "text-embedding-3-small";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly audioOutput: true;
            readonly structuredOutputModes: readonly ["native", "function", "json_object"];
            readonly files: {
                readonly uploadMethod: "upload";
            };
            readonly serviceTiers: readonly ["standard", "flex", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/responses";
                readonly dialect: "openai-responses";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
            readonly transcribe: {
                readonly path: "/audio/transcriptions";
                readonly dialect: "openai-transcription";
            };
            readonly speak: {
                readonly path: "/audio/speech";
                readonly dialect: "openai-speech";
            };
            readonly realtime: {
                readonly path: "/realtime";
                readonly dialect: "openai-realtime";
                readonly modelMatch: {
                    readonly prefix: readonly ["gpt-realtime"];
                };
                readonly url: "wss://api.openai.com/v1/realtime";
                readonly grammar: "openai_realtime_compatible";
                readonly audio: {
                    readonly input: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                    };
                    readonly output: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                        readonly voices: readonly ["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"];
                        readonly defaultVoice: "alloy";
                    };
                };
                readonly validation: {
                    readonly structuredOutputWithAudio: false;
                };
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly prefix: readonly ["gpt-6-astra"];
            };
            readonly request: {
                readonly unsupportedThinkingLevels: {
                    readonly none: "GPT-6 Astra requires reasoning; use low or higher";
                };
            };
            readonly capabilities: {
                readonly audio: false;
                readonly audioOutput: false;
            };
        }, {
            readonly match: {
                readonly prefix: readonly ["gpt-6-sol", "gpt-6-luna"];
            };
            readonly capabilities: {
                readonly audio: false;
                readonly audioOutput: false;
            };
        }];
        readonly sources: readonly ["https://platform.openai.com/docs/api-reference/responses"];
        readonly reviewedAt: "2026-09-23";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: "auto";
                readonly standard: "default";
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly anthropic: {
        readonly id: "anthropic";
        readonly name: "Anthropic";
        readonly aliases: readonly ["anthropic", "claude"];
        readonly transport: "anthropic-messages";
        readonly baseURL: "https://api.anthropic.com";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "x-api-key";
            readonly required: true;
        };
        readonly headers: {
            readonly "anthropic-version": "2023-06-01";
            readonly "anthropic-beta": "structured-outputs-2025-11-13, web-search-2025-03-05";
        };
        readonly defaults: {
            readonly model: "claude-sonnet-5";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly caching: {
                readonly types: readonly ["ephemeral"];
                readonly cacheBreakpoints: true;
            };
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/v1/messages";
                readonly dialect: "anthropic-messages";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly contains: readonly ["claude-opus-5-5", "claude-fable-5-1"];
            };
            readonly request: {
                readonly toolChoice: "unforced";
            };
            readonly capabilities: {
                readonly structuredOutputs: true;
                readonly structuredOutputModes: readonly ["native"];
            };
        }];
        readonly sources: readonly ["https://docs.anthropic.com/en/api/messages"];
        readonly reviewedAt: "2026-09-23";
    };
    readonly "google-gemini": {
        readonly id: "google-gemini";
        readonly name: "Google Gemini";
        readonly aliases: readonly ["google-gemini", "google_gemini", "gemini"];
        readonly transport: "gemini-generate-content";
        readonly baseURL: "https://generativelanguage.googleapis.com/v1beta";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "api-key-header";
            readonly header: "x-goog-api-key";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "gemini-3.6-flash";
            readonly embedModel: "gemini-embedding-2";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly audioOutput: true;
            readonly files: {
                readonly uploadMethod: "cloud";
            };
            readonly caching: {
                readonly types: readonly ["persistent"];
            };
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly responseFormatWithFunctions: false;
            readonly serviceTiers: readonly ["standard", "flex", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/models/{model}:generateContent";
                readonly dialect: "gemini-generate-content";
            };
            readonly stream_chat: {
                readonly path: "/models/{model}:streamGenerateContent?alt=sse";
                readonly dialect: "gemini-generate-content";
            };
            readonly embed: {
                readonly path: "/models/{model}:batchEmbedContents";
                readonly dialect: "gemini-generate-content";
            };
            readonly transcribe: {
                readonly path: "/models/{model}:generateContent";
                readonly dialect: "gemini-generate-content";
                readonly defaultModel: "gemini-3.5-transcribe";
                readonly body: "json";
            };
            readonly speak: {
                readonly path: "/models/{model}:generateContent";
                readonly dialect: "gemini-generate-content";
                readonly defaultModel: "gemini-3.8-flash-tts";
                readonly response: "json";
            };
            readonly realtime: {
                readonly path: "/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
                readonly dialect: "gemini-live-bidi";
                readonly modelMatch: {
                    readonly exact: readonly ["gemini-3.8-live", "gemini-3.8-live-extended-thinking"];
                    readonly prefix: readonly ["gemini-live"];
                    readonly contains: readonly ["native-audio", "-live-"];
                };
                readonly url: "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
                readonly grammar: "gemini_live_bidi";
                readonly defaultModel: "gemini-3.8-live";
                readonly audio: {
                    readonly input: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 16000;
                    };
                    readonly output: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                        readonly voices: readonly ["Kore", "Puck", "Charon", "Fenrir", "Aoede"];
                        readonly defaultVoice: "Kore";
                    };
                };
                readonly validation: {
                    readonly pcmInputOnly: true;
                    readonly rejectStructuredOutputWithAudio: true;
                };
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://ai.google.dev/api/generate-content", "https://ai.google.dev/gemini-api/docs/optimization"];
        readonly reviewedAt: "2026-09-23";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: null;
                readonly standard: "standard";
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly webllm: {
        readonly id: "webllm";
        readonly name: "WebLLM";
        readonly aliases: readonly ["webllm"];
        readonly transport: "webllm";
        readonly baseURL: null;
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "none";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "";
                readonly dialect: "webllm";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://webllm.mlc.ai/docs/"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "azure-openai": {
        readonly id: "azure-openai";
        readonly name: "Azure OpenAI";
        readonly aliases: readonly ["azure-openai", "azure_openai", "azure"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "api-key-header";
            readonly header: "api-key";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "gpt-5-mini";
            readonly embedModel: "text-embedding-3-small";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly ["standard", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
        };
        readonly endpoint: {
            readonly scheme: "https";
            readonly hostField: "resourceName";
            readonly hostSuffix: ".openai.azure.com";
            readonly path: "/openai/deployments/{deploymentName}";
            readonly fields: {
                readonly resourceName: readonly ["resource_name", "resourceName"];
                readonly deploymentName: readonly ["deployment_name", "deploymentName"];
                readonly version: readonly ["api_version", "apiVersion", "version"];
            };
            readonly required: readonly ["resourceName", "deploymentName"];
            readonly defaults: {
                readonly version: "2024-02-15-preview";
            };
            readonly normalizers: {
                readonly version: "api-version";
            };
            readonly apiVersionField: "version";
        };
        readonly capabilityGates: {
            readonly structuredOutputs: {
                readonly option: "version";
                readonly min: "2024-08-01";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://learn.microsoft.com/en-us/azure/ai-services/openai/reference", "https://learn.microsoft.com/en-us/azure/foundry/openai/concepts/priority-processing"];
        readonly reviewedAt: "2026-08-17";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: "auto";
                readonly standard: "default";
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly deepseek: {
        readonly id: "deepseek";
        readonly name: "DeepSeek";
        readonly aliases: readonly ["deepseek"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.deepseek.com";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "deepseek-v4-flash";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function", "json_object"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly exact: readonly ["deepseek-v4-flash", "deepseek-v4-pro"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
                readonly showThoughts: true;
                readonly structuredOutputs: false;
                readonly structuredOutputModes: readonly ["function"];
            };
            readonly request: {
                readonly reasoning: "thinking-object";
                readonly toolChoice: "unforced";
                readonly effortMap: {
                    readonly none: null;
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "max";
                    readonly xhigh: "max";
                    readonly max: "max";
                };
                readonly dropWhenThinking: readonly ["temperature", "top_p", "presence_penalty", "frequency_penalty"];
                readonly defaultThinkingLevel: "max";
            };
            readonly response: {
                readonly reasoningFields: readonly ["reasoning_content", "reasoning"];
            };
            readonly replay: {
                readonly assistantReasoningField: "reasoning_content";
            };
        }, {
            readonly match: {
                readonly exact: readonly ["deepseek-reasoner"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: false;
                readonly showThoughts: true;
                readonly structuredOutputs: false;
                readonly structuredOutputModes: readonly ["function"];
            };
            readonly request: {
                readonly toolChoice: "unforced";
            };
            readonly response: {
                readonly reasoningFields: readonly ["reasoning_content", "reasoning"];
            };
            readonly replay: {
                readonly assistantReasoningField: "reasoning_content";
            };
        }];
        readonly sources: readonly ["https://api-docs.deepseek.com/guides/thinking_mode/"];
        readonly reviewedAt: "2026-08-18";
    };
    readonly "deepseek-responses": {
        readonly id: "deepseek-responses";
        readonly name: "DeepSeek Responses";
        readonly aliases: readonly ["deepseek-responses", "deepseek_responses"];
        readonly transport: "openai-responses";
        readonly baseURL: "https://api.deepseek.com";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "deepseek-v4-flash";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/responses";
                readonly dialect: "openai-responses";
            };
        };
        readonly request: {
            readonly dropFields: readonly ["include", "previous_response_id", "store", "parallel_tool_calls"];
            readonly reasoningObjectFields: readonly ["effort"];
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://api-docs.deepseek.com/api/create-chat-completion"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly meta: {
        readonly id: "meta";
        readonly name: "Meta Model API";
        readonly aliases: readonly ["meta", "meta-responses", "meta_responses"];
        readonly transport: "openai-responses";
        readonly baseURL: "https://api.meta.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "muse-spark-1.3";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly files: {
                readonly uploadMethod: "inline";
            };
            readonly caching: {
                readonly types: readonly ["ephemeral"];
                readonly cacheBreakpoints: false;
            };
            readonly structuredOutputModes: readonly ["native", "function", "json_object"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/responses";
                readonly dialect: "openai-responses";
            };
            readonly transcribe: {
                readonly path: "/asr/transcribe";
                readonly dialect: "meta-transcription";
            };
            readonly realtime: {
                readonly path: "/asr/realtime";
                readonly dialect: "meta-realtime";
                readonly modelMatch: {
                    readonly exact: readonly ["muse-voice-transcribe-1.0"];
                };
                readonly url: "wss://api.meta.ai/v1/asr/realtime";
                readonly grammar: "meta_asr_realtime";
                readonly defaultModel: "muse-voice-transcribe-1.0";
                readonly audio: {
                    readonly input: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                    };
                };
            };
        };
        readonly request: {
            readonly toolChoice: "no-named";
            readonly reasoningObjectFields: readonly ["effort", "summary"];
            readonly unsupportedThinkingLevels: {
                readonly none: "Meta Muse Spark does not support reasoning level none";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly exact: readonly ["muse-image-1.0"];
            };
            readonly capabilities: {
                readonly functions: false;
                readonly functionEmulation: false;
                readonly structuredOutputs: false;
                readonly thinking: false;
                readonly audio: false;
                readonly structuredOutputModes: readonly [];
            };
        }, {
            readonly match: {
                readonly exact: readonly ["muse-voice-transcribe-1.0"];
            };
            readonly capabilities: {
                readonly functions: false;
                readonly functionEmulation: false;
                readonly structuredOutputs: false;
                readonly thinking: false;
                readonly images: false;
                readonly structuredOutputModes: readonly [];
            };
        }];
        readonly sources: readonly ["https://dev.meta.ai/docs/protocols/responses"];
        readonly reviewedAt: "2026-09-03";
    };
    readonly "meta-chat": {
        readonly id: "meta-chat";
        readonly name: "Meta Model API Chat Completions";
        readonly aliases: readonly ["meta-chat", "meta_chat"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.meta.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "muse-spark-1.3";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly files: {
                readonly uploadMethod: "inline";
            };
            readonly caching: {
                readonly types: readonly ["ephemeral"];
                readonly cacheBreakpoints: false;
            };
            readonly structuredOutputModes: readonly ["native", "function", "json_object"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly request: {
            readonly toolChoice: "no-named";
            readonly effortMap: {
                readonly minimal: "minimal";
                readonly low: "low";
                readonly medium: "medium";
                readonly high: "high";
                readonly highest: "xhigh";
            };
            readonly unsupportedThinkingLevels: {
                readonly none: "Meta Muse Spark does not support reasoning level none";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://dev.meta.ai/docs/protocols/chat-completions"];
        readonly reviewedAt: "2026-09-03";
    };
    readonly "meta-messages": {
        readonly id: "meta-messages";
        readonly name: "Meta Model API Messages";
        readonly aliases: readonly ["meta-messages", "meta_messages"];
        readonly transport: "anthropic-messages";
        readonly baseURL: "https://api.meta.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "muse-spark-1.3";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: true;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly files: {
                readonly uploadMethod: "inline";
            };
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/messages";
                readonly dialect: "anthropic-messages";
            };
        };
        readonly request: {
            readonly toolChoice: "no-named";
            readonly unsupportedThinkingLevels: {
                readonly none: "Meta Muse Spark does not support reasoning level none";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://dev.meta.ai/docs/protocols/messages"];
        readonly reviewedAt: "2026-09-03";
    };
    readonly mistral: {
        readonly id: "mistral";
        readonly name: "Mistral AI";
        readonly aliases: readonly ["mistral"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.mistral.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "mistral-small-latest";
            readonly embedModel: "mistral-embed";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly audioOutput: true;
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly ["standard", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
            readonly transcribe: {
                readonly path: "/audio/transcriptions";
                readonly dialect: "openai-transcription";
            };
            readonly speak: {
                readonly path: "/audio/speech";
                readonly dialect: "mistral-speech";
            };
        };
        readonly request: {
            readonly renameFields: {
                readonly max_completion_tokens: "max_tokens";
            };
            readonly imageURLShape: "object";
            readonly serviceTierMap: {
                readonly auto: "auto";
                readonly standard: "standard_only";
                readonly priority: "auto";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.mistral.ai/api/", "https://docs.mistral.ai/inference/priority-tier"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly cohere: {
        readonly id: "cohere";
        readonly name: "Cohere";
        readonly aliases: readonly ["cohere"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.cohere.ai/compatibility/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "command-r-plus";
            readonly embedModel: "embed-english-v3.0";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.cohere.com/reference/compatibility-api"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly grok: {
        readonly id: "grok";
        readonly name: "xAI Grok";
        readonly aliases: readonly ["grok", "xai", "x-grok", "x_grok"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.x.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "grok-4.6";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly images: true;
            readonly audio: true;
            readonly audioOutput: true;
            readonly webSearch: true;
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly ["standard", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly transcribe: {
                readonly path: "/stt";
                readonly dialect: "xai-transcription";
            };
            readonly speak: {
                readonly path: "/tts";
                readonly dialect: "xai-speech";
            };
            readonly realtime: {
                readonly path: "/realtime";
                readonly dialect: "xai-realtime";
                readonly modelMatch: {
                    readonly prefix: readonly ["grok-voice"];
                };
                readonly url: "wss://api.x.ai/v1/realtime";
                readonly grammar: "openai_realtime_compatible";
                readonly defaultModel: "grok-voice-think-fast-1.0";
                readonly audio: {
                    readonly input: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                    };
                    readonly output: {
                        readonly formats: readonly ["pcm16", "pcm"];
                        readonly sampleRate: 24000;
                        readonly voices: readonly ["eve", "ara", "rex", "sal", "leo"];
                        readonly defaultVoice: "eve";
                    };
                };
                readonly validation: {
                    readonly structuredOutputWithAudio: false;
                };
            };
        };
        readonly request: {
            readonly optionDialect: "search-parameters";
            readonly serviceTierMap: {
                readonly auto: null;
                readonly standard: "default";
                readonly priority: "priority";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly exact: readonly ["grok-4.6"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
                readonly structuredOutputs: true;
                readonly structuredOutputModes: readonly ["native", "function"];
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: null;
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "xhigh";
                    readonly xhigh: "xhigh";
                    readonly max: "xhigh";
                };
                readonly unsupportedThinkingLevels: {
                    readonly none: "xAI Grok 4.6 reasoning cannot be disabled";
                };
                readonly dropFields: readonly ["presence_penalty", "frequency_penalty", "stop"];
            };
        }, {
            readonly match: {
                readonly exact: readonly ["grok-4.5", "grok-4.5-latest", "grok-build-latest"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
                readonly structuredOutputs: true;
                readonly structuredOutputModes: readonly ["native", "function"];
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: null;
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "high";
                    readonly xhigh: "high";
                    readonly max: "high";
                };
                readonly unsupportedThinkingLevels: {
                    readonly none: "xAI Grok 4.5 reasoning cannot be disabled";
                };
                readonly dropFields: readonly ["presence_penalty", "frequency_penalty", "stop"];
            };
        }, {
            readonly match: {
                readonly exact: readonly ["grok-4.3", "grok-4.3-latest", "grok-latest"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
                readonly showThoughts: true;
                readonly structuredOutputs: true;
                readonly structuredOutputModes: readonly ["native", "function"];
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: "none";
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "high";
                    readonly xhigh: "high";
                    readonly max: "high";
                };
                readonly dropFields: readonly ["presence_penalty", "frequency_penalty", "stop"];
            };
        }, {
            readonly match: {
                readonly exact: readonly ["grok-3-mini", "grok-3-mini-latest", "grok-3-mini-beta", "grok-3-mini-fast", "grok-3-mini-fast-latest", "grok-3-mini-fast-beta"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "low";
                readonly effortMap: {
                    readonly none: null;
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "high";
                    readonly high: "high";
                    readonly highest: "high";
                    readonly xhigh: "high";
                    readonly max: "high";
                };
                readonly unsupportedThinkingLevels: {
                    readonly none: "xAI Grok 3 Mini reasoning cannot be disabled";
                };
            };
        }];
        readonly sources: readonly ["https://docs.x.ai/developers/model-capabilities/text/reasoning", "https://docs.x.ai/developers/rest-api-reference/management/auth", "https://docs.x.ai/developers/models/grok-4.5", "https://docs.x.ai/developers/advanced-api-usage/priority-processing"];
        readonly reviewedAt: "2026-08-30";
    };
    readonly reka: {
        readonly id: "reka";
        readonly name: "Reka";
        readonly aliases: readonly ["reka"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.reka.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "reka-core";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.reka.ai/"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly together: {
        readonly id: "together";
        readonly name: "Together AI";
        readonly aliases: readonly ["together", "together-ai", "together_ai"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.together.xyz/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["native", "function", "json_object"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly prefix: readonly ["deepseek-ai/DeepSeek-V4"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
                readonly showThoughts: true;
                readonly structuredOutputs: false;
                readonly structuredOutputModes: readonly ["function"];
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly toolChoice: "unforced";
                readonly effortMap: {
                    readonly none: null;
                    readonly minimal: "high";
                    readonly low: "high";
                    readonly medium: "high";
                    readonly high: "max";
                    readonly highest: "max";
                    readonly xhigh: "max";
                    readonly max: "max";
                };
                readonly defaultThinkingLevel: "max";
            };
            readonly response: {
                readonly reasoningFields: readonly ["reasoning", "reasoning_content"];
            };
            readonly replay: {
                readonly assistantReasoningField: "reasoning";
            };
        }];
        readonly sources: readonly ["https://docs.together.ai/docs/inference/chat/reasoning"];
        readonly reviewedAt: "2026-08-18";
    };
    readonly openrouter: {
        readonly id: "openrouter";
        readonly name: "OpenRouter";
        readonly aliases: readonly ["openrouter"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://openrouter.ai/api/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly ["standard", "flex", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly prefix: readonly ["deepseek/"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
                readonly showThoughts: true;
                readonly structuredOutputs: false;
                readonly structuredOutputModes: readonly ["function"];
            };
            readonly request: {
                readonly reasoning: "openrouter";
                readonly toolChoice: "unforced";
                readonly effortMap: {
                    readonly none: "none";
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "max";
                    readonly xhigh: "xhigh";
                    readonly max: "max";
                };
                readonly defaultThinkingLevel: "max";
            };
            readonly response: {
                readonly reasoningFields: readonly ["reasoning", "reasoning_content"];
                readonly reasoningDetailsFields: readonly ["reasoning_details"];
            };
            readonly replay: {
                readonly assistantReasoningField: "reasoning";
                readonly assistantReasoningDetailsField: "reasoning_details";
            };
        }];
        readonly sources: readonly ["https://openrouter.ai/docs/guides/best-practices/reasoning-tokens", "https://openrouter.ai/docs/guides/features/service-tiers"];
        readonly reviewedAt: "2026-08-18";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: null;
                readonly standard: null;
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly orcarouter: {
        readonly id: "orcarouter";
        readonly name: "OrcaRouter";
        readonly aliases: readonly ["orcarouter"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.orcarouter.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "orcarouter/auto";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://www.orcarouter.ai"];
        readonly reviewedAt: "2026-08-19";
    };
    readonly fireworks: {
        readonly id: "fireworks";
        readonly name: "Fireworks AI";
        readonly aliases: readonly ["fireworks", "fireworks-ai"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.fireworks.ai/inference/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly ["standard", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
            readonly embed: {
                readonly path: "/embeddings";
                readonly dialect: "openai-embeddings";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly contains: readonly ["deepseek-v4"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
                readonly showThoughts: true;
                readonly structuredOutputs: false;
                readonly structuredOutputModes: readonly ["function"];
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly toolChoice: "unforced";
                readonly effortMap: {
                    readonly none: "none";
                    readonly minimal: "high";
                    readonly low: "high";
                    readonly medium: "high";
                    readonly high: "high";
                    readonly highest: "max";
                    readonly xhigh: "max";
                    readonly max: "max";
                };
                readonly defaultThinkingLevel: "max";
            };
            readonly response: {
                readonly reasoningFields: readonly ["reasoning_content", "reasoning"];
            };
            readonly replay: {
                readonly assistantReasoningField: "reasoning_content";
            };
        }];
        readonly sources: readonly ["https://docs.fireworks.ai/api-reference/post-chatcompletions", "https://docs.fireworks.ai/guides/reasoning"];
        readonly reviewedAt: "2026-08-18";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: null;
                readonly standard: "default";
                readonly priority: "priority";
            };
        };
    };
    readonly "huggingface-router": {
        readonly id: "huggingface-router";
        readonly name: "Hugging Face Router";
        readonly aliases: readonly ["huggingface-router", "huggingface", "hf-router"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://router.huggingface.co/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://huggingface.co/docs/inference-providers/en/index", "https://huggingface.co/docs/inference-providers/en/tasks/chat-completion"];
        readonly reviewedAt: "2026-08-18";
    };
    readonly "amazon-bedrock": {
        readonly id: "amazon-bedrock";
        readonly name: "Amazon Bedrock";
        readonly aliases: readonly ["amazon-bedrock", "bedrock"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly ["standard", "flex", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.aws.amazon.com/bedrock/latest/userguide/inference-chat-completions-mantle.html", "https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html"];
        readonly reviewedAt: "2026-08-17";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: null;
                readonly standard: "default";
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly "azure-foundry": {
        readonly id: "azure-foundry";
        readonly name: "Azure AI Foundry";
        readonly aliases: readonly ["azure-foundry", "azure-ai-foundry", "microsoft-foundry"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "api-key-header";
            readonly header: "api-key";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly ["standard", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://learn.microsoft.com/en-us/rest/api/microsoft-foundry/azureopenai/chat", "https://learn.microsoft.com/en-us/azure/foundry/openai/concepts/priority-processing"];
        readonly reviewedAt: "2026-08-17";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: "auto";
                readonly standard: "default";
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly "vertex-ai": {
        readonly id: "vertex-ai";
        readonly name: "Vertex AI OpenAI Compatibility";
        readonly aliases: readonly ["vertex-ai", "vertex-openai"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly exact: readonly ["google/gemma-4-26b-a4b-it-maas"];
            };
            readonly capabilities: {
                readonly structuredOutputs: false;
                readonly structuredOutputModes: readonly ["json_object", "function"];
                readonly thinking: true;
            };
            readonly request: {
                readonly defaultThinkingLevel: "max";
                readonly thinkingBoolean: {
                    readonly path: readonly ["chat_template_kwargs", "enable_thinking"];
                };
            };
            readonly response: {
                readonly reasoningFields: readonly ["reasoning_content"];
            };
            readonly replay: {
                readonly assistantReasoningField: "reasoning_content";
            };
        }, {
            readonly match: {
                readonly prefix: readonly ["google/gemini-", "gemini-"];
            };
            readonly capabilities: {
                readonly structuredOutputs: true;
                readonly structuredOutputModes: readonly ["native", "function", "json_object"];
            };
        }];
        readonly sources: readonly ["https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/call-vertex-using-openai-library", "https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/maas/capabilities/structured-output", "https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/maas/capabilities/thinking"];
        readonly reviewedAt: "2026-08-18";
    };
    readonly databricks: {
        readonly id: "databricks";
        readonly name: "Databricks Model Serving";
        readonly aliases: readonly ["databricks"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly ["standard", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.databricks.com/aws/en/machine-learning/model-serving/query-chat-models", "https://docs.databricks.com/aws/en/machine-learning/foundation-model-apis/priority-mode"];
        readonly reviewedAt: "2026-08-17";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: null;
                readonly standard: "default";
                readonly priority: "priority";
            };
        };
    };
    readonly baseten: {
        readonly id: "baseten";
        readonly name: "Baseten Model APIs";
        readonly aliases: readonly ["baseten"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://inference.baseten.co/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.baseten.co/inference/model-apis/overview"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly groq: {
        readonly id: "groq";
        readonly name: "Groq";
        readonly aliases: readonly ["groq"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.groq.com/openai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly ["standard", "flex", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly exact: readonly ["openai/gpt-oss-20b", "openai/gpt-oss-120b"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: null;
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "high";
                    readonly xhigh: "high";
                    readonly max: "high";
                };
                readonly unsupportedThinkingLevels: {
                    readonly none: "Groq GPT-OSS reasoning does not support the none effort level";
                };
            };
        }, {
            readonly match: {
                readonly exact: readonly ["qwen/qwen3.6-27b"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: "none";
                    readonly minimal: "default";
                    readonly low: "default";
                    readonly medium: "default";
                    readonly high: "default";
                    readonly highest: "default";
                    readonly xhigh: "default";
                    readonly max: "default";
                };
            };
        }];
        readonly sources: readonly ["https://console.groq.com/docs/reasoning", "https://console.groq.com/docs/api-reference", "https://console.groq.com/docs/service-tiers"];
        readonly reviewedAt: "2026-08-18";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: "auto";
                readonly standard: "on_demand";
                readonly flex: "flex";
                readonly priority: "performance";
            };
        };
    };
    readonly cerebras: {
        readonly id: "cerebras";
        readonly name: "Cerebras Inference";
        readonly aliases: readonly ["cerebras"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.cerebras.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: true;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["native", "function"];
            readonly serviceTiers: readonly ["standard", "flex", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly exact: readonly ["gpt-oss-120b"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: null;
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "high";
                    readonly xhigh: "high";
                    readonly max: "high";
                };
                readonly unsupportedThinkingLevels: {
                    readonly none: "Cerebras GPT-OSS reasoning does not support the none effort level";
                };
            };
        }, {
            readonly match: {
                readonly exact: readonly ["gemma-4-31b"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: "none";
                    readonly minimal: "high";
                    readonly low: "high";
                    readonly medium: "high";
                    readonly high: "high";
                    readonly highest: "high";
                    readonly xhigh: "high";
                    readonly max: "high";
                };
            };
        }];
        readonly sources: readonly ["https://inference-docs.cerebras.ai/capabilities/reasoning", "https://inference-docs.cerebras.ai/api-reference/chat-completions", "https://inference-docs.cerebras.ai/capabilities/service-tiers"];
        readonly reviewedAt: "2026-08-18";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: "auto";
                readonly standard: "default";
                readonly flex: "flex";
                readonly priority: "priority";
            };
        };
    };
    readonly deepinfra: {
        readonly id: "deepinfra";
        readonly name: "DeepInfra";
        readonly aliases: readonly ["deepinfra"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.deepinfra.com/v1/openai";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly ["standard", "priority"];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [{
            readonly match: {
                readonly prefix: readonly ["deepseek-ai/DeepSeek-R1"];
            };
            readonly capabilities: {
                readonly thinking: true;
                readonly thinkingBudget: true;
            };
            readonly request: {
                readonly reasoning: "effort";
                readonly defaultThinkingLevel: "max";
                readonly effortMap: {
                    readonly none: "none";
                    readonly minimal: "low";
                    readonly low: "low";
                    readonly medium: "medium";
                    readonly high: "high";
                    readonly highest: "high";
                    readonly xhigh: "high";
                    readonly max: "high";
                };
            };
        }];
        readonly sources: readonly ["https://docs.deepinfra.com/chat/reasoning", "https://docs.deepinfra.com/api-reference/introduction", "https://docs.deepinfra.com/chat/overview"];
        readonly reviewedAt: "2026-08-18";
        readonly request: {
            readonly serviceTierMap: {
                readonly auto: null;
                readonly standard: null;
                readonly priority: "priority";
            };
        };
    };
    readonly sambanova: {
        readonly id: "sambanova";
        readonly name: "SambaNova Cloud";
        readonly aliases: readonly ["sambanova", "sambanova-cloud"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.sambanova.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.sambanova.ai/docs/en/api-reference/overview"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly nebius: {
        readonly id: "nebius";
        readonly name: "Nebius AI Studio";
        readonly aliases: readonly ["nebius"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.tokenfactory.nebius.com/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://api.studio.nebius.com/docs"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly novita: {
        readonly id: "novita";
        readonly name: "Novita AI";
        readonly aliases: readonly ["novita", "novita-ai"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.novita.ai/v3/openai";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://novita.ai/docs/guides/llm-api"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly hyperbolic: {
        readonly id: "hyperbolic";
        readonly name: "Hyperbolic";
        readonly aliases: readonly ["hyperbolic"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.hyperbolic.xyz/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.hyperbolic.xyz/docs/inference-api"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly siliconflow: {
        readonly id: "siliconflow";
        readonly name: "SiliconFlow";
        readonly aliases: readonly ["siliconflow"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.siliconflow.com/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.siliconflow.com/en/userguide/quickstart"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly friendli: {
        readonly id: "friendli";
        readonly name: "FriendliAI";
        readonly aliases: readonly ["friendli", "friendli-ai"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.friendli.ai/serverless/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://friendli.ai/docs/guides/tool-calling"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "cloudflare-workers-ai": {
        readonly id: "cloudflare-workers-ai";
        readonly name: "Cloudflare Workers AI";
        readonly aliases: readonly ["cloudflare-workers-ai", "workers-ai"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://developers.cloudflare.com/workers-ai/configuration/open-ai-compatibility/"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly featherless: {
        readonly id: "featherless";
        readonly name: "Featherless AI";
        readonly aliases: readonly ["featherless", "featherless-ai"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.featherless.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://featherless.ai/docs/quickstart-guide"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly nscale: {
        readonly id: "nscale";
        readonly name: "Nscale";
        readonly aliases: readonly ["nscale"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.nscale.com/docs/use-cases/chat"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly ovhcloud: {
        readonly id: "ovhcloud";
        readonly name: "OVHcloud AI Endpoints";
        readonly aliases: readonly ["ovhcloud", "ovh"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.ovhcloud.com/en/guides/public-cloud/ai-machine-learning/ai-endpoints-capabilities"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly scaleway: {
        readonly id: "scaleway";
        readonly name: "Scaleway Generative APIs";
        readonly aliases: readonly ["scaleway"];
        readonly transport: "openai-chat";
        readonly baseURL: "https://api.scaleway.ai/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://www.scaleway.com/en/developers/api/generative-apis"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "nvidia-nim": {
        readonly id: "nvidia-nim";
        readonly name: "NVIDIA NIM";
        readonly aliases: readonly ["nvidia-nim", "nim"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "runpod-vllm": {
        readonly id: "runpod-vllm";
        readonly name: "RunPod vLLM";
        readonly aliases: readonly ["runpod-vllm", "runpod"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.runpod.io/serverless/vllm/openai-compatibility"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "sagemaker-vllm": {
        readonly id: "sagemaker-vllm";
        readonly name: "SageMaker vLLM";
        readonly aliases: readonly ["sagemaker-vllm", "sagemaker"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints-openai-compatible.html"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly vllm: {
        readonly id: "vllm";
        readonly name: "vLLM";
        readonly aliases: readonly ["vllm"];
        readonly transport: "openai-chat";
        readonly baseURL: "http://localhost:8000/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.vllm.ai/en/latest/serving/openai_compatible_server/"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly ollama: {
        readonly id: "ollama";
        readonly name: "Ollama";
        readonly aliases: readonly ["ollama"];
        readonly transport: "openai-chat";
        readonly baseURL: "http://localhost:11434/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.ollama.com/api/openai-compatibility"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "lm-studio": {
        readonly id: "lm-studio";
        readonly name: "LM Studio";
        readonly aliases: readonly ["lm-studio", "lmstudio"];
        readonly transport: "openai-chat";
        readonly baseURL: "http://localhost:1234/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://lmstudio.ai/docs/developer/openai-compat"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "llama-cpp": {
        readonly id: "llama-cpp";
        readonly name: "llama.cpp Server";
        readonly aliases: readonly ["llama-cpp", "llama.cpp"];
        readonly transport: "openai-chat";
        readonly baseURL: "http://localhost:8080/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly localai: {
        readonly id: "localai";
        readonly name: "LocalAI";
        readonly aliases: readonly ["localai", "local-ai"];
        readonly transport: "openai-chat";
        readonly baseURL: "http://localhost:8080/v1";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://localai.io/features/openai-functions/"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly "baseten-engine": {
        readonly id: "baseten-engine";
        readonly name: "Baseten Inference Engine";
        readonly aliases: readonly ["baseten-engine", "truss"];
        readonly transport: "openai-chat";
        readonly baseURL: null;
        readonly requiresApiURL: true;
        readonly auth: {
            readonly type: "bearer";
            readonly required: false;
        };
        readonly defaults: {
            readonly model: "";
        };
        readonly capabilities: {
            readonly functions: true;
            readonly streaming: true;
            readonly structuredOutputs: false;
            readonly thinking: false;
            readonly multiTurn: true;
            readonly structuredOutputModes: readonly ["function"];
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/chat/completions";
                readonly dialect: "openai-chat";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://docs.baseten.co/development/model/deployment/inference"];
        readonly reviewedAt: "2026-08-17";
    };
    readonly typesafe: {
        readonly id: "typesafe";
        readonly name: "Typesafe";
        readonly aliases: readonly ["typesafe"];
        readonly transport: "typesafe-system-one";
        readonly baseURL: "https://api.typesafe.ai";
        readonly requiresApiURL: false;
        readonly auth: {
            readonly type: "bearer";
            readonly required: true;
        };
        readonly defaults: {
            readonly model: "jev-latest";
        };
        readonly capabilities: {
            readonly functions: false;
            readonly functionEmulation: false;
            readonly streaming: false;
            readonly structuredOutputs: true;
            readonly structuredOutputModes: readonly ["native"];
            readonly requiresStructuredOutput: true;
            readonly thinking: false;
            readonly multiTurn: false;
            readonly serviceTiers: readonly [];
        };
        readonly operations: {
            readonly chat: {
                readonly path: "/v1/systemone";
                readonly dialect: "typesafe-system-one";
            };
        };
        readonly modelRules: readonly [];
        readonly sources: readonly ["https://github.com/typesafe-ai/typesafe-sdk-js", "https://docs.typesafe.ai/sdk/javascript"];
        readonly reviewedAt: "2026-09-15";
    };
};
declare const axAIProviderAliases: {
    readonly openai: "openai";
    readonly "openai-compatible": "openai-compatible";
    readonly openai_compatible: "openai-compatible";
    readonly compatible: "openai-compatible";
    readonly "openai-responses": "openai-responses";
    readonly openai_responses: "openai-responses";
    readonly responses: "openai-responses";
    readonly anthropic: "anthropic";
    readonly claude: "anthropic";
    readonly "google-gemini": "google-gemini";
    readonly google_gemini: "google-gemini";
    readonly gemini: "google-gemini";
    readonly webllm: "webllm";
    readonly "azure-openai": "azure-openai";
    readonly azure_openai: "azure-openai";
    readonly azure: "azure-openai";
    readonly deepseek: "deepseek";
    readonly "deepseek-responses": "deepseek-responses";
    readonly deepseek_responses: "deepseek-responses";
    readonly meta: "meta";
    readonly "meta-responses": "meta";
    readonly meta_responses: "meta";
    readonly "meta-chat": "meta-chat";
    readonly meta_chat: "meta-chat";
    readonly "meta-messages": "meta-messages";
    readonly meta_messages: "meta-messages";
    readonly mistral: "mistral";
    readonly cohere: "cohere";
    readonly grok: "grok";
    readonly xai: "grok";
    readonly "x-grok": "grok";
    readonly x_grok: "grok";
    readonly reka: "reka";
    readonly together: "together";
    readonly "together-ai": "together";
    readonly together_ai: "together";
    readonly openrouter: "openrouter";
    readonly orcarouter: "orcarouter";
    readonly fireworks: "fireworks";
    readonly "fireworks-ai": "fireworks";
    readonly "huggingface-router": "huggingface-router";
    readonly huggingface: "huggingface-router";
    readonly "hf-router": "huggingface-router";
    readonly "amazon-bedrock": "amazon-bedrock";
    readonly bedrock: "amazon-bedrock";
    readonly "azure-foundry": "azure-foundry";
    readonly "azure-ai-foundry": "azure-foundry";
    readonly "microsoft-foundry": "azure-foundry";
    readonly "vertex-ai": "vertex-ai";
    readonly "vertex-openai": "vertex-ai";
    readonly databricks: "databricks";
    readonly baseten: "baseten";
    readonly groq: "groq";
    readonly cerebras: "cerebras";
    readonly deepinfra: "deepinfra";
    readonly sambanova: "sambanova";
    readonly "sambanova-cloud": "sambanova";
    readonly nebius: "nebius";
    readonly novita: "novita";
    readonly "novita-ai": "novita";
    readonly hyperbolic: "hyperbolic";
    readonly siliconflow: "siliconflow";
    readonly friendli: "friendli";
    readonly "friendli-ai": "friendli";
    readonly "cloudflare-workers-ai": "cloudflare-workers-ai";
    readonly "workers-ai": "cloudflare-workers-ai";
    readonly featherless: "featherless";
    readonly "featherless-ai": "featherless";
    readonly nscale: "nscale";
    readonly ovhcloud: "ovhcloud";
    readonly ovh: "ovhcloud";
    readonly scaleway: "scaleway";
    readonly "nvidia-nim": "nvidia-nim";
    readonly nim: "nvidia-nim";
    readonly "runpod-vllm": "runpod-vllm";
    readonly runpod: "runpod-vllm";
    readonly "sagemaker-vllm": "sagemaker-vllm";
    readonly sagemaker: "sagemaker-vllm";
    readonly vllm: "vllm";
    readonly ollama: "ollama";
    readonly "lm-studio": "lm-studio";
    readonly lmstudio: "lm-studio";
    readonly "llama-cpp": "llama-cpp";
    readonly "llama.cpp": "llama-cpp";
    readonly localai: "localai";
    readonly "local-ai": "localai";
    readonly "baseten-engine": "baseten-engine";
    readonly truss: "baseten-engine";
    readonly typesafe: "typesafe";
};
declare const axAIProviderProfileIds: readonly ["openai", "openai-compatible", "openai-responses", "anthropic", "google-gemini", "webllm", "azure-openai", "deepseek", "deepseek-responses", "meta", "meta-chat", "meta-messages", "mistral", "cohere", "grok", "reka", "together", "openrouter", "orcarouter", "fireworks", "huggingface-router", "amazon-bedrock", "azure-foundry", "vertex-ai", "databricks", "baseten", "groq", "cerebras", "deepinfra", "sambanova", "nebius", "novita", "hyperbolic", "siliconflow", "friendli", "cloudflare-workers-ai", "featherless", "nscale", "ovhcloud", "scaleway", "nvidia-nim", "runpod-vllm", "sagemaker-vllm", "vllm", "ollama", "lm-studio", "llama-cpp", "localai", "baseten-engine", "typesafe"];

type AxServiceTierMap = Readonly<Partial<Record<AxServiceTier, string | null>>>;
declare const axNormalizeRequestedServiceTier: (value: unknown) => AxServiceTier | undefined;
declare const axNormalizeAppliedServiceTier: (value: unknown) => AxAppliedServiceTier | undefined;
declare const axResolveServiceTier: ({ requested, fallback, supported, mapping, provider, model, }: Readonly<{
    requested?: unknown;
    fallback?: unknown;
    supported?: readonly AxServiceTier[];
    mapping?: AxServiceTierMap;
    provider: string;
    model: string;
}>) => string | undefined;

type AxAIProfileId = keyof typeof axAIProviderProfiles;
type AxAIProfileTransport = 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'gemini-generate-content' | 'webllm' | 'typesafe-system-one';
type AxAIProfileCapabilities = {
    functions: boolean;
    functionEmulation?: boolean;
    requiresStructuredOutput?: boolean;
    responseFormatWithFunctions?: boolean;
    streaming: boolean;
    structuredOutputs: boolean;
    structuredOutputModes: readonly AxStructuredOutputRung[];
    thinking: boolean;
    multiTurn: boolean;
    serviceTiers?: readonly AxServiceTier[];
    thinkingBudget?: boolean;
    showThoughts?: boolean;
    images?: boolean;
    audio?: boolean;
    audioOutput?: boolean;
    files?: {
        uploadMethod: 'inline' | 'upload' | 'cloud';
    };
    webSearch?: boolean;
    caching?: {
        types: readonly ('ephemeral' | 'persistent')[];
        cacheBreakpoints?: boolean;
    };
};
type AxAIProfileRequestRules = {
    reasoning?: 'thinking-object' | 'effort' | 'openrouter';
    toolChoice?: 'supported' | 'unforced' | 'no-named';
    defaultThinkingLevel?: NonNullable<AxAIServiceOptions['thinkingTokenBudget']> | 'xhigh' | 'max';
    effortMap?: Readonly<Record<string, string | null>>;
    unsupportedThinkingLevels?: Readonly<Record<string, string>>;
    dropWhenThinking?: readonly string[];
    dropFields?: readonly string[];
    copyFields?: Readonly<Record<string, string>>;
    renameFields?: Readonly<Record<string, string>>;
    enumMaps?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
    constructObjects?: Readonly<Record<string, Readonly<Record<string, string>>>>;
    imageURLShape?: 'object';
    reasoningObjectFields?: readonly string[];
    optionDialect?: 'search-parameters';
    thinkingBoolean?: {
        path: readonly string[];
    };
    serviceTierMap?: AxServiceTierMap;
};
type AxAIProfileModelRule = {
    match: {
        exact?: readonly string[];
        prefix?: readonly string[];
        contains?: readonly string[];
    };
    capabilities?: Partial<AxAIProfileCapabilities>;
    request?: AxAIProfileRequestRules;
    response?: {
        reasoningFields?: readonly string[];
        reasoningDetailsFields?: readonly string[];
    };
    replay?: {
        assistantReasoningField?: string;
        assistantReasoningDetailsField?: string;
    };
};
type AxAIProfileAuthentication = {
    type: 'bearer' | 'api-key-header' | 'api-key-query' | 'x-api-key' | 'none';
    header?: string;
    required: boolean;
};
type AxAIProfileOperation = {
    path: string;
    dialect: string;
    url?: string;
    /** Model an operation such as `speak` or `transcribe` uses when none is given. */
    defaultModel?: string;
    /** Request body encoding; transcription defaults to multipart upload. */
    body?: 'json' | 'multipart';
    /** Response encoding; speech defaults to raw binary audio. */
    response?: 'json' | 'binary';
};
type AxAIProfileEndpoint = {
    scheme?: string;
    hostField: string;
    hostSuffix: string;
    path: string;
    fields?: Readonly<Record<string, readonly string[]>>;
    required: readonly string[];
    defaults?: Readonly<Record<string, string>>;
    normalizers?: Readonly<Record<string, 'api-version'>>;
    apiVersionField?: string;
};
type AxAIProfileSummary = Readonly<{
    id: AxAIProfileId;
    name: string;
    aliases: readonly string[];
    transport: AxAIProfileTransport;
    baseURL?: string;
    requiresApiURL: boolean;
    endpoint?: Readonly<AxAIProfileEndpoint>;
    defaultModel?: string;
    defaultEmbedModel?: string;
    authentication: Readonly<AxAIProfileAuthentication>;
    operations: Readonly<Record<string, Readonly<AxAIProfileOperation>>>;
    modelRules: readonly Readonly<AxAIProfileModelRule>[];
    capabilities: Readonly<AxAIProfileCapabilities>;
    unsupportedThinkingLevels?: readonly NonNullable<AxAIServiceOptions['thinkingTokenBudget']>[];
    sources: readonly string[];
    reviewedAt: string;
}>;
declare const axAIProfiles: () => readonly AxAIProfileSummary[];
declare const axGetAIProfile: (name: string) => AxAIProfileSummary;
declare const axResolveAIProfileId: (name: string) => AxAIProfileId;
declare const axResolveAIProfileFeatures: (name: string, model: string) => AxAIFeatures;
type AxAIProfileArgs<TModelKey = string> = {
    name: AxAIProfileId;
    apiKey?: string;
    credentialProvider?: AxAICredentialProvider;
    apiURL?: string;
    config?: Partial<AxAIOpenAIConfig<string, string>>;
    options?: Readonly<AxAIServiceOptions> & Record<string, unknown>;
    modelInfo?: AxModelInfo[];
    models?: AxAIInputModelList<string, string, TModelKey>;
    resourceName?: string;
    deploymentName?: string;
    version?: string;
};
type AxAIDeploymentProfileId = Exclude<AxAIProfileId, 'openai' | 'openai-responses' | 'anthropic' | 'google-gemini' | 'webllm' | 'typesafe' | 'meta' | 'meta-chat' | 'meta-messages'>;
type AxAIDeploymentProfileArgs<TModelKey = string> = Omit<AxAIProfileArgs<TModelKey>, 'name'> & {
    name: AxAIDeploymentProfileId;
};
declare class AxAIOpenAIProfile<TModelKey = string> extends AxAIOpenAIBase<string, string, TModelKey> {
    private readonly profileSpec;
    private readonly profileApiURL;
    constructor(args: Readonly<AxAIProfileArgs<TModelKey>>);
    transcribe(req: Readonly<AxTranscriptionRequest<string | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<string | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
}
declare class AxAIOpenAIResponsesProfile<TModelKey = string> extends AxAIOpenAIResponsesBase<string, string, TModelKey, AxAIOpenAIResponsesRequest<string>> {
    private readonly profileSpec;
    private readonly profileApiURL;
    constructor(args: Readonly<AxAIProfileArgs<TModelKey>>);
    transcribe(req: Readonly<AxTranscriptionRequest<string | TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
}
type AxAIOpenAIProfileArgs<TModelKey> = AxAIOpenAIArgs<AxAIProfileId, string, string, TModelKey>;

/**
 * WebLLM: Models for text generation
 * Based on WebLLM's supported models
 */
declare enum AxAIWebLLMModel {
    Llama31_8B_Instruct = "Llama-3.1-8B-Instruct-q4f32_1-MLC",
    Llama31_70B_Instruct = "Llama-3.1-70B-Instruct-q4f16_1-MLC",
    Llama32_1B_Instruct = "Llama-3.2-1B-Instruct-q4f32_1-MLC",
    Llama32_3B_Instruct = "Llama-3.2-3B-Instruct-q4f32_1-MLC",
    Mistral7B_Instruct = "Mistral-7B-Instruct-v0.3-q4f32_1-MLC",
    Phi35_Mini_Instruct = "Phi-3.5-mini-instruct-q4f32_1-MLC",
    Gemma2_2B_Instruct = "gemma-2-2b-it-q4f32_1-MLC",
    Gemma2_9B_Instruct = "gemma-2-9b-it-q4f32_1-MLC",
    Qwen2_5_0_5B_Instruct = "Qwen2.5-0.5B-Instruct-q4f32_1-MLC",
    Qwen2_5_1_5B_Instruct = "Qwen2.5-1.5B-Instruct-q4f32_1-MLC",
    Qwen2_5_3B_Instruct = "Qwen2.5-3B-Instruct-q4f32_1-MLC",
    Qwen2_5_7B_Instruct = "Qwen2.5-7B-Instruct-q4f32_1-MLC"
}
type AxAIWebLLMModelId = AxAIWebLLMModel | (string & {});
interface AxAIWebLLMEngine {
    chat: {
        completions: {
            create: (request: Readonly<AxAIWebLLMChatRequest>) => Promise<AxAIWebLLMChatResponse | AsyncIterable<AxAIWebLLMChatResponseDelta> | ReadableStream<AxAIWebLLMChatResponseDelta>>;
        };
    };
}
/**
 * WebLLM: Model options for text generation
 */
type AxAIWebLLMConfig = AxModelConfig & {
    model: AxAIWebLLMModelId;
    supportsFunctions?: boolean;
    logitBias?: Record<number, number>;
    logProbs?: boolean;
    topLogprobs?: number;
};
/**
 * WebLLM: Chat request structure
 * Based on OpenAI-compatible API from WebLLM
 */
type AxAIWebLLMChatRequest = {
    model: AxAIWebLLMModelId;
    messages: Array<{
        role: 'system' | 'user';
        content?: string;
        name?: string;
    } | {
        role: 'assistant';
        content?: string;
        name?: string;
        tool_calls?: Array<{
            id: string;
            type: 'function';
            function: {
                name: string;
                arguments: string;
            };
        }>;
    } | {
        role: 'tool';
        content: string;
        tool_call_id: string;
    }>;
    temperature?: number;
    top_p?: number;
    max_tokens?: number;
    stream?: boolean;
    stop?: string | string[];
    presence_penalty?: number;
    frequency_penalty?: number;
    logit_bias?: Record<number, number>;
    logprobs?: boolean;
    top_logprobs?: number;
    response_format?: {
        type: 'json_object';
    } | {
        type: 'json_schema';
        json_schema?: unknown;
    };
    n?: number;
    stream_options?: {
        include_usage?: boolean;
    };
    tools?: Array<{
        type: 'function';
        function: {
            name: string;
            description: string;
            parameters: object;
        };
    }>;
    tool_choice?: 'none' | 'auto' | 'required' | {
        type: 'function';
        function: {
            name: string;
        };
    };
};
/**
 * WebLLM: Chat response structure
 */
type AxAIWebLLMChatResponse = {
    id: string;
    object: 'chat.completion';
    created: number;
    model: AxAIWebLLMModelId;
    choices: Array<{
        index: number;
        message: {
            role: 'assistant';
            content?: string;
            tool_calls?: Array<{
                id: string;
                type: 'function';
                function: {
                    name: string;
                    arguments: string;
                };
            }>;
        };
        finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter';
        logprobs?: {
            content: Array<{
                token: string;
                logprob: number;
                bytes: number[];
                top_logprobs: Array<{
                    token: string;
                    logprob: number;
                    bytes: number[];
                }>;
            }>;
        };
    }>;
    usage: {
        prompt_tokens: number;
        completion_tokens: number;
        total_tokens: number;
    };
};
/**
 * WebLLM: Streaming chat response structure
 */
type AxAIWebLLMChatResponseDelta = {
    id: string;
    object: 'chat.completion.chunk';
    created: number;
    model: AxAIWebLLMModelId;
    choices: Array<{
        index: number;
        delta: {
            role?: 'assistant';
            content?: string;
            tool_calls?: Array<{
                index: number;
                id?: string;
                type?: 'function';
                function?: {
                    name?: string;
                    arguments?: string;
                };
            }>;
        };
        finish_reason?: 'stop' | 'length' | 'tool_calls' | 'content_filter';
        logprobs?: {
            content: Array<{
                token: string;
                logprob: number;
                bytes: number[];
                top_logprobs: Array<{
                    token: string;
                    logprob: number;
                    bytes: number[];
                }>;
            }>;
        };
    }>;
    usage?: {
        prompt_tokens: number;
        completion_tokens: number;
        total_tokens: number;
    };
};
/**
 * WebLLM doesn't support embeddings natively
 * This is a placeholder for consistency with the framework
 */
type AxAIWebLLMEmbedModel = never;
type AxAIWebLLMEmbedRequest = never;
type AxAIWebLLMEmbedResponse = never;

declare const axAIWebLLMDefaultConfig: () => AxAIWebLLMConfig;
declare const axAIWebLLMCreativeConfig: () => AxAIWebLLMConfig;
interface AxAIWebLLMArgs<TModelKey> {
    name: 'webllm';
    engine: AxAIWebLLMEngine;
    config?: Readonly<Partial<AxAIWebLLMConfig>>;
    options?: Readonly<AxAIServiceOptions>;
    models?: AxAIInputModelList<AxAIWebLLMModelId, AxAIWebLLMEmbedModel, TModelKey>;
}
declare class AxAIWebLLM<TModelKey> extends AxBaseAI<AxAIWebLLMModelId, AxAIWebLLMEmbedModel, AxAIWebLLMChatRequest, AxAIWebLLMEmbedRequest, AxAIWebLLMChatResponse, AxAIWebLLMChatResponseDelta, AxAIWebLLMEmbedResponse, TModelKey> {
    constructor({ engine, config, options, models, }: Readonly<Omit<AxAIWebLLMArgs<TModelKey>, 'name'>>);
}

declare enum AxAIGrokModel {
    Grok46 = "grok-4.6",
    Grok45 = "grok-4.5",
    Grok45Latest = "grok-4.5-latest",
    GrokBuildLatest = "grok-build-latest",
    Grok43 = "grok-4.3",
    Grok43Latest = "grok-4.3-latest",
    GrokLatest = "grok-latest",
    Grok420Reasoning = "grok-4.20-reasoning",
    Grok420Reasoning0309 = "grok-4.20-0309-reasoning",
    Grok420NonReasoning = "grok-4.20-non-reasoning",
    Grok420NonReasoning0309 = "grok-4.20-0309-non-reasoning",
    Grok420MultiAgent = "grok-4.20-multi-agent",
    Grok420MultiAgent0309 = "grok-4.20-multi-agent-0309",
    Grok41FastReasoning = "grok-4-1-fast-reasoning",
    Grok41FastNonReasoning = "grok-4-1-fast-non-reasoning",
    GrokVoiceThinkFast = "grok-voice-think-fast-1.0",
    GrokVoiceFast = "grok-voice-fast-1.0",
    Grok3 = "grok-3",
    Grok3Mini = "grok-3-mini",
    Grok3Fast = "grok-3-fast",
    Grok3MiniFast = "grok-3-mini-fast"
}
declare enum AxAIGrokEmbedModels {
    GrokEmbedSmall = "grok-embed-small"
}

type AxAIArgs<TModelKey> = AxAIOpenAIArgs<'openai', AxAIOpenAIModel, AxAIOpenAIEmbedModel, TModelKey> | AxAIOpenAIResponsesArgs<'openai-responses', AxAIOpenAIResponsesModel, AxAIOpenAIEmbedModel, TModelKey> | AxAIAnthropicArgs<TModelKey> | AxAIGoogleGeminiArgs<TModelKey> | AxAIMetaArgs<TModelKey> | AxAITypesafeArgs<TModelKey> | AxAIDeploymentProfileArgs<TModelKey> | AxAIWebLLMArgs<TModelKey>;
type AxAIModels = AxAIOpenAIModel | AxAIAnthropicModel | AxAIGoogleGeminiModel | AxAICohereModel | AxAIMistralModel | AxAIMetaModel | AxAIDeepSeekModel | AxAIWebLLMModelId | AxAIGrokModel;
type AxAIEmbedModels = AxAIOpenAIEmbedModel | AxAIGoogleGeminiEmbedModel | AxAICohereEmbedModel;
type ExtractModelKeysAndValues<T> = T extends readonly {
    key: infer K;
    model: infer M;
}[] ? K | M : never;
type InferTModelKey<T> = T extends {
    models: infer M;
} ? ExtractModelKeysAndValues<M> : string;
/**
 * Factory function for creating AI service instances with full type safety.
 *
 * This is the recommended way to create AI instances. It automatically selects
 * the appropriate provider implementation based on the `name` field and provides
 * type-safe access to provider-specific models.
 *
 * **Supported Providers:**
 * - `'openai'` - OpenAI (GPT-4, GPT-4o, o1, o3, etc.)
 * - `'openai-responses'` - OpenAI Responses API (for web search, file search)
 * - `'anthropic'` - Anthropic (Claude 3.5 Sonnet, Claude 3 Opus, etc.)
 * - `'google-gemini'` - Google (Gemini 1.5 Pro, Gemini 2.0 Flash, etc.)
 * - `'azure-openai'` - Azure OpenAI Service
 * - `'cohere'` - Cohere (Command R+, embeddings)
 * - `'mistral'` - Mistral AI (Mistral Large, Codestral)
 * - `'deepseek'` - DeepSeek (DeepSeek-V4-Flash, DeepSeek-V4-Pro)
 * - `'deepseek-responses'` - DeepSeek's stateless Responses API
 * - `'reka'` - Reka AI
 * - `'grok'` - xAI Grok
 * // axir-nonportable:start webllm
 * - `'webllm'` - WebLLM browser runtime with a caller-supplied MLCEngine
 * // axir-nonportable:end webllm
 *
 * @param options - Provider-specific configuration. Must include `name` to identify the provider.
 * @param options.name - The provider identifier (see list above)
 * @param options.apiKey - API key for the provider
 * @param options.config - Optional default model configuration (maxTokens, temperature, etc.)
 * @param options.models - Optional custom model aliases for type-safe model selection
 *
 * @returns A configured AI service instance ready for chat completions and embeddings
 *
 * @see {@link AxModelConfig} for model configuration options
 * @see {@link AxAIServiceOptions} for runtime options like streaming and function calling
 *
 * @example Basic OpenAI setup
 * ```typescript
 * const ai = ai({
 *   name: 'openai',
 *   apiKey: process.env.OPENAI_API_KEY
 * });
 * ```
 *
 * @example Anthropic with custom defaults
 * ```typescript
 * const ai = ai({
 *   name: 'anthropic',
 *   apiKey: process.env.ANTHROPIC_API_KEY,
 *   config: {
 *     model: 'claude-sonnet-5',
 *     maxTokens: 4096
 *   }
 * });
 * ```
 *
 * @example Google Gemini with model aliases
 * ```typescript
 * const ai = ai({
 *   name: 'google-gemini',
 *   apiKey: process.env.GOOGLE_API_KEY,
 *   models: [
 *     { key: 'fast', model: 'gemini-3.5-flash-lite' },
 *     { key: 'smart', model: 'gemini-3.8-flash' }
 *   ]
 * });
 * // Now use ai with model: 'fast' or model: 'smart'
 * ```
 *
 * @example OpenAI-compatible endpoint
 * ```typescript
 * const ai = ai({
 *   name: 'openai',
 *   apiKey: process.env.PROVIDER_API_KEY,
 *   apiURL: 'https://example.com/v1',
 *   config: { model: 'provider/model-name' }
 * });
 * ```
 */
declare function ai<const T extends AxAIArgs<any>>(options: T): AxAI<InferTModelKey<T>>;
declare class AxAI<TModelKey = string> implements AxAIService<any, any, TModelKey> {
    private ai;
    private responsesClient?;
    private responsesAI?;
    private sessionConfig?;
    private sessionModels?;
    private defaultModel?;
    private lastSessionModel?;
    static create<const T extends AxAIArgs<any>>(options: T): AxAI<InferTModelKey<T>>;
    private constructor();
    getName(): string;
    getId(): string;
    getFeatures(model?: string): AxAIFeatures;
    getModelList(): AxAIModelList<TModelKey> | undefined;
    getLastUsedChatModel(): any;
    getLastUsedEmbedModel(): any;
    getLastUsedModelConfig(): AxModelConfig | undefined;
    getMetrics(): AxAIServiceMetrics;
    getEstimatedCost(modelUsage?: AxModelUsage): number;
    validateChatRequest(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): void;
    chat(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatResponse | ReadableStream<AxChatResponse>>;
    private resolveModel;
    openChatSession(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatSession>;
    embed(req: Readonly<AxEmbedRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxEmbedResponse>;
    transcribe(req: Readonly<AxTranscriptionRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
    setOptions(options: Readonly<AxAIServiceOptions>): void;
    getOptions(): Readonly<AxAIServiceOptions>;
    getLogger(): AxLoggerFunction;
}

type AxAIModelCatalogProviderName = AxAIArgs<string>['name'];
/** Portable thinking levels accepted by Ax for a catalog provider or model. */
type AxAIModelCatalogThinkingLevel = NonNullable<AxAIServiceOptions['thinkingTokenBudget']>;
type AxAIModelCatalogModelCapabilities = {
    thinkingBudget: boolean;
    /** Portable Ax thinking levels accepted for this model. Levels may collapse onto the same provider-native value. */
    thinkingLevels: AxAIModelCatalogThinkingLevel[];
    showThoughts: boolean;
    structuredOutputs: boolean;
    temperature: boolean;
    topP: boolean;
    audioInput: boolean;
    audioOutput: boolean;
    /** Omitted when the bundled model metadata does not declare exact modalities. */
    textInput?: boolean;
    imageInput?: boolean;
    videoInput?: boolean;
    pdfInput?: boolean;
    textOutput?: boolean;
    imageOutput: boolean;
    /** Verified explicit request tiers. `auto` remains available as the provider-delegated policy. */
    serviceTiers: AxServiceTier[];
};
type AxAIModelCatalogProviderCapabilities = {
    thinking: boolean;
    /** Portable Ax thinking levels accepted by the provider's default model. */
    thinkingLevels: AxAIModelCatalogThinkingLevel[];
    /** Verified explicit request tiers for the provider's default deployment profile. */
    serviceTiers: AxServiceTier[];
};
type AxAIModelCatalogAudioSupport = {
    input?: boolean;
    output?: boolean;
};
type AxAIModelCatalogModelType = 'text' | 'embeddings' | 'code' | 'audio' | 'image';
type AxAIModelCatalogFilter = 'all' | AxAIModelCatalogModelType;
type AxAIModelCatalogModel = AxModelInfo & {
    provider: AxAIModelCatalogProviderName;
    audio?: AxAIModelCatalogAudioSupport;
    type: AxAIModelCatalogModelType;
    isDefault: boolean;
    capabilities: AxAIModelCatalogModelCapabilities;
};
type AxAIModelCatalogProvider = {
    name: AxAIModelCatalogProviderName;
    displayName: string;
    defaultModel?: string;
    defaultEmbedModel?: string;
    isDynamic: boolean;
    capabilities: AxAIModelCatalogProviderCapabilities;
    models: AxAIModelCatalogModel[];
};
type AxAIModelCatalogOptions = {
    type?: AxAIModelCatalogFilter | readonly AxAIModelCatalogFilter[];
};
/**
 * Returns the static Ax AI provider/model catalog.
 *
 * The catalog is built from bundled Ax metadata and does not fetch live provider
 * pricing. Dynamic providers can support arbitrary user-selected models or
 * deployments, so their model lists are intentionally empty or static-limited.
 */
declare const axGetSupportedAIModels: (options?: Readonly<AxAIModelCatalogOptions>) => AxAIModelCatalogProvider[];

declare const axModelInfoCohere: AxModelInfo[];

declare const axModelInfoDeepSeek: AxModelInfo[];

/**
 * AxAIGoogleGemini: Model information
 */
declare const axModelInfoGoogleGemini: AxModelInfo[];

declare const axModelInfoMetaSpark: AxModelInfo[];
declare const axModelInfoMetaMessages: AxModelInfo[];
declare const axModelInfoMeta: AxModelInfo[];

interface AxAIMetricsInstruments {
    latencyHistogram?: Histogram;
    errorCounter?: Counter;
    requestCounter?: Counter;
    tokenCounter?: Counter;
    inputTokenCounter?: Counter;
    outputTokenCounter?: Counter;
    errorRateGauge?: Gauge;
    meanLatencyGauge?: Gauge;
    p95LatencyGauge?: Gauge;
    p99LatencyGauge?: Gauge;
    streamingRequestsCounter?: Counter;
    functionCallsCounter?: Counter;
    functionCallLatencyHistogram?: Histogram;
    requestSizeHistogram?: Histogram;
    responseSizeHistogram?: Histogram;
    temperatureGauge?: Gauge;
    maxTokensGauge?: Gauge;
    estimatedCostCounter?: Counter;
    promptLengthHistogram?: Histogram;
    contextWindowUsageGauge?: Gauge;
    timeoutsCounter?: Counter;
    abortsCounter?: Counter;
    thinkingBudgetUsageCounter?: Counter;
    multimodalRequestsCounter?: Counter;
    cacheReadTokensCounter?: Counter;
    cacheWriteTokensCounter?: Counter;
}

declare const axModelInfoMistral: AxModelInfo[];

type AxMockAIServiceConfig<TModelKey> = {
    name?: string;
    id?: string;
    modelInfo?: Partial<AxModelInfoWithProvider>;
    embedModelInfo?: AxModelInfoWithProvider;
    features?: {
        functions?: boolean;
        streaming?: boolean;
        structuredOutputs?: boolean;
        structuredOutputModes?: AxAIFeatures['structuredOutputModes'];
        responseFormatWithFunctions?: boolean;
        serviceTiers?: AxAIFeatures['serviceTiers'];
        media?: Partial<AxAIFeatures['media']>;
    };
    models?: AxAIModelList<TModelKey>;
    options?: AxAIServiceOptions;
    chatResponse?: AxChatResponse | ReadableStream<AxChatResponse> | (() => Promise<AxChatResponse | ReadableStream<AxChatResponse>>) | ((req: Readonly<AxChatRequest<unknown>>, options?: Readonly<AxAIServiceOptions>) => Promise<AxChatResponse | ReadableStream<AxChatResponse>>);
    embedResponse?: AxEmbedResponse | ((req: Readonly<AxEmbedRequest>) => AxEmbedResponse | Promise<AxEmbedResponse>);
    transcribeResponse?: AxTranscriptionResponse | ((req: Readonly<AxTranscriptionRequest<unknown>>) => AxTranscriptionResponse | Promise<AxTranscriptionResponse>);
    speechResponse?: AxSpeechResponse | ((req: Readonly<AxSpeechRequest<unknown>>) => AxSpeechResponse | Promise<AxSpeechResponse>);
    shouldError?: boolean;
    errorMessage?: string;
    latencyMs?: number;
};
declare class AxMockAIService<TModelKey> implements AxAIService<unknown, unknown, TModelKey> {
    private readonly config;
    private metrics;
    constructor(config?: AxMockAIServiceConfig<TModelKey>);
    getLastUsedChatModel(): unknown;
    getLastUsedEmbedModel(): unknown;
    getLastUsedModelConfig(): AxModelConfig | undefined;
    getName(): string;
    getId(): string;
    getFeatures(_model?: string): AxAIFeatures;
    getModelList(): AxAIModelList<TModelKey> | undefined;
    getMetrics(): AxAIServiceMetrics;
    getEstimatedCost(): number;
    chat(req: Readonly<AxChatRequest<unknown>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatResponse | ReadableStream<AxChatResponse>>;
    embed(req: Readonly<AxEmbedRequest>, _options?: Readonly<AxAIServiceOptions>): Promise<AxEmbedResponse>;
    transcribe(req: Readonly<AxTranscriptionRequest<unknown>>, _options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<unknown>>, _options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
    setOptions(options: Readonly<AxAIServiceOptions>): void;
    getOptions(): Readonly<AxAIServiceOptions>;
    getLogger(): AxLoggerFunction;
    private updateMetrics;
}

type AxAIServiceListItem<TModel = unknown, TEmbedModel = unknown, TModelKey = string> = {
    key: TModelKey;
    service: AxAIService<TModel, TEmbedModel, TModelKey>;
    description: string;
    isInternal?: boolean;
};
type ExtractServiceModelKeys<T> = T extends AxAIService<any, any, infer K> ? K : T extends AxAIServiceListItem<any, any, infer K> ? K : never;
type ExtractAllModelKeys<T extends readonly any[]> = T extends readonly [
    infer First,
    ...infer Rest
] ? ExtractServiceModelKeys<First> | ExtractAllModelKeys<Rest> : never;
declare class AxMultiServiceRouter<TServices extends readonly (AxAIService | AxAIServiceListItem<any, any, any>)[] = readonly AxAIService[], TModelKey = ExtractAllModelKeys<TServices>> implements AxAIService<unknown, unknown, TModelKey> {
    private options?;
    private lastUsedService?;
    private services;
    /**
     * Constructs a new multi-service router.
     * It validates that each service provides a unique set of model keys,
     * then builds a lookup (map) for routing the chat/embed requests.
     */
    constructor(services: TServices);
    /**
     * Static factory method for type-safe multi-service router creation with automatic model key inference.
     */
    static create<const TServices extends readonly (AxAIService | AxAIServiceListItem<any, any, any>)[]>(services: TServices): AxMultiServiceRouter<TServices, ExtractAllModelKeys<TServices>>;
    getLastUsedChatModel(): unknown | undefined;
    getLastUsedEmbedModel(): unknown | undefined;
    getLastUsedModelConfig(): AxModelConfig | undefined;
    /**
     * Delegates the chat call to the service matching the provided model key.
     */
    resolveChatService(req: Readonly<AxChatRequest<TModelKey>>): Promise<{
        service: Readonly<AxAIService<unknown, unknown, any>>;
        model?: string;
    }>;
    openChatSession(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatSession>;
    chat(req: Readonly<AxChatRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxChatResponse | ReadableStream<AxChatResponse>>;
    /**
     * Delegates the embed call to the service matching the provided embed model key.
     */
    embed(req: Readonly<AxEmbedRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxEmbedResponse>;
    transcribe(req: Readonly<AxTranscriptionRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxTranscriptionResponse>;
    speak(req: Readonly<AxSpeechRequest<TModelKey>>, options?: Readonly<AxAIServiceOptions>): Promise<AxSpeechResponse>;
    /**
     * Returns a composite ID built from the IDs of the underlying services.
     */
    getId(): string;
    /**
     * Returns the name of this router.
     */
    getName(): string;
    /**
     * Aggregates all available models across the underlying services.
     */
    getModelList(): AxAIModelList<TModelKey>;
    /**
     * If a model key is provided, delegate to the corresponding service's features.
     * Otherwise, returns a default feature set.
     */
    getFeatures(model?: TModelKey): AxAIFeatures;
    /**
     * Returns aggregated metrics from the underlying service.
     * Uses the metrics from the last service that was used,
     * or falls back to the first service if none has been used.
     */
    getMetrics(): AxAIServiceMetrics;
    getEstimatedCost(modelUsage?: AxModelUsage): number;
    /**
     * Sets options on all underlying services.
     */
    setOptions(options: Readonly<AxAIServiceOptions>): void;
    /**
     * Returns the options from the last used service,
     * or falls back to the first service if none has been used.
     */
    getOptions(): Readonly<AxAIServiceOptions>;
    /**
     * Returns the logger from the last used service,
     * or falls back to the first service if none has been used.
     */
    getLogger(): AxLoggerFunction;
    /**
     * Sets a service entry for a given key. This method is intended for testing purposes.
     * @param key - The model key
     * @param entry - The service entry to set
     */
    setServiceEntry(key: TModelKey, entry: {
        isInternal?: boolean;
        description: string;
        model?: string;
        embedModel?: string;
        service: AxAIService<unknown, unknown, TModelKey>;
    }): void;
}

/**
 * OpenAI: Model information
 */
declare const axModelInfoOpenAI: AxModelInfo[];
/**
 * OpenAI: Model information
 */
declare const axModelInfoOpenAIResponses: AxModelInfo[];

type OpenAICompatibleUsageDetails = {
    cached_tokens?: number;
    /**
     * Prompt tokens written to the cache on this request. Present on GPT-5.6+ and
     * billed above the uncached input rate. Writes happen whether or not caching
     * parameters were sent, so dropping this field under-reports cost for every
     * caller, not only those using breakpoints.
     */
    cache_write_tokens?: number;
    reasoning_tokens?: number;
};
type OpenAICompatibleUsage = {
    prompt_tokens?: number;
    input_tokens?: number;
    completion_tokens?: number;
    output_tokens?: number;
    total_tokens?: number;
    service_tier?: string;
    prompt_tokens_details?: OpenAICompatibleUsageDetails;
    input_tokens_details?: OpenAICompatibleUsageDetails;
    completion_tokens_details?: OpenAICompatibleUsageDetails;
    output_tokens_details?: OpenAICompatibleUsageDetails;
};
declare const axNormalizeOpenAIUsage: (usage?: Readonly<OpenAICompatibleUsage> | null, rawServiceTier?: unknown) => AxTokenUsage | undefined;

/**
 * OpenAI: Model information
 */
declare const axModelInfoReka: AxModelInfo[];

declare enum AxAIRekaModel {
    RekaCore = "reka-core",
    RekaFlash = "reka-flash",
    RekaEdge = "reka-edge"
}

/**
 * Services for converting unsupported content types to text or optimized formats
 */
interface AxContentProcessingServices {
    /** Service to convert images to text descriptions */
    imageToText?: (imageData: string) => Promise<string>;
    /** Service to convert audio to text transcriptions */
    audioToText?: (audioData: string, format?: string) => Promise<string>;
    /** Service to extract text from files */
    fileToText?: (fileData: string, mimeType: string) => Promise<string>;
    /** Service to fetch and extract text from URLs */
    urlToText?: (url: string) => Promise<string>;
    /** Service to optimize images for size/quality */
    imageOptimization?: (imageData: string, options: OptimizationOptions) => Promise<string>;
}
/**
 * Options for image optimization processing
 */
interface OptimizationOptions {
    /** Image quality (0-100) */
    quality?: number;
    /** Maximum file size in bytes */
    maxSize?: number;
    /** Target image format */
    format?: 'jpeg' | 'png' | 'webp';
}
/**
 * Configuration for multi-provider routing with fallback capabilities
 */
interface AxMultiProviderConfig {
    /** Provider hierarchy for routing */
    providers: {
        /** Primary provider to try first */
        primary: AxAIService;
        /** Alternative providers for fallback */
        alternatives: AxAIService[];
    };
    /** Routing behavior configuration */
    routing: {
        /** Order of preferences when selecting providers */
        preferenceOrder: ('capability' | 'cost' | 'speed' | 'quality')[];
        /** Capability matching requirements */
        capability: {
            /** Only use providers with full capability support */
            requireExactMatch: boolean;
            /** Allow providers that require content processing fallbacks */
            allowDegradation: boolean;
        };
    };
    /** Content processing services for unsupported media types */
    processing: AxContentProcessingServices;
}
/**
 * Result of the routing process including provider selection and processing information
 */
interface AxRoutingResult {
    /** The selected AI service provider */
    provider: AxAIService;
    /** List of content processing steps that were applied */
    processingApplied: string[];
    /** List of capability degradations that occurred */
    degradations: string[];
    /** Non-critical warnings about the routing decision */
    warnings: string[];
}
/**
 * Multi-provider router that automatically selects optimal AI providers and handles content processing.
 *
 * The router analyzes requests to determine capability requirements, scores available providers,
 * and automatically handles content transformation for unsupported media types. It provides
 * graceful degradation and fallback mechanisms for robust multi-modal AI applications.
 *
 * @example
 * ```typescript
 * const router = new AxProviderRouter({
 *   providers: {
 *     primary: openaiProvider,
 *     alternatives: [geminiProvider, cohereProvider]
 *   },
 *   routing: {
 *     preferenceOrder: ['capability', 'quality'],
 *     capability: {
 *       requireExactMatch: false,
 *       allowDegradation: true
 *     }
 *   },
 *   processing: {
 *     imageToText: async (data) => await visionService.describe(data),
 *     audioToText: async (data) => await speechService.transcribe(data)
 *   }
 * });
 *
 * const result = await router.chat(multiModalRequest);
 * console.log(`Used: ${result.routing.provider.getName()}`);
 * ```
 */
declare class AxProviderRouter {
    private providers;
    private processingServices;
    private config;
    /**
     * Creates a new provider router with the specified configuration.
     *
     * @param config - Router configuration including providers, routing preferences, and processing services
     */
    constructor(config: AxMultiProviderConfig);
    /** Select and pin a provider for one session without failover. */
    openChatSession(request: AxChatRequest, options?: AxAIServiceOptions): Promise<AxChatSession>;
    /**
     * Routes a chat request to the most appropriate provider with automatic content processing.
     *
     * This method analyzes the request, selects the optimal provider, preprocesses content
     * for compatibility, and executes the request with fallback support.
     *
     * @param request - The chat request to process
     * @param options - Extended options including fallback providers and routing preferences
     * @param options.fallbackProviders - Additional providers to try if primary selection fails
     * @param options.processingOptions - Content processing options and conversion services
     * @param options.routingOptions - Provider selection and routing behavior options
     * @param options.routingOptions.requireExactMatch - Only use providers with full capability support
     * @param options.routingOptions.allowDegradation - Allow content processing for unsupported types
     * @param options.routingOptions.maxRetries - Maximum number of fallback providers to try
     * @returns Promise resolving to the AI response and routing information
     * @throws AxMediaNotSupportedError when no suitable provider can handle the request
     *
     * @example
     * ```typescript
     * const result = await router.chat(
     *   { chatPrompt: [{ role: 'user', content: [{ type: 'image', image: '...' }] }] },
     *   {
     *     processingOptions: { fallbackBehavior: 'degrade' },
     *     routingOptions: { allowDegradation: true }
     *   }
     * );
     *
     * console.log(`Provider: ${result.routing.provider.getName()}`);
     * console.log(`Processing applied: ${result.routing.processingApplied}`);
     * ```
     */
    chat(request: AxChatRequest, options?: AxAIServiceOptions & {
        fallbackProviders?: AxAIService[];
        processingOptions?: ProcessingOptions;
        routingOptions?: {
            requireExactMatch?: boolean;
            allowDegradation?: boolean;
            maxRetries?: number;
        };
    }): Promise<{
        response: AxChatResponse | ReadableStream<AxChatResponse>;
        routing: AxRoutingResult;
    }>;
    /**
     * Preprocesses request content for the target provider
     */
    private preprocessRequest;
    /**
     * Selects provider with graceful degradation
     */
    private selectProviderWithDegradation;
    /**
     * Tries fallback providers when primary provider fails
     */
    private tryFallbackProviders;
    /**
     * Gets routing recommendation without executing the request.
     *
     * Analyzes the request and returns routing information including which provider
     * would be selected, what processing would be applied, and any degradations or warnings.
     *
     * @param request - The chat request to analyze
     * @returns Promise resolving to routing result with provider selection and processing info
     *
     * @example
     * ```typescript
     * const recommendation = await router.getRoutingRecommendation(request);
     * console.log(`Would use: ${recommendation.provider.getName()}`);
     * console.log(`Degradations: ${recommendation.degradations.join(', ')}`);
     * ```
     */
    getRoutingRecommendation(request: AxChatRequest): Promise<AxRoutingResult>;
    /**
     * Validates whether the configured providers can handle a specific request.
     *
     * Performs pre-flight validation to check if the request can be successfully
     * processed by available providers, identifies potential issues, and provides
     * recommendations for improving compatibility.
     *
     * @param request - The chat request to validate
     * @returns Promise resolving to validation result with handling capability and recommendations
     *
     * @example
     * ```typescript
     * const validation = await router.validateRequest(request);
     * if (!validation.canHandle) {
     *   console.log('Issues:', validation.issues);
     *   console.log('Recommendations:', validation.recommendations);
     * }
     * ```
     */
    validateRequest(request: AxChatRequest): Promise<{
        canHandle: boolean;
        issues: string[];
        recommendations: string[];
    }>;
    /**
     * Gets detailed statistics about the router's provider capabilities.
     *
     * Returns information about available providers, their supported capabilities,
     * and routing recommendations for analysis and debugging purposes.
     *
     * @returns Object containing provider statistics and capability matrix
     *
     * @example
     * ```typescript
     * const stats = router.getRoutingStats();
     * console.log(`Total providers: ${stats.totalProviders}`);
     * console.log('Capabilities:');
     * for (const [capability, providers] of Object.entries(stats.capabilityMatrix)) {
     *   console.log(`  ${capability}: ${providers.join(', ')}`);
     * }
     * ```
     */
    getRoutingStats(): {
        totalProviders: number;
        capabilityMatrix: {
            [capability: string]: string[];
        };
        recommendedProvider: string;
    };
}

type AxAITypesafeClientOptions = Pick<AxAIServiceOptions, 'fetch' | 'timeout' | 'retry' | 'abortSignal' | 'corsProxy' | 'verbose' | 'includeRequestBodyInErrors'>;
type AxAITypesafeClientArgs = {
    apiKey?: string;
    credentialProvider?: AxAICredentialProvider;
    apiURL?: string;
    model?: string;
    headers?: Readonly<Record<string, string>>;
    options?: Readonly<AxAITypesafeClientOptions>;
};
/** Native Typesafe API. Questions and application decision policies belong to the caller. */
declare class AxAITypesafeClient {
    private readonly args;
    constructor(args: Readonly<AxAITypesafeClientArgs>);
    systemOne<const Q extends AxAITypesafeQuestions>(request: AxAITypesafeRequest<Q>, options?: Readonly<AxAITypesafeClientOptions>): Promise<AxAITypesafeResponse<Q>>;
    listModels(options?: Readonly<AxAITypesafeClientOptions>): Promise<readonly AxAITypesafeModelCard[]>;
    private request;
}
/** Create a native Typesafe client for structured questions and their complete answers. */
declare function typesafe(args: Readonly<AxAITypesafeClientArgs>): AxAITypesafeClient;

declare function axMergeUsageContexts(defaults?: Readonly<AxUsageContext>, overrides?: Readonly<AxUsageContext>): AxUsageContext | undefined;
declare function axEmitUsageEvent(operation: AxUsageEvent['operation'], response: Readonly<AxChatResponse | AxEmbedResponse>, context: Readonly<AxUsageContext> | undefined, streaming: boolean): void;

type AxChatRequestMessage = AxChatRequest['chatPrompt'][number];
/**
 * Validates a chat request message item to ensure it meets the required criteria
 * @param item - The chat request message to validate
 * @throws {Error} When validation fails with a descriptive error message
 */
declare function axValidateChatRequestMessage(item: AxChatRequestMessage): void;
/**
 * Validates a chat response result to ensure it meets the required criteria
 * @param results - The chat response results to validate (single result or array)
 * @throws {Error} When validation fails with a descriptive error message
 */
declare function axValidateChatResponseResult(results: Readonly<AxChatResponseResult[]> | Readonly<AxChatResponseResult>): void;

/**
 * WebLLM model information
 * Note: WebLLM runs models locally in the browser, so there are no API costs
 * However, we include context window and capability information
 */
declare const axModelInfoWebLLM: AxModelInfo[];

declare const axAIGrokDefaultConfig: () => AxAIOpenAIConfig<AxAIGrokModel, AxAIGrokEmbedModels>;
declare const axAIGrokBestConfig: () => AxAIOpenAIConfig<AxAIGrokModel, AxAIGrokEmbedModels>;
declare const axAIGrokVoiceDefaultConfig: () => AxAIOpenAIConfig<AxAIGrokModel, AxAIGrokEmbedModels>;
declare const axIsGrokVoiceModel: (model: string) => boolean;
declare const axResolveGrokRealtimeAudioConfig: (providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => AxChatAudioConfig;
declare const axShouldUseGrokRealtime: (model: string, providerAudio?: Readonly<AxChatAudioConfig>, requestAudio?: Readonly<AxChatAudioConfig>) => boolean;
declare const axCreateGrokRealtimeApi: <TModel>(realtimeRequest: OpenAIRealtimeRequest<TModel>) => AxAPI;

declare const axModelInfoGrok: AxModelInfo[];

type AxDateRange = {
    start: Date;
    end: Date;
};

/**
 * Calculates the Exact Match (EM) score between a prediction and ground truth.
 *
 * The EM score is a strict metric used in machine learning to assess if the predicted
 * answer matches the ground truth exactly, commonly used in tasks like question answering.
 *
 * @param prediction The predicted text.
 * @param groundTruth The actual correct text.
 * @returns A number (1.0 for exact match, 0.0 otherwise).
 */
declare function emScore(prediction: string, groundTruth: string): number;
/**
 * Calculates the F1 score between a prediction and ground truth.
 *
 * The F1 score is a harmonic mean of precision and recall, widely used in NLP to measure
 * a model's accuracy in considering both false positives and false negatives, offering a
 * balance for evaluating classification models.
 *
 * @param prediction The predicted text.
 * @param groundTruth The actual correct text.
 * @returns The F1 score as a number.
 */
declare function f1Score(prediction: string, groundTruth: string): number;
/**
 * Calculates a novel F1 score, taking into account a history of interaction and excluding stopwords.
 *
 * This metric extends the F1 score by considering contextual relevance and filtering out common words
 * that might skew the assessment of the prediction's quality, especially in conversational models or
 * when historical context is relevant.
 *
 * @param history The historical context or preceding interactions.
 * @param prediction The predicted text.
 * @param groundTruth The actual correct text.
 * @param returnRecall Optionally return the recall score instead of F1.
 * @returns The novel F1 or recall score as a number.
 */
declare function novelF1ScoreOptimized(history: string, prediction: string, groundTruth: string, returnRecall?: boolean): number;
declare const AxEvalUtil: {
    emScore: typeof emScore;
    f1Score: typeof f1Score;
    novelF1ScoreOptimized: typeof novelF1ScoreOptimized;
};

type AxEvaluateArgs<IN extends AxGenIn, OUT extends AxGenOut> = {
    ai: AxAIService;
    program: Readonly<AxGen<IN, OUT>>;
    examples: Readonly<AxExample$1[]>;
};
declare class AxTestPrompt<IN extends AxGenIn = AxGenIn, OUT extends AxGenOut = AxGenOut> {
    private ai;
    private program;
    private examples;
    constructor({ ai, program, examples, }: Readonly<AxEvaluateArgs<IN, OUT>>);
    run(metricFn: AxMetricFn): Promise<void>;
}

type AxFunctionResultFormatter = (result: unknown) => string;
declare const axGlobals: {
    signatureStrict: boolean;
    tracer: Tracer | undefined;
    meter: Meter | undefined;
    rateLimiter: AxRateLimiterFunction | undefined;
    logger: AxLoggerFunction | undefined;
    optimizerLogger: AxOptimizerLoggerFunction | undefined;
    debug: boolean | undefined;
    abortSignal: AbortSignal | undefined;
    customLabels: Record<string, string> | undefined;
    onUsage: AxUsageObserver | undefined;
    cachingFunction: ((key: string, value?: AxGenOut) => AxGenOut | undefined | Promise<AxGenOut | undefined>) | undefined;
    functionResultFormatter: AxFunctionResultFormatter;
};

declare const axCreateDefaultColorLogger: (output?: (message: string) => void) => AxLoggerFunction;
declare const axCreateDefaultTextLogger: (output?: (message: string) => void) => AxLoggerFunction;

interface AxMetricsConfig {
    enabled: boolean;
    enabledCategories: ('generation' | 'streaming' | 'functions' | 'errors' | 'performance')[];
    maxLabelLength: number;
    samplingRate: number;
}
declare const axDefaultMetricsConfig: AxMetricsConfig;
type AxErrorCategory = 'validation_error' | 'timeout_error' | 'abort_error' | 'network_error' | 'auth_error' | 'rate_limit_error' | 'function_error' | 'parsing_error' | 'unknown_error';
interface AxGenMetricsInstruments {
    generationLatencyHistogram?: Histogram;
    generationRequestsCounter?: Counter;
    generationErrorsCounter?: Counter;
    multiStepGenerationsCounter?: Counter;
    stepsPerGenerationHistogram?: Histogram;
    maxStepsReachedCounter?: Counter;
    validationErrorsCounter?: Counter;
    errorCorrectionAttemptsHistogram?: Histogram;
    errorCorrectionSuccessCounter?: Counter;
    errorCorrectionFailureCounter?: Counter;
    maxRetriesReachedCounter?: Counter;
    functionsEnabledGenerationsCounter?: Counter;
    functionCallStepsCounter?: Counter;
    functionsExecutedPerGenerationHistogram?: Histogram;
    functionErrorCorrectionCounter?: Counter;
    fieldProcessorsExecutedCounter?: Counter;
    streamingFieldProcessorsExecutedCounter?: Counter;
    streamingGenerationsCounter?: Counter;
    streamingDeltasEmittedCounter?: Counter;
    streamingFinalizationLatencyHistogram?: Histogram;
    samplesGeneratedHistogram?: Histogram;
    resultPickerUsageCounter?: Counter;
    resultPickerLatencyHistogram?: Histogram;
    inputFieldsGauge?: Gauge;
    outputFieldsGauge?: Gauge;
    examplesUsedGauge?: Gauge;
    demosUsedGauge?: Gauge;
    promptRenderLatencyHistogram?: Histogram;
    extractionLatencyHistogram?: Histogram;
    stateCreationLatencyHistogram?: Histogram;
    memoryUpdateLatencyHistogram?: Histogram;
}
declare const axCheckMetricsHealth: () => {
    healthy: boolean;
    issues: string[];
};
declare const axUpdateMetricsConfig: (config: Readonly<Partial<AxMetricsConfig>>) => void;
declare const axGetMetricsConfig: () => AxMetricsConfig;

type AxOptimizeOptions = AxOptimizerArgs & Omit<AxCompileOptions, 'bootstrap'> & {
    bootstrap?: boolean | AxBootstrapOptimizerOptions;
};
declare function optimize<IN, OUT extends AxGenOut>(program: Readonly<AxProgrammable<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn | AxMultiMetricFn, options: Readonly<AxOptimizeOptions>): Promise<AxParetoResult<OUT>>;

/**
 * Factory function to create a default optimizer logger with color formatting
 */
declare const axCreateDefaultOptimizerColorLogger: (output?: (message: string) => void) => AxOptimizerLoggerFunction;
/**
 * Factory function to create a text-only optimizer logger (no colors)
 */
declare const axCreateDefaultOptimizerTextLogger: (output?: (message: string) => void) => AxOptimizerLoggerFunction;
/**
 * Default optimizer logger instance with color formatting
 */
declare const axDefaultOptimizerLogger: AxOptimizerLoggerFunction;

interface AxACECompileOptions extends AxCompileOptions {
    aceOptions?: AxACEOptions;
}
interface AxACEResult<OUT extends AxGenOut> extends AxOptimizerResult<OUT> {
    optimizedProgram?: AxACEOptimizedProgram<OUT>;
    playbook: AxACEPlaybook;
    artifact: AxACEOptimizationArtifact;
}
/**
 * Optimized program artifact that persists ACE playbook updates.
 */
declare class AxACEOptimizedProgram<OUT = any> extends AxOptimizedProgramImpl<OUT> {
    readonly playbook: AxACEPlaybook;
    readonly artifact: AxACEOptimizationArtifact;
    private readonly baseInstruction?;
    constructor(config: {
        baseInstruction?: string;
        playbook: AxACEPlaybook;
        artifact: AxACEOptimizationArtifact;
        bestScore: number;
        stats: AxOptimizationStats;
        optimizerType: string;
        optimizationTime: number;
        totalRounds: number;
        converged: boolean;
        demos?: AxOptimizedProgram<OUT>['demos'];
        examples?: AxExample$1[];
        modelConfig?: AxOptimizedProgram<OUT>['modelConfig'];
        scoreHistory?: number[];
        configurationHistory?: Record<string, unknown>[];
    });
    applyTo<IN, T extends AxGenOut>(program: AxGen<IN, T>): void;
}
/**
 * AxACE implements the Agentic Context Engineering loop (Generator → Reflector → Curator).
 * The implementation mirrors the paper's architecture while integrating with the Ax optimizer
 * ergonomics (unified optimized program artifacts, metrics, and checkpointing).
 */
declare class AxACE extends AxBaseOptimizer {
    private readonly aceConfig;
    private playbook;
    private baseInstruction?;
    private generatorHistory;
    private deltaHistory;
    private reflectorProgram?;
    private curatorProgram?;
    private program?;
    constructor(args: Readonly<AxOptimizerArgs>, options?: Readonly<AxACEOptions>);
    reset(): void;
    hydrate<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, state?: Readonly<{
        baseInstruction?: string;
        playbook?: AxACEPlaybook;
        artifact?: Partial<AxACEOptimizationArtifact>;
    }>): void;
    getPlaybook(): AxACEPlaybook;
    getBaseInstruction(): string | undefined;
    getArtifact(): AxACEOptimizationArtifact;
    applyCurrentState<IN, OUT extends AxGenOut>(program?: AxGen<IN, OUT>): void;
    configureAuto(level: 'light' | 'medium' | 'heavy'): void;
    compile<IN, OUT extends AxGenOut>(program: Readonly<AxGen<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn, options?: AxACECompileOptions): Promise<AxACEResult<OUT>>;
    /**
     * Apply ACE updates after each online inference. Mirrors the online adaptation
     * flow described in the paper; can be called by user-land code between queries.
     */
    applyOnlineUpdate(args: Readonly<{
        example: AxExample$1;
        prediction: unknown;
        feedback?: string;
    }>): Promise<AxACECuratorOutput | undefined>;
    private composeInstruction;
    private createArtifact;
    private extractProgramInstruction;
    private createGeneratorOutput;
    private createMetricFeedback;
    private extractFieldValues;
    private extractBoundedFieldValues;
    private createQuestionContext;
    private createExpectedAnswer;
    private stringifyBounded;
    private boundSerializedValue;
    private boundSerializedFieldValue;
    private truncateSerializedString;
    private resolveCuratorOperationTargets;
    private locateBullet;
    private locateFallbackBullet;
    private collectProtectedBulletIds;
    private normalizeCuratorOperations;
    private runReflectionRounds;
    private runReflector;
    private runCurator;
    private getOrCreateReflectorProgram;
    private getOrCreateCuratorProgram;
}

type AxRolloutTrace<Out = unknown> = {
    calls: AxFunctionCallTrace[];
    output?: Out;
    error?: string;
};

declare class AxBootstrapFewShot extends AxBaseOptimizer {
    private maxRounds;
    private maxDemos;
    private maxExamples;
    private batchSize;
    private earlyStoppingPatience;
    private costMonitoring;
    private maxTokensPerGeneration;
    private verboseMode;
    private debugMode;
    private qualityThreshold;
    private traces;
    constructor(args: Readonly<AxOptimizerArgs & {
        options?: AxBootstrapOptimizerOptions;
    }>);
    private compileRound;
    compile<IN, OUT extends AxGenOut>(program: Readonly<AxProgrammable<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise<AxOptimizerResult<OUT>>;
}

/** Structured optimization report */
interface AxGEPAOptimizationReport {
    summary: string;
    bestSolution: {
        overallScore: number;
        objectives: Record<string, {
            value: number;
            percentage: number;
        }>;
    };
    paretoFrontier: {
        solutionCount: number;
        objectiveSpaceCoverage: number;
        hypervolume: number;
        tradeoffs?: Array<Record<string, number>>;
    };
    statistics: {
        totalEvaluations: number;
        candidatesExplored: number;
        converged: boolean;
    };
    recommendations: {
        status: 'good' | 'limited' | 'single';
        suggestions: string[];
    };
}
/**
 * Internal target descriptor used by AxGEPA: each "target" is one optimizable
 * component (a string-valued artifact identified by a globally unique key) plus
 * the metadata needed by the reflection LLM to mutate it intelligently.
 */
/** Single-module GEPA (reflective prompt evolution with Pareto sampling) */
declare class AxGEPA extends AxBaseOptimizer {
    private numTrials;
    private minibatch;
    private minibatchSize;
    private earlyStoppingTrials;
    private minImprovementThreshold;
    private sampleCount;
    private paretoSetSize;
    private crossoverEvery;
    private tieEpsilon;
    private mergeMax;
    private mergesUsed;
    private mergesDue;
    private totalMergesTested;
    private lastIterFoundNewProgram;
    private mergeAttemptKeys;
    private mergeCompositionKeys;
    private rngState;
    private samplerState;
    private localScoreHistory;
    private localConfigurationHistory;
    constructor(args: Readonly<AxOptimizerArgs>);
    reset(): void;
    /**
     * Multi-objective GEPA: reflective evolution with Pareto frontier
     */
    compile<IN, OUT extends AxGenOut>(program: Readonly<AxProgrammable<IN, OUT>>, examples: readonly AxTypedExample<IN>[], metricFn: AxMetricFn | AxMultiMetricFn, options?: AxCompileOptions): Promise<AxParetoResult<OUT>>;
    /** Lightweight auto presets */
    configureAuto(level: 'light' | 'medium' | 'heavy'): void;
    private evaluateOnSet;
    private evaluateAvg;
    private evaluateOne;
    private reflectTargetInstruction;
    private logTeacherFailure;
    private updateSamplerShuffled;
    private nextMinibatchIndices;
    private rand;
    private systemAwareMergeWithSig;
    private generateOptimizationReport;
}

type AxGEPABatchRow = {
    input: AxExample$1;
    prediction: unknown;
    scores: Record<string, number>;
    scalar: number;
};
type AxGEPABatchEvaluation = {
    rows: AxGEPABatchRow[];
    avg: Record<string, number>;
    scalars: number[];
    sum: number;
    trajectories?: readonly unknown[];
};
type AxGEPAEvaluationState = {
    totalCalls: number;
    observedScoreKeys: Set<string>;
};

type AxGEPAReflectiveTuple = {
    input: AxExample$1;
    prediction: unknown;
    score: number;
};
type AxGEPATraceSummaryCall = {
    componentId?: string;
    fn: string;
    ok: boolean;
    ms: number;
    args: string;
    result: string;
};
type AxGEPATraceSummary = {
    score: number;
    calls: AxGEPATraceSummaryCall[];
    output?: string;
    error?: string;
};

type AxRefineStrategy = 'auto' | 'native-samples' | 'serial';
type AxRewardFnArgs<IN, OUT extends AxGenOut> = {
    input: Readonly<IN>;
    prediction: Readonly<OUT>;
    attempt: number;
    round: number;
    sampleIndex: number;
    traces: readonly AxProgramTrace<IN, OUT>[];
    chatLog: readonly AxChatLogEntry[];
};
type AxRewardFn<IN, OUT extends AxGenOut> = (args: Readonly<AxRewardFnArgs<IN, OUT>>) => number | Promise<number>;
type AxAttempt<IN, OUT extends AxGenOut> = {
    attempt: number;
    round: number;
    sampleIndex: number;
    strategy: Exclude<AxRefineStrategy, 'auto'>;
    input: IN;
    prediction?: OUT;
    reward?: number;
    metThreshold: boolean;
    traces: AxProgramTrace<IN, OUT>[];
    chatLog: AxChatLogEntry[];
    usage: AxProgramUsage[];
    error?: unknown;
    advice?: Record<string, string>;
    adviceApplied?: boolean;
};
type AxBestOfNOptions<IN, OUT extends AxGenOut> = {
    n: number;
    rewardFn: AxRewardFn<IN, OUT>;
    threshold?: number;
    failCount?: number;
    modelConfig?: Partial<AxModelConfig>;
    strategy?: AxRefineStrategy;
    onAttempt?: (attempt: Readonly<AxAttempt<IN, OUT>>) => void | Promise<void>;
};
type AxRefineOptions<IN, OUT extends AxGenOut> = {
    rounds: number;
    samplesPerRound?: number;
    rewardFn: AxRewardFn<IN, OUT>;
    threshold?: number;
    failCount?: number;
    modelConfig?: Partial<AxModelConfig>;
    strategy?: AxRefineStrategy;
    feedbackAI?: Readonly<AxAIService>;
    feedbackModelConfig?: Partial<AxModelConfig>;
    rewardDescription?: string;
    programDescription?: string;
    onAttempt?: (attempt: Readonly<AxAttempt<IN, OUT>>) => void | Promise<void>;
};
type RunBatchArgs<IN> = {
    ai: Readonly<AxAIService>;
    input: IN;
    forwardOptions?: Readonly<AxProgramForwardOptions<any>>;
    count: number;
    round: number;
    failCount: number;
    strategy: Exclude<AxRefineStrategy, 'auto'>;
    threshold?: number;
};
declare class AxRefineError extends Error {
    readonly attempts: readonly AxAttempt<any, any>[];
    constructor(message: string, attempts?: readonly AxAttempt<any, any>[]);
}
declare abstract class AxRefineBase<IN, OUT extends AxGenOut> implements AxProgrammable<IN, OUT> {
    protected readonly program: Readonly<AxProgrammable<IN, OUT>>;
    protected abstract readonly modelConfig?: Partial<AxModelConfig>;
    protected abstract readonly rewardFn: AxRewardFn<IN, OUT>;
    protected attempts: AxAttempt<IN, OUT>[];
    protected selectedAttempt?: AxAttempt<IN, OUT>;
    constructor(program: Readonly<AxProgrammable<IN, OUT>>);
    abstract forward(ai: Readonly<AxAIService>, input: IN, options?: Readonly<AxProgramForwardOptions<any>>): Promise<OUT>;
    getAttempts(): readonly AxAttempt<IN, OUT>[];
    getSignature(): AxSignature;
    getId(): string;
    setId(id: string): void;
    getTraces(): AxProgramTrace<IN, OUT>[];
    namedProgramInstances(): AxNamedProgramInstance<any, any>[];
    setDemos(demos: readonly AxProgramDemos<IN, OUT>[], options?: {
        modelConfig?: Record<string, unknown>;
    }): void;
    applyOptimization(optimizedProgram: AxOptimizedProgram<OUT>): void;
    getOptimizableComponents(): readonly AxOptimizableComponent[];
    applyOptimizedComponents(updates: Readonly<Record<string, string>>): void;
    getUsage(): AxProgramUsage[];
    getChatLog(): readonly AxChatLogEntry[];
    resetUsage(): void;
    streamingForward(_ai: Readonly<AxAIService>, _values: IN, _options?: Readonly<AxProgramStreamingForwardOptions<any>>): AxGenStreamingOut<OUT>;
    protected resetRun(): void;
    protected emitAttempt(onAttempt: AxBestOfNOptions<IN, OUT>['onAttempt'] | undefined, attempt: AxAttempt<IN, OUT>): Promise<void>;
    protected runCandidateBatch({ ai, input, forwardOptions, count, round, failCount, strategy, threshold, }: RunBatchArgs<IN>): Promise<AxAttempt<IN, OUT>[]>;
    private runNativeSampleBatch;
    private runSerialBatch;
    protected selectBest(attempts: readonly AxAttempt<IN, OUT>[]): (AxAttempt<IN, OUT> & {
        prediction: OUT;
        reward: number;
    }) | undefined;
    protected firstThreshold(attempts: readonly AxAttempt<IN, OUT>[]): AxAttempt<IN, OUT> | undefined;
}
declare class AxBestOfN<IN, OUT extends AxGenOut> extends AxRefineBase<IN, OUT> {
    private readonly n;
    private readonly failCount;
    private readonly threshold?;
    private readonly strategy?;
    protected readonly modelConfig?: Partial<AxModelConfig>;
    protected readonly rewardFn: AxRewardFn<IN, OUT>;
    private readonly onAttempt?;
    constructor(program: Readonly<AxProgrammable<IN, OUT>>, options: Readonly<AxBestOfNOptions<IN, OUT>>);
    forward(ai: Readonly<AxAIService>, input: IN, options?: Readonly<AxProgramForwardOptions<any>>): Promise<OUT>;
}
declare class AxRefine<IN, OUT extends AxGenOut> extends AxRefineBase<IN, OUT> {
    private readonly rounds;
    private readonly samplesPerRound;
    private readonly failCount;
    private readonly threshold?;
    private readonly strategy?;
    protected readonly modelConfig?: Partial<AxModelConfig>;
    protected readonly rewardFn: AxRewardFn<IN, OUT>;
    private readonly feedbackAI?;
    private readonly feedbackModelConfig?;
    private readonly rewardDescription?;
    private readonly programDescription?;
    private readonly onAttempt?;
    constructor(program: Readonly<AxProgrammable<IN, OUT>>, options: Readonly<AxRefineOptions<IN, OUT>>);
    forward(ai: Readonly<AxAIService>, input: IN, options?: Readonly<AxProgramForwardOptions<any>>): Promise<OUT>;
    private captureInstructionComponents;
    private applyAdvice;
    private restoreInstructionComponents;
    private generateAdvice;
}
declare function bestOfN<IN, OUT extends AxGenOut>(program: Readonly<AxProgrammable<IN, OUT>>, options: Readonly<AxBestOfNOptions<IN, OUT>>): AxBestOfN<IN, OUT>;
declare function refine<IN, OUT extends AxGenOut>(program: Readonly<AxProgrammable<IN, OUT>>, options: Readonly<AxRefineOptions<IN, OUT>>): AxRefine<IN, OUT>;

interface AxSamplePickerOptions<OUT> {
    resultPicker?: AxResultPickerFunction<OUT>;
}

declare const AxStringUtil: {
    trimNonAlphaNum: (str: string) => string;
    splitIntoTwo: (str: string, separator: Readonly<RegExp | string>) => string[];
    dedup: (seq: readonly string[]) => string[];
    extractIdAndText: (input: string) => {
        id: number;
        text: string;
    };
    extractIndexPrefixedText: (input: string) => string;
    batchArray: <T>(arr: readonly T[], size: number) => T[][];
};

/**
 * AxSynth - Synthetic data generator for bootstrapping optimization datasets.
 *
 * Generates diverse input examples and uses a teacher model to produce
 * high-quality labeled outputs. Solves the "cold start" problem when
 * users have no training data.
 */

/**
 * Configuration for synthetic data generation.
 */
interface AxSynthOptions {
    /** Teacher AI to use for labeling generated inputs */
    teacher: AxAIService;
    /**
     * Diversity strategy for input generation.
     * - 'semantic': Use embeddings to maximize semantic diversity
     * - 'lexical': Use token-based diversity
     * - 'none': No diversity filtering (default)
     */
    diversity?: 'semantic' | 'lexical' | 'none';
    /** Domain context for generating relevant examples */
    domain?: string;
    /**
     * Edge case hints for generating challenging examples.
     * Examples: "empty inputs", "very long queries", "special characters"
     */
    edgeCases?: string[];
    /** Temperature for input generation (default: 0.8) */
    temperature?: number;
    /** Model to use for generation (optional, uses teacher's default) */
    model?: string;
}
/**
 * A single synthesized example with input and expected output.
 */
interface AxSynthExample {
    /** Generated input values */
    input: Record<string, unknown>;
    /** Expected output values from teacher model */
    expected: Record<string, unknown>;
    /** Category of the example (normal, edge case, etc.) */
    category?: string;
}
/**
 * Result from a synthesis run.
 */
interface AxSynthResult {
    /** Generated examples */
    examples: AxSynthExample[];
    /** Statistics about the generation */
    stats: {
        requested: number;
        generated: number;
        labelingSuccessRate: number;
        durationMs: number;
    };
}
/**
 * AxSynth generates synthetic training data.
 *
 * @example
 * ```typescript
 * const synth = new AxSynth(signature, {
 *   teacher: ai('openai', { model: 'gpt-4o' }),
 *   domain: 'customer support',
 *   edgeCases: ['angry customers', 'vague requests'],
 * });
 *
 * const { examples } = await synth.generate(100);
 * ```
 */
declare class AxSynth<IN extends AxGenIn, OUT extends AxGenOut> {
    private signature;
    private options;
    constructor(signature: AxSignature<IN, OUT>, options: AxSynthOptions);
    /**
     * Generate synthetic examples.
     */
    generate(count: number, options?: {
        batchSize?: number;
    }): Promise<AxSynthResult>;
    /**
     * Generate diverse input examples using a synthesis prompt.
     */
    private generateInputs;
    /**
     * Generate edge case inputs based on hints.
     */
    private generateEdgeCaseInputs;
    /**
     * Label an input using the teacher model.
     */
    private labelInput;
    /**
     * Get the signature being used.
     */
    getSignature(): AxSignature<IN, OUT>;
    /**
     * Get the teacher AI service.
     */
    getTeacher(): AxAIService;
}

/**
 * Creates a type-safe signature from a string template.
 *
 * @param signature - The signature string in the format `"inputFields -> outputFields"`
 * @returns A typed AxSignature instance
 *
 * @example
 * ```typescript
 * const sig = s('question: string -> answer: string');
 * ```
 */
declare function s<const T extends string>(signature: T): AxSignature<ParseSignature<T>['inputs'], ParseSignature<T>['outputs']>;
/**
 * Creates a type-safe AI generator from a signature string or AxSignature object.
 *
 * This is the primary way to define AI-powered functions in Ax. The signature string
 * declares input and output fields with their types, which are then used to generate
 * prompts and parse responses.
 *
 * **Signature String Format:**
 * ```
 * "inputField1: type, inputField2: type -> outputField1: type, outputField2: type"
 * ```
 *
 * **Supported Field Types:**
 * - `string` - Text content (default if no type specified)
 * - `number` - Numeric values (integers or floats)
 * - `boolean` - True/false values
 * - `json` - Arbitrary JSON objects
 * - `date` - Date in YYYY-MM-DD format
 * - `datetime` - ISO 8601 datetime
 * - `dateRange` - date range with start/end dates
 * - `datetimeRange` - datetime range with start/end datetimes
 * - `code` - Code blocks (preserves formatting)
 * - `image` - Image input (for multimodal models)
 * - `audio` - Audio input
 * - `class` - Classification with predefined options: `class(option1, option2, option3)`
 *
 * **Type Modifiers:**
 * - `[]` suffix - Array of values: `tags: string[]`
 * - `?` suffix - Optional field: `context?: string`
 * - `!` prefix - Internal field (hidden from output): `!reasoning: string`
 *
 * **Field Descriptions:**
 * Add descriptions after the type using a string literal:
 * ```
 * "question: string 'The user question' -> answer: string 'A helpful response'"
 * ```
 *
 * @param signature - Either a signature string or a pre-built AxSignature object
 * @param options - Optional configuration for the generator
 * @param options.thoughtFieldName - Custom name for chain-of-thought field (default: 'thought')
 *
 * @returns An AxGen instance that can be executed with `.forward(ai, inputs)`
 *
 * @example Simple question-answering
 * ```typescript
 * const qa = ax('question: string -> answer: string');
 * const result = await qa.forward(ai, { question: 'What is TypeScript?' });
 * console.log(result.answer);
 * ```
 *
 * @example Classification with predefined options
 * ```typescript
 * const classifier = ax('text: string -> sentiment: class(positive, negative, neutral)');
 * const result = await classifier.forward(ai, { text: 'I love this!' });
 * console.log(result.sentiment); // 'positive'
 * ```
 *
 * @example Multiple outputs with arrays
 * ```typescript
 * const extractor = ax(`
 *   document: string ->
 *   summary: string,
 *   keywords: string[],
 *   wordCount: number
 * `);
 * const result = await extractor.forward(ai, { document: longText });
 * ```
 *
 * @example With chain-of-thought reasoning
 * ```typescript
 * const solver = ax('problem: string -> solution: string', {
 *   thoughtFieldName: 'reasoning'
 * });
 * // Enable thinking in forward options to get step-by-step reasoning
 * ```
 *
 * @example Using function tools
 * ```typescript
 * const agent = ax('query: string -> response: string');
 * const result = await agent.forward(ai, { query: 'What is 25 * 4?' }, {
 *   functions: [{
 *     name: 'calculate',
 *     description: 'Perform math calculations',
 *     parameters: { type: 'object', properties: { expression: { type: 'string' } } },
 *     func: ({ expression }) => eval(expression)
 *   }]
 * });
 * ```
 */
declare function ax<const T extends string, ThoughtKey extends string = 'thought'>(signature: T, options?: Readonly<AxProgramForwardOptions<any> & {
    thoughtFieldName?: ThoughtKey;
}>): AxGen<ParseSignature<T>['inputs'], ParseSignature<T>['outputs'] & (string extends ThoughtKey ? {
    thought?: string;
} : {
    [P in ThoughtKey]?: string;
})>;
declare function ax<TInput extends Record<string, any>, TOutput extends Record<string, any>, ThoughtKey extends string = 'thought'>(signature: AxSignature<TInput, TOutput>, options?: Readonly<AxProgramForwardOptions<any> & {
    thoughtFieldName?: ThoughtKey;
}>): AxGen<TInput, TOutput & (string extends ThoughtKey ? {
    thought?: string;
} : {
    [P in ThoughtKey]?: string;
})>;
declare function ax(signature: Readonly<AxSignatureConfig>, options?: Readonly<AxProgramForwardOptions<any>>): AxGen<AxGenIn, AxGenOut>;

interface AxEventStoreConformanceInstance {
    store: AxEventStore;
    stateStore: AxProgramStateStore;
}
interface AxEventStoreConformanceFactoryOptions {
    databaseKey: string;
    maxPendingDeliveries?: number;
}
type AxEventStoreConformanceFactory = (options: Readonly<AxEventStoreConformanceFactoryOptions>) => AxEventStoreConformanceInstance | Promise<AxEventStoreConformanceInstance>;
interface AxEventStoreConformanceReport {
    assertions: number;
    capability: Readonly<AxEventStore['capabilities']>;
}
/** Runs the normative persistent/multi-worker Ax event-store contract. */
declare function runAxEventStoreConformance(createStore: AxEventStoreConformanceFactory, options: Readonly<{
    clock: AxEventClock & {
        advanceBy(ms: number): void;
    };
}>): Promise<AxEventStoreConformanceReport>;

declare const eventPath: Readonly<{
    data: (...segments: AxEventPathSegment[]) => Readonly<AxEventPath<unknown>>;
    id: () => Readonly<AxEventPath<string>>;
    source: () => Readonly<AxEventPath<string>>;
    type: () => Readonly<AxEventPath<string>>;
    subject: () => Readonly<AxEventPath<string | undefined>>;
    time: () => Readonly<AxEventPath<string | undefined>>;
    extension: (name: string) => Readonly<AxEventPath<unknown>>;
    identity: (name: "tenantId" | "accountId" | "userId" | "sessionId") => Readonly<AxEventPath<string | undefined>>;
    trust: () => Readonly<AxEventPath<unknown>>;
    correlation: (kind: string) => Readonly<AxEventPath<string | undefined>>;
    continuation: (...segments: AxEventPathSegment[]) => Readonly<AxEventPath<unknown>>;
    constant: <T>(value: T) => Readonly<AxEventPath<T>>;
}>;
declare function eventInput<IN = Record<string, unknown>>(): AxEventInputBuilder<IN>;
type TargetFactoryInstance = Readonly<{
    targetId: string;
    instanceKey: string;
    identity: Readonly<AxEventIdentity>;
}>;
declare class AxEventTargetBuilder<IN = Record<string, unknown>, OUT = unknown> {
    private readonly value;
    constructor(id: string);
    program<NextInput, NextOutput>(program: AxProgrammable<NextInput, NextOutput>): AxEventTargetBuilder<NextInput, NextOutput>;
    createProgram<NextInput, NextOutput>(signature: Readonly<AxSignature>, factory: (instance: TargetFactoryInstance) => AxProgrammable<NextInput, NextOutput> | Promise<AxProgrammable<NextInput, NextOutput>>): AxEventTargetBuilder<NextInput, NextOutput>;
    ai(ai: Readonly<AxAIService>): this;
    input(definition: AxEventInputDefinition<IN>): this;
    wakeInput(definition: AxEventInputDefinition<IN>): this;
    resumeInput(definition: AxEventInputDefinition<IN>): this;
    waitFor(kind: string, value: Readonly<AxEventPath>, options?: Readonly<{
        expiresInMs?: number;
        metadata?: Readonly<Record<string, Readonly<AxEventPath>>>;
    }>): this;
    forwardOptions(options: Readonly<AxProgramForwardOptions<string>>): this;
    execution(execution: 'forward' | 'streaming'): this;
    state(state: AxEventProgramStateAdapter<AxProgrammable<IN, OUT>>): this;
    sink(sink: AxEventSink<OUT>): this;
    retrySafety(retrySafety: 'idempotent' | 'unknown'): this;
    build(): AxEventTarget<IN, OUT>;
}
declare class AxEventRouteBuilder {
    private readonly id;
    private matcher;
    private predicate?;
    private action?;
    private target?;
    private requireAuthenticated?;
    private authorizeHandler?;
    private observeHandler?;
    private invalidator?;
    private instanceKeyHandler?;
    private correlationHandler?;
    private debounceMs?;
    private coalesce?;
    private orderingMode?;
    constructor(id: string);
    match(match: AxEventRoute['match']): this;
    types(...types: string[]): this;
    sources(...sources: string[]): this;
    subjects(...subjects: string[]): this;
    extensions(extensions: Readonly<Record<string, AxEventScalar>>): this;
    authenticated(): this;
    authorize(authorize: NonNullable<AxEventRoute['authorize']>): this;
    instanceKey(selector: Readonly<AxEventPath> | NonNullable<AxEventRoute['instanceKey']>): this;
    correlate(kind: string, selector: Readonly<AxEventPath>): this;
    correlation(correlation: (ingress: Readonly<AxEventIngress>) => Readonly<AxEventCorrelationKey> | undefined): this;
    wake(target: AxEventTarget<any, any>): this;
    resume(target: AxEventTarget<any, any>): this;
    observe(observe?: (ingress: Readonly<AxEventIngress>, context: Readonly<AxEventContext>) => void | Promise<void>): this;
    invalidate(invalidator: AxEventInvalidator): this;
    debounce(ms: number, options?: Readonly<{
        coalesce?: 'latest';
    }>): this;
    ordering(ordering: 'strict' | 'relaxed'): this;
    build(): AxEventRoute;
    private assertMatcherFields;
    private addMatcher;
    private setAction;
}

interface AxMCPEventSourceIdentity {
    identity?: Readonly<AxEventIdentity>;
    trust?: AxEventTrust;
}
type AxMCPResourceSubscriptionPolicy = 'none' | 'all' | readonly string[] | {
    select: (resource: Readonly<AxMCPResource>, catalog: Readonly<AxMCPCatalogSnapshot>) => boolean;
};
interface AxMCPEventSourceOptions {
    id?: string;
    client: AxMCPClient;
    resourceSubscriptions?: AxMCPResourceSubscriptionPolicy;
    /** @deprecated Use resourceSubscriptions with an explicit URI array. */
    resources?: readonly string[];
    identity?: Readonly<AxEventIdentity>;
    trust?: AxEventTrust;
    resolveIdentity?: (event: Readonly<AxMCPClientEvent>) => Readonly<AxMCPEventSourceIdentity> | Promise<Readonly<AxMCPEventSourceIdentity>>;
    requiresDurable?: boolean;
    unsubscribeOnClose?: boolean;
    reconnectDelayMs?: number;
}
/** Adapts MCP notifications and task snapshots into the generic event inbox. */
declare class AxMCPEventSource implements AxEventSource {
    private readonly options;
    readonly id: string;
    readonly requiresDurable: boolean;
    private readonly subscriptionOwner;
    private readonly selectedSubscriptions;
    constructor(options: Readonly<AxMCPEventSourceOptions>);
    start(context: Readonly<AxEventSourceContext>): Promise<AxEventSourceHandle>;
    private getSubscriptionPolicy;
    private reconcileSubscriptions;
    private releaseSubscriptions;
    private toIngress;
}
interface AxMCPDefaultEventRoutesOptions {
    client: AxMCPClient;
    onCatalogInvalidated?: (catalog: 'tools' | 'prompts' | 'resources', revision: number) => void | Promise<void>;
    onObserve?: (ingress: Readonly<AxEventIngress>) => void | Promise<void>;
}
/** Safe MCP defaults. Resource updates intentionally have no implicit wake route. */
declare function axMCPEventRoutes(options: Readonly<AxMCPDefaultEventRoutesOptions>): readonly AxEventRoute[];

interface AxInMemoryEventStoreOptions {
    clock?: AxEventClock;
    maxPendingDeliveries?: number;
    maxPendingBytes?: number;
    maxEventBytes?: number;
}
declare class AxInMemoryEventStore implements AxEventStore {
    readonly capabilities: {
        readonly durability: "volatile";
        readonly coordination: "single-worker";
        readonly leases: false;
        readonly transactions: false;
        readonly compareAndSet: false;
        readonly outputPersistence: true;
    };
    private readonly clock;
    private readonly maxPendingDeliveries;
    private readonly maxPendingBytes;
    private readonly maxEventBytes;
    private readonly deliveries;
    private readonly deliveryOrdering;
    private readonly deliveryOrder;
    private readonly dedupe;
    private readonly runs;
    private readonly continuations;
    private readonly continuationKeys;
    private readonly deadLetters;
    private readonly workWaiters;
    private readonly capacityWaiters;
    private sequence;
    private pendingDeliveries;
    private pendingBytes;
    constructor(options?: Readonly<AxInMemoryEventStoreOptions>);
    enqueue(request: Readonly<AxEventEnqueueRequest>, signal?: AbortSignal): Promise<AxEventPublishReceipt>;
    claim(workerId: string, now: number, leaseMs?: number): Promise<AxEventDelivery | undefined>;
    renewClaim(deliveryId: string, workerId: string, fencingToken: number, leaseExpiresAt: number): Promise<void>;
    getDelivery(deliveryId: string): Promise<Readonly<AxEventDelivery> | undefined>;
    saveDelivery(delivery: Readonly<AxEventDelivery>): Promise<void>;
    saveRun(run: Readonly<AxEventRun>): Promise<void>;
    getRun(runId: string): Promise<Readonly<AxEventRun> | undefined>;
    registerContinuation(continuation: Readonly<AxEventContinuation>): Promise<void>;
    findContinuation(identityScope: string, correlation: Readonly<AxEventCorrelationKey>, now: number): Promise<Readonly<AxEventContinuation> | undefined>;
    completeContinuation(id: string): Promise<void>;
    addDeadLetter(deadLetter: Readonly<AxEventDeadLetter>): Promise<void>;
    getDeadLetter(id: string): Promise<Readonly<AxEventDeadLetter> | undefined>;
    removeDeadLetter(id: string): Promise<void>;
    listDeadLetters(): Promise<readonly Readonly<AxEventDeadLetter>[]>;
    redriveDelivery(deliveryId: string, now: number): Promise<void>;
    nextAvailableAt(_now: number): Promise<number | undefined>;
    waitForWork(signal?: AbortSignal): Promise<void>;
    isIdle(): Promise<boolean>;
    close(): Promise<void>;
    private hasCapacity;
    private waitForCapacity;
    private hasEarlierInstanceWork;
    private findCoalescible;
    private capacityRequirement;
    private isTerminal;
    private notify;
}
declare class AxInMemoryProgramStateStore implements AxProgramStateStore {
    private readonly states;
    load(key: string): Promise<Readonly<AxProgramStateEnvelope> | undefined>;
    compareAndSet(key: string, expectedRevision: number | undefined, state: Readonly<Omit<AxProgramStateEnvelope, 'revision'>>, _fence?: Readonly<{
        deliveryId: string;
        fencingToken: number;
    }>): Promise<Readonly<AxProgramStateEnvelope>>;
    delete(key: string): Promise<void>;
}

declare function eventTarget(id: string): AxEventTargetBuilder;
declare function eventTarget<IN, OUT>(target: Readonly<AxEventTarget<IN, OUT>>): AxEventTarget<IN, OUT>;
declare function eventRoute(id: string): AxEventRouteBuilder;
declare function eventRoute(route: Readonly<AxEventRoute>): AxEventRoute;
declare class AxEventRuntime {
    readonly id: string;
    private readonly options;
    private readonly store;
    private readonly stateStore;
    private readonly clock;
    private readonly routes;
    private readonly targets;
    private readonly targetSources;
    private readonly singletonTargetInstances;
    private readonly activeRuns;
    private readonly sourceHandles;
    private readonly sourceController;
    private readonly workerController;
    private workerPromises;
    private started;
    private closing;
    constructor(options: Readonly<AxEventRuntimeOptions>);
    start(): Promise<void>;
    publish(ingress: Readonly<AxEventIngress>, signal?: AbortSignal): Promise<AxEventPublishReceipt>;
    getRun(runId: string): Promise<Readonly<AxEventRun> | undefined>;
    listDeadLetters(): Promise<readonly Readonly<AxEventDeadLetter>[]>;
    redrive(deadLetterId: string): Promise<void>;
    cancelRun(runId: string, reason?: string): boolean;
    waitForIdle(timeoutMs?: number): Promise<void>;
    close(options?: Readonly<AxEventCloseOptions>): Promise<void>;
    private routeMatches;
    private workerLoop;
    private processDelivery;
    private invokeTarget;
    private persistProgramState;
    private resolveProgram;
    private defaultStateAdapter;
    private dispatchFinalSinks;
    private dispatchChunkSink;
    private heartbeatClaim;
    private deadLetterDelivery;
}
declare function eventRuntime(options: Readonly<AxEventRuntimeOptions>): AxEventRuntime;

declare class AxPushEventSource implements AxEventSource {
    readonly id: string;
    readonly requiresDurable: boolean;
    private context?;
    constructor(id: string, requiresDurable?: boolean);
    start(context: Readonly<AxEventSourceContext>): AxEventSourceHandle;
    publish(ingress: Readonly<AxEventIngress>, signal?: AbortSignal): Promise<AxEventPublishReceipt>;
}
interface AxTimerEventSourceOptions<T extends AxEventValue> {
    id: string;
    intervalMs: number;
    source?: string;
    type: string;
    subject?: string;
    data?: T | (() => T | Promise<T>);
    identity?: Readonly<AxEventIdentity>;
    trust?: AxEventTrust;
    fireImmediately?: boolean;
    clock?: AxEventClock;
}
declare class AxTimerEventSource<T extends AxEventValue = AxEventValue> implements AxEventSource {
    private readonly options;
    readonly id: string;
    readonly requiresDurable = false;
    private readonly clock;
    constructor(options: Readonly<AxTimerEventSourceOptions<T>>);
    start(context: Readonly<AxEventSourceContext>): AxEventSourceHandle;
    private loop;
    private fire;
}

interface AxUCPWebhookEventSourceOptions {
    id?: string;
    client: Pick<AxUCPClient, 'verifyOrderEvent'>;
    identity?: Readonly<AxEventIdentity> | ((event: Readonly<AxUCPOrderEvent>, request: Request) => Readonly<AxEventIdentity> | undefined | Promise<Readonly<AxEventIdentity> | undefined>);
    source?: string;
}
/**
 * Application-hosted UCP webhook ingress.
 *
 * The UCP client verifies signer profile, RFC 9421 signature, freshness, body
 * digest, and replay state before this adapter publishes anything. Application
 * identity mapping happens only after verification and remains separate from
 * the untrusted business payload.
 */
declare class AxUCPWebhookEventSource implements AxEventSource {
    private readonly options;
    readonly id: string;
    readonly requiresDurable = true;
    private context?;
    constructor(options: Readonly<AxUCPWebhookEventSourceOptions>);
    start(context: Readonly<AxEventSourceContext>): AxEventSourceHandle;
    ingest(request: Request, signal?: AbortSignal): Promise<AxEventPublishReceipt>;
}

declare function axEventId(prefix: string): string;
declare function axEventIdentityScope(identity: Readonly<AxEventIdentity> | undefined): string;
declare function axEventScopedDedupeKey(ingress: Readonly<AxEventIngress>): string;
declare function axEventScopedCorrelationKey(identityScope: string, kind: string, value: string): string;
declare function axValidateEventEnvelope(envelope: Readonly<AxEventEnvelope<unknown>>): asserts envelope is Readonly<AxEventEnvelope<AxEventValue>>;
declare function axEventSizeBytes(ingress: Readonly<AxEventIngress>): number;
declare function axEventMatches(ingress: Readonly<AxEventIngress>, matcher: Readonly<AxEventMatcher>): boolean;
declare function axEventErrorMessage(error: unknown): string;

/**
 * Best-effort static dependency extraction for flow execute mappings.
 *
 * This intentionally never invokes user code. It only recognizes direct state
 * reads that are safe to recognize from function source. Unknown state access is
 * marked unsafe so the planner can keep execution sequential.
 */
interface AxFlowStateDependencyAnalysis {
    dependencies: string[];
    isSafe: boolean;
}

type AxFlowState = Record<string, unknown>;
interface AxFlowOptions extends Pick<AxProgramForwardOptions<string>, 'mcp' | 'ucp' | 'mcpContext' | 'mcpInheritance' | 'eventContext' | 'eventInheritance'> {
    autoParallel?: boolean;
    batchSize?: number;
    logger?: AxFlowLoggerFunction;
    debug?: boolean;
    rateLimiter?: AxProgramForwardOptions<string>['rateLimiter'];
    tracer?: Tracer;
    meter?: Meter;
}
type AxFlowForwardOptions<T extends Readonly<AxAIService>> = AxProgramForwardOptionsWithModels<T> & {
    autoParallel?: boolean;
    abortController?: AbortController;
};
interface AxFlowDynamicContext<T extends Readonly<AxAIService>> {
    ai?: T;
    options?: AxProgramForwardOptions<NonNullable<ReturnType<T['getModelList']>>[number]['key']>;
}
type GetGenIn<T extends AxProgrammable<any, any>> = T extends AxProgrammable<infer IN, any> ? IN : never;
type GetGenOut<T extends AxProgrammable<any, any>> = T extends AxProgrammable<any, infer OUT> ? OUT : never;
type InferAxGen<TSig extends string> = AxGen<ParseSignature<TSig>['inputs'], ParseSignature<TSig>['outputs']>;
type NodeResultKey<TNodeName extends string> = `${TNodeName}Result`;
type AddNodeResult<TState extends AxFlowState, TNodeName extends string, TNodeOut> = TState & {
    [K in NodeResultKey<TNodeName>]: TNodeOut;
};
/**
 * Interface for flows that can be tuned, executed, and used in compositions.
 * Provides methods for building and executing complex AI workflows.
 */
interface AxFlowable<IN, OUT> extends AxProgrammable<IN, OUT> {
}
type AxFlowTypedParallelBranch<TNodes extends Record<string, AxProgrammable<any, any>>, TState extends AxFlowState> = (subFlow: AxFlowTypedSubContext<TNodes, TState>) => AxFlowTypedSubContext<TNodes, AxFlowState>;
interface AxFlowTypedSubContext<TNodes extends Record<string, AxProgrammable<any, any>>, TState extends AxFlowState> {
    execute<TNodeName extends keyof TNodes & string, TAI extends Readonly<AxAIService>>(nodeName: TNodeName, mapping: (state: TState) => GetGenIn<TNodes[TNodeName]>, dynamicContext?: AxFlowDynamicContext<TAI>): AxFlowTypedSubContext<TNodes, AddNodeResult<TState, TNodeName, GetGenOut<TNodes[TNodeName]>>>;
    map<TNewState extends AxFlowState>(transform: (state: TState) => TNewState): AxFlowTypedSubContext<TNodes, TNewState>;
    executeSteps(initialState: TState, context: Readonly<{
        mainAi: AxAIService;
        mainOptions?: AxProgramForwardOptions<string>;
        executeSteps?: (steps: readonly unknown[], initialState: AxFlowState) => Promise<AxFlowState>;
    }>): Promise<AxFlowState>;
}
interface AxFlowExecutionPlanStep {
    type: 'execute' | 'map' | 'returns' | 'branch' | 'while' | 'feedback' | 'parallel' | 'parallelMerge' | 'derive';
    nodeName?: string;
    dependencies: string[];
    produces: string[];
    stepIndex: number;
    isBarrier: boolean;
}
interface AxFlowExecutionPlanGroup {
    level: number;
    steps: AxFlowExecutionPlanStep[];
}
interface AxFlowExecutionPlan {
    totalSteps: number;
    parallelGroups: number;
    maxParallelism: number;
    steps: AxFlowExecutionPlanStep[];
    groups: AxFlowExecutionPlanGroup[];
}

/**
 * Data types for different AxFlow logging events
 */
interface AxFlowLoggerData {
    name: string;
    timestamp: number;
    [key: string]: unknown;
}
interface AxFlowStartData extends AxFlowLoggerData {
    name: 'FlowStart';
    inputFields: string[];
    totalSteps: number;
    parallelGroups: number;
    maxParallelism: number;
    autoParallelEnabled: boolean;
}
interface AxFlowStepStartData extends AxFlowLoggerData {
    name: 'StepStart';
    stepIndex: number;
    stepType: 'execute' | 'map' | 'merge' | 'parallel-map' | 'parallel' | 'derive' | 'branch' | 'feedback' | 'while' | 'other';
    nodeName?: string;
    dependencies: string[];
    produces: string[];
    state: AxFlowState;
}
interface AxFlowStepCompleteData extends AxFlowLoggerData {
    name: 'StepComplete';
    stepIndex: number;
    stepType: 'execute' | 'map' | 'merge' | 'parallel-map' | 'parallel' | 'derive' | 'branch' | 'feedback' | 'while' | 'other';
    nodeName?: string;
    executionTime: number;
    state: AxFlowState;
    newFields?: string[];
    result?: any;
}
interface AxFlowParallelGroupStartData extends AxFlowLoggerData {
    name: 'ParallelGroupStart';
    groupLevel: number;
    stepsCount: number;
    stepTypes: string[];
}
interface AxFlowParallelGroupCompleteData extends AxFlowLoggerData {
    name: 'ParallelGroupComplete';
    groupLevel: number;
    stepsCount: number;
    executionTime: number;
}
interface AxFlowBranchEvaluationData extends AxFlowLoggerData {
    name: 'BranchEvaluation';
    branchValue: unknown;
    hasMatchingBranch: boolean;
    branchStepsCount: number;
}
interface AxFlowCompleteData extends AxFlowLoggerData {
    name: 'FlowComplete';
    totalExecutionTime: number;
    finalState: AxFlowState;
    outputFields: string[];
    stepsExecuted: number;
}
interface AxFlowErrorData extends AxFlowLoggerData {
    name: 'FlowError';
    error: string;
    stepIndex?: number;
    stepType?: string;
    nodeName?: string;
    state?: AxFlowState;
}
type AxFlowLogData = AxFlowStartData | AxFlowStepStartData | AxFlowStepCompleteData | AxFlowParallelGroupStartData | AxFlowParallelGroupCompleteData | AxFlowBranchEvaluationData | AxFlowCompleteData | AxFlowErrorData;
/**
 * Function type for AxFlow logging
 */
type AxFlowLoggerFunction = (data: AxFlowLogData) => void;
/**
 * Factory function to create a colorized AxFlow logger
 */
declare const axCreateFlowColorLogger: (output?: (message: string) => void) => AxFlowLoggerFunction;
/**
 * Factory function to create a text-only AxFlow logger (no colors)
 */
declare const axCreateFlowTextLogger: (output?: (message: string) => void) => AxFlowLoggerFunction;
/**
 * Default AxFlow logger with colors
 */
declare const axDefaultFlowLogger: AxFlowLoggerFunction;

type AxFlowStepKind = 'execute' | 'map' | 'returns' | 'branch' | 'while' | 'feedback' | 'parallel' | 'parallelMerge' | 'derive';
interface AxFlowExecutionContext {
    mainAi: AxAIService;
    mainOptions?: AxProgramForwardOptions<string>;
    autoParallel: boolean;
    batchSize?: number;
    executeSteps: (steps: readonly AxFlowStep[], initialState: AxFlowState) => Promise<AxFlowState>;
    checkAbort: (location: string) => void;
    captureRemoteTasks?: () => unknown;
    cancelRemoteTasksSince?: (snapshot: unknown) => Promise<void>;
}
type AxFlowStepRunner = (state: AxFlowState, context: AxFlowExecutionContext) => Promise<AxFlowState> | AxFlowState;
type AxFlowStepDecision = {
    readonly nodeName: string;
    readonly field: string;
    readonly value?: unknown;
};
type AxFlowStepMeta = {
    readonly kind: 'branch';
    readonly predicate: (state: AxFlowState) => unknown;
    readonly branches: ReadonlyArray<readonly [unknown, readonly AxFlowStep[]]>;
    readonly decision?: AxFlowStepDecision;
} | {
    readonly kind: 'while';
    readonly bodySteps: readonly AxFlowStep[];
    readonly condition: (state: AxFlowState) => boolean;
    readonly maxIterations: number;
    readonly conditionName?: string;
} | {
    readonly kind: 'feedback';
    readonly bodySteps: readonly AxFlowStep[];
    readonly targetLabel: string;
    readonly condition: (state: AxFlowState) => boolean;
    readonly maxIterations: number;
    readonly decision?: AxFlowStepDecision;
    readonly conditionName?: string;
} | {
    readonly kind: 'parallel';
    readonly branchFns: ReadonlyArray<(subContext: unknown) => unknown>;
} | {
    readonly kind: 'parallelMerge';
    readonly resultKey: string;
} | {
    readonly kind: 'map';
    readonly name?: string;
} | {
    readonly kind: 'returns';
    readonly synthetic?: boolean;
};
interface AxFlowStep {
    readonly kind: AxFlowStepKind;
    readonly nodeName?: string;
    readonly reads: readonly string[];
    readonly writes: readonly string[];
    readonly isBarrier: boolean;
    readonly run: AxFlowStepRunner;
    readonly meta?: AxFlowStepMeta;
}

interface AxFlowNodeExecutionRecorder {
    recordUsage(nodeName: string, usage: AxProgramUsage[]): void;
    recordTraces(nodeName: string, traces: AxProgramTrace<any, any>[]): void;
    recordChatLog(nodeName: string, entries: AxChatLogEntry[]): void;
}

interface AxFlowMermaidRenderOptions {
    direction?: 'TD' | 'LR' | 'BT' | 'RL';
}
declare class AxFlowMermaidError extends Error {
    readonly line: number;
    readonly context: string;
    readonly suggestion?: string | undefined;
    constructor(message: string, line: number, context: string, suggestion?: string | undefined);
}
type AxFlowMermaidNodeBinding = string | AxSignature | {
    forward: (...args: any[]) => any;
} | ((state: AxFlowState) => AxFlowState | Promise<AxFlowState>);
interface AxFlowMermaidBindings {
    /**
     * Node implementations. A signature (string or AxSignature) or any
     * AxProgrammable overrides/satisfies a node's `%%ax` directive; a plain
     * function becomes a map step (full state in, full state out).
     */
    nodes?: Record<string, AxFlowMermaidNodeBinding>;
    /** Predicates referenced by `if <name>` / `while <name>` edge labels. */
    conditions?: Record<string, (state: AxFlowState) => boolean>;
    options?: AxFlowOptions;
}

declare class AxFlow<IN extends Record<string, any>, OUT, TNodes extends Record<string, AxProgrammable<any, any>> = Record<string, never>, TState extends AxFlowState = IN> implements AxFlowable<IN, OUT>, AxFlowNodeExecutionRecorder {
    private readonly steps;
    private currentSteps;
    private readonly nodeGenerators;
    private readonly stepLabels;
    private readonly loopStack;
    private branchContext;
    private program?;
    private flowName?;
    private readonly autoParallelConfig;
    private readonly flowLogger?;
    private readonly timingLogger?;
    private readonly defaultAIOptions?;
    private nodeUsage;
    private nodeTraces;
    private nodeChatLog;
    private activeAbortControllers;
    private _stopRequested;
    private constructor();
    static create<IN extends Record<string, any> = Record<string, unknown>, OUT = {}, TNodes extends Record<string, AxProgrammable<any, any>> = Record<string, never>, TState extends AxFlowState = IN>(options?: AxFlowOptions): AxFlow<IN, OUT, TNodes, TState>;
    private toCamelCase;
    stop(): void;
    private addStep;
    private getCacheKey;
    private inferSignatureFromFlow;
    private findProjectedOutputField;
    private ensureProgram;
    getId(): string;
    setId(id: string): void;
    namedPrograms(): Array<{
        id: string;
        signature?: string;
    }>;
    namedProgramInstances(): AxNamedProgramInstance<IN, OUT>[];
    getTraces(): AxProgramTrace<IN, OUT>[];
    setDemos(demos: readonly AxProgramDemos<IN, OUT, keyof TNodes extends never ? string : `${string}.${string & keyof TNodes}`>[], options?: {
        modelConfig?: Record<string, unknown>;
    }): void;
    description(name: string, description: string): this;
    toFunction(): AxFunction;
    getUsage(): AxProgramUsage[];
    getChatLog(): readonly AxChatLogEntry[];
    resetUsage(): void;
    resetTraces(): void;
    resetChatLog(): void;
    getUsageReport(): Record<string, AxProgramUsage[]>;
    getNodePrograms(): ReadonlyArray<{
        name: string;
        program: AxProgrammable<any, any>;
    }>;
    setNodeInstruction(name: string, instruction: string): boolean;
    setAllNodeInstructions(map: Readonly<Record<string, string>>): void;
    getTracesReport(): Record<string, AxProgramTrace<any, any>[]>;
    recordUsage(nodeName: string, usage: AxProgramUsage[]): void;
    recordTraces(nodeName: string, traces: AxProgramTrace<any, any>[]): void;
    recordChatLog(_nodeName: string, entries: AxChatLogEntry[]): void;
    streamingForward<T extends Readonly<AxAIService>>(ai: T, values: IN, options?: Readonly<AxProgramStreamingForwardOptionsWithModels<T>>): AxGenStreamingOut<OUT>;
    forward<T extends Readonly<AxAIService>>(ai: T, values: IN, options?: Readonly<AxFlowForwardOptions<T>>): Promise<OUT>;
    node<TName extends string, TSig extends string>(name: TName, signature: TSig): AxFlow<IN, OUT, TNodes & {
        [K in TName]: InferAxGen<TSig>;
    }, TState>;
    node<TName extends string>(name: TName, signature: AxSignature): AxFlow<IN, OUT, TNodes & {
        [K in TName]: AxGen<AxGenIn, AxGenOut>;
    }, TState>;
    node<TName extends string, TProgram extends new () => AxProgrammable<any, any>>(name: TName, programClass: TProgram): AxFlow<IN, OUT, TNodes & {
        [K in TName]: InstanceType<TProgram>;
    }, TState>;
    node<TName extends string, TProgram extends AxProgrammable<any, any>>(name: TName, programInstance: TProgram): AxFlow<IN, OUT, TNodes & {
        [K in TName]: TProgram;
    }, TState>;
    n<TName extends string, TSig extends string>(name: TName, signature: TSig): AxFlow<IN, OUT, TNodes & {
        [K in TName]: InferAxGen<TSig>;
    }, TState>;
    n<TName extends string>(name: TName, signature: AxSignature): AxFlow<IN, OUT, TNodes & {
        [K in TName]: AxGen<AxGenIn, AxGenOut>;
    }, TState>;
    n<TName extends string, TProgram extends new () => AxProgrammable<any, any>>(name: TName, programClass: TProgram): AxFlow<IN, OUT, TNodes & {
        [K in TName]: InstanceType<TProgram>;
    }, TState>;
    n<TName extends string, TProgram extends AxProgrammable<any, any>>(name: TName, programInstance: TProgram): AxFlow<IN, OUT, TNodes & {
        [K in TName]: TProgram;
    }, TState>;
    map<TNewState extends AxFlowState>(transform: (_state: TState) => TNewState): AxFlow<IN, OUT, TNodes, TNewState>;
    map<TNewState extends AxFlowState>(transform: (_state: TState) => Promise<TNewState>): AxFlow<IN, OUT, TNodes, TNewState>;
    map<TNewState extends AxFlowState>(transforms: Array<(_state: TState) => TNewState>, options: {
        parallel: true;
    }): AxFlow<IN, OUT, TNodes, TNewState>;
    map<TNewState extends AxFlowState>(transforms: Array<(_state: TState) => Promise<TNewState>>, options: {
        parallel: true;
    }): AxFlow<IN, OUT, TNodes, TNewState>;
    map<TNewState extends AxFlowState>(transform: (_state: TState) => TNewState | Promise<TNewState>, options?: {
        parallel?: boolean;
    }): AxFlow<IN, OUT, TNodes, TNewState>;
    m<TNewState extends AxFlowState>(transform: (_state: TState) => TNewState): AxFlow<IN, OUT, TNodes, TNewState>;
    m<TNewState extends AxFlowState>(transform: (_state: TState) => Promise<TNewState>): AxFlow<IN, OUT, TNodes, TNewState>;
    m<TNewState extends AxFlowState>(transforms: Array<(_state: TState) => TNewState>, options: {
        parallel: true;
    }): AxFlow<IN, OUT, TNodes, TNewState>;
    m<TNewState extends AxFlowState>(transforms: Array<(_state: TState) => Promise<TNewState>>, options: {
        parallel: true;
    }): AxFlow<IN, OUT, TNodes, TNewState>;
    returns<TNewOut extends Record<string, unknown>>(transform: (_state: TState) => TNewOut): AxFlow<IN, TNewOut, TNodes, TState>;
    r<TNewOut extends Record<string, unknown>>(transform: (_state: TState) => TNewOut): AxFlow<IN, TNewOut, TNodes, TState>;
    label(label: string): this;
    l(label: string): this;
    private createExecuteStep;
    execute<TNodeName extends keyof TNodes & string, TAI extends Readonly<AxAIService>>(nodeName: TNodeName, mapping: (_state: TState) => GetGenIn<TNodes[TNodeName]>, dynamicContext?: AxFlowDynamicContext<TAI>): AxFlow<IN, OUT, TNodes, AddNodeResult<TState, TNodeName, GetGenOut<TNodes[TNodeName]>>>;
    e<TNodeName extends keyof TNodes & string, TAI extends Readonly<AxAIService>>(nodeName: TNodeName, mapping: (_state: TState) => GetGenIn<TNodes[TNodeName]>, dynamicContext?: AxFlowDynamicContext<TAI>): AxFlow<IN, OUT, TNodes, AddNodeResult<TState, TNodeName, GetGenOut<TNodes[TNodeName]>>>;
    applyOptimization(optimizedProgram: AxOptimizedProgram<any>): void;
    getOptimizableComponents(): readonly AxOptimizableComponent[];
    applyOptimizedComponents(updates: Readonly<Record<string, string>>): void;
    branch(predicate: (_state: TState) => unknown): this;
    b(predicate: (_state: TState) => unknown): this;
    when(value: unknown): this;
    w(value: unknown): this;
    merge<TMergedState extends AxFlowState = TState>(): AxFlow<IN, OUT, TNodes, TMergedState>;
    mg<TMergedState extends AxFlowState = TState>(): AxFlow<IN, OUT, TNodes, TMergedState>;
    parallel(branches: AxFlowTypedParallelBranch<TNodes, TState>[]): {
        merge<T, TResultKey extends string>(resultKey: TResultKey, mergeFunction: (..._results: unknown[]) => T): AxFlow<IN, OUT, TNodes, TState & {
            [K in TResultKey]: T;
        }>;
    };
    p(branches: AxFlowTypedParallelBranch<TNodes, TState>[]): {
        merge<T, TResultKey extends string>(resultKey: TResultKey, mergeFunction: (..._results: unknown[]) => T): AxFlow<IN, OUT, TNodes, TState & {
            [K in TResultKey]: T;
        }>;
    };
    feedback(condition: (_state: TState) => boolean, targetLabel: string, maxIterations?: number): this;
    fb(condition: (_state: TState) => boolean, targetLabel: string, maxIterations?: number): this;
    while(condition: (state: TState) => boolean, maxIterations?: number): this;
    wh(condition: (_state: TState) => boolean, maxIterations?: number): this;
    endWhile(): this;
    end(): this;
    derive<T>(outputFieldName: string, inputFieldName: string, transformFn: (value: any, index?: number, state?: TState) => T, options?: {
        batchSize?: number;
    }): this;
    getExecutionPlan(): {
        totalSteps: number;
        parallelGroups: number;
        maxParallelism: number;
        autoParallelEnabled: boolean;
        steps?: AxFlowExecutionPlanStep[];
        groups?: AxFlowExecutionPlanGroup[];
    };
    /**
     * Renders this flow as a mermaid flowchart in the AxFlow mermaid dialect:
     * node contracts are emitted as `%%ax nodeId: <signature>` comment
     * directives (invisible to mermaid renderers) and control flow becomes
     * nodes and edges — branch decisions render as diamonds with labeled
     * out-edges, feedback loops as back-edges with `max N` caps.
     *
     * `String(flow)` and template-literal interpolation yield the diagram —
     * mirroring `AxSignature.toString()` returning the signature string — and
     * `flow(String(f))` round-trips exactly. Pass options for render control,
     * e.g. `f.toString({ direction: 'LR' })` (like `Number.toString(radix)`).
     *
     * Flows built with opaque closures (map/derive/returns/custom conditions)
     * render with placeholder nodes plus `%% bind ...` comments naming what
     * must be supplied via bindings to re-import the diagram. A `while` loop
     * renders with its body inlined once and a back-edge (the zero-iteration
     * exit is not drawable).
     */
    toString(options?: AxFlowMermaidRenderOptions): string;
    getSignature(): AxSignature;
    nodeExtended<TName extends string>(name: TName, baseSignature: string | AxSignature, extensions: {
        prependInputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
        appendInputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
        prependOutputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
        appendOutputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
    }): AxFlow<IN, OUT, TNodes & {
        [K in TName]: AxGen<AxGenIn, AxGenOut>;
    }, TState>;
    nx<TName extends string>(name: TName, baseSignature: string | AxSignature, extensions: {
        prependInputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
        appendInputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
        prependOutputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
        appendOutputs?: Array<{
            name: string;
            type: AxFieldType;
        }>;
    }): AxFlow<IN, OUT, TNodes & {
        [K in TName]: AxGen<AxGenIn, AxGenOut>;
    }, TState>;
    /**
     * Patches the most recently added step. Used by the mermaid compiler
     * (`flow(text)`) to record decision fields, synthetic-returns markers, and
     * the declared reads/writes of generated projection steps (so signature
     * inference sees through them) on steps it just emitted through the public
     * builder.
     * @internal
     */
    static patchLastStep(target: AxFlow<any, any, any, any>, patch: {
        meta?: (existing: AxFlowStepMeta | undefined) => AxFlowStepMeta | undefined;
        reads?: readonly string[];
        writes?: readonly string[];
    }): void;
}
declare function flowFn<TInput extends Record<string, any> = Record<string, unknown>, TOutput = {}>(options?: AxFlowOptions): AxFlow<TInput, TOutput, {}, TInput>;
declare function flowFn<TInput extends Record<string, any> = Record<string, any>, TOutput = Record<string, any>>(mermaid: string, bindings?: AxFlowMermaidBindings): AxFlow<TInput, TOutput, any, any>;
/**
 * Creates a new AxFlow builder. Passing a string compiles a mermaid
 * flowchart in the AxFlow dialect (see AxFlow.toString) into a runnable
 * flow — node contracts come from `%%ax nodeId: <signature>` directives or
 * from `bindings.nodes`, data wiring is by field name (a node input binds to
 * the nearest upstream producer of that field), labeled out-edges of a
 * decision node become branches, and back-edges become feedback/while
 * loops. `flow(String(otherFlow))` round-trips.
 */
declare const flow: typeof flowFn;

type AxFlowMetricsInstruments = Readonly<{
    requests: Counter;
    errors: Counter;
    duration: Histogram;
}>;

interface AxDockerContainer {
    Id: string;
    Names: string[];
    Image: string;
    ImageID: string;
    Command: string;
    Created: number;
    State: {
        Status: string;
        Running: boolean;
        Paused: boolean;
        Restarting: boolean;
        OOMKilled: boolean;
        Dead: boolean;
        Pid: number;
        ExitCode: number;
        Error: string;
        StartedAt: Date;
        FinishedAt: Date;
    };
    Status: string;
    Ports: Array<{
        IP: string;
        PrivatePort: number;
        PublicPort: number;
        Type: string;
    }>;
    Labels: {
        [key: string]: string;
    };
    SizeRw: number;
    SizeRootFs: number;
    HostConfig: {
        NetworkMode: string;
    };
    NetworkSettings: {
        Networks: {
            [key: string]: {
                IPAddress: string;
                IPPrefixLen: number;
                Gateway: string;
                MacAddress: string;
            };
        };
    };
    Mounts: Array<{
        Type: string;
        Source: string;
        Destination: string;
        Mode: string;
        RW: boolean;
        Propagation: string;
    }>;
}
declare class AxDockerSession {
    private readonly apiUrl;
    private containerId;
    constructor(apiUrl?: string);
    pullImage(imageName: string): Promise<void>;
    createContainer({ imageName, volumes, doNotPullImage, tag, }: Readonly<{
        imageName: string;
        volumes?: Array<{
            hostPath: string;
            containerPath: string;
        }>;
        doNotPullImage?: boolean;
        tag?: string;
    }>): Promise<{
        Id: string;
    }>;
    findOrCreateContainer({ imageName, volumes, doNotPullImage, tag, }: Readonly<{
        imageName: string;
        volumes?: Array<{
            hostPath: string;
            containerPath: string;
        }>;
        doNotPullImage?: boolean;
        tag: string;
    }>): Promise<{
        Id: string;
        isNew: boolean;
    }>;
    startContainer(): Promise<void>;
    connectToContainer(containerId: string): Promise<void>;
    stopContainers({ tag, remove, timeout, }: Readonly<{
        tag?: string;
        remove?: boolean;
        timeout?: number;
    }>): Promise<Array<{
        Id: string;
        Action: 'stopped' | 'removed';
    }>>;
    listContainers(all?: boolean): Promise<AxDockerContainer[]>;
    getContainerLogs(): Promise<string>;
    executeCommand(command: string): Promise<string>;
    private getContainerInfo;
    private waitForContainerToBeRunning;
    private fetchDockerAPI;
    toFunction(): AxFunction;
}

declare class AxEmbeddingAdapter {
    private aiService;
    private info;
    private func;
    constructor({ ai, info, func, }: Readonly<{
        ai: AxAIService;
        info: Readonly<{
            name: string;
            description: string;
            argumentDescription: string;
        }>;
        func: (args: readonly number[], extra?: Readonly<AxAIServiceOptions>) => Promise<unknown>;
    }>);
    private embedAdapter;
    toFunction(): AxFunction;
}

/**
 * Host-side security configuration helpers for AxJSRuntime.
 *
 * This module intentionally contains no worker-session state. It normalizes the
 * public security options into runtime/worker flags used by jsRuntime.ts and
 * jsRuntimeWorkers.ts.
 */
/**
 * Permissions that can be granted to the RLM JS interpreter sandbox.
 * By default all dangerous globals are blocked; users opt in via this enum.
 */
declare enum AxJSRuntimePermission {
    /** fetch, XMLHttpRequest, WebSocket, EventSource */
    NETWORK = "network",
    /** indexedDB, caches */
    STORAGE = "storage",
    /** importScripts */
    CODE_LOADING = "code-loading",
    /** BroadcastChannel */
    COMMUNICATION = "communication",
    /** performance */
    TIMING = "timing",
    /**
     * Worker, SharedWorker.
     * Warning: sub-workers spawn with fresh, unlocked globals — granting
     * WORKERS without other restrictions implicitly grants all capabilities
     * (e.g. fetch, indexedDB) inside child workers.
     */
    WORKERS = "workers",
    /** node:fs and related — gates Node Permission Model --allow-fs-* and Deno read/write */
    FILESYSTEM = "filesystem",
    /** node:child_process — gates --allow-child-process and Deno run */
    CHILD_PROCESS = "child-process"
}
/**
 * Fine-grained Node Permission Model allowlist. Scopes `--allow-fs-*` and
 * gates additional `--allow-*` flags that aren't covered by the high-level
 * permission enum.
 */
type AxJSRuntimeNodePermissionAllowlist = Readonly<{
    fsRead?: readonly string[];
    fsWrite?: readonly string[];
    childProcess?: boolean;
    addons?: boolean;
    wasi?: boolean;
}>;
/**
 * Node worker_threads resource limits passthrough.
 */
type AxJSRuntimeResourceLimits = Readonly<{
    maxOldGenerationSizeMb?: number;
    maxYoungGenerationSizeMb?: number;
    codeRangeSizeMb?: number;
    stackSizeMb?: number;
}>;

type AxJSRuntimeOutputMode = 'return' | 'stdout';
/**
 * Browser-compatible JavaScript interpreter for RLM using Web Workers.
 * Creates persistent sessions where variables survive across `execute()` calls.
 */
declare class AxJSRuntime implements AxCodeRuntime {
    readonly language = "JavaScript";
    private readonly timeout;
    private readonly permissions;
    private readonly allowUnsafeNodeHostAccess;
    private readonly nodeWorkerPoolSize;
    private readonly debugNodeWorkerPool;
    private readonly outputMode;
    private readonly captureConsole;
    private readonly blockDynamicImport;
    private readonly allowedModules;
    private readonly freezeIntrinsics;
    private readonly blockShadowRealm;
    private readonly lockWorkerIPC;
    private readonly preventGlobalThisExtensions;
    private readonly useNodePermissionModel;
    private readonly nodePermissionAllowlist?;
    private readonly resourceLimits?;
    private readonly allowDenoRemoteImport;
    constructor(options?: Readonly<{
        timeout?: number;
        permissions?: readonly AxJSRuntimePermission[];
        outputMode?: AxJSRuntimeOutputMode;
        captureConsole?: boolean;
        /**
         * Warning: enables direct access to Node host globals (e.g. process/require)
         * from model-generated code in Node worker runtime.
         *
         * Defaults to false for safer behavior.
         */
        allowUnsafeNodeHostAccess?: boolean;
        /**
         * Node-only: prewarm pool size for worker_threads.
         * Defaults to an adaptive value based on availableParallelism() when available.
         */
        nodeWorkerPoolSize?: number;
        /**
         * Node-only: prints resolved worker pool size to console.debug.
         * Can also be enabled via AX_RLM_DEBUG_NODE_POOL=1.
         */
        debugNodeWorkerPool?: boolean;
        /**
         * Block dynamic `import()` at execute time (language-level block on Node
         * via `node:vm` rejector; Deno relies on permission model).
         *
         * Default: true.
         */
        blockDynamicImport?: boolean;
        /**
         * Module specifier allowlist when `blockDynamicImport` is true. This is
         * a narrow dynamic-import gate: allowlisted specifiers are attempted, but
         * full Node module namespace passthrough depends on Node vm semantics.
         * Default: [].
         */
        allowedModules?: readonly string[];
        /**
         * Freeze Object.prototype / Array.prototype / Function.prototype and
         * other intrinsics to prevent prototype pollution.
         *
         * Default: true.
         */
        freezeIntrinsics?: boolean;
        /**
         * Lock `globalThis.ShadowRealm` to undefined. Default: true.
         */
        blockShadowRealm?: boolean;
        /**
         * Lock `self.postMessage` / `self.onmessage` in browser/Deno workers
         * to prevent host-function privilege escalation. Default: true.
         */
        lockWorkerIPC?: boolean;
        /**
         * Call `Object.preventExtensions(globalThis)` in the worker. Breaks
         * top-level `var/let/const` persistence — opt-in only. Default: false.
         */
        preventGlobalThisExtensions?: boolean;
        /**
         * Node-only: engage the Node Permission Model at worker spawn for
         * kernel-enforced defense-in-depth on top of the language-level
         * lockdown. Emits `--permission` on Node ≥ 23.5 (stable flag) or
         * `--experimental-permission` on Node 20–23.4 (same runtime
         * enforcement, pre-stabilization flag name).
         *
         * - 'auto' (default): engage unconditionally on any supported Node.
         *   With no FILESYSTEM/CHILD_PROCESS permission granted, fs and
         *   child_process are blocked at the OS level. Silently skips on
         *   Node < 20, Deno, and browsers (language-level defenses still
         *   apply).
         * - true: engage unconditionally; hard-fail on Node < 20.
         * - false: never engage.
         */
        useNodePermissionModel?: boolean | 'auto';
        /**
         * Fine-grained Node Permission Model allowlist (e.g. fs-read paths).
         */
        nodePermissionAllowlist?: AxJSRuntimeNodePermissionAllowlist;
        /**
         * Node-only: resource limits passed to `worker_threads.Worker`.
         */
        resourceLimits?: AxJSRuntimeResourceLimits;
        /**
         * Deno-only: allow remote module imports (`await import('https://...')`).
         * Default: false — sets `import: false` in the Deno permission set when
         * NETWORK is granted, so data-plane fetch works but remote module
         * loading is blocked at the runtime level.
         */
        allowDenoRemoteImport?: boolean;
    }>);
    /**
     * Computes Node execArgv for the Permission Model when it should engage,
     * otherwise returns undefined.
     *
     * - 'auto': engages unconditionally on supported Node versions; skips
     *   silently where the Node Permission Model is unavailable.
     * - true: engages unconditionally; hard-fails on Node < 20.
     * - false: never engages.
     */
    private computeNodeExecArgv;
    private computeSecurityPostureHash;
    getUsageInstructions(): string;
    /**
     * Creates a persistent execution session.
     *
     * Message flow:
     * 1) Main thread sends `init` with globals, function proxies, permissions.
     * 2) Main thread sends `execute` with correlation ID and code.
     * 3) Worker returns `result` or requests host callbacks via `fn-call`.
     * 4) Host responds to callback requests with `fn-result`.
     *
     * Session closes on:
     * - explicit close(),
     * - timeout,
     * - abort signal,
     * - worker error.
     */
    createSession(globals?: Record<string, unknown>, options?: {
        shouldBubbleError?: (err: unknown) => boolean;
    }): AxCodeSession;
    toFunction(): AxFunction;
}
/**
 * Factory function for creating an AxJSRuntime.
 */
declare function axCreateJSRuntime(options?: Readonly<{
    timeout?: number;
    permissions?: readonly AxJSRuntimePermission[];
    outputMode?: AxJSRuntimeOutputMode;
    captureConsole?: boolean;
    allowUnsafeNodeHostAccess?: boolean;
    nodeWorkerPoolSize?: number;
    debugNodeWorkerPool?: boolean;
    blockDynamicImport?: boolean;
    allowedModules?: readonly string[];
    freezeIntrinsics?: boolean;
    blockShadowRealm?: boolean;
    lockWorkerIPC?: boolean;
    preventGlobalThisExtensions?: boolean;
    useNodePermissionModel?: boolean | 'auto';
    nodePermissionAllowlist?: AxJSRuntimeNodePermissionAllowlist;
    resourceLimits?: AxJSRuntimeResourceLimits;
    allowDenoRemoteImport?: boolean;
}>): AxJSRuntime;

type AxWorkerRuntimeConfig = Readonly<{
    functionRefKey: string;
    maxErrorCauseDepth: number;
}>;
declare function axWorkerRuntime(config: AxWorkerRuntimeConfig): void;

declare const AX_MCP_APP_RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
type AxMCPAppVisibility = 'model' | 'app';
type AxMCPAppDisplayMode = 'inline' | 'fullscreen' | 'pip';
interface AxMCPAppToolMeta {
    resourceUri?: string;
    visibility?: readonly AxMCPAppVisibility[];
}
interface AxMCPAppResourceCSP {
    connectDomains?: readonly string[];
    resourceDomains?: readonly string[];
    frameDomains?: readonly string[];
    baseUriDomains?: readonly string[];
}
interface AxMCPAppPermissions {
    camera?: Record<string, never>;
    microphone?: Record<string, never>;
    geolocation?: Record<string, never>;
    clipboardWrite?: Record<string, never>;
}
interface AxMCPAppResourceMeta {
    csp?: AxMCPAppResourceCSP;
    permissions?: AxMCPAppPermissions;
    domain?: string;
    prefersBorder?: boolean;
}
interface AxMCPAppResource {
    uri: string;
    mimeType: typeof AX_MCP_APP_RESOURCE_MIME_TYPE;
    html: string;
    meta: AxMCPAppResourceMeta;
    sandbox: 'allow-scripts allow-same-origin';
    contentSecurityPolicy: string;
    permissionPolicy: string;
}
interface AxMCPAppContextUpdate {
    content?: readonly AxMCPContent[];
    structuredContent?: Readonly<Record<string, unknown>>;
    /** Apps are remote, untrusted UI principals. */
    untrusted: true;
    source: Readonly<{
        kind: 'mcp-app';
        namespace: string;
        tool: string;
    }>;
}
interface AxMCPAppBridgeOptions {
    client: AxMCPClient;
    tool: string | AxMCPTool;
    sendToView?: (message: Readonly<AxMCPJSONRPCMessage>) => void | Promise<void>;
    hostCapabilities?: Readonly<Record<string, unknown>>;
    hostContext?: Readonly<Record<string, unknown>>;
    authorize?: (action: Readonly<{
        method: string;
        params: unknown;
        namespace: string;
        tool: string;
    }>) => boolean | Promise<boolean>;
    openLink?: (url: string) => void | Promise<void>;
    sendMessage?: (message: Readonly<Record<string, unknown>>) => void | Promise<void>;
    updateModelContext?: (update: Readonly<AxMCPAppContextUpdate>) => void | Promise<void>;
    requestDisplayMode?: (mode: AxMCPAppDisplayMode) => AxMCPAppDisplayMode | Promise<AxMCPAppDisplayMode>;
    log?: (params: unknown) => void | Promise<void>;
    sizeChanged?: (size: Readonly<{
        width: number;
        height: number;
    }>) => void;
}
declare function axMCPAppToolMeta(tool: Readonly<AxMCPTool>): AxMCPAppToolMeta;
declare function axMCPToolVisibleTo(tool: Readonly<AxMCPTool>, principal: AxMCPAppVisibility): boolean;
/**
 * Protocol and policy core for an MCP Apps host. Rendering remains host-owned;
 * this bridge supplies the validated sandbox payload and JSON-RPC dispatch.
 */
declare class AxMCPAppBridge {
    private readonly options;
    private readonly tool;
    private initialized;
    private nextRequestId;
    constructor(options: Readonly<AxMCPAppBridgeOptions>);
    loadResource(): Promise<AxMCPAppResource>;
    handleViewMessage(message: Readonly<AxMCPJSONRPCMessage>): Promise<AxMCPJSONRPCResponse | undefined>;
    notifyToolInput(arguments_: Readonly<Record<string, unknown>>): Promise<void>;
    notifyToolInputPartial(arguments_: Readonly<Record<string, unknown>>): Promise<void>;
    notifyToolResult(result: Readonly<AxMCPToolCallResult>): Promise<void>;
    notifyToolCancelled(reason: string): Promise<void>;
    notifyHostContextChanged(context: Readonly<Record<string, unknown>>): Promise<void>;
    teardown(reason: string): Promise<void>;
    private handleRequest;
    private authorize;
    private success;
    private sendNotification;
}

interface AxMCPChatResult {
    response: AxChatResponse;
    messages: AxChatRequest['chatPrompt'];
}
type AxMCPChatOptions = AxProgramForwardOptions<string> & {
    maxSteps?: number;
};
/** High-level chat loop with native MCP/UCP tool dispatch and retained history. */
declare function axMCPChat(ai: Readonly<AxAIService>, request: Readonly<AxChatRequest>, options?: Readonly<AxMCPChatOptions>): Promise<AxMCPChatResult>;

/** A JSON-RPC protocol error returned by an MCP peer. */
declare class AxMCPProtocolError extends Error {
    readonly code: number;
    readonly data?: unknown;
    constructor(code: number, message: string, data?: unknown);
}
/** An HTTP failure that did not yield an in-band MCP response. */
declare class AxMCPHTTPStatusError extends Error {
    readonly status: number;
    readonly statusText: string;
    readonly body?: unknown;
    constructor(status: number, statusText: string, body?: unknown);
}

interface AxMCPRequestMetaOptions {
    protocolVersion: string;
    clientCapabilities: AxMCPClientCapabilities;
    clientInfo: AxMCPImplementationInfo;
    logLevel?: AxMCPLoggingLevel;
    traceparent?: string;
    tracestate?: string;
    existing?: Readonly<AxMCPMeta>;
}
/** Builds the required per-request metadata for MCP 2026-07-28. */
declare function axMCPBuildRequestMeta(options: Readonly<AxMCPRequestMetaOptions>): AxMCPMeta;
/** Reads a well-formed server identity from modern result metadata. */
declare function axMCPServerInfoFromMeta(meta: Readonly<AxMCPMeta> | undefined): AxMCPImplementationInfo | undefined;

interface AxMCPInputRequestHandlers {
    roots?: readonly AxMCPRoot[];
    sampling?: (params: Readonly<AxMCPSamplingCreateMessageParams>) => AxMCPSamplingCreateMessageResult | Promise<AxMCPSamplingCreateMessageResult>;
    elicitation?: (params: Readonly<AxMCPElicitationCreateParams>) => AxMCPElicitationCreateResult | Promise<AxMCPElicitationCreateResult>;
}
/** Fulfills one MCP 2026-07-28 multi round-trip input request map. */
declare function axMCPFulfillInputRequests(inputRequests: Readonly<Record<string, AxMCPInputRequest>>, handlers: Readonly<AxMCPInputRequestHandlers>): Promise<Record<string, AxMCPInputResponse>>;

interface AxMCPVerifiedJWT {
    header: Readonly<Record<string, unknown>>;
    claims: Readonly<Record<string, unknown>>;
}
/** Browser-compatible OAuth/OIDC JWT verifier backed by Web Crypto and JWKS. */
declare class AxMCPOAuthJWTVerifier {
    private readonly options;
    private readonly jwksCache;
    constructor(options?: Readonly<AxMCPOAuthJWTValidationOptions>);
    verify(token: string, expected: Readonly<{
        issuer: string;
        audience: string | readonly string[];
        nonce?: string;
        jwksUri: string;
    }>): Promise<AxMCPVerifiedJWT>;
    clearJWKSCache(jwksUri?: string): void;
    private getJWKS;
    private validateClaims;
}

declare class AxMCPStreamableHTTPTransport implements AxMCPTransport {
    private readonly options;
    readonly eraCacheKey: string;
    private mcpEndpoint;
    private era?;
    private sessionId?;
    private protocolVersion?;
    private pendingRequests;
    private messageHandler?;
    private lifecycleHandler?;
    private customHeaders;
    private oauthHelper;
    private listeningAbort?;
    private oauthToken?;
    private readonly requestMetadata;
    private readonly responseRetryCounts;
    private readonly defaultRetryStatuses;
    constructor(mcpEndpoint: string, options?: Readonly<AxMCPStreamableHTTPTransportOptions>);
    setHeaders(headers: Record<string, string>): void;
    setAuthorization(authorization: string): void;
    getHeaders(): Record<string, string>;
    setProtocolVersion(protocolVersion: string): void;
    setEra(era: AxMCPEra): void;
    takeRequestMetadata(id: string | number): Readonly<{
        retryCount?: number;
    }> | undefined;
    private buildHeaders;
    private fetchEndpoint;
    setMessageHandler(handler: (message: Readonly<AxMCPJSONRPCMessage>) => void | Promise<void>): void;
    setLifecycleHandler(handler: (state: 'reconnected') => void | Promise<void>): void;
    connect(): Promise<void>;
    openListeningStream(): Promise<void>;
    startListening(options?: Readonly<AxMCPListeningOptions>): AxMCPListeningHandle;
    openRequestStream(request: Readonly<AxMCPJSONRPCRequest<unknown>>, options?: Readonly<AxMCPListeningOptions>): AxMCPListeningHandle;
    send(message: Readonly<AxMCPJSONRPCRequest<unknown>>, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPJSONRPCResponse<unknown>>;
    sendBatch(messages: readonly Readonly<AxMCPJSONRPCRequest<unknown>>[], options?: Readonly<AxMCPRequestOptions>): Promise<readonly AxMCPJSONRPCResponse<unknown>[]>;
    sendNotification(message: Readonly<AxMCPJSONRPCNotification>): Promise<void>;
    sendResponse(message: Readonly<AxMCPJSONRPCResponse>): Promise<void>;
    terminateSession(): Promise<void>;
    close(): void;
    private postMessage;
    private headerContextForMessage;
    private parseHTTPJSONRPCError;
    private readHTTPErrorBody;
    private shouldTryLegacySSEFallback;
    private openLegacySSEEndpoint;
    private parseLegacyEndpoint;
    private applyOAuthIfNeeded;
    private handleSSEResponse;
    private consumeListeningStream;
    private consumeRequestStream;
    private openGETStream;
    private consumeSSE;
    private parseJSONRPCEvent;
    private readJSONResponse;
    private readJSONValue;
    private isSafeToRetry;
    private fetchWithRetry;
    private retryDelayMs;
    private delay;
}
/**
 * @deprecated Use AxMCPStreamableHTTPTransport. This misspelled export remains
 * for backward compatibility.
 */
declare class AxMCPStreambleHTTPTransport extends AxMCPStreamableHTTPTransport {
}

type AxMCPTransportRecordingEntry = {
    direction: 'request';
    message: AxMCPJSONRPCRequest<unknown>;
    response: AxMCPJSONRPCResponse<unknown>;
} | {
    direction: 'notification';
    message: AxMCPJSONRPCNotification;
} | {
    direction: 'response';
    message: AxMCPJSONRPCResponse;
} | {
    direction: 'inbound';
    message: AxMCPJSONRPCMessage;
};
declare class AxMCPRecordingTransport implements AxMCPTransport {
    private readonly inner;
    readonly evaluationMode: "record";
    private readonly entries;
    private handler?;
    private lifecycleHandler?;
    constructor(inner: AxMCPTransport);
    get eraHint(): AxMCPEra | undefined;
    get eraCacheKey(): string | undefined;
    setEra(era: AxMCPEra): void;
    getRecording(): readonly AxMCPTransportRecordingEntry[];
    send(message: Readonly<AxMCPJSONRPCRequest<unknown>>, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPJSONRPCResponse<unknown>>;
    sendBatch(messages: readonly Readonly<AxMCPJSONRPCRequest<unknown>>[], options?: Readonly<AxMCPRequestOptions>): Promise<readonly AxMCPJSONRPCResponse<unknown>[]>;
    sendNotification(message: Readonly<AxMCPJSONRPCNotification>): Promise<void>;
    sendResponse(message: Readonly<AxMCPJSONRPCResponse>): Promise<void>;
    setMessageHandler(handler: (message: Readonly<AxMCPJSONRPCMessage>) => void | Promise<void>): void;
    setLifecycleHandler(handler: (state: AxMCPTransportLifecycleState) => void | Promise<void>): void;
    setProtocolVersion(protocolVersion: string): void;
    takeRequestMetadata(id: string | number): Readonly<{
        retryCount?: number;
    }> | undefined;
    connect(): Promise<void>;
    startListening(options?: Readonly<AxMCPListeningOptions>): AxMCPListeningHandle | Promise<AxMCPListeningHandle>;
    terminateSession(): Promise<void>;
    close(): Promise<void>;
}
declare class AxMCPReplayTransport implements AxMCPTransport {
    private readonly options;
    readonly evaluationMode: "replay";
    readonly eraHint: AxMCPEra;
    private requestIndex;
    private readonly requests;
    constructor(recording: readonly AxMCPTransportRecordingEntry[], options?: Readonly<{
        strict?: boolean;
    }>);
    send(message: Readonly<AxMCPJSONRPCRequest<unknown>>): Promise<AxMCPJSONRPCResponse<unknown>>;
    sendBatch(messages: readonly Readonly<AxMCPJSONRPCRequest<unknown>>[]): Promise<readonly AxMCPJSONRPCResponse<unknown>[]>;
    sendNotification(): Promise<void>;
    takeRequestMetadata(): Readonly<{
        retryCount?: number;
    }>;
}

/** @deprecated Use `AxMCPStreamableHTTPTransport`; this transport is for legacy HTTP/SSE servers. */
declare class AxMCPHTTPSSETransport implements AxMCPTransport {
    private readonly options;
    private endpoint;
    private sseUrl;
    private eventSource?;
    private customHeaders;
    private oauthHelper;
    private sseAbort?;
    private pendingRequests;
    private messageHandler?;
    private endpointReady?;
    private streamDone?;
    constructor(sseUrl: string, options?: Readonly<AxMCPStreamableHTTPTransportOptions>);
    private buildHeaders;
    private fetchEndpoint;
    setMessageHandler(handler: (message: Readonly<AxMCPJSONRPCMessage>) => void | Promise<void>): void;
    private openSSEWithFetch;
    private createEndpointReady;
    private consumeSSEStream;
    connect(): Promise<void>;
    startListening(): Promise<AxMCPListeningHandle>;
    send(message: Readonly<AxMCPJSONRPCRequest<unknown>>): Promise<AxMCPJSONRPCResponse<unknown>>;
    sendNotification(message: Readonly<AxMCPJSONRPCNotification>): Promise<void>;
    sendResponse(message: Readonly<AxMCPJSONRPCResponse>): Promise<void>;
    close(): void;
}

interface AxMCPWebSocketLike {
    readyState: number;
    /**
     * Set to `'arraybuffer'` by the transport so that binary frames arrive in a
     * form it can decode synchronously.
     */
    binaryType?: string;
    send(data: string): void;
    close(code?: number, reason?: string): void;
    addEventListener(type: 'open' | 'message' | 'error' | 'close', listener: (event: any) => void, options?: {
        once?: boolean;
    }): void;
}
interface AxMCPWebSocketTransportOptions {
    protocols?: string | string[];
    webSocketFactory?: (url: string, protocols?: string | string[]) => AxMCPWebSocketLike;
}
declare class AxMCPWebSocketTransport implements AxMCPTransport {
    private readonly url;
    private readonly options;
    readonly eraHint: "legacy";
    private socket?;
    private connectPromise?;
    private listeningDone?;
    private resolveListening?;
    private rejectListening?;
    private closing;
    private protocolVersion?;
    private handler?;
    private readonly pending;
    constructor(url: string, options?: Readonly<AxMCPWebSocketTransportOptions>);
    connect(): Promise<void>;
    startListening(): Promise<AxMCPListeningHandle>;
    setProtocolVersion(protocolVersion: string): void;
    takeRequestMetadata(): Readonly<{
        retryCount?: number;
    }>;
    setMessageHandler(handler: (message: Readonly<AxMCPJSONRPCMessage>) => void | Promise<void>): void;
    send(message: Readonly<AxMCPJSONRPCRequest<unknown>>, options?: Readonly<AxMCPRequestOptions>): Promise<AxMCPJSONRPCResponse<unknown>>;
    sendBatch(messages: readonly Readonly<AxMCPJSONRPCRequest<unknown>>[], options?: Readonly<AxMCPRequestOptions>): Promise<readonly AxMCPJSONRPCResponse<unknown>[]>;
    sendNotification(message: Readonly<AxMCPJSONRPCNotification>): Promise<void>;
    sendResponse(message: Readonly<AxMCPJSONRPCResponse>): Promise<void>;
    close(): void;
    private handlePayload;
}

/** True when an MCP mirrored value can be emitted without sentinel encoding. */
declare function axMCPIsPlainHeaderValue(value: string): boolean;
/** Encodes an MCP name or mirrored parameter as an RFC 9110 field value. */
declare function axMCPEncodeHeaderValue(value: string): string;
/** Decodes the MCP Base64 sentinel form, leaving ordinary field values intact. */
declare function axMCPDecodeHeaderValue(value: string): string;

interface AxMCPParamHeaderBinding {
    /** Full HTTP field name, including the MCP prefix. */
    headerName: string;
    /** Exact object-property path used to read the tool argument. */
    path: readonly string[];
    type: 'string' | 'integer' | 'boolean';
}
/** Raised when an `x-mcp-header` annotation makes a tool schema invalid. */
declare class AxMCPParamHeaderSchemaError extends Error {
    constructor(message: string);
}
/** Validates and extracts every statically reachable parameter-header binding. */
declare function axMCPParamHeaderBindings(inputSchema: Readonly<AxMCPJSONSchema>): readonly AxMCPParamHeaderBinding[];
/** Builds encoded `Mcp-Param-*` fields from validated tool arguments. */
declare function axMCPBuildParamHeaders(inputSchema: Readonly<AxMCPJSONSchema>, args: unknown): Readonly<Record<string, string>>;

declare const axSpanAttributes: {
    readonly LLM_SYSTEM: "gen_ai.system";
    readonly LLM_OPERATION_NAME: "gen_ai.operation.name";
    readonly LLM_REQUEST_MODEL: "gen_ai.request.model";
    readonly LLM_REQUEST_MAX_TOKENS: "gen_ai.request.max_tokens";
    readonly LLM_REQUEST_TEMPERATURE: "gen_ai.request.temperature";
    readonly LLM_REQUEST_TOP_K: "gen_ai.request.top_k";
    readonly LLM_REQUEST_FREQUENCY_PENALTY: "gen_ai.request.frequency_penalty";
    readonly LLM_REQUEST_PRESENCE_PENALTY: "gen_ai.request.presence_penalty";
    readonly LLM_REQUEST_STOP_SEQUENCES: "gen_ai.request.stop_sequences";
    readonly LLM_REQUEST_LLM_IS_STREAMING: "gen_ai.request.llm_is_streaming";
    readonly LLM_REQUEST_TOP_P: "gen_ai.request.top_p";
    readonly LLM_RESPONSE_ID: "gen_ai.response.id";
    readonly LLM_RESPONSE_MODEL: "gen_ai.response.model";
    readonly LLM_CONVERSATION_ID: "gen_ai.conversation.id";
    readonly LLM_USAGE_INPUT_TOKENS: "gen_ai.usage.input_tokens";
    readonly LLM_USAGE_OUTPUT_TOKENS: "gen_ai.usage.output_tokens";
    readonly LLM_USAGE_TOTAL_TOKENS: "gen_ai.usage.total_tokens";
    readonly LLM_USAGE_THOUGHTS_TOKENS: "gen_ai.usage.thoughts_tokens";
    readonly AX_SESSION_ID: "ax.session.id";
    readonly AX_PROVIDER_REQUEST_ID: "ax.provider.request_id";
    readonly AX_PROVIDER_SESSION_ID: "ax.provider.session_id";
};
declare const axSpanEvents: {
    readonly GEN_AI_USER_MESSAGE: "gen_ai.user.message";
    readonly GEN_AI_SYSTEM_MESSAGE: "gen_ai.system.message";
    readonly GEN_AI_ASSISTANT_MESSAGE: "gen_ai.assistant.message";
    readonly GEN_AI_TOOL_MESSAGE: "gen_ai.tool.message";
    readonly GEN_AI_CHOICE: "gen_ai.choice";
    readonly GEN_AI_USAGE: "gen_ai.usage";
};

interface AxRateLimiterTokenUsageOptions {
    debug?: boolean;
}
declare class AxRateLimiterTokenUsage {
    private options?;
    private maxTokens;
    private refillRate;
    private currentTokens;
    private lastRefillTime;
    constructor(maxTokens: number, refillRate: number, options?: Readonly<AxRateLimiterTokenUsageOptions>);
    private refillTokens;
    private waitUntilTokensAvailable;
    acquire(tokens: number): Promise<void>;
}

/**
 * Non-serializable runtime-hook state propagated through nested programs.
 * Symbols survive object spreads but are ignored by JSON, cache keys, and
 * exported program state.
 */
declare const axRuntimeHookFrame: unique symbol;
type AxRuntimeHookFrame = Readonly<{
    globals: AxRuntimeHooks;
    /** The option hook fields are fully resolved and may intentionally be empty. */
    resolved?: boolean;
}>;
type AxRuntimeHookFramedOptions = Readonly<{
    [axRuntimeHookFrame]?: AxRuntimeHookFrame;
}>;
declare function axGetRuntimeHookFrame(options: unknown): AxRuntimeHookFrame | undefined;
declare function axFailOpenSpan(span: Span): Span;
declare function axStartSpanFailOpen(tracer: Tracer | undefined, name: string, options?: SpanOptions, parentContext?: Context): Span | undefined;
declare function axStartActiveSpanFailOpen<T>(tracer: Tracer | undefined, name: string, options: SpanOptions, parentContext: Context | undefined, operation: (span?: Span) => Promise<T>): Promise<T>;

export { AxACE, type AxACEBullet, type AxACECuratorOperation, type AxACECuratorOperationType, type AxACECuratorOutput, type AxACEFeedbackEvent, type AxACEGeneratorOutput, type AxACEOptimizationArtifact, AxACEOptimizedProgram, type AxACEOptions, type AxACEPlaybook, type AxACEReflectionOutput, type AxACEResult, AxAI, AxAIAnthropic, type AxAIAnthropicArgs, type AxAIAnthropicChatError, type AxAIAnthropicChatRequest, type AxAIAnthropicChatRequestCacheParam, type AxAIAnthropicChatResponse, type AxAIAnthropicChatResponseDelta, type AxAIAnthropicConfig, type AxAIAnthropicContentBlockDeltaEvent, type AxAIAnthropicContentBlockStartEvent, type AxAIAnthropicContentBlockStopEvent, type AxAIAnthropicEffortLevel, type AxAIAnthropicEffortLevelMapping, type AxAIAnthropicErrorEvent, type AxAIAnthropicFunctionTool, type AxAIAnthropicMessageDeltaEvent, type AxAIAnthropicMessageStartEvent, type AxAIAnthropicMessageStopEvent, AxAIAnthropicModel, type AxAIAnthropicOutputConfig, type AxAIAnthropicPingEvent, type AxAIAnthropicRequestTool, type AxAIAnthropicStopDetails, type AxAIAnthropicTaskBudget, type AxAIAnthropicThinkingConfig, type AxAIAnthropicThinkingTokenBudgetLevels, type AxAIAnthropicThinkingWire, AxAIAnthropicVertexModel, type AxAIAnthropicWebSearchTool, type AxAIArgs, AxAICohereEmbedModel, AxAICohereModel, type AxAICredentialProvider, type AxAICredentialRequest, AxAIDeepSeekModel, type AxAIDeploymentProfileArgs, type AxAIDeploymentProfileId, type AxAIEmbedModels, type AxAIFeatures, AxAIGoogleGemini, type AxAIGoogleGeminiArgs, type AxAIGoogleGeminiBatchEmbedRequest, type AxAIGoogleGeminiBatchEmbedResponse, type AxAIGoogleGeminiCacheCreateRequest, type AxAIGoogleGeminiCacheResponse, type AxAIGoogleGeminiCacheUpdateRequest, type AxAIGoogleGeminiChatRequest, type AxAIGoogleGeminiChatResponse, type AxAIGoogleGeminiChatResponseDelta, type AxAIGoogleGeminiConfig, type AxAIGoogleGeminiContent, type AxAIGoogleGeminiContentPart, AxAIGoogleGeminiEmbedModel, AxAIGoogleGeminiEmbedTypes, type AxAIGoogleGeminiGenerationConfig, AxAIGoogleGeminiModel, type AxAIGoogleGeminiOptionsTools, type AxAIGoogleGeminiRetrievalConfig, AxAIGoogleGeminiSafetyCategory, type AxAIGoogleGeminiSafetySettings, AxAIGoogleGeminiSafetyThreshold, type AxAIGoogleGeminiThinkingConfig, type AxAIGoogleGeminiThinkingLevel, type AxAIGoogleGeminiThinkingLevelMapping, type AxAIGoogleGeminiThinkingTokenBudgetLevels, type AxAIGoogleGeminiTool, type AxAIGoogleGeminiToolConfig, type AxAIGoogleGeminiToolFunctionDeclaration, type AxAIGoogleGeminiToolGoogleMaps, type AxAIGoogleGeminiToolGoogleSearchRetrieval, type AxAIGoogleVertexBatchEmbedRequest, type AxAIGoogleVertexBatchEmbedResponse, type AxAIGoogleVertexEmbedContentRequest, type AxAIGoogleVertexEmbedContentResponse, AxAIGrokEmbedModels, AxAIGrokModel, type AxAIInputModelList, type AxAIMemory, type AxAIMetaArgs, type AxAIMetaChatArgs, type AxAIMetaChatConfig, type AxAIMetaMessagesArgs, type AxAIMetaMessagesConfig, AxAIMetaModel, type AxAIMetaResponsesArgs, type AxAIMetaResponsesConfig, type AxAIMetaSparkModel, type AxAIMetricsInstruments, AxAIMistralEmbedModels, AxAIMistralModel, type AxAIModelCatalogAudioSupport, type AxAIModelCatalogFilter, type AxAIModelCatalogModel, type AxAIModelCatalogModelCapabilities, type AxAIModelCatalogModelType, type AxAIModelCatalogOptions, type AxAIModelCatalogProvider, type AxAIModelCatalogProviderCapabilities, type AxAIModelCatalogProviderName, type AxAIModelCatalogThinkingLevel, type AxAIModelList, type AxAIModelListBase, type AxAIModels, AxAIOpenAI, type AxAIOpenAIAnnotation, type AxAIOpenAIArgs, AxAIOpenAIBase, type AxAIOpenAIBaseArgs, type AxAIOpenAIChatContentPart, type AxAIOpenAIChatRequest, type AxAIOpenAIChatResponse, type AxAIOpenAIChatResponseDelta, type AxAIOpenAIConfig, AxAIOpenAIEmbedModel, type AxAIOpenAIEmbedRequest, type AxAIOpenAIEmbedResponse, type AxAIOpenAILogprob, AxAIOpenAIModel, AxAIOpenAIProfile, type AxAIOpenAIProfileArgs, type AxAIOpenAIPromptCacheBreakpoint, type AxAIOpenAIResponseDelta, AxAIOpenAIResponses, type AxAIOpenAIResponsesArgs, AxAIOpenAIResponsesBase, type AxAIOpenAIResponsesCodeInterpreterToolCall, type AxAIOpenAIResponsesComputerToolCall, type AxAIOpenAIResponsesConfig, type AxAIOpenAIResponsesContentPartAddedEvent, type AxAIOpenAIResponsesContentPartDoneEvent, type AxAIOpenAIResponsesDefineFunctionTool, type AxAIOpenAIResponsesDefineImageGenerationTool, type AxAIOpenAIResponsesErrorEvent, type AxAIOpenAIResponsesFileSearchCallCompletedEvent, type AxAIOpenAIResponsesFileSearchCallInProgressEvent, type AxAIOpenAIResponsesFileSearchCallSearchingEvent, type AxAIOpenAIResponsesFileSearchToolCall, type AxAIOpenAIResponsesFunctionCallArgumentsDeltaEvent, type AxAIOpenAIResponsesFunctionCallArgumentsDoneEvent, type AxAIOpenAIResponsesFunctionCallItem, type AxAIOpenAIResponsesImageGenerationCallCompletedEvent, type AxAIOpenAIResponsesImageGenerationCallGeneratingEvent, type AxAIOpenAIResponsesImageGenerationCallInProgressEvent, type AxAIOpenAIResponsesImageGenerationCallPartialImageEvent, type AxAIOpenAIResponsesImageGenerationToolCall, type AxAIOpenAIResponsesInputAudioContentPart, type AxAIOpenAIResponsesInputContentPart, type AxAIOpenAIResponsesInputFileContentPart, type AxAIOpenAIResponsesInputFunctionCallItem, type AxAIOpenAIResponsesInputFunctionCallOutputItem, type AxAIOpenAIResponsesInputImageGenerationCallItem, type AxAIOpenAIResponsesInputImageUrlContentPart, type AxAIOpenAIResponsesInputItem, type AxAIOpenAIResponsesInputMessageItem, type AxAIOpenAIResponsesInputReasoningItem, type AxAIOpenAIResponsesInputTextContentPart, type AxAIOpenAIResponsesInputVideoContentPart, type AxAIOpenAIResponsesLocalShellToolCall, type AxAIOpenAIResponsesMCPCallArgumentsDeltaEvent, type AxAIOpenAIResponsesMCPCallArgumentsDoneEvent, type AxAIOpenAIResponsesMCPCallCompletedEvent, type AxAIOpenAIResponsesMCPCallFailedEvent, type AxAIOpenAIResponsesMCPCallInProgressEvent, type AxAIOpenAIResponsesMCPListToolsCompletedEvent, type AxAIOpenAIResponsesMCPListToolsFailedEvent, type AxAIOpenAIResponsesMCPListToolsInProgressEvent, type AxAIOpenAIResponsesMCPToolCall, AxAIOpenAIResponsesModel, type AxAIOpenAIResponsesOutputItem, type AxAIOpenAIResponsesOutputItemAddedEvent, type AxAIOpenAIResponsesOutputItemDoneEvent, type AxAIOpenAIResponsesOutputMessageItem, type AxAIOpenAIResponsesOutputRefusalContentPart, type AxAIOpenAIResponsesOutputTextAnnotationAddedEvent, type AxAIOpenAIResponsesOutputTextContentPart, type AxAIOpenAIResponsesOutputTextDeltaEvent, type AxAIOpenAIResponsesOutputTextDoneEvent, AxAIOpenAIResponsesProfile, type AxAIOpenAIResponsesReasoningDeltaEvent, type AxAIOpenAIResponsesReasoningDoneEvent, type AxAIOpenAIResponsesReasoningItem, type AxAIOpenAIResponsesReasoningSummaryDeltaEvent, type AxAIOpenAIResponsesReasoningSummaryDoneEvent, type AxAIOpenAIResponsesReasoningSummaryPart, type AxAIOpenAIResponsesReasoningSummaryPartAddedEvent, type AxAIOpenAIResponsesReasoningSummaryPartDoneEvent, type AxAIOpenAIResponsesReasoningSummaryTextDeltaEvent, type AxAIOpenAIResponsesReasoningSummaryTextDoneEvent, type AxAIOpenAIResponsesReasoningTextDeltaEvent, type AxAIOpenAIResponsesReasoningTextDoneEvent, type AxAIOpenAIResponsesRefusalDeltaEvent, type AxAIOpenAIResponsesRefusalDoneEvent, type AxAIOpenAIResponsesRequest, type AxAIOpenAIResponsesResponse, type AxAIOpenAIResponsesResponseCompletedEvent, type AxAIOpenAIResponsesResponseCreatedEvent, type AxAIOpenAIResponsesResponseFailedEvent, type AxAIOpenAIResponsesResponseInProgressEvent, type AxAIOpenAIResponsesResponseIncompleteEvent, type AxAIOpenAIResponsesResponseQueuedEvent, type AxAIOpenAIResponsesStreamEvent, type AxAIOpenAIResponsesStreamEventBase, type AxAIOpenAIResponsesToolCall, type AxAIOpenAIResponsesToolCallBase, type AxAIOpenAIResponsesToolChoice, type AxAIOpenAIResponsesToolDefinition, type AxAIOpenAIResponsesWebSearchCallCompletedEvent, type AxAIOpenAIResponsesWebSearchCallInProgressEvent, type AxAIOpenAIResponsesWebSearchCallSearchingEvent, type AxAIOpenAIResponsesWebSearchToolCall, type AxAIOpenAIUrlCitation, type AxAIOpenAIUsage, type AxAIProfileArgs, type AxAIProfileAuthentication, type AxAIProfileCapabilities, type AxAIProfileEndpoint, type AxAIProfileId, type AxAIProfileModelRule, type AxAIProfileOperation, type AxAIProfileRequestRules, type AxAIProfileSummary, type AxAIProfileTransport, AxAIRefusalError, AxAIRekaModel, type AxAIService, AxAIServiceAbortedError, type AxAIServiceActionOptions, AxAIServiceAuthenticationError, AxAIServiceError, type AxAIServiceImpl, type AxAIServiceMetrics, type AxAIServiceModelType, AxAIServiceNetworkError, type AxAIServiceOptions, AxAIServiceResponseError, AxAIServiceStatusError, AxAIServiceStreamTerminatedError, AxAIServiceTimeoutError, AxAITypesafe, type AxAITypesafeAnswer, type AxAITypesafeArgs, type AxAITypesafeChoiceQuestion, AxAITypesafeClient, type AxAITypesafeClientArgs, type AxAITypesafeClientOptions, type AxAITypesafeEntry, type AxAITypesafeJsonValue, type AxAITypesafeModelCard, type AxAITypesafeNoulQuestion, type AxAITypesafeQuestion, type AxAITypesafeQuestions, type AxAITypesafeRequest, type AxAITypesafeResponse, type AxAITypesafeScoreQuestion, AxAIWebLLM, type AxAIWebLLMArgs, type AxAIWebLLMChatRequest, type AxAIWebLLMChatResponse, type AxAIWebLLMChatResponseDelta, type AxAIWebLLMConfig, type AxAIWebLLMEmbedModel, type AxAIWebLLMEmbedRequest, type AxAIWebLLMEmbedResponse, type AxAIWebLLMEngine, AxAIWebLLMModel, type AxAIWebLLMModelId, type AxAPI, type AxAPIConfig, type AxAPIResponseMetadata, AxAgent, type AxAgentActorTurnCallback, type AxAgentActorTurnCallbackArgs, type AxAgentAutoPromotionRecord, type AxAgentAutoUpgrade, type AxAgentCatalogSkill, type AxAgentCitations, type AxAgentCitationsOutput, type AxAgentClarification, type AxAgentClarificationChoice, AxAgentClarificationError, type AxAgentClarificationKind, type AxAgentCompletionProtocol, type AxAgentConfig, type AxAgentContextEvent, AxAgentContextMap, type AxAgentContextMapConfig, type AxAgentContextMapOperation, type AxAgentContextMapOptions, type AxAgentContextMapSnapshot, type AxAgentContextMapUpdateResult, type AxAgentContextPressure, type AxAgentContextStage, type AxAgentDemos, type AxAgentDirectResponse, type AxAgentDiscoveryPromptState, type AxAgentEvalBatchResult, type AxAgentEvalBudget, type AxAgentEvalDataset, type AxAgentEvalFunctionCall, type AxAgentEvalPrediction, type AxAgentEvalTask, type AxAgentExecutorResultPayload, type AxAgentFailureCluster, type AxAgentFailureReport, type AxAgentFailureSignal, type AxAgentFailureSignalKind, type AxAgentForwardOptions, type AxAgentFunction, type AxAgentFunctionCall, type AxAgentFunctionCallRecorder, type AxAgentFunctionCollection, type AxAgentFunctionExample, type AxAgentFunctionGroup, type AxAgentFunctionModuleMeta, type AxAgentGuidanceLogEntry, type AxAgentGuidancePayload, type AxAgentGuidanceState, type AxAgentIdentity, type AxAgentInputUpdateCallback, type AxAgentJudgeEvalInput, type AxAgentJudgeEvalOutput, type AxAgentJudgeInput, type AxAgentJudgeOptions, type AxAgentJudgeOutput, type AxAgentMemoriesSearchFn, type AxAgentMemoryEntry, type AxAgentMemoryResult, type AxAgentMetricsInstruments, type AxAgentOnContextEvent, type AxAgentOnFunctionCall, type AxAgentOptimizationTargetDescriptor, type AxAgentOptimizeOptions, type AxAgentOptimizeResult, type AxAgentOptimizeTarget, type AxAgentOptions, AxAgentPlaybook, type AxAgentPlaybookConfig, type AxAgentPlaybookEvolveOptions, type AxAgentPlaybookEvolveOutcome, type AxAgentPlaybookEvolveProgressEvent, type AxAgentPlaybookEvolveProposal, type AxAgentPlaybookEvolveResult, type AxAgentPlaybookEvolveRunRecord, type AxAgentPlaybookLearnOptions, type AxAgentPlaybookOptions, type AxAgentPlaybookSkipReason, type AxAgentPlaybookUpdateResult, type AxAgentPlaybookUpdateStatus, type AxAgentPlaybookWeakness, AxAgentProtocolCompletionSignal, type AxAgentRecursionOptions, type AxAgentRecursiveExpensiveNode, type AxAgentRecursiveFunctionCall, type AxAgentRecursiveNodeRole, type AxAgentRecursiveStats, type AxAgentRecursiveTargetId, type AxAgentRecursiveTraceNode, type AxAgentRecursiveTurn, type AxAgentRecursiveUsage, type AxAgentRuntimeCompletionState, type AxAgentRuntimeExecutionContext, type AxAgentRuntimeInputState, AxAgentSharedRuntimeSession, type AxAgentSkillResult, type AxAgentSkillsPromptState, type AxAgentSkillsSearchFn, type AxAgentStagePolicy, type AxAgentStageVariant, type AxAgentState, type AxAgentStateActionLogEntry, type AxAgentStateCheckpointState, type AxAgentStateExecutorModelState, type AxAgentStateRuntimeEntry, type AxAgentStreamingForwardOptions, type AxAgentStructuredClarification, type AxAgentTestCompletionPayload, type AxAgentTestResult, type AxAgentUsage, type AxAgentUsedMemoriesCallback, type AxAgentUsedMemory, type AxAgentUsedSkill, type AxAgentUsedSkillsCallback, type AxAgentic, type AxAnyAgentic, type AxAppliedServiceTier, type AxAssertion, AxAssertionError, type AxAttempt, type AxAudioFormat, type AxAudioInput, AxBalancer, type AxBalancerAdaptiveStrategy, type AxBalancerCandidateScore, type AxBalancerCostContext, type AxBalancerExpectedTokens, type AxBalancerFailureReason, type AxBalancerOptions, type AxBalancerRouteStats, type AxBalancerRoutingContext, type AxBalancerRoutingEvent, type AxBalancerStatsKey, type AxBalancerStatsObservation, type AxBalancerStatsStore, AxBaseAI, type AxBaseAIArgs, AxBaseOptimizer, AxBestOfN, type AxBestOfNOptions, AxBootstrapFewShot, type AxBootstrapOptimizerOptions, type AxChatAudioConfig, type AxChatAudioOutput, type AxChatImageOutput, type AxChatLogEntry, type AxChatLogMessage, type AxChatRequest, type AxChatResponse, type AxChatResponseFunctionCall, type AxChatResponseResult, type AxChatSession, type AxChatSessionEvent, type AxCheckpointLoadFn, type AxCheckpointSaveFn, type AxCitation, type AxCodeExecutionResult, type AxCodeRuntime, type AxCodeSession, type AxCodeSessionSnapshot, type AxCodeSessionSnapshotEntry, type AxCompileOptions, AxContentProcessingError, type AxContentProcessingServices, type AxContextCacheInfo, type AxContextCacheOperation, type AxContextCacheOptions, type AxContextCacheRegistry, type AxContextCacheRegistryEntry, type AxContextFieldInput, type AxContextFieldPromptConfig, AxContextMetricsCollector, type AxContextMetricsRow, type AxContextMetricsSummary, type AxContextPolicyBudget, type AxContextPolicyConfig, type AxContextPolicyPreset, type AxContextScenario, type AxContextTurnSample, type AxCostTracker, type AxCostTrackerOptions, type AxDateRange, type AxDateRangeValue, type AxDebugChatResponseUsage, AxDefaultCostTracker, type AxDiscoveryTurnSummary, type AxDockerContainer, AxDockerSession, type AxEmbedRequest, type AxEmbedResponse, AxEmbeddingAdapter, type AxErrorCategory, AxEvalUtil, type AxEvaluateArgs, AxEventBackpressureError, type AxEventClock, type AxEventCloseOptions, type AxEventContext, type AxEventContinuation, AxEventContinuationNotFoundError, type AxEventContinuationPlan, type AxEventContinuationRegistration, type AxEventCorrelationKey, type AxEventDeadLetter, type AxEventDelivery, type AxEventDeliveryStatus, type AxEventEnqueueRequest, type AxEventEnvelope, type AxEventIdentity, type AxEventIngress, type AxEventInheritance, type AxEventInputBuilder, type AxEventInputDefinition, AxEventInputError, type AxEventInputFieldMapping, type AxEventInputPlan, type AxEventInvalidator, type AxEventMatcher, AxEventOutcomeUnknownError, type AxEventPath, type AxEventPathRoot, type AxEventPathSegment, type AxEventPayloadStore, type AxEventProgramStateAdapter, type AxEventPublishReceipt, type AxEventRoute, type AxEventRouteAction, AxEventRouteBuilder, type AxEventRun, type AxEventRunStatus, AxEventRuntime, type AxEventRuntimeOptions, type AxEventScalar, type AxEventSink, type AxEventSinkAttempt, type AxEventSinkContext, type AxEventSource, type AxEventSourceContext, type AxEventSourceHandle, type AxEventStore, type AxEventStoreCapabilities, type AxEventStoreConformanceFactory, type AxEventStoreConformanceFactoryOptions, type AxEventStoreConformanceInstance, type AxEventStoreConformanceReport, type AxEventTarget, AxEventTargetBuilder, type AxEventTargetInputContext, type AxEventTrust, type AxEventValue, type AxEvidenceDescriptor, type AxExample, type AxExamples, type AxExecutorModelPolicy, type AxExecutorModelPolicyEntry, type AxField, type AxFieldOptions, type AxFieldProcessor, type AxFieldProcessorProcess, type AxFieldTemplateFn, type AxFieldType, type AxFieldValue, AxFlow, type AxFlowBranchEvaluationData, type AxFlowCompleteData, type AxFlowDynamicContext, type AxFlowErrorData, type AxFlowExecutionPlan, type AxFlowExecutionPlanGroup, type AxFlowExecutionPlanStep, type AxFlowForwardOptions, type AxFlowLogData, type AxFlowLoggerData, type AxFlowLoggerFunction, type AxFlowMermaidBindings, AxFlowMermaidError, type AxFlowMermaidNodeBinding, type AxFlowMermaidRenderOptions, type AxFlowMetricsInstruments, type AxFlowOptions, type AxFlowParallelGroupCompleteData, type AxFlowParallelGroupStartData, type AxFlowStartData, type AxFlowState, type AxFlowStateDependencyAnalysis, type AxFlowStepCompleteData, type AxFlowStepStartData, type AxFlowTypedParallelBranch, type AxFlowTypedSubContext, type AxFlowable, type AxFluentFieldInfo, AxFluentFieldType, type AxForwardable, type AxFunction, type AxFunctionCallRecord, type AxFunctionCallTrace, AxFunctionError, type AxFunctionHandler, type AxFunctionJSONSchema, AxFunctionProcessor, type AxFunctionProvider, type AxFunctionResult, type AxFunctionResultContent, type AxFunctionResultFormatter, AxGEPA, type AxGEPAAdapter, type AxGEPABatchEvaluation, type AxGEPABatchRow, type AxGEPABootstrapOptions, type AxGEPAComponentBanditState, AxGEPAComponentSelector, type AxGEPAComponentTarget, type AxGEPAEvaluationBatch, type AxGEPAEvaluationState, type AxGEPAOptimizationReport, type AxGEPAReflectiveTuple, type AxGEPATraceSummary, type AxGEPATraceSummaryCall, AxGen, type AxGenDeltaOut, type AxGenIn, type AxGenInput, type AxGenMetricsInstruments, type AxGenOut, type AxGenOutput, type AxGenStreamingOut, AxGenerateError, type AxGenerateErrorDetails, type AxGenerateResult, type AxIField, AxInMemoryBalancerStatsStore, AxInMemoryEventStore, type AxInMemoryEventStoreOptions, AxInMemoryProgramStateStore, type AxInputFunctionType, AxJSRuntime, type AxJSRuntimeNodePermissionAllowlist, type AxJSRuntimeOutputMode, AxJSRuntimePermission, type AxJSRuntimeResourceLimits, type AxJudgeForwardOptions, type AxJudgeOptions, type AxLlmQueryBudgetState, type AxLlmQueryPromptMode, type AxLoggerData, type AxLoggerFunction, type AxMCPAnnotations, AxMCPAppBridge, type AxMCPAppBridgeOptions, type AxMCPAppContextUpdate, type AxMCPAppDisplayMode, type AxMCPAppPermissions, type AxMCPAppResource, type AxMCPAppResourceCSP, type AxMCPAppResourceMeta, type AxMCPAppToolMeta, type AxMCPAppVisibility, type AxMCPAudioContent, type AxMCPAuthentication, type AxMCPAuthenticationRequest, type AxMCPAuthenticationResult, type AxMCPAuthenticationStrategy, type AxMCPBaseAnnotated, type AxMCPBatchRequest, type AxMCPBatchResponse, type AxMCPBlobResourceContents, type AxMCPCacheInfo, type AxMCPCacheableResult, type AxMCPCatalogCacheName, type AxMCPCatalogSnapshot, type AxMCPChatOptions, type AxMCPChatResult, AxMCPClient, type AxMCPClientCapabilities, type AxMCPClientEvent, type AxMCPClientListeningOptions, type AxMCPClientOptions, type AxMCPCompletionArgument, type AxMCPCompletionReference, type AxMCPCompletionRequest, type AxMCPCompletionResult, type AxMCPContent, type AxMCPContextRequest, type AxMCPContinuationState, type AxMCPCreateTaskResult, type AxMCPDPoPOptions, AxMCPDPoPProofFactory, type AxMCPDPoPProofRequest, type AxMCPDefaultEventRoutesOptions, type AxMCPDiscoverResult, type AxMCPElicitationAction, type AxMCPElicitationCreateParams, type AxMCPElicitationCreateResult, type AxMCPEmbeddedResource, type AxMCPEnterpriseAuthorizationContext, type AxMCPEnterpriseIdentityAssertionType, type AxMCPEnterpriseManagedAuthorizationOptions, type AxMCPEra, type AxMCPEraStore, AxMCPEventSource, type AxMCPEventSourceIdentity, type AxMCPEventSourceOptions, AxMCPExecutionContext, type AxMCPExtensionCapability, type AxMCPFetchOptions, type AxMCPFunctionDescription, type AxMCPFunctionOverride, AxMCPHTTPSSETransport, AxMCPHTTPStatusError, type AxMCPIcon, type AxMCPImageContent, type AxMCPImplementationInfo, type AxMCPInheritance, type AxMCPInitializeParams, type AxMCPInitializeResult, type AxMCPInputRequest, type AxMCPInputRequestHandlers, type AxMCPInputRequiredResult, type AxMCPInputResponse, type AxMCPInputResponseRequestParams, type AxMCPJSONRPCErrorResponse, type AxMCPJSONRPCMessage, type AxMCPJSONRPCNotification, type AxMCPJSONRPCRequest, type AxMCPJSONRPCResponse, type AxMCPJSONRPCSuccessResponse, type AxMCPJSONSchema, type AxMCPLegacyCreateTaskResult, type AxMCPListRootsResult, type AxMCPListeningHandle, type AxMCPListeningOptions, type AxMCPLoggingLevel, type AxMCPMTLSOptions, type AxMCPMeta, type AxMCPOAuthClientRegistration, type AxMCPOAuthJWTValidationOptions, AxMCPOAuthJWTVerifier, type AxMCPOAuthOptions, type AxMCPOAuthTokenEndpointAuthMethod, type AxMCPOAuthTokenIntrospection, type AxMCPOfficialExtension, type AxMCPPaginatedRequest, type AxMCPParamHeaderBinding, AxMCPParamHeaderSchemaError, type AxMCPProgressNotificationParams, type AxMCPPrompt, type AxMCPPromptArgument, type AxMCPPromptGetResult, type AxMCPPromptMessage, type AxMCPPromptsListResult, AxMCPProtocolError, type AxMCPProtocolVersion, AxMCPRecordingTransport, AxMCPReplayTransport, type AxMCPRequestMetaOptions, type AxMCPRequestOptions, type AxMCPResolvedContext, type AxMCPResource, type AxMCPResourceLink, type AxMCPResourceReadResult, type AxMCPResourceSubscriptionPolicy, type AxMCPResourceTemplate, type AxMCPResourceTemplatesListResult, type AxMCPResourcesListResult, type AxMCPResultType, type AxMCPRoot, type AxMCPSSRFProtectionContext, type AxMCPSSRFProtectionOptions, type AxMCPSamplingCreateMessageParams, type AxMCPSamplingCreateMessageResult, type AxMCPSamplingMessage, type AxMCPSamplingToolChoice, type AxMCPServerCapabilities, AxMCPStreamableHTTPTransport, type AxMCPStreamableHTTPTransportOptions, AxMCPStreambleHTTPTransport, type AxMCPSubscriptionFilter, type AxMCPSubscriptionsAcknowledgedParams, type AxMCPSubscriptionsListenParams, type AxMCPTask, type AxMCPTaskMetadata, type AxMCPTaskResult, type AxMCPTaskSnapshot, type AxMCPTaskStatus, type AxMCPTasksListResult, type AxMCPTextContent, type AxMCPTextResourceContents, type AxMCPTokenSet, type AxMCPTool, type AxMCPToolAnnotations, type AxMCPToolCallOutcome, type AxMCPToolCallParams, type AxMCPToolCallResult, type AxMCPToolsListResult, type AxMCPTransport, type AxMCPTransportLifecycleState, type AxMCPTransportRecordingEntry, type AxMCPVerifiedJWT, type AxMCPWebSocketLike, AxMCPWebSocketTransport, type AxMCPWebSocketTransportOptions, AxManualEventClock, AxMediaNotSupportedError, AxMemory, type AxMemoryData, type AxMemoryMessageValue, type AxMetricFn, type AxMetricFnArgs, type AxMetricsConfig, AxMockAIService, type AxMockAIServiceConfig, type AxModelConfig, type AxModelInfo, type AxModelInfoWithProvider, type AxModelUsage, type AxModuleRankInput, type AxMultiMetricFn, type AxMultiProviderConfig, AxMultiServiceRouter, type AxNamedProgramInstance, type AxOpenAIReasoningContentMode, type AxOptimizableComponent, type AxOptimizableValidator, type AxOptimizationCheckpoint, type AxOptimizationProgress, type AxOptimizationStats, type AxOptimizeOptions, type AxOptimizedProgram, AxOptimizedProgramImpl, type AxOptimizer, type AxOptimizerArgs, type AxOptimizerLoggerData, type AxOptimizerLoggerFunction, type AxOptimizerMetricsConfig, type AxOptimizerMetricsInstruments, type AxOptimizerResult, type AxParetoResult, AxPlaybook, type AxPlaybookEvolveOptions, type AxPlaybookEvolveResult, type AxPlaybookOptions, type AxPlaybookSnapshot, AxProgram, type AxProgramDemos, type AxProgramExamples, type AxProgramForwardOptions, type AxProgramForwardOptionsWithModels, type AxProgramOptions, type AxProgramStateEnvelope, type AxProgramStateStore, type AxProgramStreamingForwardOptions, type AxProgramStreamingForwardOptionsWithModels, type AxProgramTrace, type AxProgramUsage, type AxProgrammable, type AxPromptMetrics, AxPromptTemplate, type AxPromptTemplateOptions, type AxProviderMetadata, AxProviderRouter, AxPushEventSource, type AxRLMConfig, type AxRankDocumentsOptions, type AxRankModulesOptions, type AxRankableDocument, type AxRankableField, type AxRankedDocument, type AxRankedModule, type AxRateLimitInfo, type AxRateLimiterFunction, AxRateLimiterTokenUsage, type AxRateLimiterTokenUsageOptions, AxRefine, AxRefineError, type AxRefineOptions, type AxRefineStrategy, type AxRelevanceHints, type AxRenderedPrompt, type AxResolvedAgentPlaybookConfig, type AxResolvedAgentPlaybookLearn, type AxResolvedAutoUpgrade, type AxResolvedCitations, type AxResolvedContextPolicy, type AxResolvedExecutorModelPolicy, type AxResolvedExecutorModelPolicyEntry, type AxResultPickerFunction, type AxResultPickerFunctionFieldResults, type AxResultPickerFunctionFunctionResults, type AxRewardFn, type AxRewardFnArgs, type AxRolloutTrace, type AxRoutingResult, AxRunControl, type AxRunControlEvent, type AxRuntimeCallableFormatArgs, type AxRuntimeHookFrame, type AxRuntimeHookFramedOptions, type AxRuntimeHooks, type AxRuntimeLanguageInfo, type AxRuntimePrimitive, type AxRuntimePrimitiveExample, type AxRuntimePrimitiveOverrideMap, type AxRuntimePrimitiveSignature, type AxRuntimePrimitiveStage, type AxSamplePickerOptions, type AxSelfTuningConfig, type AxSerializedOptimizedProgram, type AxServiceTier, type AxServiceTierMap, type AxServiceTierPricing, type AxSetExamplesOptions, type AxSharedSessionPhase, AxSignature, AxSignatureBuilder, type AxSignatureConfig, type AxSignatureInput, type AxSpeechConfig, type AxSpeechRequest, type AxSpeechResponse, type AxStageDefinitionBuildOptions, type AxStageOptions, type AxStepContext, type AxStepHooks, type AxStepUsage, AxStopFunctionCallException, type AxStreamingAssertion, AxStreamingAssertionError, type AxStreamingEvent, type AxStreamingFieldProcessorProcess, AxStringUtil, type AxStructuredOutputMode, type AxStructuredOutputRung, AxSynth, type AxSynthExample, type AxSynthOptions, type AxSynthResult, type AxSynthesizerInit, type AxSynthesizerOptions, type AxSynthesizerRole, AxSystemEventClock, AxTestPrompt, type AxThoughtBlockItem, AxTimerEventSource, type AxTimerEventSourceOptions, AxTokenLimitError, type AxTokenUsage, type AxTranscriptionRequest, type AxTranscriptionResponse, type AxTranscriptionSegment, type AxTunable, type AxTypedExample, type AxUCPAttribution, type AxUCPBuyerContext, type AxUCPCallOptions, type AxUCPCartInput, type AxUCPCatalogLookupRequest, type AxUCPCatalogSearchRequest, type AxUCPCheckoutCompletion, type AxUCPCheckoutInput, AxUCPClient, type AxUCPClientOptions, type AxUCPDiscounts, type AxUCPFulfillment, AxUCPHTTPMessageSignatureError, type AxUCPHTTPMessageSignatureErrorCode, type AxUCPHTTPMessageSignatureOptions, type AxUCPHTTPMessageVerificationOptions, AxUCPHTTPMessageVerifier, type AxUCPIdentityLinkingConfig, type AxUCPMessage, type AxUCPNegotiatedProfile, type AxUCPOperation, type AxUCPOrderEvent, type AxUCPOutcome, type AxUCPPayment, type AxUCPPaymentHandler, type AxUCPProductRequest, type AxUCPProfile, type AxUCPProfileBody, type AxUCPResponseMetadata, AxUCPSchemaValidationError, type AxUCPSchemaValidationOptions, AxUCPSchemaValidator, type AxUCPService, type AxUCPTransportKind, type AxUCPValue, type AxUCPVersionedDeclaration, AxUCPWebhookEventSource, type AxUCPWebhookEventSourceOptions, type AxUsable, type AxUsageContext, type AxUsageEvent, type AxUsageObserver, type AxWorkerRuntimeConfig, agent, ai, ax, axAIAnthropicDefaultConfig, axAIAnthropicVertexDefaultConfig, axAIGoogleGeminiDefaultConfig, axAIGoogleGeminiDefaultCreativeConfig, axAIGoogleGeminiLiveAudioDefaultConfig, axAIGrokBestConfig, axAIGrokDefaultConfig, axAIGrokVoiceDefaultConfig, axAIOpenAIAudioDefaultConfig, axAIOpenAIBestConfig, axAIOpenAICreativeConfig, axAIOpenAIDefaultConfig, axAIOpenAIFastConfig, axAIOpenAIRealtimeDefaultConfig, axAIOpenAIRealtimeTranscriptionDefaultConfig, axAIOpenAIResponsesBestConfig, axAIOpenAIResponsesCreativeConfig, axAIOpenAIResponsesDefaultConfig, axAIProfiles, axAIProviderAliases, axAIProviderProfileIds, axAIProviderProfiles, axAIWebLLMCreativeConfig, axAIWebLLMDefaultConfig, axAnalyzeChatPromptRequirements, axAnalyzeRequestRequirements, axApplyMCPAuthentication, axApplyOpenAIChatAudioRequest, axAudioFormatFromMimeType, axAudioInputFilename, axAudioInputToBlob, axAudioMimeType, axAudioParamsFromMimeType, axBaseAIDefaultConfig, axBaseAIDefaultCreativeConfig, axBuildDistillerDefinition, axBuildExecutorDefinition, axBuildResponderDefinition, axCheckMetricsHealth, axConcatBase64, axCreateDefaultColorLogger, axCreateDefaultOptimizerColorLogger, axCreateDefaultOptimizerTextLogger, axCreateDefaultTextLogger, axCreateFlowColorLogger, axCreateFlowTextLogger, axCreateGeminiLiveAudioApi, axCreateGrokRealtimeApi, axCreateJSRuntime, axCreateOpenAIRealtimeApi, axDefaultFlowLogger, axDefaultMetricsConfig, axDefaultOptimizerLogger, axDefaultOptimizerMetricsConfig, axDeserializeOptimizedProgram, axEmitUsageEvent, axEventErrorMessage, axEventId, axEventIdentityScope, axEventMatches, axEventScopedCorrelationKey, axEventScopedDedupeKey, axEventSizeBytes, axFailOpenSpan, axFetchJsonSpeech, axFetchMultipartTranscription, axGetAIProfile, axGetCompatibilityReport, axGetFormatCompatibility, axGetMetricsConfig, axGetOptimizerMetricsConfig, axGetProvidersWithMediaSupport, axGetRuntimeHookFrame, axGetSupportedAIModels, axGlobals, axGoogleGeminiLiveAudioDefaults, axIsAudioOutputEnabled, axIsGeminiLiveAudioModel, axIsGrokVoiceModel, axIsOpenAIChatAudioModel, axIsOpenAIRealtimeModel, axIsOpenAIRealtimeTranscriptionModel, axMCPAPIKeyAuthentication, axMCPAppToolMeta, axMCPBasicAuthentication, axMCPBearerAuthentication, axMCPBuildParamHeaders, axMCPBuildRequestMeta, axMCPChat, axMCPChildExecutionOptions, axMCPDecodeHeaderValue, axMCPEncodeHeaderValue, axMCPEventRoutes, axMCPFulfillInputRequests, axMCPHMACAuthentication, axMCPIsPlainHeaderValue, axMCPParamHeaderBindings, axMCPServerInfoFromMeta, axMCPToolInputSchemaToFunctionSchema, axMCPToolVisibleTo, axMapGeminiLiveAudioPart, axMapOpenAIChatAudioDelta, axMapOpenAIChatAudioResponse, axMapOpenAIInputAudioPart, axMergeChatAudioConfig, axMergeUsageContexts, axModelInfoAnthropic, axModelInfoCohere, axModelInfoDeepSeek, axModelInfoGoogleGemini, axModelInfoGrok, axModelInfoMeta, axModelInfoMetaMessages, axModelInfoMetaSpark, axModelInfoMistral, axModelInfoOpenAI, axModelInfoOpenAIResponses, axModelInfoReka, axModelInfoWebLLM, axNormalizeAppliedServiceTier, axNormalizeOpenAIUsage, axNormalizeRequestedServiceTier, axNormalizeTranscriptionResponse, axOpenAIChatAudioDefaults, axOptimizableValidators, axPlaybookFailureSection, axProcessContentForProvider, axResolveAIProfileFeatures, axResolveAIProfileId, axResolveGeminiLiveAudioConfig, axResolveGrokRealtimeAudioConfig, axResolveMCPExecutionContext, axResolveOpenAIChatAudioConfig, axResolveOpenAIRealtimeAudioConfig, axResolveServiceTier, axRuntimeHookFrame, axRuntimePrimitives, axScoreProvidersForRequest, axSelectOptimalProvider, axSerializeOptimizedProgram, axShouldUseGeminiLiveAudio, axShouldUseGrokRealtime, axShouldUseOpenAIRealtime, axSignUCPRequest, axSpanAttributes, axSpanEvents, axStartActiveSpanFailOpen, axStartSpanFailOpen, axUpdateBalancerRouteStats, axUpdateMetricsConfig, axUpdateOptimizerMetricsConfig, axValidateChatRequestMessage, axValidateChatResponseResult, axValidateEventEnvelope, axValidateGeminiLiveAudioInput, axValidateProviderCapabilities, axWorkerRuntime, bestOfN, eventInput, eventPath, eventRoute, eventRuntime, eventTarget, f, flow, fn, optimize, playbook, refine, runAxEventStoreConformance, runControl, s, typesafe };
