import { M as ModelInfo, F as FullAgentConfig, I as IAgentService, T as ToolDefinition, U as UsageData } from './agent-CW9XbmG_.js';
import { E as ErrorCode } from './errors-C-so0M4t.js';
import { A as AuthToken } from './types-BxggH0Yh.js';

/**
 * @witqq/agent-sdk/chat/backends/types
 *
 * IChatBackend — core backend interface for sending/streaming messages.
 * IResumableBackend — extends IChatBackend with session resume support.
 */

/** Options for creating a backend adapter */
interface BackendAdapterOptions {
    /** Agent configuration (model, systemPrompt, tools, etc.) */
    agentConfig: FullAgentConfig;
    /** Pre-created agent service (if adapter should not own lifecycle) */
    agentService?: IAgentService;
    /** Factory for lazy service creation (called on first use, not at construction) */
    agentServiceFactory?: () => IAgentService;
}
/**
 * Core chat backend — send, stream, models, validate, dispose.
 * All backends implement this. Resume support is optional.
 *
 * Note: `agentService` is intentionally NOT on this interface.
 * It's an implementation detail exposed on BaseBackendAdapter for
 * advanced consumers who need direct service access.
 */
interface IChatBackend {
    /** Backend name (e.g. "copilot", "claude", "vercel-ai") */
    readonly name: string;
    /** Send a message and receive a complete response */
    sendMessage(session: ChatSession, message: string, options?: SendMessageOptions): Promise<ChatMessage>;
    /** Stream a message response as ChatEvents */
    streamMessage(session: ChatSession, message: string, options?: SendMessageOptions): AsyncIterable<ChatEvent>;
    /** List available models */
    listModels(): Promise<ModelInfo[]>;
    /** Validate backend configuration/credentials */
    validate(): Promise<{
        valid: boolean;
        errors: string[];
    }>;
    /** Dispose resources */
    dispose(): Promise<void>;
    /** Current effective model */
    readonly currentModel: string | undefined;
}
/**
 * Extended backend with session resume capabilities.
 * Only backends with persistent sessions (Copilot, Claude) implement this.
 * Use `isResumableBackend()` to type-narrow at runtime.
 */
interface IResumableBackend extends IChatBackend {
    /** Whether this adapter supports session resume */
    canResume(): boolean;
    /**
     * Resume a previous session by its backend session ID.
     * Streams events from the resumed session.
     * @throws ChatError with SESSION_EXPIRED if session is no longer valid
     * @throws ChatError with SESSION_NOT_FOUND if session ID is unknown
     */
    resume(session: ChatSession, backendSessionId: string, options?: SendMessageOptions): AsyncIterable<ChatEvent>;
    /** The backend session ID from the last stream, or null if not yet streamed */
    readonly backendSessionId: string | null;
}
/** Type guard: checks if a backend adapter supports session resume */
declare function isResumableBackend(adapter: IChatBackend): adapter is IResumableBackend;

/** Branded type for unique identifiers */
type ChatId = string & {
    readonly __brand: "ChatId";
};
/**
 * Generate a new unique ChatId (crypto.randomUUID-based)
 * @returns Branded ChatId string
 */
declare function createChatId(): ChatId;
/**
 * Cast a string to ChatId with UUID format validation.
 * Use this instead of manual `as ChatId` type assertions.
 *
 * @param value - String to validate and cast
 * @returns Branded ChatId
 * @throws {TypeError} If value is not a valid UUID v4 format
 */
declare function toChatId(value: string): ChatId;
/**
 * Accepts either a plain string or branded ChatId for API convenience.
 * Use this in public API signatures so consumers don't need `as ChatId` casts.
 */
type ChatIdLike = string | ChatId;
/** Lifecycle status of a message part (text, reasoning, etc.) */
type PartStatus = "pending" | "streaming" | "complete" | "error";
/** Lifecycle status of a tool call within a message */
type ToolCallStatus = "pending" | "running" | "requires_approval" | "complete" | "error" | "denied";
/** Lifecycle status of an entire message */
type MessageStatus = "pending" | "streaming" | "complete" | "error" | "cancelled";
/** Lifecycle status of a chat session */
type SessionStatus = "active";
/** Lifecycle status of the chat runtime */
type RuntimeStatus = "idle" | "streaming" | "error" | "disposed";
/** Plain text content part */
interface TextPart {
    type: "text";
    text: string;
    status: PartStatus;
}
/** Model reasoning/thinking content part */
interface ReasoningPart {
    type: "reasoning";
    text: string;
    status: PartStatus;
}
/** Tool invocation part with call ID, arguments, optional result */
interface ToolCallPart {
    type: "tool_call";
    toolCallId: string;
    name: string;
    args: unknown;
    result?: unknown;
    status: ToolCallStatus;
    error?: string;
}
/** Source reference part (URL citation) */
interface SourcePart {
    type: "source";
    url: string;
    title?: string;
    status: PartStatus;
}
/** File attachment part (base64-encoded data) */
interface FilePart {
    type: "file";
    name: string;
    mimeType: string;
    data: string;
    status: PartStatus;
}
/** Union of all message part types */
type MessagePart = TextPart | ReasoningPart | ToolCallPart | SourcePart | FilePart;
/** Role of message author */
type ChatRole = "user" | "assistant" | "system";
/** Metadata attached to messages — useful preset for the TMetadata generic */
interface ChatMessageMetadata {
    model?: string;
    backend?: string;
    usage?: UsageData;
    isSummary?: boolean;
    estimatedTokens?: number;
    custom?: Record<string, unknown>;
}
/** Message status */
type ChatMessageStatus = MessageStatus;
/** A single chat message — the fundamental unit of conversation */
interface ChatMessage<TMetadata = unknown> {
    id: ChatId;
    role: ChatRole;
    parts: MessagePart[];
    metadata?: TMetadata;
    createdAt: string;
    updatedAt?: string;
    status: MessageStatus;
}
/** Session configuration snapshot */
interface ChatSessionConfig {
    model: string;
    backend: string;
    systemPrompt?: string;
    temperature?: number;
    maxTokens?: number;
}
/**
 * Session metadata tracking usage statistics and custom extensions.
 *
 * Updated automatically by session stores on each `addMessage()` call.
 * The generic `TCustom` parameter allows type-safe application-specific
 * metadata via the `custom` field.
 *
 * @typeParam TCustom - Shape of the `custom` field (defaults to `Record<string, unknown>`)
 */
interface ChatSessionMetadata<TCustom extends Record<string, unknown> = Record<string, unknown>> {
    /** Number of messages in the session (updated by session store) */
    messageCount: number;
    /** Total token count across all messages in the session */
    totalTokens: number;
    /** Optional tags for session categorization and filtering */
    tags?: string[];
    /** Application-specific metadata — typed via the TCustom generic parameter */
    custom?: TCustom;
}
/** Chat session — a conversation with ordered messages (pure serializable data) */
interface ChatSession<TCustom extends Record<string, unknown> = Record<string, unknown>> {
    id: ChatId;
    title?: string;
    messages: ChatMessage[];
    config: ChatSessionConfig;
    metadata: ChatSessionMetadata<TCustom>;
    status: SessionStatus;
    createdAt: string;
    updatedAt: string;
    backendSessionId?: string;
}
/**
 * Reactive wrapper around ChatSession — provides subscribe/getSnapshot for
 * React useSyncExternalStore integration and lastMessage convenience getter.
 * Session stores may optionally return ObservableSession instances.
 */
interface ObservableSession<TCustom extends Record<string, unknown> = Record<string, unknown>> extends ChatSession<TCustom> {
    /** Subscribe to session changes (for React useSyncExternalStore) */
    subscribe(callback: () => void): () => void;
    /** Get immutable snapshot of session state (for React useSyncExternalStore) */
    getSnapshot(): ChatSession<TCustom>;
    /** Last message in the session */
    readonly lastMessage: ChatMessage | undefined;
}
/** Lightweight session info for listing (without full message array) */
interface SessionInfo {
    id: ChatId;
    title?: string;
    status: SessionStatus;
    messageCount: number;
    lastMessage?: ChatMessage;
    createdAt: string;
    updatedAt: string;
}
/** Events emitted during chat operation */
type ChatEvent = {
    type: "message:start";
    messageId: ChatId;
    role: ChatRole;
} | {
    type: "message:delta";
    messageId: ChatId;
    text: string;
} | {
    type: "message:complete";
    messageId: ChatId;
    message: ChatMessage;
} | {
    type: "tool:start";
    messageId: ChatId;
    toolCallId: string;
    toolName: string;
    args: Record<string, unknown>;
} | {
    type: "tool:complete";
    messageId: ChatId;
    toolCallId: string;
    toolName: string;
    result: unknown;
    isError?: boolean;
} | {
    type: "thinking:start";
    messageId: ChatId;
} | {
    type: "thinking:delta";
    messageId: ChatId;
    text: string;
} | {
    type: "thinking:end";
    messageId: ChatId;
} | {
    type: "permission:request";
    messageId: ChatId;
    toolName: string;
    toolArgs: Record<string, unknown>;
} | {
    type: "permission:response";
    messageId: ChatId;
    toolName: string;
    allowed: boolean;
} | {
    type: "usage";
    promptTokens: number;
    completionTokens: number;
    model?: string;
} | {
    type: "session:created";
    sessionId: ChatId;
} | {
    type: "session:updated";
    sessionId: ChatId;
} | {
    type: "error";
    error: string;
    recoverable: boolean;
    code?: ErrorCode;
    messageId?: ChatId;
} | {
    type: "typing:start";
} | {
    type: "typing:end";
} | {
    type: "heartbeat";
} | {
    type: "done";
    finalOutput?: string;
};
/** All possible ChatEvent type strings */
type ChatEventType = ChatEvent["type"];
/** Context passed to ChatMiddleware hooks */
interface ChatMiddlewareContext {
    sessionId: ChatId;
    signal: AbortSignal;
}
/** Runtime-level middleware for the send/receive lifecycle.
 *  Different from EventMiddleware which operates at the event bus level. */
interface ChatMiddleware {
    /** Transform message before sending to backend. Return null to reject the send. */
    onBeforeSend?(message: ChatMessage, context: ChatMiddlewareContext): ChatMessage | null | Promise<ChatMessage | null>;
    /** Transform/intercept stream events */
    onEvent?(event: ChatEvent, context: ChatMiddlewareContext): ChatEvent | null | Promise<ChatEvent | null>;
    /** Transform completed message after receiving from backend */
    onAfterReceive?(message: ChatMessage, context: ChatMiddlewareContext): ChatMessage | Promise<ChatMessage>;
    /** Intercept errors — return null to suppress, return error to propagate */
    onError?(error: Error, context: ChatMiddlewareContext): Error | null | Promise<Error | null>;
}
/** Options for sending a message to a provider */
interface SendMessageOptions {
    signal?: AbortSignal;
    /** Model to use for this request. Required for server-side runtime.send(). */
    model?: string;
    /** Per-call system prompt override (forwarded to the backend agent) */
    systemPrompt?: string;
    context?: Record<string, unknown>;
    /** Additional tools to include in this request */
    tools?: ToolDefinition[];
}
/** Options for runtime.send() — requires backend routing info */
interface RuntimeSendOptions {
    /** Backend to route this request to (key in backends map) */
    backend: string;
    /** Authentication credentials for the backend factory */
    credentials: AuthToken;
    /** Model to use for this request */
    model: string;
    /** Per-call system prompt override (forwarded to the backend agent) */
    systemPrompt?: string;
    /** Abort signal */
    signal?: AbortSignal;
    /** Request-scoped context */
    context?: Record<string, unknown>;
    /** Additional tools */
    tools?: ToolDefinition[];
}
/**
 * @deprecated IChatProvider has been inlined into IChatBackend.
 * Import IChatBackend from "@witqq/agent-sdk/chat/backends" instead.
 * Kept as type alias for backward compatibility.
 */
type IChatProvider = IChatBackend;
/**
 * Create a simple text ChatMessage.
 *
 * @param text - Message text content
 * @param role - Message role (default: "user")
 * @returns A complete ChatMessage with a single TextPart
 */
declare function createTextMessage(text: string, role?: ChatRole): ChatMessage;
/** Type guard: checks if a session has reactive API (subscribe/getSnapshot) */
declare function isObservableSession<TCustom extends Record<string, unknown> = Record<string, unknown>>(session: ChatSession<TCustom>): session is ObservableSession<TCustom>;

export { type ChatSessionMetadata as A, type BackendAdapterOptions as B, type ChatEventType as C, type FilePart as F, type IChatBackend as I, type MessageStatus as M, type ObservableSession as O, type PartStatus as P, type RuntimeStatus as R, type SendMessageOptions as S, type ToolCallStatus as T, type ChatEvent as a, type ChatId as b, type ChatMessage as c, type IResumableBackend as d, type ChatMiddleware as e, type ChatIdLike as f, type ChatSession as g, type RuntimeSendOptions as h, isResumableBackend as i, type ChatSessionConfig as j, type ChatMessageMetadata as k, type ChatMessageStatus as l, type ChatMiddlewareContext as m, type ChatRole as n, type IChatProvider as o, type MessagePart as p, type ReasoningPart as q, type SessionInfo as r, type SessionStatus as s, type SourcePart as t, type TextPart as u, type ToolCallPart as v, createChatId as w, createTextMessage as x, isObservableSession as y, toChatId as z };
