import * as react from 'react';
import { ReactNode, ComponentType } from 'react';
import { IChatClient, BackendInfo, SelectionChangeCallback } from './runtime.js';
import { c as ChatMessage, R as RuntimeStatus, r as SessionInfo, u as TextPart, q as ReasoningPart, v as ToolCallPart, t as SourcePart, F as FilePart, g as ChatSession, a as ChatEvent, b as ChatId, f as ChatIdLike, S as SendMessageOptions } from '../types-ajANVzf7.js';
import { A as AuthToken } from '../types-BxggH0Yh.js';
import { P as ProviderConfig } from '../provider-types-PTSlRPNB.js';
import { ContextStats } from './context.js';
import { M as ModelInfo } from '../agent-CW9XbmG_.js';
import { CreateSessionOptions, SessionListOptions } from './sessions.js';
import '../errors-C-so0M4t.js';
import 'zod';
import './storage.js';
import '../errors-CmVvczxZ.js';

/** Props for ChatProvider. */
interface ChatProviderProps {
    /** The chat runtime or client instance to provide to descendants. Accepts IChatClient (or any structurally compatible type). */
    runtime: IChatClient;
    children: ReactNode;
}
/**
 * React context provider wrapping IChatClient.
 * All chat hooks must be used within a ChatProvider.
 */
declare function ChatProvider({ runtime, children }: ChatProviderProps): react.FunctionComponentElement<react.ProviderProps<IChatClient<Record<string, unknown>> | null>>;
/**
 * Access the IChatClient from context.
 * Must be used within a ChatProvider.
 *
 * @throws {Error} If used outside ChatProvider
 */
declare function useChatRuntime(): IChatClient;

/** Options for the useChat hook. */
interface UseChatOptions {
    /** Session ID. If omitted, a new session is created on first send. */
    sessionId?: string;
    /** Called on error during send. */
    onError?: (error: Error) => void;
    /** Auto-dismiss errors after this many ms (0 = disabled, default: 0). */
    autoDismissMs?: number;
}
/** Token usage data from the last completed response. */
interface ChatUsage {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
    model?: string;
}
/** Return value from useChat. */
interface UseChatReturn {
    /** Current session ID (null until session created). */
    sessionId: string | null;
    /** Ordered messages in the current session. */
    messages: ChatMessage[];
    /** Send a user message and trigger assistant response. */
    sendMessage: (content: string) => Promise<void>;
    /** Abort the current generation. */
    stop: () => void;
    /** Whether the assistant is currently generating. */
    isGenerating: boolean;
    /** Current runtime status. */
    status: RuntimeStatus;
    /** Current error, if any. */
    error: Error | null;
    /** Clear the error state. */
    clearError: () => void;
    /** Retry the last failed message. No-op if no error or no last user message. */
    retryLastMessage: () => Promise<void>;
    /** Create a new session, resetting messages. */
    newSession: () => Promise<string>;
    /** Token usage from the last completed response. */
    usage: ChatUsage | null;
}
/**
 * Convenience hook for chat interaction.
 * Wraps IChatRuntime with React state management and progressive streaming.
 * Messages update in real-time as tokens arrive (not after full response).
 */
declare function useChat(options?: UseChatOptions): UseChatReturn;

/** Options for the useMessages hook. */
interface UseMessagesOptions {
    /** Session ID to observe. */
    sessionId: string;
}
/** Return value from useMessages. */
interface UseMessagesReturn {
    /** Ordered messages in the session. */
    messages: ChatMessage[];
    /** Whether the session was found. */
    isLoaded: boolean;
}
/**
 * Reactive message list via useSyncExternalStore.
 *
 * If the session supports subscribe/getSnapshot (reactive session),
 * uses useSyncExternalStore for granular updates.
 * Otherwise, falls back to polling via getSession().
 */
declare function useMessages(options: UseMessagesOptions): UseMessagesReturn;

/**
 * @witqq/agent-sdk/chat/react — useSessions
 *
 * Reactive session list hook that subscribes to runtime session changes.
 * Auto-updates without manual polling via `onSessionChange` subscription.
 */

/** Return type of useSessions hook. */
interface UseSessionsReturn {
    /** Current session list (lightweight SessionInfo format) */
    sessions: SessionInfo[];
    /** Whether initial load or refresh is in progress */
    loading: boolean;
    /** Last error from session fetch */
    error: Error | null;
    /** Manually trigger a refresh */
    refresh: () => void;
}
/**
 * Reactive session list hook.
 * Subscribes to `runtime.onSessionChange()` and refreshes the list automatically
 * on create, delete, and message send completion.
 */
declare function useSessions(): UseSessionsReturn;

/** Props for the Message component. */
interface MessageProps {
    message: ChatMessage;
    renderText?: (part: TextPart, index: number) => ReactNode;
    renderReasoning?: (part: ReasoningPart, index: number) => ReactNode;
    renderToolCall?: (part: ToolCallPart, index: number) => ReactNode;
    renderSource?: (part: SourcePart, index: number) => ReactNode;
    renderFile?: (part: FilePart, index: number) => ReactNode;
}
/**
 * Headless message component rendering ChatMessage parts.
 * Wraps parts in a div with data-role and data-status attributes.
 */
declare function Message(props: MessageProps): ReactNode;

/** Props for the ThinkingBlock component. */
interface ThinkingBlockProps {
    text: string;
    isStreaming?: boolean;
    defaultOpen?: boolean;
}
/**
 * Headless thinking/reasoning block using native details/summary elements.
 * Displays "Thinking..." while streaming, "Reasoning" when complete.
 */
declare function ThinkingBlock({ text, isStreaming, defaultOpen }: ThinkingBlockProps): ReactNode;

/** Props for the ToolCallView component. */
interface ToolCallViewProps {
    part: ToolCallPart;
    onApprove?: () => void;
    onDeny?: () => void;
    renderArgs?: (args: unknown) => ReactNode;
    renderResult?: (result: unknown) => ReactNode;
}
/**
 * Headless tool call display component.
 * Shows tool name, status, collapsible args/result, and approval buttons when needed.
 */
declare function ToolCallView({ part, onApprove, onDeny, renderArgs, renderResult }: ToolCallViewProps): ReactNode;

/** A pending tool call requiring user approval. */
interface PendingToolRequest {
    toolCallId: string;
    toolName: string;
    toolArgs: Record<string, unknown>;
    messageId: string;
}
/** Return value from useToolApproval. */
interface UseToolApprovalReturn {
    pendingRequests: PendingToolRequest[];
    approve: (toolCallId: string) => void;
    deny: (toolCallId: string) => void;
}
/**
 * Hook that tracks tool calls requiring approval from messages.
 *
 * Scans messages for ToolCallParts with status "requires_approval"
 * and provides approve/deny callbacks. Currently state-only
 * (no ChatEventBus integration).
 *
 * @param messages - Messages to scan for pending tool approvals
 * @param onApprove - Called when a tool call is approved
 * @param onDeny - Called when a tool call is denied
 */
declare function useToolApproval(messages: ChatMessage[], onApprove?: (toolCallId: string) => void, onDeny?: (toolCallId: string) => void): UseToolApprovalReturn;

/** Props for the MarkdownRenderer component. */
interface MarkdownRendererProps {
    content: string;
    renderCode?: (code: string, language?: string) => ReactNode;
    renderLink?: (href: string, text: string) => ReactNode;
}
/**
 * Headless markdown renderer.
 * Parses markdown text to semantic HTML elements via createElement.
 * Supports headings, paragraphs, bold, italic, inline code, code blocks,
 * links, blockquotes, and lists. No external dependencies.
 */
declare function MarkdownRenderer(props: MarkdownRendererProps): ReactNode;

/** Props for the Thread component. */
interface ThreadProps {
    messages: ChatMessage[];
    isGenerating?: boolean;
    autoScroll?: boolean;
    className?: string;
}
/**
 * Headless thread component wrapping a scrollable message list.
 * Auto-scrolls to bottom when new messages arrive unless user has scrolled up.
 * Shows a scroll-to-bottom button when scrolled up and an empty state when no messages.
 */
declare function Thread({ messages, isGenerating, autoScroll, className, }: ThreadProps): ReactNode;

/** Props for the Composer component. */
interface ComposerProps {
    onSend: (text: string) => void;
    onStop?: () => void;
    isGenerating?: boolean;
    disabled?: boolean;
    placeholder?: string;
    maxRows?: number;
    className?: string;
}
/**
 * Headless composer component for sending messages.
 * Includes auto-resizing textarea, send/stop buttons, and keyboard shortcuts.
 */
declare function Composer({ onSend, onStop, isGenerating, disabled, placeholder, maxRows, className, }: ComposerProps): ReactNode;

/** Slot override functions for Thread customization. */
interface ThreadSlotOverrides {
    renderMessage?: (message: ChatMessage, index: number) => ReactNode;
    renderToolCall?: (part: ToolCallPart, index: number) => ReactNode;
    renderThinkingBlock?: (part: ReasoningPart, index: number) => ReactNode;
}
/** Props for ThreadProvider. */
interface ThreadProviderProps extends ThreadSlotOverrides {
    children: ReactNode;
}
/**
 * Provides slot-based customization for Thread message rendering.
 * Wrap a Thread in ThreadProvider to override how messages, tool calls,
 * or thinking blocks are rendered.
 */
declare function ThreadProvider({ children, renderMessage, renderToolCall, renderThinkingBlock, }: ThreadProviderProps): ReactNode;
/**
 * Access slot overrides from ThreadProvider context.
 * @throws {Error} If used outside a ThreadProvider
 */
declare function useThreadSlots(): ThreadSlotOverrides;
/**
 * Access slot overrides if inside a ThreadProvider, or null if not.
 * Safe to call without a ThreadProvider ancestor.
 */
declare function useOptionalThreadSlots(): ThreadSlotOverrides | null;

/** A session item that ThreadList can display — either full ChatSession or lightweight SessionInfo. */
type SessionItem = SessionInfo | ChatSession;
/** Props for the ThreadList component. */
interface ThreadListProps {
    sessions: SessionItem[];
    activeSessionId?: string;
    onSelect: (id: string) => void;
    onCreate?: () => void;
    onDelete?: (id: string) => void;
    searchQuery?: string;
    onSearchChange?: (query: string) => void;
    className?: string;
}
/**
 * Session sidebar component for listing, searching, creating, and deleting sessions.
 */
declare function ThreadList({ sessions, activeSessionId, onSelect, onCreate, onDelete, searchQuery, onSearchChange, className, }: ThreadListProps): ReactNode;

/** Connection status of the SSE hook. */
type SSEStatus = "idle" | "connecting" | "open" | "closed" | "error";
/** Options for the useSSE hook. */
interface UseSSEOptions {
    /** HTTP method (default: "GET") */
    method?: "GET" | "POST";
    /** Request body for POST requests (JSON-serialized automatically) */
    body?: unknown;
    headers?: Record<string, string>;
    onEvent?: (event: ChatEvent) => void;
    onError?: (error: Error) => void;
    reconnect?: boolean;
    reconnectInterval?: number;
}
/** Return type for the useSSE hook. */
interface UseSSEReturn {
    status: SSEStatus;
    connect: () => void;
    disconnect: () => void;
    lastEvent: ChatEvent | null;
}
/**
 * SSE transport hook using fetch (not EventSource).
 * Parses text/event-stream format with support for multi-line data and event types.
 */
declare function useSSE(url: string | null, options?: UseSSEOptions): UseSSEReturn;

/** Model display option returned by useModels (mapped from core ModelInfo). */
interface ModelOption {
    id: string;
    name: string;
    tier?: string;
    /** Provider/backend name for multi-provider context. */
    provider?: string;
}
/** Return type for the useModels hook. */
interface UseModelsReturn {
    models: ModelOption[];
    isLoading: boolean;
    error: Error | null;
    refresh: () => void;
    search: (query: string) => ModelOption[];
}
/**
 * Hook for fetching and searching available models from the chat runtime.
 */
declare function useModels(): UseModelsReturn;

/** Props for the ModelSelector component. */
interface ModelSelectorProps {
    models: ModelOption[];
    selectedModel?: string;
    onSelect: (modelId: string) => void;
    placeholder?: string;
    className?: string;
    /** Allow free-text model input when models list is empty. Default: true. */
    allowFreeText?: boolean;
}
/**
 * Dropdown model selector with search and keyboard navigation.
 * Falls back to a free-text input when models list is empty.
 */
declare function ModelSelector({ models, selectedModel, onSelect, placeholder, className, allowFreeText, }: ModelSelectorProps): ReactNode;

/**
 * @witqq/agent-sdk/chat/react — useRemoteAuth
 *
 * Server-delegated authentication hook. Delegates all auth flows to
 * the server auth handler (createAuthHandler) via HTTP, avoiding
 * browser crypto dependencies entirely.
 *
 * Replaces useAuth for browser contexts. Same interface shape for easy migration.
 */

/** Supported remote auth backends. */
type RemoteAuthBackend = "copilot" | "claude" | "vercel-ai";
/** Auth status state machine: idle → pending → authenticated | error. */
type RemoteAuthStatus = "idle" | "pending" | "authenticated" | "error";
/** Options for the useRemoteAuth hook. */
interface UseRemoteAuthOptions {
    /** Auth backend to use */
    backend: RemoteAuthBackend;
    /** Base URL of the auth server (e.g. "http://localhost:3456/api/auth") */
    baseUrl: string;
    /** Called after successful authentication */
    onAuthenticated?: (token: AuthToken) => void;
    /** Optional fetch override (for testing) */
    fetch?: typeof globalThis.fetch;
    /** Optional headers for all requests */
    headers?: Record<string, string>;
}
/** Return value from useRemoteAuth. */
interface UseRemoteAuthReturn {
    status: RemoteAuthStatus;
    error: Error | null;
    startDeviceFlow: () => Promise<void>;
    deviceCode: string | null;
    verificationUrl: string | null;
    startOAuthFlow: () => Promise<void>;
    authorizeUrl: string | null;
    completeOAuth: (codeOrUrl: string) => Promise<void>;
    submitApiKey: (key: string, baseUrl?: string) => Promise<void>;
    start: (provider?: RemoteAuthBackend) => Promise<void>;
    token: AuthToken | null;
    reset: () => void;
    savedProviders: string[];
    loadSavedTokens: () => Promise<void>;
    useSavedToken: (provider: RemoteAuthBackend) => Promise<void>;
    clearTokens: () => Promise<void>;
}
/**
 * Server-delegated authentication hook.
 *
 * Communicates with server auth handler endpoints (POST /auth/start,
 * POST /auth/copilot/poll, etc.) instead of running auth flows in the browser.
 * No node:crypto dependency since all crypto operations happen server-side.
 *
 * @param options - Hook configuration
 * @returns Auth state and action methods
 *
 * @example
 * ```ts
 * const auth = useRemoteAuth({
 *   backend: "copilot",
 *   baseUrl: "/api/auth",
 *   onAuthenticated: (token) => console.log("Authenticated:", token),
 * });
 * ```
 */
declare function useRemoteAuth(options: UseRemoteAuthOptions): UseRemoteAuthReturn;

/**
 * @witqq/agent-sdk/chat/react — useRemoteChat
 *
 * Lifecycle hook that orchestrates auth → runtime → session.
 *
 * On mount, checks for saved auth tokens and auto-restores.
 * Once authenticated, creates a RemoteChatClient and initial session.
 * Exposes readiness phase, the client instance, and the auth sub-hook.
 */

/** Lifecycle phase for the useRemoteChat hook. */
type RemoteChatPhase = "initializing" | "unauthenticated" | "authenticating" | "creating" | "ready" | "error";
/** Options for useRemoteChat. */
interface UseRemoteChatOptions {
    /** Base URL for chat API (e.g. "/api/chat"). */
    chatBaseUrl: string;
    /** Base URL for auth API (e.g. "/api/auth"). */
    authBaseUrl: string;
    /** Auth backend to use. */
    backend: RemoteAuthBackend;
    /** Called when lifecycle reaches "ready" phase. */
    onReady?: () => void;
    /** Custom fetch for testability. */
    fetch?: typeof globalThis.fetch;
    /** Optional headers for all requests. */
    headers?: Record<string, string>;
}
/** Return value from useRemoteChat. */
interface UseRemoteChatReturn {
    /** Current lifecycle phase. */
    phase: RemoteChatPhase;
    /** Chat client (null until phase = "ready"). */
    runtime: IChatClient | null;
    /** Initial session ID (null until phase = "ready"). */
    sessionId: string | null;
    /** Auth sub-hook for manual auth control. */
    auth: UseRemoteAuthReturn;
    /** Current error (null when no error). */
    error: Error | null;
    /** Create a new chat session. Returns session ID. */
    newSession: () => Promise<string>;
    /** Logout: clear tokens, dispose runtime, reset to unauthenticated. */
    logout: () => Promise<void>;
}
/**
 * Lifecycle hook: auth → runtime → session.
 *
 * @example
 * ```tsx
 * const chat = useRemoteChat({
 *   chatBaseUrl: "/api/chat",
 *   authBaseUrl: "/api/auth",
 *   backend: "copilot",
 * });
 *
 * if (chat.phase === "unauthenticated") {
 *   return <button onClick={() => chat.auth.start()}>Login</button>;
 * }
 * if (chat.phase === "ready" && chat.runtime) {
 *   return <ChatProvider runtime={chat.runtime}>...</ChatProvider>;
 * }
 * ```
 */
declare function useRemoteChat(options: UseRemoteChatOptions): UseRemoteChatReturn;

/**
 * Props passed to per-backend auth form components.
 * Each backend implements its own form using these props.
 */
interface AuthFormProps {
    /** The remote auth hook instance, pre-configured for this backend. */
    auth: UseRemoteAuthReturn;
    /** Called when authentication completes successfully. */
    onAuthComplete: () => void;
}
/** A backend auth form component. */
type AuthFormComponent = (props: AuthFormProps) => ReactNode;

/**
 * Copilot (GitHub) auth form — device flow.
 *
 * Shows "Authenticate with GitHub" button → device code + verification URL →
 * "Waiting..." → "✓ Authenticated" + "Continue →".
 *
 * Co-located with the Copilot backend.
 */
declare function CopilotAuthForm({ auth, onAuthComplete }: AuthFormProps): ReactNode;

/**
 * Claude auth form — OAuth Authorization Code + PKCE.
 *
 * Shows "Authenticate with Claude" button → authorize URL link +
 * paste-code input + "Submit" button.
 *
 * Co-located with the Claude backend.
 */
declare function ClaudeAuthForm({ auth, onAuthComplete }: AuthFormProps): ReactNode;

/**
 * Vercel AI auth form — API key + optional base URL.
 *
 * Shows base URL input + API key input + "Connect" button.
 *
 * Co-located with the Vercel AI backend.
 */
declare function VercelAIAuthForm({ auth, onAuthComplete }: AuthFormProps): ReactNode;

/** Props for the BackendSelector component. */
interface BackendSelectorProps {
    backends: BackendInfo[];
    onSelect: (name: string) => void;
    className?: string;
}
/**
 * Headless backend selector showing registered backends with active indicator.
 * Uses data attributes for styling:
 * - `[data-backend-selector]` on root
 * - `[data-backend-item]` on each item
 * - `[data-backend-active="true"]` on the active backend
 * - `[data-backend-name]` with backend name value
 */
declare function BackendSelector({ backends, onSelect, className, }: BackendSelectorProps): ReactNode;

/** Return type for the useBackends hook. */
interface UseBackendsReturn {
    backends: BackendInfo[];
    isLoading: boolean;
    error: Error | null;
    refresh: () => void;
}
/**
 * Hook for discovering registered backends and switching between them.
 */
declare function useBackends(): UseBackendsReturn;

/** Return type for the useProviders hook. */
interface UseProvidersReturn {
    providers: ProviderConfig[];
    isLoading: boolean;
    error: Error | null;
    refresh: () => void;
    createProvider: (config: Omit<ProviderConfig, "id" | "createdAt">) => Promise<void>;
    updateProvider: (id: string, changes: Partial<Omit<ProviderConfig, "id" | "createdAt">>) => Promise<void>;
    deleteProvider: (id: string) => Promise<void>;
    selectProvider: (id: string) => void;
}
/**
 * Hook for managing providers (backend + model combos).
 * Requires an IChatClient with provider methods (e.g. RemoteChatClient).
 */
declare function useProviders(): UseProvidersReturn;

/** Props for the ProviderSelector component. */
interface ProviderSelectorProps {
    providers: ProviderConfig[];
    activeProviderId?: string;
    onSelect: (id: string) => void;
    onSettingsClick?: () => void;
    className?: string;
}
/**
 * Headless dropdown for selecting a configured provider.
 * Uses data attributes for styling hooks. Follows ModelSelector pattern.
 */
declare function ProviderSelector({ providers, activeProviderId, onSelect, onSettingsClick, className, }: ProviderSelectorProps): ReactNode;

/** A unified item rendered in the ProviderModelSelector dropdown. */
interface ProviderModelItem {
    id: string;
    label: string;
    sublabel?: string;
    tier?: string;
    type: "provider" | "model";
}
/** Props for the ProviderModelSelector component. */
interface ProviderModelSelectorProps {
    /** Configured providers (backend + model combos). When non-empty, provider mode is used. */
    providers?: ProviderConfig[];
    /** Available models. Used when providers is empty or undefined. */
    models?: ModelOption[];
    /** Currently selected provider ID. */
    activeProviderId?: string;
    /** Currently selected model ID (fallback mode). */
    selectedModel?: string;
    /** Called when a provider is selected. */
    onSelectProvider?: (id: string) => void;
    /** Called when a model is selected (fallback mode). */
    onSelectModel?: (modelId: string) => void;
    /** Called when settings gear is clicked. */
    onSettingsClick?: () => void;
    /** Placeholder text for the trigger button. */
    placeholder?: string;
    className?: string;
}
/**
 * Unified selector that shows providers when available, falls back to model list.
 * Replaces the need for separate ProviderSelector + ModelSelector in ChatUI.
 */
declare function ProviderModelSelector({ providers, models, activeProviderId, selectedModel, onSelectProvider, onSelectModel, onSettingsClick, placeholder, className, }: ProviderModelSelectorProps): ReactNode;

/** Props for the ProviderSettings component. */
interface ProviderSettingsProps {
    providers: ProviderConfig[];
    onClose?: () => void;
    onProviderCreated?: (p: ProviderConfig) => void;
    onProviderDeleted?: (id: string) => void;
    onProviderUpdated?: (id: string, changes: {
        model?: string;
        label?: string;
    }) => void;
    /** Called when authentication succeeds (before configure step). Parent should refresh providers. */
    onAuthCompleted?: (backend: string) => void;
    authBaseUrl?: string;
    className?: string;
}
/**
 * Headless settings panel for managing providers.
 * States: list (all providers), add (new provider flow), edit (existing).
 */
declare function ProviderSettings({ providers, onClose, onProviderCreated, onProviderDeleted, onProviderUpdated, onAuthCompleted, authBaseUrl, className, }: ProviderSettingsProps): ReactNode;

/** Props for the ContextStatsDisplay component. */
interface ContextStatsDisplayProps {
    /** Context stats from runtime.getContextStats(sessionId). Null = nothing to display. */
    stats: ContextStats | null;
    /** CSS class on the root element. */
    className?: string;
}
/**
 * Headless component displaying context window statistics.
 *
 * When real usage data is available (realPromptTokens + modelContextWindow),
 * displays actual token usage and model context window size.
 * When real data is not yet available (before first API response), returns null.
 *
 * All elements use `data-*` attributes for CSS styling — no inline styles.
 */
declare function ContextStatsDisplay({ stats, className }: ContextStatsDisplayProps): ReactNode;

/**
 * @witqq/agent-sdk/chat/react — ChatUI
 *
 * Composite component that wires Thread, Composer, ThreadList, ModelSelector,
 * and ProviderSettings into a complete chat interface. Consumers get a full AI chat
 * in ~3 lines:
 *
 *   import { ChatUI } from "@witqq/agent-sdk/chat/react";
 *   <ChatUI runtime={myRuntime} />
 *
 * Slot system: replace any sub-component while keeping all others as defaults.
 *
 * Built from composable sub-components: ChatLayout, ChatHeader, ChatInputArea,
 * ChatSettingsOverlay — each usable independently for custom layouts.
 */

/** Slot overrides for ChatUI sub-components. */
interface ChatUISlots {
    /** Replace the Thread component. */
    thread?: ComponentType<ThreadProps>;
    /** Replace the Composer component. */
    composer?: ComponentType<ComposerProps>;
    /** Replace the ThreadList (sidebar) component. */
    threadList?: ComponentType<ThreadListProps>;
    /** Replace the ModelSelector component (used in header when no providers). */
    modelSelector?: ComponentType<ModelSelectorProps>;
    /** Replace the BackendSelector component. */
    backendSelector?: ComponentType<BackendSelectorProps>;
    /** Replace the ProviderSelector component (legacy, use providerModelSelector). */
    providerSelector?: ComponentType<ProviderSelectorProps>;
    /** Replace the unified ProviderModelSelector component (near composer). */
    providerModelSelector?: ComponentType<ProviderModelSelectorProps>;
    /** Replace the ProviderSettings component. */
    providerSettings?: ComponentType<ProviderSettingsProps>;
    /** Replace the ContextStatsDisplay component. */
    contextStats?: ComponentType<ContextStatsDisplayProps>;
    /** Custom auth dialog element rendered when provided. */
    authDialog?: ReactNode;
    /** Custom message renderer (forwarded to ThreadProvider). */
    renderMessage?: (message: ChatMessage, index: number) => ReactNode;
    /** Custom tool call renderer (forwarded to ThreadProvider). */
    renderToolCall?: (part: ToolCallPart, index: number) => ReactNode;
    /** Custom thinking block renderer (forwarded to ThreadProvider). */
    renderThinkingBlock?: (part: ReasoningPart, index: number) => ReactNode;
}
/** Props for the ChatUI composite component. */
interface ChatUIProps {
    /** The chat runtime or client instance. ChatUI wraps it in ChatProvider. Accepts IChatClient. */
    runtime: IChatClient;
    /** Slot overrides for sub-components. */
    slots?: ChatUISlots;
    /** CSS class on the root element. */
    className?: string;
    /** Show the session sidebar. Default: true. */
    showSidebar?: boolean;
    /** Show the model selector header. Default: true. */
    showModelSelector?: boolean;
    /** Show the backend selector in header. Default: false. */
    showBackendSelector?: boolean;
    /** Show the provider selector near composer. Default: auto (true when providers available). */
    showProviderSelector?: boolean;
    /** Base URL for auth API (needed by ProviderSettings). */
    authBaseUrl?: string;
    /** Placeholder text for the Composer textarea. */
    placeholder?: string;
}
/**
 * Composite chat component — complete AI chat interface in one import.
 *
 * ```tsx
 * import { ChatUI } from "@witqq/agent-sdk/chat/react";
 *
 * function App() {
 *   return <ChatUI runtime={myRuntime} />;
 * }
 * ```
 */
declare function ChatUI({ runtime, ...rest }: ChatUIProps): ReactNode;

/**
 * @witqq/agent-sdk/chat/react — ChatLayout
 *
 * Pure layout container for chat interfaces. Renders sidebar + main area
 * without any logic or state. ChatUI uses this internally.
 */

/** Props for the ChatLayout component. */
interface ChatLayoutProps {
    /** Main chat content (thread, input area, etc.). */
    children: ReactNode;
    /** Sidebar content (thread list, session list, etc.). */
    sidebar?: ReactNode;
    /** Modal/overlay content. Accepts a single node or array of nodes. */
    overlay?: ReactNode | ReactNode[];
    /** CSS class on the root element. */
    className?: string;
}
/**
 * Pure layout container — flex row with optional sidebar and overlay.
 *
 * Renders `[data-chat-ui]` root with:
 * - overlay (rendered first for z-index stacking)
 * - sidebar (rendered before main content)
 * - children (main chat area)
 */
declare function ChatLayout({ children, sidebar, overlay, className }: ChatLayoutProps): ReactNode;

/**
 * @witqq/agent-sdk/chat/react — ChatHeader
 *
 * Selector composition for the chat header area. Renders backend selector,
 * model selector, or nothing based on configuration.
 */

/** Props for the ChatHeader component. */
interface ChatHeaderProps {
    /** Whether to show backend selector. Default: false. */
    showBackendSelector?: boolean;
    /** Whether to show model selector. Default: true. */
    showModelSelector?: boolean;
    /** Whether providers are configured (hides model selector when true). */
    hasProviders?: boolean;
    /** Available backends list. */
    backends?: BackendInfo[];
    /** Available models list. */
    models?: ModelOption[];
    /** Currently selected model. */
    selectedModel?: string;
    /** Backend selection handler. */
    onBackendSelect?: (name: string) => void;
    /** Model selection handler. */
    onModelSelect?: (modelId: string) => void;
    /** Slot override for BackendSelector. */
    BackendSelectorComponent?: ComponentType<BackendSelectorProps>;
    /** Slot override for ModelSelector. */
    ModelSelectorComponent?: ComponentType<ModelSelectorProps>;
}
/**
 * Header area with backend and model selectors.
 * Returns null when no selectors need to be shown.
 */
declare function ChatHeader({ showBackendSelector, showModelSelector, hasProviders, backends, models, selectedModel, onBackendSelect, onModelSelect, BackendSelectorComponent: BSC, ModelSelectorComponent: MSC, }: ChatHeaderProps): ReactNode;

/**
 * @witqq/agent-sdk/chat/react — ChatInputArea
 *
 * Input area combining the unified provider/model selector with the composer.
 */

/** Props for the ChatInputArea component. */
interface ChatInputAreaProps {
    /** Send message handler. */
    onSend: (message: string) => void;
    /** Stop generation handler. */
    onStop?: () => void;
    /** Whether generation is in progress. */
    isGenerating?: boolean;
    /** Placeholder text for the textarea. */
    placeholder?: string;
    /** Available providers. */
    providers?: ProviderConfig[];
    /** Available models. */
    models?: ModelOption[];
    /** Active provider ID. */
    activeProviderId?: string;
    /** Selected model. */
    selectedModel?: string;
    /** Provider selection handler. */
    onSelectProvider?: (id: string) => void;
    /** Model selection handler. */
    onSelectModel?: (modelId: string) => void;
    /** Settings button handler. */
    onSettingsClick?: () => void;
    /** Slot override for Composer. */
    ComposerComponent?: ComponentType<ComposerProps>;
    /** Slot override for ProviderModelSelector. */
    ProviderModelSelectorComponent?: ComponentType<ProviderModelSelectorProps>;
    /** Token usage data to display. */
    usage?: ChatUsage | null;
}
/**
 * Input area — unified selector + composer in a `[data-chat-input-area]` container.
 */
declare function ChatInputArea({ onSend, onStop, isGenerating, placeholder, providers, models, activeProviderId, selectedModel, onSelectProvider, onSelectModel, onSettingsClick, ComposerComponent: CC, ProviderModelSelectorComponent: PMSC, usage, }: ChatInputAreaProps): ReactNode;

/**
 * @witqq/agent-sdk/chat/react — ChatSettingsOverlay
 *
 * Modal overlay for provider settings management.
 * Features: backdrop click-to-close, ESC key handler, focus trap.
 */

/** Props for the ChatSettingsOverlay component. */
interface ChatSettingsOverlayProps {
    /** Whether the overlay is visible. */
    open: boolean;
    /** Close handler. */
    onClose: () => void;
    /** Available providers. */
    providers?: ProviderConfig[];
    /** Auth API base URL. */
    authBaseUrl?: string;
    /** Provider created handler. */
    onProviderCreated?: (provider: {
        backend: string;
        model: string;
        label?: string;
    }) => void;
    /** Provider deleted handler. */
    onProviderDeleted?: (id: string) => void;
    /** Provider updated handler. */
    onProviderUpdated?: (id: string, changes: Partial<ProviderConfig>) => void;
    /** Called when authentication succeeds. Parent should refresh providers. */
    onAuthCompleted?: (backend: string) => void;
    /** Slot override for ProviderSettings. */
    ProviderSettingsComponent?: ComponentType<ProviderSettingsProps>;
}
/**
 * Settings modal — renders `[data-provider-settings-overlay]` when open.
 * Returns null when closed.
 * Backdrop click and Escape key close the overlay with exit animation.
 * Focus is trapped within the overlay content.
 */
declare function ChatSettingsOverlay({ open, onClose, providers, authBaseUrl, onProviderCreated, onProviderDeleted, onProviderUpdated, onAuthCompleted, ProviderSettingsComponent: PSC, }: ChatSettingsOverlayProps): ReactNode;

/** Props for the UsageBadge component. */
interface UsageBadgeProps {
    usage: ChatUsage | null;
    className?: string;
}
/** Compact token usage display. Shows prompt/completion/total tokens. */
declare function UsageBadge({ usage, className }: UsageBadgeProps): ReactNode;

/**
 * Client-side adapter that implements IChatClient by delegating
 * operations over HTTP/SSE to a remote server.
 *
 * Bridges the gap between SDK React hooks (which require an in-process runtime)
 * and the common architecture where ChatRuntime runs on a server.
 *
 * @example
 * ```ts
 * import { RemoteChatClient } from "@witqq/agent-sdk/chat/react";
 * import { ChatProvider } from "@witqq/agent-sdk/chat/react";
 *
 * const client = new RemoteChatClient({ baseUrl: "/api" });
 * <ChatProvider runtime={client}> ... </ChatProvider>
 * ```
 */

/**
 * Standard server endpoint contract.
 * Server implementations expose these routes to work with RemoteChatClient.
 *
 * POST   {baseUrl}/sessions/create   — Create session
 * GET    {baseUrl}/sessions/{id}     — Get session
 * GET    {baseUrl}/sessions          — List sessions
 * DELETE {baseUrl}/sessions/{id}     — Delete session
 * GET    {baseUrl}/sessions/{id}/context-stats — Get context window stats
 * POST   {baseUrl}/send              — Send message (SSE stream response)
 * POST   {baseUrl}/abort             — Abort current stream
 * GET    {baseUrl}/models            — List models
 * GET    {baseUrl}/backends          — List backends
 * POST   {baseUrl}/model/switch      — Switch model
 * POST   {baseUrl}/provider/switch   — Switch provider (backend + model)
 * GET    {baseUrl}/providers         — List providers
 * POST   {baseUrl}/providers         — Create provider
 * PUT    {baseUrl}/providers/{id}    — Update provider
 * DELETE {baseUrl}/providers/{id}    — Delete provider
 */
interface RemoteChatClientOptions {
    /** Base URL for API endpoints (e.g. "/api" or "https://example.com/api") */
    baseUrl: string;
    /** Optional headers for all requests (e.g. auth tokens) */
    headers?: Record<string, string>;
    /** Custom fetch implementation for testability */
    fetch?: typeof globalThis.fetch;
}
declare class RemoteChatClient implements IChatClient {
    private _status;
    private _activeSessionId;
    private _selectedProviderId;
    private _abortController;
    private readonly baseUrl;
    private readonly headers;
    private readonly _fetch;
    private readonly _selectionListeners;
    constructor(options: RemoteChatClientOptions);
    get status(): RuntimeStatus;
    dispose(): Promise<void>;
    private assertNotDisposed;
    get selectedProviderId(): string | null;
    selectProvider(providerId: string): void;
    onSelectionChange(callback: SelectionChangeCallback): () => void;
    private _notifySelectionChange;
    get activeSessionId(): ChatId | null;
    createSession(options: CreateSessionOptions): Promise<ChatSession>;
    getSession(id: ChatIdLike): Promise<ChatSession | null>;
    listSessions(_options?: SessionListOptions): Promise<ChatSession[]>;
    deleteSession(id: ChatIdLike): Promise<void>;
    /**
     * Fetch context window stats from server.
     * Returns null if stats not available (e.g. no messages sent yet).
     */
    getContextStats(sessionId: ChatIdLike): Promise<ContextStats | null>;
    switchSession(id: ChatIdLike): Promise<ChatSession>;
    send(sessionId: ChatIdLike, message: string, options?: SendMessageOptions): AsyncIterable<ChatEvent>;
    abort(): void;
    listModels(): Promise<ModelInfo[]>;
    listBackends(): Promise<BackendInfo[]>;
    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>;
    private readonly _sessionListeners;
    onSessionChange(callback: () => void): () => void;
    private _notifySessionChange;
    private _get;
    private _post;
    private _delete;
    private _put;
    private _parseSSEStream;
}

/**
 * @witqq/agent-sdk/chat/react — useCopilotAuth
 *
 * Server-delegated Copilot Device Flow authentication hook.
 * Independently usable — does not require useRemoteAuth orchestrator.
 */

/** Options for useCopilotAuth. */
interface UseCopilotAuthOptions {
    /** Base URL of the auth server (e.g. "/api/auth") */
    baseUrl: string;
    /** Called after successful authentication */
    onAuthenticated?: (token: AuthToken) => void;
    /** Called on authentication error */
    onError?: (error: Error) => void;
    /** Optional fetch override (for testing) */
    fetch?: typeof globalThis.fetch;
    /** Optional headers for all requests */
    headers?: Record<string, string>;
}
/** Return value from useCopilotAuth. */
interface UseCopilotAuthReturn {
    status: "idle" | "pending" | "authenticated" | "error";
    error: Error | null;
    token: AuthToken | null;
    deviceCode: string | null;
    verificationUrl: string | null;
    /** Start the device flow. Shows deviceCode and verificationUrl, then polls for completion. */
    start: () => Promise<void>;
    reset: () => void;
}
/**
 * Copilot Device Flow authentication.
 * Starts device flow on server, provides code/URL for user, polls until complete.
 */
declare function useCopilotAuth(options: UseCopilotAuthOptions): UseCopilotAuthReturn;

/**
 * @witqq/agent-sdk/chat/react — useClaudeAuth
 *
 * Server-delegated Claude OAuth + PKCE authentication hook.
 * Independently usable — does not require useRemoteAuth orchestrator.
 */

/** Options for useClaudeAuth. */
interface UseClaudeAuthOptions {
    /** Base URL of the auth server (e.g. "/api/auth") */
    baseUrl: string;
    /** Called after successful authentication */
    onAuthenticated?: (token: AuthToken) => void;
    /** Called on authentication error */
    onError?: (error: Error) => void;
    /** Optional fetch override (for testing) */
    fetch?: typeof globalThis.fetch;
    /** Optional headers for all requests */
    headers?: Record<string, string>;
}
/** Return value from useClaudeAuth. */
interface UseClaudeAuthReturn {
    status: "idle" | "pending" | "authenticated" | "error";
    error: Error | null;
    token: AuthToken | null;
    authorizeUrl: string | null;
    /** Start OAuth flow. Sets authorizeUrl for user redirect. */
    start: () => Promise<void>;
    /** Complete OAuth after redirect. Pass the code or callback URL. */
    complete: (codeOrUrl: string) => Promise<void>;
    reset: () => void;
}
/**
 * Claude OAuth + PKCE authentication.
 * Two-step flow: start() gets authorizeUrl → user redirects → complete(code) finishes.
 */
declare function useClaudeAuth(options: UseClaudeAuthOptions): UseClaudeAuthReturn;

/**
 * @witqq/agent-sdk/chat/react — useApiKeyAuth
 *
 * Server-delegated API key authentication hook (for Vercel AI / OpenRouter / etc.).
 * Independently usable — does not require useRemoteAuth orchestrator.
 */

/** Options for useApiKeyAuth. */
interface UseApiKeyAuthOptions {
    /** Base URL of the auth server (e.g. "/api/auth") */
    baseUrl: string;
    /** Called after successful authentication */
    onAuthenticated?: (token: AuthToken) => void;
    /** Called on authentication error */
    onError?: (error: Error) => void;
    /** Optional fetch override (for testing) */
    fetch?: typeof globalThis.fetch;
    /** Optional headers for all requests */
    headers?: Record<string, string>;
}
/** Return value from useApiKeyAuth. */
interface UseApiKeyAuthReturn {
    status: "idle" | "pending" | "authenticated" | "error";
    error: Error | null;
    token: AuthToken | null;
    /** Submit an API key (and optional provider base URL). */
    submit: (key: string, apiBaseUrl?: string) => Promise<void>;
    reset: () => void;
}
/**
 * API key authentication.
 * Sends key to server for validation and storage.
 */
declare function useApiKeyAuth(options: UseApiKeyAuthOptions): UseApiKeyAuthReturn;

export { type AuthFormComponent, type AuthFormProps, BackendSelector, type BackendSelectorProps, ChatHeader, type ChatHeaderProps, ChatInputArea, type ChatInputAreaProps, ChatLayout, type ChatLayoutProps, ChatProvider, ChatSettingsOverlay, type ChatSettingsOverlayProps, ChatUI, type ChatUIProps, type ChatUISlots, type ChatUsage, ClaudeAuthForm, Composer, type ComposerProps, ContextStatsDisplay, type ContextStatsDisplayProps, CopilotAuthForm, MarkdownRenderer, type MarkdownRendererProps, Message, type MessageProps, type ModelOption, ModelSelector, type ModelSelectorProps, type PendingToolRequest, type ProviderModelItem, ProviderModelSelector, type ProviderModelSelectorProps, ProviderSelector, type ProviderSelectorProps, ProviderSettings, type ProviderSettingsProps, type RemoteAuthBackend, type RemoteAuthStatus, RemoteChatClient, type RemoteChatClientOptions, type RemoteChatPhase, type SSEStatus, ThinkingBlock, type ThinkingBlockProps, Thread, ThreadList, type ThreadListProps, type ThreadProps, ThreadProvider, type ThreadProviderProps, type ThreadSlotOverrides, ToolCallView, type ToolCallViewProps, UsageBadge, type UsageBadgeProps, type UseApiKeyAuthOptions, type UseApiKeyAuthReturn, type UseBackendsReturn, type UseChatOptions, type UseChatReturn, type UseClaudeAuthOptions, type UseClaudeAuthReturn, type UseCopilotAuthOptions, type UseCopilotAuthReturn, type UseMessagesOptions, type UseMessagesReturn, type UseModelsReturn, type UseProvidersReturn, type UseRemoteAuthOptions, type UseRemoteAuthReturn, type UseRemoteChatOptions, type UseRemoteChatReturn, type UseSSEOptions, type UseSSEReturn, type UseSessionsReturn, type UseToolApprovalReturn, VercelAIAuthForm, useApiKeyAuth, useBackends, useChat, useChatRuntime, useClaudeAuth, useCopilotAuth, useMessages, useModels, useOptionalThreadSlots, useProviders, useRemoteAuth, useRemoteChat, useSSE, useSessions, useThreadSlots, useToolApproval };
