/**
 * Chat协议相关类型定义
 * 支持OpenAI Chat Completions的JSON↔SSE双向转换
 */
import type { BaseSseEvent, StreamDirection } from './core-interfaces.js';
type JsonObject = Record<string, unknown>;
export type ChatSseEventType = 'chat_chunk' | 'chat.done' | 'error' | 'ping';
export interface ChatSseEvent extends BaseSseEvent {
    /** 事件类型（SSE标准wire格式） */
    event: ChatSseEventType;
    /** 重写type字段以满足BaseSseEvent要求，与event保持一致 */
    type: string;
    /** 时间戳 */
    timestamp: number;
    /** 事件ID（SSE标准字段） */
    id?: string;
    /** 重试间隔（SSE标准字段） */
    retry?: number;
    /** 协议标识 */
    protocol: 'chat';
    /** 方向标识 */
    direction: StreamDirection;
}
export interface ChatSseEventWithEventField {
    id?: string;
    event: ChatSseEventType;
    data: string;
    timestamp?: number;
    retry?: number;
    sequenceNumber?: number;
}
export interface ChatCompletionChunk {
    id: string;
    object: 'chat.completion.chunk';
    created: number;
    model: string;
    system_fingerprint?: string;
    choices: ChatChoiceChunk[];
    usage?: ChatUsage;
}
export interface ChatChoiceChunk {
    index: number;
    delta: ChatDelta;
    finish_reason?: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call' | null;
    logprobs?: ChatLogProbs;
}
export interface ChatDelta {
    role?: 'system' | 'user' | 'assistant' | 'tool';
    content?: string | null;
    reasoning?: string;
    function_call?: ChatFunctionCall;
    tool_calls?: ChatToolCallChunk[];
}
export interface ChatFunctionCall {
    name?: string;
    arguments?: string;
}
export interface ChatToolCallChunk {
    index: number;
    id?: string;
    type?: 'function';
    function?: {
        name?: string;
        arguments?: string;
    };
}
export interface ChatLogProbs {
    content?: ChatTokenLogProb[];
}
export interface ChatTokenLogProb {
    token: string;
    logprob: number;
    bytes?: number[];
    top_logprobs?: ChatTopLogProb[];
}
export interface ChatTopLogProb {
    token: string;
    logprob: number;
    bytes?: number[];
}
export interface ChatUsage {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
}
export interface ChatCompletionRequest {
    model: string;
    messages: ChatMessage[];
    functions?: ChatFunction[];
    function_call?: 'auto' | 'none' | {
        name: string;
    };
    tools?: ChatTool[];
    tool_choice?: 'auto' | 'none' | 'required' | {
        type: 'function';
        function: {
            name: string;
        };
    };
    temperature?: number;
    top_p?: number;
    n?: number;
    stream?: boolean;
    stop?: string | string[] | null;
    max_tokens?: number;
    presence_penalty?: number;
    frequency_penalty?: number;
    logit_bias?: Record<string, number>;
    user?: string;
    response_format?: {
        type: 'text' | 'json_object';
    };
    seed?: number;
}
export interface ChatMessage {
    role: 'system' | 'user' | 'assistant' | 'tool';
    content?: string | null;
    name?: string;
    reasoning_content?: string;
    reasoning?: string;
    function_call?: ChatFunctionCall;
    tool_calls?: ChatToolCall[];
    tool_call_id?: string;
}
export interface ChatFunction {
    name: string;
    description?: string;
    parameters?: Record<string, unknown>;
}
export interface ChatTool {
    type: 'function';
    function: ChatFunction;
}
export interface ChatToolCall {
    id: string;
    type: 'function';
    function: ChatFunctionCall;
}
export interface ChatCompletionResponse {
    id: string;
    object: 'chat.completion';
    created: number;
    model: string;
    system_fingerprint?: string;
    choices: ChatChoice[];
    usage?: ChatUsage;
}
export interface ChatChoice {
    index: number;
    message: ChatMessage;
    finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call';
    logprobs?: ChatLogProbs;
}
export interface ChatJsonToSseContext {
    requestId: string;
    model: string;
    chatRequest: ChatCompletionRequest;
    options: ChatJsonToSseOptions;
    startTime: number;
    sequenceCounter: number;
    choiceIndexCounter: number;
    toolCallIndexCounter: number;
    isStreaming: boolean;
    currentChunk: Partial<ChatCompletionChunk>;
    eventStats: ChatEventStats;
    contentIndexCounter?: Map<string, number>;
    currentRequest?: ChatCompletionRequest;
    currentResponse?: ChatCompletionResponse;
    chatResponse?: ChatCompletionResponse;
}
export interface SseToChatJsonContext {
    requestId: string;
    model: string;
    options: SseToChatJsonOptions;
    startTime: number;
    aggregatedChunks: ChatCompletionChunk[];
    currentResponse: Partial<ChatCompletionResponse>;
    choiceIndexMap: Map<number, ChatChoiceBuilder>;
    toolCallIndexMap: Map<number, Map<number, ChatToolCallBuilder>>;
    eventStats: ChatEventStats;
    isCompleted: boolean;
}
export interface ChatChoiceBuilder {
    index: number;
    delta: ChatDelta;
    finishReason?: ChatChoice['finish_reason'];
    logprobs?: ChatLogProbs;
    messageBuilder: ChatMessageBuilder;
    isCompleted: boolean;
    accumulatedContent: string;
    toolCallBuilders: Map<number, ChatToolCallBuilder>;
}
export interface ChatMessageBuilder {
    role?: 'system' | 'user' | 'assistant' | 'tool';
    content?: string;
    reasoningContent?: string;
    name?: string;
    functionCall?: ChatFunctionCall;
    toolCalls?: ChatToolCall[];
    toolCallId?: string;
    isCompleted: boolean;
}
export interface ChatToolCallBuilder {
    index: number;
    id?: string;
    type?: 'function';
    function?: {
        name?: string;
        arguments?: string;
    };
    isCompleted: boolean;
    accumulatedArguments: string;
}
export type ChatReasoningMode = 'channel' | 'text' | 'drop';
export interface ChatJsonToSseOptions {
    requestId: string;
    model: string;
    timeoutMs?: number;
    enableHeartbeat?: boolean;
    heartbeatIntervalMs?: number;
    chunkDelayMs?: number;
    includeSystemFingerprint?: boolean;
    includeLogprobs?: boolean;
    maxTokensPerChunk?: number;
    validationMode?: 'none' | 'basic' | 'strict';
    reasoningMode?: ChatReasoningMode;
    reasoningTextPrefix?: string;
    onChunk?: (chunk: ChatCompletionChunk) => void;
    onError?: (error: Error) => void;
    onComplete?: () => void;
}
export interface SseToChatJsonOptions {
    requestId: string;
    model: string;
    timeoutMs?: number;
    validateChunks?: boolean;
    enableSequenceValidation?: boolean;
    accumulateToolCalls?: boolean;
    reasoningMode?: ChatReasoningMode;
    reasoningTextPrefix?: string;
    onPartialResponse?: (partial: Partial<ChatCompletionResponse>) => void;
    onEvent?: (event: ChatSseEvent) => void;
    onChunk?: (chunk: ChatCompletionChunk) => void;
    onCompletion?: (final: ChatCompletionResponse) => void;
    onError?: (error: Error) => void;
    onTimeout?: () => void;
}
export interface ChatEventStats {
    totalChunks: number;
    totalTokens: number;
    totalChoices: number;
    totalToolCalls: number;
    startTime: number;
    endTime?: number;
    duration?: number;
    tokenRate: number;
    chunkRate: number;
    errorCount: number;
    retryCount: number;
    totalEvents?: number;
    eventTypes?: Record<string, number>;
    lastEventTime?: number;
}
export interface ChatConversionError extends Error {
    code: string;
    requestId: string;
    chunkId?: string;
    choiceIndex?: number;
    toolCallIndex?: number;
    context?: JsonObject;
}
export declare const CHAT_CONVERSION_ERROR_CODES: {
    readonly TIMEOUT: "CHAT_TIMEOUT";
    readonly INVALID_CHUNK: "CHAT_INVALID_CHUNK";
    readonly SEQUENCE_ERROR: "CHAT_SEQUENCE_ERROR";
    readonly TOOL_CALL_ERROR: "CHAT_TOOL_CALL_ERROR";
    readonly PARSE_ERROR: "CHAT_PARSE_ERROR";
    readonly VALIDATION_ERROR: "CHAT_VALIDATION_ERROR";
    readonly STREAM_ERROR: "CHAT_STREAM_ERROR";
};
export interface ChatEventValidationRule {
    eventType: ChatSseEventType;
    requiredFields: string[];
    optionalFields: string[];
    dataValidation?: {
        schema?: JsonObject;
        customValidator?: (data: JsonObject) => boolean;
    };
}
export interface ChatConversionConfig {
    defaultTimeoutMs: number;
    heartbeatIntervalMs: number;
    chunkTimeoutMs: number;
    defaultChunkDelayMs: number;
    maxTokensPerChunk: number;
    maxChunkSize: number;
    enableChunkValidation: boolean;
    strictMode: boolean;
    validateToolCalls: boolean;
    maxConcurrentChoices: number;
    maxConcurrentToolCalls: number;
    eventBufferSize: number;
    debugMode: boolean;
    logLevel: 'debug' | 'info' | 'warn' | 'error';
    enableMetrics: boolean;
    reasoningMode: ChatReasoningMode;
    reasoningTextPrefix?: string;
}
export declare const DEFAULT_CHAT_CONVERSION_CONFIG: ChatConversionConfig;
export interface ChatSseEventStream extends AsyncIterable<ChatSseEvent> {
    getStats(): ChatEventStats;
    getConfig(): ChatConversionConfig;
    complete(): void;
    abort(error?: Error): void;
    on(event: 'error', handler: (error: Error) => void): this;
    on(event: 'complete', handler: () => void): this;
    on(event: 'timeout', handler: () => void): this;
    on(event: 'chunk', handler: (chunk: ChatCompletionChunk) => void): this;
    on(event: 'stats', handler: (stats: ChatEventStats) => void): this;
}
export {};
