import { AgentOutputItem } from '@openai/agents';
import { FunctionTool } from '@openai/agents';
import { LanguageModelV1 } from '@openrouter/ai-sdk-provider';
import type { LanguageModelV1 as LanguageModelV1_2 } from '@ai-sdk/provider';
import { LanguageModelV1CallWarning } from '@ai-sdk/provider';
import { LanguageModelV1FinishReason } from '@ai-sdk/provider';
import { LanguageModelV1FunctionToolCall } from '@ai-sdk/provider';
import { LanguageModelV1LogProbs } from '@ai-sdk/provider';
import { LanguageModelV1ProviderMetadata } from '@ai-sdk/provider';
import { LanguageModelV1Source } from '@ai-sdk/provider';
import { MCPServer } from '@openai/agents';
import { Model as Model_2 } from '@openai/agents';
import { ModelRequest } from '@openai/agents';
import type { OpenAIProvider } from '@ai-sdk/openai';
import { ResponseStreamEvent } from '@openai/agents';
import { Usage as Usage_2 } from '@openai/agents';
import { z as _zod } from 'zod';

/**
 * Wraps a model from the AI SDK that adheres to the LanguageModelV1 spec to be used used as a model
 * in the OpenAI Agents SDK to use other models.
 *
 * While you can use this with the OpenAI models, it is recommended to use the default OpenAI model
 * provider instead.
 *
 * If tracing is enabled, the model will send generation spans to your traces processor.
 *
 * ```ts
 * import { aisdk } from '@openai/agents-extensions';
 * import { openai } from '@ai-sdk/openai';
 *
 * const model = aisdk(openai('gpt-4o'));
 *
 * const agent = new Agent({
 *   name: 'My Agent',
 *   model
 * });
 * ```
 *
 * @param model - The Vercel AI SDK model to wrap.
 * @returns The wrapped model.
 */
declare class AiSdkModel implements Model_2 {
    #private;
    constructor(model: LanguageModelV1_2);
    getResponse(request: ModelRequest): Promise<{
        responseId: string;
        usage: Usage_2;
        output: AgentOutputItem[];
        providerData: {
            text?: string;
            reasoning?: string | Array<{
                type: "text";
                text: string;
                signature?: string;
            } | {
                type: "redacted";
                data: string;
            }>;
            files?: Array<{
                data: string | Uint8Array;
                mimeType: string;
            }>;
            toolCalls?: Array<LanguageModelV1FunctionToolCall>;
            finishReason: LanguageModelV1FinishReason;
            usage: {
                promptTokens: number;
                completionTokens: number;
            };
            rawCall: {
                rawPrompt: unknown;
                rawSettings: Record<string, unknown>;
            };
            rawResponse?: {
                headers?: Record<string, string>;
                body?: unknown;
            };
            request?: {
                body?: string;
            };
            response?: {
                id?: string;
                timestamp?: Date;
                modelId?: string;
            };
            warnings?: LanguageModelV1CallWarning[];
            providerMetadata?: LanguageModelV1ProviderMetadata;
            sources?: LanguageModelV1Source[];
            logprobs?: LanguageModelV1LogProbs;
        };
    }>;
    getStreamedResponse(request: ModelRequest): AsyncIterable<ResponseStreamEvent>;
}

declare type ApprovalCategory = 'read' | 'write' | 'command' | 'network';

declare type ApprovalContext = {
    toolName: string;
    params: Record<string, any>;
    approvalMode: string;
    context: any;
};

declare type ApprovalMode = 'default' | 'autoEdit' | 'yolo';

declare type AssistantContent = string | Array<TextPart | ReasoningPart | ToolUsePart>;

declare type AssistantMessage = {
    role: 'assistant';
    content: AssistantContent;
    text: string;
    model: string;
    usage: {
        input_tokens: number;
        output_tokens: number;
        cache_read_input_tokens?: number;
        cache_creation_input_tokens?: number;
    };
};

declare interface BaseSlashCommand {
    name: string;
    description: string;
    isEnabled?: boolean;
}

declare type CommitConfig = {
    language: string;
};

declare type Config = {
    model: string;
    planModel: string;
    language: string;
    quiet: boolean;
    approvalMode: ApprovalMode;
    plugins: string[];
    mcpServers: Record<string, McpServerConfig>;
    provider?: Record<string, ProviderConfig>;
    systemPrompt?: string;
    todo?: boolean;
    /**
     * Controls whether automatic conversation compression is enabled.
     * When set to false, conversation history will accumulate and context limit will be exceeded.
     *
     * @default true
     */
    autoCompact?: boolean;
    commit?: CommitConfig;
    outputStyle?: string;
    outputFormat?: 'text' | 'stream-json' | 'json';
    autoUpdate?: boolean;
};

export declare class _ConfigManager {
    globalConfig: Partial<Config>;
    projectConfig: Partial<Config>;
    argvConfig: Partial<Config>;
    globalConfigPath: string;
    projectConfigPath: string;
    constructor(cwd: string, productName: string, argvConfig: Partial<Config>);
    get config(): Config;
    removeConfig(global: boolean, key: string, values?: string[]): void;
    addConfig(global: boolean, key: string, values: string[]): void;
    getConfig(global: boolean, key: string): any;
    setConfig(global: boolean, key: string, value: string): void;
    updateConfig(global: boolean, newConfig: Partial<Config>): void;
}

export declare class Context {
    #private;
    cwd: string;
    productName: string;
    productASCIIArt?: string;
    version: string;
    config: Config;
    paths: Paths;
    argvConfig: Record<string, any>;
    mcpManager: MCPManager;
    constructor(opts: ContextOpts);
    apply(applyOpts: Omit<PluginApplyOpts, 'pluginContext'>): Promise<any>;
    destroy(): Promise<void>;
    static create(opts: ContextCreateOpts): Promise<Context>;
}

declare type ContextCreateOpts = {
    cwd: string;
    productName: string;
    productASCIIArt?: string;
    version: string;
    argvConfig: Record<string, any>;
    plugins: (string | Plugin_2)[];
};

declare type ContextOpts = {
    cwd: string;
    productName: string;
    productASCIIArt?: string;
    version: string;
    config: Config;
    pluginManager: PluginManager;
    paths: Paths;
    argvConfig: Record<string, any>;
    mcpManager: MCPManager;
};

export declare function createTool<TSchema extends _zod.ZodTypeAny>(config: {
    name: string;
    description: string;
    parameters: TSchema;
    execute: (params: _zod.infer<TSchema>) => Promise<ToolResult> | ToolResult;
    approval?: ToolApprovalInfo;
    getDescription?: ({ params, cwd, }: {
        params: _zod.infer<TSchema>;
        cwd: string;
    }) => string;
}): Tool<_zod.infer<TSchema>>;

declare type DiffViewerReturnDisplay = {
    type: 'diff_viewer';
    originalContent: string | {
        inputKey: string;
    };
    newContent: string | {
        inputKey: string;
    };
    filePath: string;
    [key: string]: any;
};

declare type Enforce = 'pre' | 'post';

declare type ImagePart = {
    type: 'image';
    data: string;
    mimeType: string;
};

declare interface LocalCommand extends BaseSlashCommand {
    type: 'local';
    call(args: string, context: Context): Promise<string>;
}

declare interface LocalJSXCommand extends BaseSlashCommand {
    type: 'local-jsx';
    call(onDone: (result: string | null) => void, context: Context): Promise<React.ReactNode>;
}

declare type LoopResult = {
    success: true;
    data: Record<string, any>;
    metadata: {
        turnsCount: number;
        toolCallsCount: number;
        duration: number;
    };
} | {
    success: false;
    error: {
        type: 'tool_denied' | 'max_turns_exceeded' | 'api_error' | 'canceled';
        message: string;
        details?: Record<string, any>;
    };
};

declare interface MCPConfig {
    type?: 'stdio' | 'sse' | 'http';
    command?: string;
    args?: string[];
    env?: Record<string, string>;
    url?: string;
    disable?: boolean;
    /**
     * The timeout for tool calls in milliseconds.
     */
    timeout?: number;
    headers?: Record<string, string>;
}

declare type McpHttpServerConfig = {
    type: 'http';
    url: string;
    disable?: boolean;
    headers?: Record<string, string>;
};

declare class MCPManager {
    #private;
    private servers;
    private configs;
    private isInitialized;
    private initPromise?;
    private initLock;
    static create(mcpServers: Record<string, MCPConfig>): MCPManager;
    initAsync(): Promise<void>;
    private _performInit;
    private _connectServer;
    getAllTools(): Promise<Tool[]>;
    getTools(keys: string[]): Promise<Tool[]>;
    destroy(): Promise<void>;
    getServerNames(): string[];
    hasServer(name: string): boolean;
    getServerStatus(name: string): MCPServerStatus | undefined;
    getServerError(name: string): string | undefined;
    getAllServerStatus(): Promise<Record<string, {
        status: MCPServerStatus;
        error?: string;
        toolCount: number;
    }>>;
    isReady(): boolean;
    isLoading(): boolean;
    retryConnection(serverName: string): Promise<void>;
    getAllMcpTools(mcpServers: MCPServer[], convertSchemasToStrict?: boolean): Promise<Tool[]>;
    getFunctionToolsFromServer<TContext = UnknownContext>(server: MCPServer, convertSchemasToStrict: boolean): Promise<FunctionTool<TContext, any, string>[]>;
    private _isTemporaryError;
}

declare type McpServerConfig = McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig;

declare type MCPServerStatus = 'pending' | 'connecting' | 'connected' | 'failed' | 'disconnected';

declare type McpSSEServerConfig = {
    type: 'sse';
    url: string;
    disable?: boolean;
    headers?: Record<string, string>;
};

declare type McpStdioServerConfig = {
    type: 'stdio';
    command: string;
    args: string[];
    env?: Record<string, string>;
    disable?: boolean;
};

declare type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage;

declare interface Model {
    id: string;
    name: string;
    shortName?: string;
    attachment: boolean;
    reasoning: boolean;
    temperature: boolean;
    tool_call: boolean;
    knowledge: string;
    release_date: string;
    last_updated: string;
    modalities: ModelModalities;
    open_weights: boolean;
    cost: ModelCost;
    limit: ModelLimit;
}

declare type ModelAlias = Record<string, string>;

declare interface ModelCost {
    input: number;
    output: number;
    cache_read?: number;
    cache_write?: number;
}

declare type ModelInfo = {
    provider: Provider;
    model: Omit<Model, 'cost'>;
    aisdk: AiSdkModel;
};

declare interface ModelLimit {
    context: number;
    output: number;
}

declare type ModelMap = Record<string, Omit<Model, 'id' | 'cost'>>;

declare interface ModelModalities {
    input: ('text' | 'image' | 'audio' | 'video' | 'pdf')[];
    output: ('text' | 'audio' | 'image')[];
}

declare type NormalizedMessage = Message & {
    type: 'message';
    timestamp: string;
    uuid: string;
    parentUuid: string | null;
    uiContent?: string;
};

declare class OutputStyle {
    name: string;
    description: string;
    isCodingRelated: boolean;
    prompt: string;
    constructor(opts: OutputStyleOpts);
    isDefault(): boolean;
}

declare type OutputStyleOpts = {
    name: string;
    description: string;
    isCodingRelated: boolean;
    prompt: string;
};

declare class Paths {
    globalConfigDir: string;
    globalProjectDir: string;
    projectConfigDir: string;
    constructor(opts: {
        productName: string;
        cwd: string;
    });
    getSessionLogPath(sessionId: string): string;
    getLatestSessionId(): string;
    getAllSessions(): {
        sessionId: string;
        modified: Date;
        created: Date;
        messageCount: number;
        summary: string;
    }[];
    getGlobalDataPath(): string;
}

declare type Plugin_2 = {
    enforce?: Enforce;
    name?: string;
    config?: (this: TempPluginContext, opts: {
        config: Config;
        argvConfig: Record<string, any>;
    }) => Partial<Config> | Promise<Partial<Config>>;
    slashCommand?: (this: PluginContext) => Promise<SlashCommand[]> | SlashCommand[];
    outputStyle?: (this: PluginContext) => Promise<OutputStyle[]> | OutputStyle[];
    provider?: (this: PluginContext, providers: ProvidersMap, opts: {
        models: ModelMap;
        defaultModelCreator: (name: string, provider: Provider) => LanguageModelV1;
        createOpenAI: (options: any) => OpenAIProvider;
    }) => Promise<ProvidersMap> | ProvidersMap;
    modelAlias?: (this: PluginContext, modelAlias: ModelAlias) => Promise<ModelAlias> | ModelAlias;
    initialized?: (this: PluginContext, opts: {
        cwd: string;
        quiet: boolean;
    }) => Promise<void> | void;
    destroy?: (this: PluginContext) => Promise<void> | void;
    context?: (this: PluginContext, opts: {
        userPrompt: string | null;
        sessionId: string;
    }) => Promise<Record<string, string> | {}> | Record<string, string> | {};
    env?: (this: PluginContext, opts: {
        userPrompt: string | null;
        sessionId: string;
    }) => Promise<Record<string, string> | {}> | Record<string, string> | {};
    userPrompt?: (this: PluginContext, userPrompt: string, opts: {
        sessionId: string;
    }) => Promise<string> | string;
    systemPrompt?: (this: PluginContext, systemPrompt: string, opts: {
        isPlan?: boolean;
        sessionId: string;
    }) => Promise<string> | string;
    tool?: (this: PluginContext, opts: {
        isPlan?: boolean;
        sessionId: string;
    }) => Promise<Tool[]> | Tool[];
    toolUse?: (this: PluginContext, toolUse: ToolUse, opts: {
        sessionId: string;
    }) => Promise<ToolUse> | ToolUse;
    toolResult?: (this: PluginContext, toolResult: ToolResult, opts: {
        toolUse: ToolUse;
        approved: boolean;
        sessionId: string;
    }) => Promise<ToolResult> | ToolResult;
    query?: (this: PluginContext, opts: {
        usage: Usage;
        startTime: Date;
        endTime: Date;
        sessionId: string;
    }) => Promise<void> | void;
    conversation?: (this: PluginContext, opts: {
        userPrompt: string | null;
        result: LoopResult;
        startTime: Date;
        endTime: Date;
        sessionId: string;
    }) => Promise<void> | void;
    status?: (this: PluginContext) => Promise<Status> | Status;
    telemetry?: (this: PluginContext, opts: {
        name: string;
        payload: Record<string, any>;
    }) => Promise<void> | void;
    _serverAppData?: (this: PluginContext, opts: {
        context: any;
        cwd: string;
    }) => Promise<any> | any;
    _serverRoutes?: (this: PluginContext, opts: {
        app: any;
        prefix: string;
        opts: any;
    }) => Promise<any> | any;
    _serverRouteCompletions?: (this: PluginContext, opts: {
        message: {
            role: 'user';
            content: string;
            attachedContexts: any[];
            contextContent: string;
        };
        attachedContexts: any[];
    }) => Promise<any> | any;
};
export { Plugin_2 as Plugin }

declare type PluginApplyOpts = {
    hook: keyof Plugin_2;
    args: any[];
    memo?: any;
    type: PluginHookType;
    pluginContext: any;
};

declare type PluginContext = Context;

declare enum PluginHookType {
    First = "first",
    Series = "series",
    SeriesMerge = "seriesMerge",
    SeriesLast = "seriesLast",
    Parallel = "parallel"
}

declare class PluginManager {
    #private;
    constructor(rawPlugins: Plugin_2[]);
    apply({ hook, args, memo, type, pluginContext, }: PluginApplyOpts): Promise<any>;
}

declare interface PromptCommand extends BaseSlashCommand {
    type: 'prompt';
    progressMessage?: string;
    model?: string;
    getPromptForCommand(args: string): Promise<Array<{
        role: string;
        content: string;
    }>>;
}

declare interface Provider {
    id: string;
    env: string[];
    name: string;
    apiEnv?: string[];
    api?: string;
    doc: string;
    models: Record<string, string | Omit<Model, 'id' | 'cost'>>;
    createModel(name: string, provider: Provider, globalConfigDir: string): Promise<LanguageModelV1> | LanguageModelV1;
    options?: {
        baseURL?: string;
        apiKey?: string;
        headers?: Record<string, string>;
    };
}

declare type ProviderConfig = Partial<Omit<Provider, 'createModel'>>;

declare type ProvidersMap = Record<string, Provider>;

export declare function _query(opts: {
    userPrompt: string;
    messages?: NormalizedMessage[];
    context?: Context;
    model?: ModelInfo;
    systemPrompt?: string;
    onMessage?: (message: NormalizedMessage) => Promise<void>;
}): Promise<LoopResult>;

declare type ReasoningPart = {
    type: 'reasoning';
    text: string;
};

export declare function runArk(opts: {
    productName: string;
    productASCIIArt?: string;
    version: string;
    plugins: Plugin_2[];
    upgrade?: UpgradeOptions;
}): Promise<void>;

declare type SlashCommand = LocalCommand | LocalJSXCommand | PromptCommand;

declare type Status = Record<string, {
    description?: string;
    items: string[];
}>;

declare type SystemMessage = {
    role: 'system';
    content: string;
};

declare type TempPluginContext = ContextCreateOpts & {
    pluginManager: PluginManager;
    config: Config;
    apply: (opts: PluginApplyOpts) => Promise<any> | any;
};

declare type TextPart = {
    type: 'text';
    text: string;
};

declare type TodoItem = _zod.infer<typeof TodoItemSchema>;

declare const TodoItemSchema: _zod.ZodObject<{
    id: _zod.ZodString;
    content: _zod.ZodString;
    status: _zod.ZodEnum<["pending", "in_progress", "completed"]>;
    priority: _zod.ZodEnum<["low", "medium", "high"]>;
}, "strip", _zod.ZodTypeAny, {
    id: string;
    content: string;
    status: "in_progress" | "completed" | "pending";
    priority: "low" | "medium" | "high";
}, {
    id: string;
    content: string;
    status: "in_progress" | "completed" | "pending";
    priority: "low" | "medium" | "high";
}>;

declare type TodoReadReturnDisplay = {
    type: 'todo_read';
    todos: TodoItem[];
};

declare type TodoWriteReturnDisplay = {
    type: 'todo_write';
    oldTodos: TodoItem[];
    newTodos: TodoItem[];
};

declare interface Tool<T = any> {
    name: string;
    description: string;
    getDescription?: ({ params, cwd }: {
        params: T;
        cwd: string;
    }) => string;
    displayName?: string;
    execute: (params: T) => Promise<ToolResult> | ToolResult;
    approval?: ToolApprovalInfo;
    parameters: _zod.ZodSchema<T>;
}

declare type ToolApprovalInfo = {
    needsApproval?: (context: ApprovalContext) => Promise<boolean> | boolean;
    category?: ApprovalCategory;
};

declare type ToolContent = Array<ToolResultPart>;

declare type ToolMessage = {
    role: 'user';
    content: ToolContent;
};

declare type ToolResult = {
    llmContent: string | (TextPart | ImagePart)[];
    returnDisplay?: string | DiffViewerReturnDisplay | TodoReadReturnDisplay | TodoWriteReturnDisplay;
    isError?: boolean;
};

declare type ToolResultPart = {
    type: 'tool_result';
    id: string;
    name: string;
    input: Record<string, any>;
    result: ToolResult;
};

declare type ToolUse = {
    name: string;
    params: Record<string, any>;
    callId: string;
};

declare type ToolUsePart = {
    type: 'tool_use';
    id: string;
    name: string;
    input: Record<string, any>;
    displayName?: string;
    description?: string;
};

declare type UnknownContext = unknown;

declare type UpgradeOptions = {
    registryBase: string;
    name: string;
    version: string;
    installDir: string;
    files: string[];
    channel?: string;
    changelogUrl?: string;
};

declare class Usage {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
    constructor(init?: Partial<Usage>);
    static empty(): Usage;
    static fromEventUsage(eventUsage: any): Usage;
    static fromAssistantMessage(message: AssistantMessage): Usage;
    add(other: Usage): void;
    reset(): void;
    clone(): Usage;
    isValid(): boolean;
}

declare type UserContent = string | Array<TextPart | ImagePart>;

declare type UserMessage = {
    role: 'user';
    content: UserContent;
    hidden?: boolean;
};

export { _zod }

export { }
