import { I as IChatBackend, e as ChatMiddleware, f as ChatIdLike, c as ChatMessage, R as RuntimeStatus, g as ChatSession, b as ChatId, S as SendMessageOptions, a as ChatEvent, h as RuntimeSendOptions } from '../types-ajANVzf7.js';
import { T as ToolDefinition, M as ModelInfo } from '../agent-CW9XbmG_.js';
import { IChatSessionStore, CreateSessionOptions, SessionListOptions } from './sessions.js';
import { ContextWindowConfig, ContextStats } from './context.js';
import { A as AuthToken } from '../types-BxggH0Yh.js';
import { P as ProviderConfig } from '../provider-types-PTSlRPNB.js';
import '../errors-C-so0M4t.js';
import 'zod';
import './storage.js';
import '../errors-CmVvczxZ.js';

/**
 * @witqq/agent-sdk/chat/runtime
 *
 * Unified chat runtime orchestrator. Creates a fully-wired runtime instance
 * from a configuration object, managing backend adapters, sessions, context
 * trimming, streaming, and middleware in a single facade.
 *
 * Usage:
 * ```typescript
 * import { createChatRuntime } from "@witqq/agent-sdk/chat/runtime";
 * const runtime = createChatRuntime({ backends: { ... }, sessionStore, ... });
 * const session = await runtime.createSession({ config: { model: "gpt-4", backend: "copilot" } });
 * for await (const event of runtime.send(session.id, "Hello")) { ... }
 * ```
 */

/** Factory function that creates a backend adapter on demand */
type BackendAdapterFactory = (credentials: AuthToken) => IChatBackend | Promise<IChatBackend>;
/** Configuration for creating a chat runtime via createChatRuntime() */
interface ChatRuntimeOptions {
    /** Map of backend name → adapter factory (lazy creation on first use) */
    backends: Record<string, BackendAdapterFactory>;
    /** Default backend name (must be a key in `backends`) */
    defaultBackend: string;
    /** Session store for persistence */
    sessionStore: IChatSessionStore;
    /** Context window configuration (optional) */
    context?: ContextWindowConfig;
    /** Middleware pipeline (optional, applied in order) */
    middleware?: ChatMiddleware[];
    /** Retry configuration for pre-stream connection errors */
    retryConfig?: StreamRetryConfig;
    /**
     * Stream inactivity timeout in milliseconds (optional).
     * When set, aborts the stream if no events arrive within this window.
     * Timer resets after each received event.
     */
    streamTimeoutMs?: number;
    /**
     * Called when context trimming removes messages.
     * Use for archiving, logging, or analytics.
     */
    onContextTrimmed?: (sessionId: ChatIdLike, removedMessages: ChatMessage[]) => void;
    /**
     * Initial tools to register on the runtime.
     * Equivalent to calling `registerTool()` for each tool after creation.
     */
    tools?: ToolDefinition[];
}
/** Retry configuration for pre-stream failures (renamed to avoid clash with agent-level RetryConfig) */
interface StreamRetryConfig {
    /** Maximum number of attempts (default: 1 = no retry) */
    maxAttempts: number;
    /** Delay between retries in milliseconds */
    delayMs: number;
}
/** @deprecated Use StreamRetryConfig */
type RetryConfig = StreamRetryConfig;
/** Information about a registered backend */
interface BackendInfo {
    /** Backend name (key in backends map) */
    name: string;
}
/**
 * Provider CRUD operations — separated per Interface Segregation Principle.
 * Implemented by IChatClient (which needs provider management for UI).
 * Not required on IChatRuntime (providers are a handler-layer concern).
 */
interface IProviderClient {
    listProviders(): Promise<ProviderConfig[]>;
    createProvider(config: Omit<ProviderConfig, "id" | "createdAt">): Promise<ProviderConfig>;
    updateProvider(id: string, changes: Partial<Omit<ProviderConfig, "id" | "createdAt">>): Promise<void>;
    deleteProvider(id: string): Promise<void>;
}
/** Callback for provider selection changes */
type SelectionChangeCallback = (providerId: string | null) => void;
/**
 * Client-side interface for interacting with a remote chat server.
 * Fully self-contained — no shared base with IChatRuntime.
 * Extends IProviderClient for provider CRUD (ISP).
 * Used by React components and remote clients.
 *
 * @typeParam TMetadata - Type-level convenience for message metadata.
 *   NOT enforced at the storage boundary — session stores always use `unknown`.
 *   Consumers are responsible for metadata shape consistency.
 */
interface IChatClient<TMetadata extends Record<string, unknown> = Record<string, unknown>> extends IProviderClient {
    readonly status: RuntimeStatus;
    dispose(): Promise<void>;
    createSession(options: CreateSessionOptions<TMetadata>): Promise<ChatSession<TMetadata>>;
    getSession(id: ChatIdLike): Promise<ChatSession<TMetadata> | null>;
    listSessions(options?: SessionListOptions): Promise<ChatSession<TMetadata>[]>;
    deleteSession(id: ChatIdLike): Promise<void>;
    switchSession(id: ChatIdLike): Promise<ChatSession<TMetadata>>;
    readonly activeSessionId: ChatId | null;
    /**
     * Send a message. Options are optional — the server handler resolves
     * model and backend from provider selection state.
     * Compare with IChatRuntime.send() where RuntimeSendOptions is required.
     */
    send(sessionId: ChatIdLike, message: string, options?: SendMessageOptions): AsyncIterable<ChatEvent>;
    abort(): void;
    selectProvider(providerId: string): void;
    readonly selectedProviderId: string | null;
    onSelectionChange(callback: SelectionChangeCallback): () => void;
    onSessionChange(callback: () => void): () => void;
    listModels(): Promise<ModelInfo[]>;
    listBackends(): Promise<BackendInfo[]>;
    getContextStats(sessionId: ChatIdLike): Promise<ContextStats | null>;
}
/**
 * Server-side chat runtime. Fully self-contained — no shared base with IChatClient.
 * Manages backend adapters, tools, middleware, and context trimming.
 * Does NOT include client-facing provider CRUD or selection — those are
 * handled by the server handler layer.
 *
 * @typeParam TMetadata - Type-level convenience for message metadata.
 *   NOT enforced at the storage boundary — session stores always use `unknown`.
 *   Casts in `ChatRuntime.createSession()`/`getSession()` are intentionally unsafe
 *   to provide typed access. Consumers are responsible for metadata shape consistency.
 */
interface IChatRuntime<TMetadata extends Record<string, unknown> = Record<string, unknown>> {
    readonly status: RuntimeStatus;
    dispose(): Promise<void>;
    createSession(options: CreateSessionOptions<TMetadata>): Promise<ChatSession<TMetadata>>;
    getSession(id: ChatIdLike): Promise<ChatSession<TMetadata> | null>;
    listSessions(options?: SessionListOptions): Promise<ChatSession<TMetadata>[]>;
    deleteSession(id: ChatIdLike): Promise<void>;
    /**
     * Send a message. RuntimeSendOptions is required on the server — the caller
     * (usually a handler) must supply backend, model, and credentials.
     * Compare with IChatClient.send() where options are optional.
     */
    send(sessionId: ChatIdLike, message: string, options: RuntimeSendOptions): AsyncIterable<ChatEvent>;
    abort(): void;
    onSessionChange(callback: () => void): () => void;
    listModels(options?: {
        backend?: string;
        credentials?: AuthToken;
    }): Promise<ModelInfo[]>;
    listBackends(): Promise<BackendInfo[]>;
    registerTool(tool: ToolDefinition): void;
    removeTool(name: string): void;
    readonly registeredTools: ReadonlyMap<string, ToolDefinition>;
    use(middleware: ChatMiddleware): void;
    removeMiddleware(middleware: ChatMiddleware): void;
    getContextStats(sessionId: ChatIdLike): Promise<ContextStats | null>;
}
/**
 * Create a fully-wired chat runtime from configuration.
 *
 * @param options - Runtime configuration (backends, session store, context, middleware)
 * @returns IChatRuntime instance ready to use
 *
 * @example
 * ```typescript
 * import { createChatRuntime } from "@witqq/agent-sdk/chat/runtime";
 * import { InMemorySessionStore } from "@witqq/agent-sdk/chat/sessions";
 *
 * const runtime = createChatRuntime({
 *   backends: {
 *     copilot: () => new CopilotAdapter({ agentConfig: { model: "gpt-4" } }),
 *   },
 *   defaultBackend: "copilot",
 *   sessionStore: new InMemorySessionStore(),
 * });
 * ```
 */
declare function createChatRuntime<TMetadata extends Record<string, unknown> = Record<string, unknown>>(options: ChatRuntimeOptions): IChatRuntime<TMetadata>;

export { type BackendAdapterFactory, type BackendInfo, type ChatRuntimeOptions, type IChatClient, type IChatRuntime, type IProviderClient, type RetryConfig, type SelectionChangeCallback, type StreamRetryConfig, createChatRuntime };
