import { z } from 'zod';

/** JSON-serializable value used for tool arguments and results */
type JSONValue = string | number | boolean | null | JSONValue[] | {
    [key: string]: JSONValue;
};

/** What the LLM sees — name, description, schema. Passed to all backends. */
interface ToolDeclaration<TParams = unknown> {
    name: string;
    description: string;
    parameters: z.ZodType<TParams>;
    needsApproval?: boolean;
    metadata?: {
        category?: string;
        icon?: string;
        tags?: string[];
    };
}
/** Full tool with execute function. Required for API-based backends.
 *  CLI backends extract declaration; execute map held internally.
 *  The optional second parameter receives request-scoped context
 *  when invoked through ChatRuntime (session ID, user data, custom metadata). */
interface ToolDefinition<TParams = unknown> extends ToolDeclaration<TParams> {
    execute: (params: TParams, context?: ToolContext) => Promise<unknown> | unknown;
}
/** Request-scoped context passed to tool execute functions via ChatRuntime.
 *  Contains session identity and user-defined metadata from the current session. */
interface ToolContext {
    /** Active chat session ID */
    sessionId: string;
    /** Custom metadata from the session (e.g. user ID, tenant, permissions) */
    custom?: Record<string, unknown>;
}
/** A tool call made by the LLM during execution */
interface ToolCall {
    id: string;
    name: string;
    args: JSONValue;
}
/** Result of executing a tool call */
interface ToolResult {
    toolCallId: string;
    name: string;
    result: JSONValue;
    isError?: boolean;
}

/** Message content — plain string or array of text/image parts */
type MessageContent = string | Array<ContentPart>;
/** Individual content part within a multi-part message */
type ContentPart = {
    type: "text";
    text: string;
} | {
    type: "image";
    data: string;
    mimeType: string;
};
/** Conversation message — discriminated union on `role` */
type Message = {
    role: "user";
    content: MessageContent;
} | {
    role: "assistant";
    content: MessageContent;
    toolCalls?: ToolCall[];
} | {
    role: "tool";
    content?: string;
    toolResults: ToolResult[];
} | {
    role: "system";
    content: string;
};

/** Scope for "remember this decision" */
type PermissionScope = "once" | "session" | "project" | "always";
/** What the permission callback receives */
interface PermissionRequest {
    toolName: string;
    toolArgs: Record<string, unknown>;
    /** Unique identifier for this specific tool call */
    toolCallId?: string;
    /** SDK-suggested scope (from Claude CLI's suggestions) */
    suggestedScope?: PermissionScope;
    /** Original SDK permission request (for pass-through) */
    rawSDKRequest?: unknown;
}
/** What the permission callback returns */
interface PermissionDecision {
    allowed: boolean;
    /** How long to remember this decision */
    scope?: PermissionScope;
    /** Modified tool arguments (tool args may be altered by user) */
    modifiedInput?: Record<string, unknown>;
    /** Denial reason (if denied) */
    reason?: string;
}
/** Permission callback signature */
type PermissionCallback = (request: PermissionRequest, signal: AbortSignal) => Promise<PermissionDecision>;
/** Request for user input — separate from permissions */
interface UserInputRequest {
    question: string;
    choices?: string[];
    /** Whether to allow freeform text input (default: true) */
    allowFreeform?: boolean;
}
/** Response from user to an input request */
interface UserInputResponse {
    answer: string;
    /** true if user typed a custom answer instead of selecting a choice */
    wasFreeform: boolean;
    /** Index of selected choice (if choice was selected) */
    selectedChoiceIndex?: number;
}
/** Hooks for supervisor/UI to intercept agent actions */
interface SupervisorHooks {
    onPermission?: PermissionCallback;
    onAskUser?: (request: UserInputRequest, signal: AbortSignal) => Promise<UserInputResponse>;
}

/** Model metadata returned by listModels() */
interface ModelInfo {
    id: string;
    name?: string;
    provider?: string;
    /** Model tier for UI categorization and cost hints */
    tier?: "fast" | "standard" | "premium";
    /** Context window size in tokens */
    contextWindow?: number;
    /** Model capabilities (e.g. "vision", "tools", "structured") */
    capabilities?: string[];
}
/** LLM model parameters */
interface ModelParams {
    temperature?: number;
    maxTokens?: number;
    topP?: number;
    stopSequences?: string[];
}
/** Result of backend validation check */
interface ValidationResult {
    valid: boolean;
    errors: string[];
}

/** Unified error codes for all SDK errors — single source of truth. */
declare enum ErrorCode {
    AUTH_EXPIRED = "AUTH_EXPIRED",
    AUTH_INVALID = "AUTH_INVALID",
    RATE_LIMIT = "RATE_LIMIT",
    NETWORK = "NETWORK",
    TIMEOUT = "TIMEOUT",
    PROVIDER_ERROR = "PROVIDER_ERROR",
    MODEL_NOT_FOUND = "MODEL_NOT_FOUND",
    MODEL_OVERLOADED = "MODEL_OVERLOADED",
    CONTEXT_OVERFLOW = "CONTEXT_OVERFLOW",
    INVALID_INPUT = "INVALID_INPUT",
    INVALID_RESPONSE = "INVALID_RESPONSE",
    REENTRANCY = "REENTRANCY",
    DISPOSED = "DISPOSED",
    ABORTED = "ABORTED",
    INVALID_TRANSITION = "INVALID_TRANSITION",
    DEPENDENCY_MISSING = "DEPENDENCY_MISSING",
    BACKEND_NOT_INSTALLED = "BACKEND_NOT_INSTALLED",
    TOOL_EXECUTION = "TOOL_EXECUTION",
    PERMISSION_DENIED = "PERMISSION_DENIED",
    SESSION_NOT_FOUND = "SESSION_NOT_FOUND",
    SESSION_EXPIRED = "SESSION_EXPIRED",
    PROVIDER_NOT_FOUND = "PROVIDER_NOT_FOUND",
    AUTH_REQUIRED = "AUTH_REQUIRED",
    STORAGE_ERROR = "STORAGE_ERROR",
    STORAGE_NOT_FOUND = "STORAGE_NOT_FOUND",
    STORAGE_DUPLICATE_KEY = "STORAGE_DUPLICATE_KEY",
    STORAGE_IO_ERROR = "STORAGE_IO_ERROR",
    STORAGE_SERIALIZATION_ERROR = "STORAGE_SERIALIZATION_ERROR"
}
/** Check if an error code is recoverable */
declare function isRecoverableErrorCode(code: ErrorCode): boolean;
/** Classify an error message string into an ErrorCode */
declare function classifyAgentError(error: string | Error): ErrorCode;

/** Usage data from LLM execution — tokens consumed plus optional metadata */
interface UsageData {
    promptTokens: number;
    completionTokens: number;
    model?: string;
    backend?: string;
}
/** Events emitted during streaming agent execution */
type AgentEvent = {
    type: "text_delta";
    text: string;
} | {
    type: "thinking_delta";
    text: string;
} | {
    type: "tool_call_start";
    toolCallId: string;
    toolName: string;
    args: JSONValue;
} | {
    type: "tool_call_end";
    toolCallId: string;
    toolName: string;
    result: JSONValue;
} | {
    type: "permission_request";
    request: PermissionRequest;
} | {
    type: "permission_response";
    toolName: string;
    decision: PermissionDecision;
} | {
    type: "ask_user";
    request: UserInputRequest;
} | {
    type: "ask_user_response";
    answer: string;
} | {
    type: "thinking_start";
} | {
    type: "thinking_end";
} | {
    type: "usage_update";
    promptTokens: number;
    completionTokens: number;
    model?: string;
    backend?: string;
} | {
    type: "session_info";
    sessionId: string;
    transcriptPath?: string;
    backend: string;
} | {
    type: "heartbeat";
} | {
    type: "error";
    error: string;
    recoverable: boolean;
    code?: ErrorCode;
} | {
    type: "done";
    finalOutput: string | null;
    structuredOutput?: unknown;
    streamed?: boolean;
};
/** Context passed to stream middleware — immutable per stream invocation */
interface StreamContext {
    model: string;
    backend: string;
    abortController: AbortController;
    /** Agent config snapshot. Loosely typed to avoid leaking internal FullAgentConfig to external middleware consumers. */
    config: Readonly<Record<string, unknown>>;
}
/** A composable transform over the agent event stream.
 *  Receives the upstream source and context, returns a transformed stream. */
type StreamMiddleware = (source: AsyncIterable<AgentEvent>, context: StreamContext) => AsyncIterable<AgentEvent>;

/** Pluggable store for persisting permission (scope) decisions across runs. */
interface IPermissionStore {
    /** Check if tool is already approved */
    isApproved(toolName: string): Promise<boolean>;
    /** Store an approval decision */
    approve(toolName: string, scope: PermissionScope): Promise<void>;
    /** Revoke approval for a tool */
    revoke(toolName: string): Promise<void>;
    /** Clear all approvals */
    clear(): Promise<void>;
    /** Dispose resources */
    dispose(): Promise<void>;
}
/** In-memory store — approvals live until process exits (or dispose). */
declare class InMemoryPermissionStore implements IPermissionStore {
    private approvals;
    isApproved(toolName: string): Promise<boolean>;
    approve(toolName: string, scope: PermissionScope): Promise<void>;
    revoke(toolName: string): Promise<void>;
    clear(): Promise<void>;
    dispose(): Promise<void>;
}
/** File-backed store — reads/writes a JSON file for persistent approvals. */
declare class FilePermissionStore implements IPermissionStore {
    private readonly filePath;
    constructor(filePath: string);
    isApproved(toolName: string): Promise<boolean>;
    approve(toolName: string, scope: PermissionScope): Promise<void>;
    revoke(toolName: string): Promise<void>;
    clear(): Promise<void>;
    dispose(): Promise<void>;
    private readFile;
    private writeFileAtomic;
}
/**
 * Composes multiple stores — checks in order, routes writes by scope.
 *
 * - "session" → sessionStore (in-memory)
 * - "project" → projectStore (file-based in project directory)
 * - "always"  → userStore (file-based in user home)
 */
declare class CompositePermissionStore implements IPermissionStore {
    private readonly sessionStore;
    private readonly projectStore;
    private readonly userStore;
    constructor(sessionStore: IPermissionStore, projectStore: IPermissionStore, userStore?: IPermissionStore);
    isApproved(toolName: string): Promise<boolean>;
    approve(toolName: string, scope: PermissionScope): Promise<void>;
    revoke(toolName: string): Promise<void>;
    clear(): Promise<void>;
    dispose(): Promise<void>;
}
/** Create a default composite store with separate project and user-level persistence. */
declare function createDefaultPermissionStore(projectDir?: string): CompositePermissionStore;

/** Per-call overrides passed to run(), stream(), runStructured().
 *  Allows overriding the model, tools, signal, and other parameters
 *  on a per-request basis without modifying the agent configuration. */
interface CallOptions {
    /** Override the default model for this call */
    model?: string;
    /** Override/extend tools for this call */
    tools?: ToolDefinition[];
    /** Per-call abort signal */
    signal?: AbortSignal;
    /** Override system message for this call */
    systemMessage?: string;
    /** Provider-specific options passed through to the underlying SDK */
    providerOptions?: Record<string, unknown>;
    /** Per-call timeout in milliseconds */
    timeout?: number;
    /** Per-call token limit */
    maxTokens?: number;
    /** Retry configuration for this call */
    retry?: RetryConfig;
}
/** Configuration for automatic retries on transient errors */
interface RetryConfig {
    /** Maximum number of retries (default: 0 — no retry) */
    maxRetries?: number;
    /** Initial delay in ms before first retry (default: 1000) */
    initialDelayMs?: number;
    /** Backoff multiplier (default: 2) */
    backoffMultiplier?: number;
    /** Which error codes to retry (default: all recoverable codes) */
    retryableErrors?: ErrorCode[];
}
/** Configuration for typed structured output from LLM */
interface StructuredOutputConfig<T = unknown> {
    schema: z.ZodType<T>;
    name?: string;
    description?: string;
}
/** Options passed to agent.run() / agent.stream().
 *  Extends CallOptions with run-specific fields (context, activityTimeoutMs).
 *  model is REQUIRED — every agent call must specify the model explicitly. */
interface RunOptions extends CallOptions {
    /** Model to use for this call (required — no implicit defaults) */
    model: string;
    /** Arbitrary context passed to the agent run */
    context?: Record<string, unknown>;
    /** Inactivity timeout for streaming (ms). When set, the stream aborts if no
     *  event (including heartbeats/progress) arrives within this period. Resets on
     *  every received event. Default: no timeout. Only affects stream()/streamWithContext(). */
    activityTimeoutMs?: number;
}
/** Timeout configuration for agent operations */
interface TimeoutConfig {
    /** Max time for entire agent run (ms) */
    total?: number;
    /** Max time for a single tool execution (ms) */
    perTool?: number;
    /** Max time for a single LLM request (ms) */
    perLLMRequest?: number;
}
/** Error handling strategy configuration */
interface ErrorHandlingConfig {
    /** What to do when a tool throws */
    onToolError?: "fail" | "continue" | "ask-llm";
    /** Retry config for transient LLM failures */
    retryLLM?: {
        maxAttempts: number;
        backoffMs: number;
    };
    /** Global error callback for monitoring */
    onError?: (error: Error, context: {
        phase: "tool" | "llm" | "permission" | "ask-user";
    }) => void;
}
/** Identity-only agent configuration — defines the agent's behavior, NOT per-call defaults.
 *  For creating an agent with model/tools defaults, use FullAgentConfig. */
interface AgentConfig {
    systemPrompt: string;
    supervisor?: SupervisorHooks;
    maxTurns?: number;
    timeout?: TimeoutConfig;
    errorHandling?: ErrorHandlingConfig;
    /** Pluggable store for persisting permission scope decisions across runs */
    permissionStore?: IPermissionStore;
    /** How to apply systemPrompt: "append" adds to backend default, "replace" overrides it.
     *  Default: "append". Currently used by the Copilot backend. */
    systemMessageMode?: "append" | "replace";
    /**
     * Filter for backend built-in tools (e.g. `["web_search", "web_fetch"]` for Copilot).
     * When set, only listed built-in tools are available. Backend-specific.
     *
     * **Security note**: This is a trust boundary — it controls which backend-native tools
     * the AI agent can invoke. By default, backends expose ALL their built-in tools.
     * Set this to restrict access (e.g. prevent file system access in a web-facing agent).
     */
    availableTools?: string[];
    /** Callback invoked with usage data after run completion or during streaming.
     *  Fire-and-forget: errors are logged but not propagated. */
    onUsage?: (usage: UsageData) => void;
    /** Interval in milliseconds for emitting heartbeat events during streaming.
     *  When set, heartbeat events are emitted to keep the stream alive during
     *  long tool executions. Default: off (no heartbeats). */
    heartbeatInterval?: number;
    /** Session reuse mode for CLI backends (Copilot, Claude).
     *  "per-call" (default): creates a fresh CLI session for each run/stream call.
     *  "persistent": reuses the same CLI session across calls, preserving conversation
     *  history natively in the CLI backend. Session is destroyed on agent dispose(). */
    sessionMode?: "per-call" | "persistent";
}
/** Per-call defaults that can be provided at agent creation time.
 *  Each field can also be overridden on individual calls via RunOptions. */
interface CallDefaults {
    /** Default model (overridable per-call via RunOptions.model) */
    model?: string;
    /** Default model parameters */
    modelParams?: ModelParams;
    /** Default tools (overridable per-call via RunOptions.tools) */
    tools?: ToolDefinition[];
    /** Provider-specific options passed through to the underlying SDK.
     *  For Vercel AI: passed as providerOptions to generateText/streamText.
     *  Example: { google: { thinkingConfig: { thinkingBudget: 1024 } } } */
    providerOptions?: Record<string, Record<string, unknown>>;
}
/** Full agent configuration: identity + per-call defaults.
 *  This is what createAgent() accepts. Backward-compatible with the old AgentConfig shape. */
type FullAgentConfig = AgentConfig & CallDefaults;
/** Result of an agent run, generic over structured output type T */
interface AgentResult<T = void> {
    output: string | null;
    structuredOutput: T extends void ? undefined : T;
    toolCalls: Array<{
        toolName: string;
        args: JSONValue;
        result: JSONValue;
        approved: boolean;
    }>;
    messages: Message[];
    usage?: UsageData;
}
/** Agent lifecycle state */
type AgentState = "idle" | "running" | "streaming" | "disposed";
/** Core agent interface — run prompts, stream events, manage lifecycle */
interface IAgent {
    /** The CLI session ID when using persistent session mode. Undefined in per-call mode
     *  or before the first call. Can be stored externally for session resume. */
    readonly sessionId: string | undefined;
    /** Run a single prompt and return the result. Wraps prompt in a user message. */
    run(prompt: MessageContent, options: RunOptions): Promise<AgentResult>;
    /** Run with full conversation history. Messages are passed directly to the backend. */
    runWithContext(messages: Message[], options: RunOptions): Promise<AgentResult>;
    /** Run with structured output validated against a Zod schema. */
    runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options: RunOptions): Promise<AgentResult<T>>;
    /** Stream events for a single prompt. Wraps prompt in a user message. */
    stream(prompt: MessageContent, options: RunOptions): AsyncIterable<AgentEvent>;
    /** Stream events with full conversation history. Messages are passed directly to the backend. */
    streamWithContext(messages: Message[], options: RunOptions): AsyncIterable<AgentEvent>;
    /** Abort the current operation. No-op if not running. */
    abort(): void;
    /** Gracefully interrupt the current operation. Resolves when the backend acknowledges. */
    interrupt(): Promise<void>;
    /** Get current agent lifecycle state. */
    getState(): AgentState;
    /** Get frozen agent configuration. */
    getConfig(): Readonly<FullAgentConfig>;
    /** Release resources. After dispose(), agent must not be used. */
    dispose(): void;
}
/** Backend service interface — creates agents, lists models, validates config */
interface IAgentService {
    readonly name: string;
    createAgent(config: FullAgentConfig): IAgent;
    listModels(): Promise<ModelInfo[]>;
    validate(): Promise<ValidationResult>;
    dispose(): Promise<void>;
}

/** Options for Copilot CLI backend */
interface CopilotBackendOptions {
    cliPath?: string;
    workingDirectory?: string;
    githubToken?: string;
    useLoggedInUser?: boolean;
    /** Extra CLI arguments passed to the Copilot subprocess (e.g. ["--allow-all"]) */
    cliArgs?: string[];
    /** Timeout in milliseconds for sendAndWait() calls. When undefined, uses copilot-sdk default (60s). */
    timeout?: number;
    /** Timeout in milliseconds for CLI startup and auth check (default: 30000). */
    startupTimeoutMs?: number;
    /** Custom environment variables merged into the subprocess env */
    env?: Record<string, string | undefined>;
    /** Session ID to resume after server restart. On startup, the backend attempts
     *  to resume this session before creating a new one. */
    resumeSessionId?: string;
}
/** Options for Claude CLI backend */
interface ClaudeBackendOptions {
    cliPath?: string;
    workingDirectory?: string;
    maxTurns?: number;
    /** OAuth token for Claude authentication (set as CLAUDE_CODE_OAUTH_TOKEN env var) */
    oauthToken?: string;
    /** Custom environment variables merged into the subprocess env */
    env?: Record<string, string | undefined>;
    /** Session ID to resume after server restart. On startup, the backend attempts
     *  to resume this session before creating a new one. */
    resumeSessionId?: string;
}
/** Options for Vercel AI SDK backend */
interface VercelAIBackendOptions {
    apiKey: string;
    provider?: string;
    baseUrl?: string;
}

/** Type guard: checks if a ToolDeclaration has an execute function (i.e., is a ToolDefinition) */
declare function isToolDefinition(tool: ToolDeclaration): tool is ToolDefinition;
/** Type guard: checks if MessageContent is plain string */
declare function isTextContent(content: MessageContent): content is string;
/** Type guard: checks if MessageContent is multi-part array */
declare function isMultiPartContent(content: MessageContent): content is ContentPart[];
/** Extract text from MessageContent regardless of format */
declare function getTextContent(content: MessageContent): string;

/** Options for constructing an AgentSDKError */
interface AgentSDKErrorOptions extends ErrorOptions {
    /** Machine-readable error code */
    code?: string;
    /** Whether this error is retryable (default: false) */
    retryable?: boolean;
    /** HTTP status code hint (e.g. 401, 429, 500) */
    httpStatus?: number;
}
/** Base error class for agent-sdk.
 *
 * Use `AgentSDKError.is(err)` for reliable cross-module `instanceof` checks
 * (works across separately bundled entry points where `instanceof` may fail). */
declare class AgentSDKError extends Error {
    /** @internal Marker for cross-bundle identity checks */
    readonly _agentSDKError: true;
    /** Machine-readable error code. Prefer values from the ErrorCode enum. */
    readonly code?: string;
    /** Whether this error is safe to retry */
    readonly retryable: boolean;
    /** HTTP status code hint for error classification */
    readonly httpStatus?: number;
    constructor(message: string, options?: AgentSDKErrorOptions);
    /** Check if an error is an AgentSDKError (works across bundled copies) */
    static is(error: unknown): error is AgentSDKError;
}
/** Thrown when agent.run() is called while already running (M8 re-entrancy guard) */
declare class ReentrancyError extends AgentSDKError {
    constructor();
}
/** Thrown when an operation is attempted on a disposed agent/service */
declare class DisposedError extends AgentSDKError {
    constructor(entity: string);
}
/** Thrown when a backend is not found in the registry */
declare class BackendNotFoundError extends AgentSDKError {
    constructor(backend: string);
}
/** Thrown when a backend is already registered */
declare class BackendAlreadyRegisteredError extends AgentSDKError {
    constructor(backend: string);
}
/** Thrown when subprocess management fails */
declare class SubprocessError extends AgentSDKError {
    constructor(message: string, options?: ErrorOptions);
}
/** Thrown when a required peer dependency is not installed */
declare class DependencyError extends AgentSDKError {
    readonly packageName: string;
    constructor(packageName: string);
}
/** Thrown when an agent run is aborted */
declare class AbortError extends AgentSDKError {
    constructor();
}
/** Thrown when a tool execution fails */
declare class ToolExecutionError extends AgentSDKError {
    readonly toolName: string;
    constructor(toolName: string, message: string, options?: ErrorOptions);
}
/** Thrown when a stream has no activity within the configured timeout */
declare class ActivityTimeoutError extends AgentSDKError {
    constructor(timeoutMs: number);
}
/** Thrown when structured output parsing fails */
declare class StructuredOutputError extends AgentSDKError {
    constructor(message: string, options?: ErrorOptions);
}

/** Factory function that creates a backend service from options */
type BackendFactory<TOptions = unknown> = (options: TOptions) => IAgentService | Promise<IAgentService>;
/** Map of built-in backend names to their options types */
interface BackendOptionsMap {
    copilot: CopilotBackendOptions;
    claude: ClaudeBackendOptions;
    "vercel-ai": VercelAIBackendOptions;
}
/** All known backend names (built-in + custom) */
type BuiltinBackendName = keyof BackendOptionsMap;
/** Register a custom backend factory */
declare function registerBackend<TOptions = unknown>(name: string, factory: BackendFactory<TOptions>): void;
/** Unregister a backend (primarily for testing) */
declare function unregisterBackend(name: string): boolean;
/** Check if a backend is registered (eagerly or lazily) */
declare function hasBackend(name: string): boolean;
/** List all registered backend names (eager + lazy) */
declare function listBackends(): string[];
/** Reset registry to initial state (for testing) */
declare function resetRegistry(): void;
/** Dispose all cached service instances for a backend, or a single named config.
 *  Returns the number of instances disposed. */
declare function disposeBackend(name: string, configId?: string): Promise<number>;
/** List all active config IDs for a backend */
declare function listConfigs(name: string): string[];
/**
 * Register a lazy-loaded backend. The loader is called once on first use,
 * then the resulting factory is cached in the main registry.
 * Use this for backends that have heavy dependencies (peer deps, native modules).
 */
declare function registerLazyBackend(name: string, loader: () => Promise<BackendFactory>): void;
/** Create a backend service with type-safe options.
 *  When `configId` is provided, the service instance is cached and reused
 *  on subsequent calls with the same name+configId pair. Without configId,
 *  a new instance is created every call. */
declare function createAgentService<K extends BuiltinBackendName>(name: K, options: BackendOptionsMap[K], configId?: string): Promise<IAgentService>;
declare function createAgentService(name: string, options: unknown, configId?: string): Promise<IAgentService>;

/** Abstract base agent with shared lifecycle logic.
 *  Concrete backends extend this and implement the protected _run/_stream methods. */
declare abstract class BaseAgent implements IAgent {
    protected state: AgentState;
    protected abortController: AbortController | null;
    protected readonly config: FullAgentConfig;
    private _cleanupExternalSignal;
    private _streamMiddleware;
    /** Backend identifier (e.g. "copilot", "claude", "vercel-ai") */
    protected abstract readonly backendName: string;
    /** CLI session ID for persistent mode. Override in backends that support it. */
    get sessionId(): string | undefined;
    constructor(config: FullAgentConfig);
    run(prompt: MessageContent, options: RunOptions): Promise<AgentResult>;
    runWithContext(messages: Message[], options: RunOptions): Promise<AgentResult>;
    runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options: RunOptions): Promise<AgentResult<T>>;
    stream(prompt: MessageContent, options: RunOptions): AsyncIterable<AgentEvent>;
    streamWithContext(messages: Message[], options: RunOptions): AsyncIterable<AgentEvent>;
    /** Register a stream middleware. Applied in registration order after built-in transforms. */
    addStreamMiddleware(middleware: StreamMiddleware): void;
    /** Apply built-in transforms (enrich→timeout→heartbeat) then custom middleware */
    private applyStreamPipeline;
    abort(): void;
    /** Default interrupt — falls back to abort(). Backends may override with graceful shutdown. */
    interrupt(): Promise<void>;
    getState(): AgentState;
    getConfig(): Readonly<FullAgentConfig>;
    /** Mark agent as disposed. Override to add cleanup. */
    dispose(): void;
    /** Execute a blocking run. Backend implements the actual LLM call. */
    protected abstract executeRun(messages: Message[], options: RunOptions, signal: AbortSignal): Promise<AgentResult>;
    /** Execute a structured output run. Backend implements parsing. */
    protected abstract executeRunStructured<T>(messages: Message[], schema: StructuredOutputConfig<T>, options: RunOptions, signal: AbortSignal): Promise<AgentResult<T>>;
    /** Execute a streaming run. Backend yields events. */
    protected abstract executeStream(messages: Message[], options: RunOptions, signal: AbortSignal): AsyncIterable<AgentEvent>;
    /** Check if an error should be retried given the retry configuration. */
    private isRetryableError;
    /** Execute a function with retry logic per RetryConfig. */
    private withRetry;
    /** Execute a stream factory with pre-stream retry: retries until first event, then committed. */
    private streamWithRetry;
    /** Resolve tools to use for this call (per-call override > config default) */
    protected resolveTools(options?: RunOptions): ToolDefinition[];
    /** Enrich result usage with model/backend and fire onUsage callback */
    private enrichAndNotifyUsage;
    /** Wrap a stream to enrich usage_update events and fire onUsage callback */
    private enrichStream;
    /** Fire onUsage callback (fire-and-forget: errors logged, not propagated) */
    private callOnUsage;
    /** Wrap a stream to emit heartbeat events at configured intervals.
     *  When heartbeatInterval is not set, passes through directly. */
    private heartbeatStream;
    /** Wrap a stream to abort on inactivity. Resets timer on every event.
     *  When timeoutMs is not set, passes through directly. */
    private activityTimeoutStream;
    protected guardReentrancy(): void;
    protected guardDisposed(): void;
    /** Throw AbortError if signal is already aborted */
    protected checkAbort(signal: AbortSignal): void;
    /** Clean up after a run completes (success, error, or abort). */
    private cleanupRun;
    private createAbortController;
}

/** Convert a Zod schema to JSON Schema.
 *  Detection order: toJSONSchema() (Zod v4) → jsonSchema() (Zod v3.24+) → _def extraction (Zod v3 legacy). */
declare function zodToJsonSchema(schema: z.ZodType): Record<string, unknown>;

/** Convert our Message[] to a flat prompt string (for CLIs that accept text) */
declare function messagesToPrompt(messages: Message[]): string;
/** Convert MessageContent to plain text */
declare function contentToText(content: MessageContent): string;
/** Build a system prompt with optional structured output instruction */
declare function buildSystemPrompt(base: string, schemaInstruction?: string): string;

export { AbortError, ActivityTimeoutError, type AgentConfig, type AgentEvent, type AgentResult, AgentSDKError, type AgentSDKErrorOptions, type AgentState, BackendAlreadyRegisteredError, type BackendFactory, BackendNotFoundError, type BackendOptionsMap, BaseAgent, type BuiltinBackendName, type CallDefaults, type CallOptions, type ClaudeBackendOptions, CompositePermissionStore, type ContentPart, type CopilotBackendOptions, DependencyError, DisposedError, ErrorCode, type ErrorHandlingConfig, FilePermissionStore, type FullAgentConfig, type IAgent, type IAgentService, type IPermissionStore, InMemoryPermissionStore, type JSONValue, type Message, type MessageContent, type ModelInfo, type ModelParams, type PermissionCallback, type PermissionDecision, type PermissionRequest, type PermissionScope, ReentrancyError, type RetryConfig, type RunOptions, type StreamContext, type StreamMiddleware, type StructuredOutputConfig, StructuredOutputError, SubprocessError, type SupervisorHooks, type TimeoutConfig, type ToolCall, type ToolContext, type ToolDeclaration, type ToolDefinition, ToolExecutionError, type ToolResult, type UsageData, type UserInputRequest, type UserInputResponse, type ValidationResult, type VercelAIBackendOptions, buildSystemPrompt, classifyAgentError, contentToText, createAgentService, createDefaultPermissionStore, disposeBackend, getTextContent, hasBackend, isMultiPartContent, isRecoverableErrorCode, isTextContent, isToolDefinition, listBackends, listConfigs, messagesToPrompt, registerBackend, registerLazyBackend, resetRegistry, unregisterBackend, zodToJsonSchema };
