import EventEmitter from 'events';
import { LanguageModelV2 } from '@openrouter/ai-sdk-provider';
import type { OpenAIProvider } from '@ai-sdk/openai';
import * as z from 'zod';
import { z as _zod } from 'zod';

/** Supported application types for open and detect operations */
declare type App = 'cursor' | 'vscode' | 'vscode-insiders' | 'zed' | 'windsurf' | 'iterm' | 'warp' | 'terminal' | 'antigravity' | 'finder' | 'sourcetree';

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

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 BackgroundTask {
    id: string;
    command: string;
    pid: number;
    pgid?: number;
    status: 'running' | 'completed' | 'killed' | 'failed';
    createdAt: number;
    output: string;
    exitCode: number | null;
}

declare class BackgroundTaskManager {
    private tasks;
    createTask(input: CreateTaskInput): string;
    getTask(id: string): BackgroundTask | null;
    getAllTasks(): BackgroundTask[];
    appendOutput(id: string, output: string): void;
    updateTaskStatus(id: string, status: BackgroundTask['status'], exitCode?: number | null): void;
    deleteTask(id: string): void;
    private isProcessAlive;
    killTask(id: string): Promise<boolean>;
}

declare type BaseMessage = {
    id: MessageId;
    timestamp: number;
};

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

declare type CommitConfig = {
    language: string;
    systemPrompt?: string;
    model?: string;
};

declare type Config = {
    model: string;
    planModel: string;
    smallModel?: string;
    visionModel?: 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;
    browser?: boolean;
    temperature?: number;
    httpProxy?: string;
    desktop?: DesktopConfig;
    /**
     * Extensions configuration for third-party custom agents.
     * Allows arbitrary nested configuration without validation.
     */
    extensions?: Record<string, any>;
    /**
     * Tools configuration for enabling/disabling specific tools.
     * Key is the tool name, value is boolean (false to disable).
     */
    tools?: Record<string, boolean>;
};

declare type ConfigGetInput = {
    cwd: string;
    isGlobal: boolean;
    key: string;
};

declare type ConfigGetOutput = {
    success: boolean;
    data: {
        value: any;
    };
};

declare type ConfigListInput = {
    cwd: string;
};

declare type ConfigListOutput = {
    success: boolean;
    data: {
        globalConfigDir: string;
        projectConfigDir: string;
        config: any;
    };
};

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;
}

declare type ConfigRemoveInput = {
    cwd: string;
    isGlobal: boolean;
    key: string;
    values?: string[];
};

declare type ConfigSetInput = {
    cwd: string;
    isGlobal: boolean;
    key: string;
    value: string;
};

export declare class Context {
    #private;
    cwd: string;
    productName: string;
    productASCIIArt?: string;
    version: string;
    config: Config;
    paths: Paths;
    argvConfig: Record<string, any>;
    mcpManager: MCPManager;
    backgroundTaskManager: BackgroundTaskManager;
    messageBus?: MessageBus;
    plugins: (string | Plugin_2)[];
    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)[];
    messageBus?: MessageBus;
};

declare type ContextOpts = {
    cwd: string;
    productName: string;
    productASCIIArt?: string;
    version: string;
    config: Config;
    pluginManager: PluginManager;
    paths: Paths;
    argvConfig: Record<string, any>;
    mcpManager: MCPManager;
    backgroundTaskManager: BackgroundTaskManager;
    messageBus?: MessageBus;
    plugins: (string | Plugin_2)[];
};

declare interface CreateTaskInput {
    command: string;
    pid: number;
    pgid?: number;
}

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

declare type DesktopConfig = {
    theme?: 'light' | 'dark' | 'system';
    sendMessageWith?: 'enter' | 'cmdEnter';
    terminalFont?: string;
    terminalFontSize?: number;
};

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

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

/** Standard error response */
declare type ErrorResponse = {
    success: false;
    error: string;
};

declare type EventHandler = (data: any) => void;

declare type EventMessage = BaseMessage & {
    type: 'event';
    event: string;
    data: any;
};

declare type GitCloneInput = {
    url: string;
    destination: string;
    taskId?: string;
};

declare type GitCloneOutput = {
    success: boolean;
    data?: {
        clonePath: string;
        repoName: string;
    };
    error?: string;
    errorCode?: string;
    needsCredentials?: boolean;
};

declare type GitCommitInput = {
    cwd: string;
    message: string;
    noVerify?: boolean;
};

declare type GitCreateBranchInput = {
    cwd: string;
    name: string;
};

declare type GitCreateBranchOutput = {
    success: boolean;
    data?: {
        branchName: string;
        wasRenamed: boolean;
    };
    error?: string;
};

declare type GitPushInput = {
    cwd: string;
};

declare type GitStageInput = {
    cwd: string;
    all?: boolean;
};

declare type GitStatusInput = {
    cwd: string;
};

declare type GitStatusOutput = {
    success: boolean;
    data?: {
        isRepo: boolean;
        hasUncommittedChanges: boolean;
        hasStagedChanges: boolean;
        isGitInstalled: boolean;
        isUserConfigured: {
            name: boolean;
            email: boolean;
        };
        isMerging: boolean;
    };
    error?: string;
};

/**
 * Central type registry for all message bus handlers.
 * Maps handler method names to their input and output types.
 */
declare type HandlerMap = {
    'config.get': {
        input: ConfigGetInput;
        output: ConfigGetOutput;
    };
    'config.set': {
        input: ConfigSetInput;
        output: SuccessResponse;
    };
    'config.remove': {
        input: ConfigRemoveInput;
        output: SuccessResponse;
    };
    'config.list': {
        input: ConfigListInput;
        output: ConfigListOutput;
    };
    'git.clone': {
        input: GitCloneInput;
        output: GitCloneOutput;
    };
    'git.clone.cancel': {
        input: {
            taskId: string;
        };
        output: SuccessResponse;
    };
    'git.status': {
        input: GitStatusInput;
        output: GitStatusOutput;
    };
    'git.stage': {
        input: GitStageInput;
        output: SuccessResponse | ErrorResponse;
    };
    'git.commit': {
        input: GitCommitInput;
        output: SuccessResponse | ErrorResponse;
    };
    'git.push': {
        input: GitPushInput;
        output: SuccessResponse | ErrorResponse;
    };
    'git.createBranch': {
        input: GitCreateBranchInput;
        output: GitCreateBranchOutput;
    };
    'mcp.getStatus': {
        input: McpGetStatusInput;
        output: McpGetStatusOutput;
    };
    'mcp.reconnect': {
        input: McpReconnectInput;
        output: McpReconnectOutput;
    };
    'mcp.list': {
        input: McpListInput;
        output: McpListOutput;
    };
    'models.list': {
        input: ModelsListInput;
        output: ModelsListOutput;
    };
    'outputStyles.list': {
        input: OutputStylesListInput;
        output: OutputStylesListOutput;
    };
    'project.addHistory': {
        input: ProjectAddHistoryInput;
        output: SuccessResponse;
    };
    'project.clearContext': {
        input: ProjectClearContextInput;
        output: SuccessResponse;
    };
    'project.addMemory': {
        input: ProjectAddMemoryInput;
        output: SuccessResponse;
    };
    'project.analyzeContext': {
        input: ProjectAnalyzeContextInput;
        output: ProjectAnalyzeContextOutput;
    };
    'project.getRepoInfo': {
        input: ProjectGetRepoInfoInput;
        output: ProjectGetRepoInfoOutput;
    };
    'project.workspaces.list': {
        input: ProjectWorkspacesListInput;
        output: ProjectWorkspacesListOutput;
    };
    'project.workspaces.get': {
        input: ProjectWorkspacesGetInput;
        output: ProjectWorkspacesGetOutput;
    };
    'project.workspaces.create': {
        input: ProjectWorkspacesCreateInput;
        output: ProjectWorkspacesCreateOutput;
    };
    'project.workspaces.delete': {
        input: ProjectWorkspacesDeleteInput;
        output: ProjectWorkspacesDeleteOutput;
    };
    'project.workspaces.merge': {
        input: ProjectWorkspacesMergeInput;
        output: ProjectWorkspacesMergeOutput;
    };
    'project.workspaces.createGithubPR': {
        input: ProjectWorkspacesCreateGithubPRInput;
        output: ProjectWorkspacesCreateGithubPROutput;
    };
    'project.generateCommit': {
        input: ProjectGenerateCommitInput;
        output: ProjectGenerateCommitOutput;
    };
    'providers.list': {
        input: ProvidersListInput;
        output: ProvidersListOutput;
    };
    'session.initialize': {
        input: SessionInitializeInput;
        output: SessionInitializeOutput;
    };
    'session.messages.list': {
        input: SessionMessagesListInput;
        output: SessionMessagesListOutput;
    };
    'session.getModel': {
        input: SessionGetModelInput;
        output: SessionGetModelOutput;
    };
    'session.send': {
        input: SessionSendInput;
        output: SessionSendOutput;
    };
    'session.cancel': {
        input: SessionCancelInput;
        output: SuccessResponse;
    };
    'session.addMessages': {
        input: SessionAddMessagesInput;
        output: SuccessResponse;
    };
    'session.compact': {
        input: SessionCompactInput;
        output: SessionCompactOutput;
    };
    'session.config.setApprovalMode': {
        input: SessionConfigSetApprovalModeInput;
        output: SuccessResponse;
    };
    'session.config.addApprovalTools': {
        input: SessionConfigAddApprovalToolsInput;
        output: SuccessResponse;
    };
    'session.config.setSummary': {
        input: SessionConfigSetSummaryInput;
        output: SuccessResponse;
    };
    'session.config.setPastedTextMap': {
        input: SessionConfigSetPastedTextMapInput;
        output: SuccessResponse;
    };
    'session.config.setPastedImageMap': {
        input: SessionConfigSetPastedImageMapInput;
        output: SuccessResponse;
    };
    'session.config.getAdditionalDirectories': {
        input: SessionConfigGetAdditionalDirectoriesInput;
        output: SessionConfigGetAdditionalDirectoriesOutput;
    };
    'session.config.addDirectory': {
        input: SessionConfigAddDirectoryInput;
        output: SuccessResponse;
    };
    'session.config.removeDirectory': {
        input: SessionConfigRemoveDirectoryInput;
        output: SuccessResponse;
    };
    'session.config.set': {
        input: SessionConfigSetInput;
        output: SuccessResponse;
    };
    'session.config.get': {
        input: SessionConfigGetInput;
        output: SessionConfigGetOutput;
    };
    'session.config.remove': {
        input: SessionConfigRemoveInput;
        output: SuccessResponse;
    };
    'sessions.list': {
        input: SessionsListInput;
        output: SessionsListOutput;
    };
    'sessions.resume': {
        input: SessionsResumeInput;
        output: SessionsResumeOutput;
    };
    'slashCommand.list': {
        input: SlashCommandListInput;
        output: SlashCommandListOutput;
    };
    'slashCommand.get': {
        input: SlashCommandGetInput;
        output: SlashCommandGetOutput;
    };
    'slashCommand.execute': {
        input: SlashCommandExecuteInput;
        output: SlashCommandExecuteOutput;
    };
    'status.get': {
        input: StatusGetInput;
        output: StatusGetOutput;
    };
    'utils.query': {
        input: UtilsQueryInput;
        output: UtilsQueryOutput;
    };
    'utils.quickQuery': {
        input: UtilsQuickQueryInput;
        output: UtilsQuickQueryOutput;
    };
    'utils.summarizeMessage': {
        input: UtilsSummarizeMessageInput;
        output: UtilsSummarizeMessageOutput;
    };
    'utils.getPaths': {
        input: UtilsGetPathsInput;
        output: UtilsGetPathsOutput;
    };
    'utils.telemetry': {
        input: UtilsTelemetryInput;
        output: SuccessResponse;
    };
    'utils.files.list': {
        input: UtilsFilesListInput;
        output: UtilsFilesListOutput;
    };
    'utils.tool.executeBash': {
        input: UtilsToolExecuteBashInput;
        output: UtilsToolExecuteBashOutput;
    };
    'utils.open': {
        input: UtilsOpenInput;
        output: SuccessResponse;
    };
    'utils.detectApps': {
        input: UtilsDetectAppsInput;
        output: UtilsDetectAppsOutput;
    };
    toolApproval: {
        input: ToolApprovalInput;
        output: ToolApprovalOutput;
    };
};

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, args?: string): 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 McpGetStatusInput = {
    cwd: string;
};

declare type McpGetStatusOutput = {
    success: boolean;
    error?: string;
    data: {
        servers: Record<string, {
            status: string;
            error?: string;
            toolCount: number;
            tools: string[];
        }>;
        configs: Record<string, McpServerConfig>;
        globalConfigPath: string;
        projectConfigPath: string;
        isReady: boolean;
        isLoading: boolean;
    };
};

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

declare type McpListInput = {
    cwd: string;
};

declare type McpListOutput = {
    success: boolean;
    data: {
        projectServers: Record<string, McpServerConfig>;
        globalServers: Record<string, McpServerConfig>;
        activeServers: Record<string, {
            status: 'pending' | 'connecting' | 'connected' | 'failed' | 'disconnected';
            config: McpServerConfig;
            error?: string;
            toolCount?: number;
            tools: string[];
            scope: 'global' | 'project';
        }>;
        projectConfigPath: string;
        globalConfigPath: string;
        isReady: boolean;
        isLoading: boolean;
    };
};

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>;
    private _createClient;
    private _testConnectionAndFetchTools;
    private _isTemporaryError;
}

declare type McpReconnectInput = {
    cwd: string;
    serverName: string;
};

declare type McpReconnectOutput = {
    success: boolean;
    message?: string;
    error?: string;
};

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 = RequestMessage | ResponseMessage | EventMessage;

declare type Message_2 = SystemMessage | UserMessage | AssistantMessage | ToolMessage | ToolMessage2;

declare class MessageBus extends EventEmitter {
    messageHandlers: Map<string, MessageHandler>;
    private transport?;
    private pendingRequests;
    private eventHandlers;
    constructor();
    setTransport(transport: MessageTransport): void;
    isConnected(): boolean;
    request<K extends keyof HandlerMap>(method: K, params: HandlerMap[K]['input'], options?: {
        timeout?: number;
    }): Promise<HandlerMap[K]['output']>;
    request(method: string, params: any, options?: {
        timeout?: number;
    }): Promise<any>;
    registerHandler<K extends keyof HandlerMap>(method: K, handler: (data: HandlerMap[K]['input']) => Promise<HandlerMap[K]['output']>): void;
    registerHandler(method: string, handler: MessageHandler): void;
    unregisterHandler(method: string): void;
    emitEvent(event: string, data: any): Promise<void>;
    onEvent(event: string, handler: EventHandler): void;
    offEvent(event: string, handler: EventHandler): void;
    private handleIncomingMessage;
    private handleRequest;
    private handleResponse;
    private handleEvent;
    private sendResponse;
}

declare type MessageHandler = (data: any) => Promise<any>;

declare type MessageId = string;

declare interface MessageTransport {
    send: (message: Message) => Promise<void>;
    onMessage: (handler: (message: Message) => void) => void;
    onError: (handler: (error: Error) => void) => void;
    onClose: (handler: () => void) => void;
    close: () => Promise<void>;
    isConnected: () => boolean;
}

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'>;
    thinkingConfig?: Record<string, any>;
    _mCreator: () => Promise<LanguageModelV2>;
};

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 ModelsListInput = {
    cwd: string;
};

declare type ModelsListOutput = {
    success: boolean;
    data: {
        groupedModels: Array<{
            provider: string;
            providerId: string;
            models: Array<{
                name: string;
                modelId: string;
                value: string;
            }>;
        }>;
        currentModel: any;
        currentModelInfo: {
            providerName: string;
            modelName: string;
            modelId: string;
            modelContextLimit: number;
        } | null;
    };
};

declare type NormalizedMessage = Message_2 & {
    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 type OutputStylesListInput = {
    cwd: string;
};

declare type OutputStylesListOutput = {
    success: boolean;
    data: {
        outputStyles: Array<{
            name: string;
            description: string;
        }>;
        currentOutputStyle: any;
    };
};

declare class Paths {
    globalConfigDir: string;
    globalProjectDir: string;
    projectConfigDir: string;
    constructor(opts: {
        productName: string;
        cwd: string;
    });
    getSessionLogPath(sessionId: string): string;
    getLatestSessionId(): string | undefined;
    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) => LanguageModelV2;
        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 type ProjectAddHistoryInput = {
    cwd: string;
    history: string;
};

declare type ProjectAddMemoryInput = {
    cwd: string;
    global: boolean;
    rule: string;
};

declare type ProjectAnalyzeContextInput = {
    cwd: string;
    sessionId: string;
};

declare type ProjectAnalyzeContextOutput = {
    success: boolean;
    error?: string;
    data?: {
        systemPrompt: {
            tokens: number;
            percentage: number;
        };
        systemTools: {
            tokens: number;
            percentage: number;
        };
        mcpTools: {
            tokens: number;
            percentage: number;
        };
        messages: {
            tokens: number;
            percentage: number;
        };
        freeSpace: {
            tokens: number;
            percentage: number;
        };
        totalContextWindow: number;
    };
};

declare type ProjectClearContextInput = {
    cwd?: string;
};

declare type ProjectGenerateCommitInput = {
    cwd: string;
    language?: string;
    systemPrompt?: string;
    model?: string;
    diff?: string;
    fileList?: string;
};

declare type ProjectGenerateCommitOutput = {
    success: boolean;
    error?: string;
    data?: {
        commitMessage: string;
        branchName: string;
        isBreakingChange: boolean;
        summary: string;
    };
};

declare type ProjectGetRepoInfoInput = {
    cwd: string;
};

declare type ProjectGetRepoInfoOutput = {
    success: boolean;
    error?: string;
    data?: {
        repoData: {
            path: string;
            name: string;
            workspaceIds: string[];
            metadata: {
                lastAccessed: number;
                settings: any;
            };
            gitRemote: {
                originUrl: string | null;
                defaultBranch: string | null;
                syncStatus: any;
            };
        };
    };
};

declare type ProjectWorkspacesCreateGithubPRInput = {
    cwd: string;
    name: string;
    title?: string;
    description?: string;
    baseBranch?: string;
};

declare type ProjectWorkspacesCreateGithubPROutput = {
    success: boolean;
    error?: string;
    data?: {
        prUrl: string;
        prNumber: number;
    };
};

declare type ProjectWorkspacesCreateInput = {
    cwd: string;
    name?: string;
    skipUpdate?: boolean;
};

declare type ProjectWorkspacesCreateOutput = {
    success: boolean;
    error?: string;
    data?: {
        workspace: {
            name: string;
            path: string;
            branch: string;
        };
    };
};

declare type ProjectWorkspacesDeleteInput = {
    cwd: string;
    name: string;
    force?: boolean;
};

declare type ProjectWorkspacesDeleteOutput = {
    success: boolean;
    error?: string;
};

declare type ProjectWorkspacesGetInput = {
    cwd: string;
    workspaceId: string;
};

declare type ProjectWorkspacesGetOutput = {
    success: boolean;
    error?: string;
    data?: WorkspaceData;
};

declare type ProjectWorkspacesListInput = {
    cwd: string;
};

declare type ProjectWorkspacesListOutput = {
    success: boolean;
    error?: string;
    data?: {
        workspaces: WorkspaceData[];
    };
};

declare type ProjectWorkspacesMergeInput = {
    cwd: string;
    name: string;
};

declare type ProjectWorkspacesMergeOutput = {
    success: boolean;
    error?: string;
};

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, options: {
        globalConfigDir: string;
        setGlobalConfig: (key: string, value: string, isGlobal: boolean) => void;
    }): Promise<LanguageModelV2> | LanguageModelV2;
    options?: {
        baseURL?: string;
        apiKey?: string;
        headers?: Record<string, string>;
        httpProxy?: string;
    };
}

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

declare type ProvidersListInput = {
    cwd: string;
};

declare type ProvidersListOutput = {
    success: boolean;
    data: {
        providers: Array<{
            id: string;
            name: string;
            doc?: string;
            env?: string[];
            apiEnv?: string[];
            validEnvs: string[];
            hasApiKey: boolean;
        }>;
    };
};

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>;
    thinking?: ThinkingConfig | false;
    responseFormat?: ResponseFormat;
}): Promise<LoopResult>;

declare type ReasoningEffort = 'low' | 'medium' | 'high';

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

declare type RequestMessage = BaseMessage & {
    type: 'request';
    method: string;
    params: any;
};

declare type ResponseFormat = {
    type: 'text';
} | {
    type: 'json';
    schema?: any;
    name?: string;
    description?: string;
};

declare type ResponseMessage = BaseMessage & {
    type: 'response';
    result?: any;
    error?: any;
};

declare type ReturnDisplay = string | DiffViewerReturnDisplay | TodoReadReturnDisplay | TodoWriteReturnDisplay;

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

declare type SessionAddMessagesInput = {
    cwd: string;
    sessionId: string;
    messages: Message_2[];
    parentUuid?: string;
};

declare type SessionCancelInput = {
    cwd: string;
    sessionId: string;
};

declare type SessionCompactInput = {
    cwd: string;
    sessionId: string;
    messages: NormalizedMessage[];
};

declare type SessionCompactOutput = {
    success: boolean;
    data: {
        summary: string;
    };
};

declare type SessionConfigAddApprovalToolsInput = {
    cwd: string;
    sessionId: string;
    approvalTool: string;
};

declare type SessionConfigAddDirectoryInput = {
    cwd: string;
    sessionId: string;
    directory: string;
};

declare type SessionConfigGetAdditionalDirectoriesInput = {
    cwd: string;
    sessionId: string;
};

declare type SessionConfigGetAdditionalDirectoriesOutput = {
    success: boolean;
    data: {
        directories: string[];
    };
};

declare type SessionConfigGetInput = {
    cwd: string;
    sessionId: string;
    key?: string;
};

declare type SessionConfigGetOutput = {
    success: boolean;
    data: {
        value: any;
    };
};

declare type SessionConfigRemoveDirectoryInput = {
    cwd: string;
    sessionId: string;
    directory: string;
};

declare type SessionConfigRemoveInput = {
    cwd: string;
    sessionId: string;
    key: string;
};

declare type SessionConfigSetApprovalModeInput = {
    cwd: string;
    sessionId: string;
    approvalMode: ApprovalMode;
};

declare type SessionConfigSetInput = {
    cwd: string;
    sessionId: string;
    key: string;
    value: any;
};

declare type SessionConfigSetPastedImageMapInput = {
    cwd: string;
    sessionId: string;
    pastedImageMap: Record<string, string>;
};

declare type SessionConfigSetPastedTextMapInput = {
    cwd: string;
    sessionId: string;
    pastedTextMap: Record<string, string>;
};

declare type SessionConfigSetSummaryInput = {
    cwd: string;
    sessionId: string;
    summary: string;
};

declare type SessionGetModelInput = {
    cwd: string;
    sessionId: string;
    includeModelInfo?: boolean;
};

declare type SessionGetModelOutput = {
    success: true;
    data: {
        model: string | null;
    };
} | {
    success: true;
    data: {
        model: string | null;
        modelInfo: ModelInfo | null;
        providers: ProvidersMap;
    };
} | {
    success: false;
    error: any;
};

declare type SessionInitializeInput = {
    cwd: string;
    sessionId?: string;
};

declare type SessionInitializeOutput = {
    success: boolean;
    error?: any;
    data: {
        productName: string;
        productASCIIArt: string | undefined;
        version: string;
        model: any;
        planModel: string | undefined;
        initializeModelError: string | null;
        providers: any;
        approvalMode: ApprovalMode;
        sessionSummary: string | undefined;
        pastedTextMap: Record<string, string>;
        pastedImageMap: Record<string, string>;
    };
};

declare type SessionMessagesListInput = {
    cwd: string;
    sessionId: string;
};

declare type SessionMessagesListOutput = {
    success: boolean;
    data: {
        messages: NormalizedMessage[];
    };
};

declare type SessionSendInput = {
    message: string | null;
    cwd: string;
    sessionId: string | undefined;
    planMode: boolean;
    model?: string;
    attachments?: ImagePart[];
    parentUuid?: string;
    thinking?: ThinkingConfig;
};

declare type SessionSendOutput = any;

declare type SessionsListInput = {
    cwd: string;
};

declare type SessionsListOutput = {
    success: boolean;
    data: {
        sessions: Array<{
            sessionId: string;
            modified: Date;
            created: Date;
            messageCount: number;
            summary: string;
        }>;
    };
};

declare type SessionsResumeInput = {
    cwd: string;
    sessionId: string;
};

declare type SessionsResumeOutput = {
    success: boolean;
    data: {
        sessionId: string;
        logFile: string;
    };
};

declare type SlashCommand = LocalCommand | LocalJSXCommand | PromptCommand;

declare type SlashCommandExecuteInput = {
    cwd: string;
    sessionId: string;
    command: string;
    args: string;
};

declare type SlashCommandExecuteOutput = {
    success: boolean;
    data: {
        messages: any[];
    };
};

declare type SlashCommandGetInput = {
    cwd: string;
    command: string;
};

declare type SlashCommandGetOutput = {
    success: boolean;
    data: {
        commandEntry: any;
    };
};

declare type SlashCommandListInput = {
    cwd: string;
};

declare type SlashCommandListOutput = {
    success: boolean;
    data: {
        slashCommands: any[];
    };
};

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

declare type StatusGetInput = {
    cwd: string;
    sessionId: string;
};

declare type StatusGetOutput = {
    success: boolean;
    data: {
        status: Record<string, {
            description?: string;
            items: string[];
        }>;
    };
};

/** Standard success response without data */
declare type SuccessResponse = {
    success: true;
};

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 ThinkingConfig = {
    effort: ReasoningEffort;
};

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

declare const TodoItemSchema: _zod.ZodObject<{
    id: _zod.ZodString;
    content: _zod.ZodString;
    status: _zod.ZodEnum<{
        completed: "completed";
        pending: "pending";
        in_progress: "in_progress";
    }>;
    priority: _zod.ZodEnum<{
        low: "low";
        medium: "medium";
        high: "high";
    }>;
}, _zod.core.$strip>;

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

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

declare interface Tool<TSchema extends z.ZodTypeAny = z.ZodTypeAny> {
    name: string;
    description: string;
    getDescription?: ({ params, cwd, }: {
        params: z.output<TSchema>;
        cwd: string;
    }) => string;
    displayName?: string;
    execute: (params: z.output<TSchema>) => Promise<ToolResult> | ToolResult;
    approval?: ToolApprovalInfo;
    parameters: TSchema;
}

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

declare type ToolApprovalInput = {
    toolUse: ToolUse;
    category?: ApprovalCategory;
};

declare type ToolApprovalOutput = {
    approved: boolean;
    params?: Record<string, unknown>;
};

declare type ToolContent = Array<ToolResultPart>;

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

declare type ToolMessage2 = {
    role: 'tool';
    content: ToolResultPart2[];
};

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

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

declare type ToolResultPart2 = {
    type: 'tool-result';
    toolCallId: string;
    toolName: 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 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;
};

declare type UtilsDetectAppsInput = {
    cwd: string;
    apps?: App[];
};

declare type UtilsDetectAppsOutput = {
    success: boolean;
    data: {
        apps: App[];
    };
};

declare type UtilsFilesListInput = {
    cwd: string;
    query?: string;
};

declare type UtilsFilesListOutput = {
    success: boolean;
    data: {
        files: any[];
    };
};

declare type UtilsGetPathsInput = {
    cwd: string;
    maxFiles?: number;
};

declare type UtilsGetPathsOutput = {
    success: boolean;
    data: {
        paths: string[];
    };
};

declare type UtilsOpenInput = {
    cwd: string;
    sessionId?: string;
    app: App;
};

declare type UtilsQueryInput = {
    userPrompt: string;
    cwd: string;
    systemPrompt?: string;
    model?: string;
    thinking?: ThinkingConfig;
    responseFormat?: ResponseFormat;
};

declare type UtilsQueryOutput = any;

declare type UtilsQuickQueryInput = {
    userPrompt: string;
    cwd: string;
    systemPrompt?: string;
    model?: string;
    thinking?: ThinkingConfig;
    responseFormat?: ResponseFormat;
};

declare type UtilsQuickQueryOutput = any;

declare type UtilsSummarizeMessageInput = {
    message: string;
    cwd: string;
    model?: string;
};

declare type UtilsSummarizeMessageOutput = any;

declare type UtilsTelemetryInput = {
    cwd: string;
    name: string;
    payload: Record<string, any>;
};

declare type UtilsToolExecuteBashInput = {
    cwd: string;
    command: string;
};

declare type UtilsToolExecuteBashOutput = {
    success: boolean;
    data?: any;
    error?: {
        message: string;
    };
};

declare type WorkspaceData = {
    id: string;
    repoPath: string;
    branch: string;
    worktreePath: string;
    sessionIds: string[];
    gitState: {
        currentCommit: string;
        isDirty: boolean;
        pendingChanges: string[];
    };
    metadata: {
        createdAt: number;
        description: string;
        status: 'active' | 'archived' | 'stale';
    };
    context: {
        activeFiles: string[];
        settings: any;
        preferences: Record<string, unknown>;
    };
};

export { _zod }

export { }
