import type { AgentMessage as KoiMessage } from "@mariozechner/pi-agent-core";
import type { Command } from "commander";
import type { IncomingMessage, ServerResponse } from "node:http";
import type { AuthProfileCredential, OAuthCredential } from "../koi/auth-profiles/types.js";
import type { AnyKoiTool } from "../koi/tools/common.js";
import type { ReplyPayload } from "../auto-reply/types.js";
import type { ChannelDock } from "../channels/dock.js";
import type { ChannelPlugin } from "../channels/plugins/types.js";
import type { createVpsAwareOAuthHandlers } from "../commands/oauth-flow.js";
import type { SKYKOIConfig } from "../config/config.js";
import type { ModelProviderConfig } from "../config/types.js";
import type { GatewayRequestHandler } from "../gateway/server-methods/types.js";
import type { InternalHookHandler } from "../hooks/internal-hooks.js";
import type { HookEntry } from "../hooks/types.js";
import type { RuntimeEnv } from "../runtime.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import type { PluginRuntime } from "./runtime/types.js";
export type { PluginRuntime } from "./runtime/types.js";
export type PluginLogger = {
    debug?: (message: string) => void;
    info: (message: string) => void;
    warn: (message: string) => void;
    error: (message: string) => void;
};
export type PluginConfigUiHint = {
    label?: string;
    help?: string;
    advanced?: boolean;
    sensitive?: boolean;
    placeholder?: string;
};
export type PluginKind = "memory";
export type PluginConfigValidation = {
    ok: true;
    value?: unknown;
} | {
    ok: false;
    errors: string[];
};
export type SKYKOIPluginConfigSchema = {
    safeParse?: (value: unknown) => {
        success: boolean;
        data?: unknown;
        error?: {
            issues?: Array<{
                path: Array<string | number>;
                message: string;
            }>;
        };
    };
    parse?: (value: unknown) => unknown;
    validate?: (value: unknown) => PluginConfigValidation;
    uiHints?: Record<string, PluginConfigUiHint>;
    jsonSchema?: Record<string, unknown>;
};
export type SKYKOIPluginToolContext = {
    config?: SKYKOIConfig;
    workspaceDir?: string;
    koiDir?: string;
    koiId?: string;
    sessionKey?: string;
    messageChannel?: string;
    koiAccountId?: string;
    sandboxed?: boolean;
};
export type SKYKOIPluginToolFactory = (ctx: SKYKOIPluginToolContext) => AnyKoiTool | AnyKoiTool[] | null | undefined;
export type SKYKOIPluginToolOptions = {
    name?: string;
    names?: string[];
    optional?: boolean;
};
export type SKYKOIPluginHookOptions = {
    entry?: HookEntry;
    name?: string;
    description?: string;
    register?: boolean;
};
export type ProviderAuthKind = "oauth" | "api_key" | "token" | "device_code" | "custom";
export type ProviderAuthResult = {
    profiles: Array<{
        profileId: string;
        credential: AuthProfileCredential;
    }>;
    configPatch?: Partial<SKYKOIConfig>;
    defaultModel?: string;
    notes?: string[];
};
export type ProviderAuthContext = {
    config: SKYKOIConfig;
    koiDir?: string;
    workspaceDir?: string;
    prompter: WizardPrompter;
    runtime: RuntimeEnv;
    isRemote: boolean;
    openUrl: (url: string) => Promise<void>;
    oauth: {
        createVpsAwareHandlers: typeof createVpsAwareOAuthHandlers;
    };
};
export type ProviderAuthMethod = {
    id: string;
    label: string;
    hint?: string;
    kind: ProviderAuthKind;
    run: (ctx: ProviderAuthContext) => Promise<ProviderAuthResult>;
};
export type ProviderPlugin = {
    id: string;
    label: string;
    docsPath?: string;
    aliases?: string[];
    envVars?: string[];
    models?: ModelProviderConfig;
    auth: ProviderAuthMethod[];
    formatApiKey?: (cred: AuthProfileCredential) => string;
    refreshOAuth?: (cred: OAuthCredential) => Promise<OAuthCredential>;
};
export type SKYKOIPluginGatewayMethod = {
    method: string;
    handler: GatewayRequestHandler;
};
/**
 * Context passed to plugin command handlers.
 */
export type PluginCommandContext = {
    /** The sender's identifier (e.g., Telegram user ID) */
    senderId?: string;
    /** The channel/surface (e.g., "telegram", "discord") */
    channel: string;
    /** Whether the sender is on the allowlist */
    isAuthorizedSender: boolean;
    /** Raw command arguments after the command name */
    args?: string;
    /** The full normalized command body */
    commandBody: string;
    /** Current SKYKOI configuration */
    config: SKYKOIConfig;
};
/**
 * Result returned by a plugin command handler.
 */
export type PluginCommandResult = ReplyPayload;
/**
 * Handler function for plugin commands.
 */
export type PluginCommandHandler = (ctx: PluginCommandContext) => PluginCommandResult | Promise<PluginCommandResult>;
/**
 * Definition for a plugin-registered command.
 */
export type SKYKOIPluginCommandDefinition = {
    /** Command name without leading slash (e.g., "tts") */
    name: string;
    /** Description shown in /help and command menus */
    description: string;
    /** Whether this command accepts arguments */
    acceptsArgs?: boolean;
    /** Whether only authorized senders can use this command (default: true) */
    requireAuth?: boolean;
    /** The handler function */
    handler: PluginCommandHandler;
};
export type SKYKOIPluginHttpHandler = (req: IncomingMessage, res: ServerResponse) => Promise<boolean> | boolean;
export type SKYKOIPluginHttpRouteHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;
export type SKYKOIPluginCliContext = {
    program: Command;
    config: SKYKOIConfig;
    workspaceDir?: string;
    logger: PluginLogger;
};
export type SKYKOIPluginCliRegistrar = (ctx: SKYKOIPluginCliContext) => void | Promise<void>;
export type SKYKOIPluginServiceContext = {
    config: SKYKOIConfig;
    workspaceDir?: string;
    stateDir: string;
    logger: PluginLogger;
};
export type SKYKOIPluginService = {
    id: string;
    start: (ctx: SKYKOIPluginServiceContext) => void | Promise<void>;
    stop?: (ctx: SKYKOIPluginServiceContext) => void | Promise<void>;
};
export type SKYKOIPluginChannelRegistration = {
    plugin: ChannelPlugin;
    dock?: ChannelDock;
};
export type SKYKOIPluginDefinition = {
    id?: string;
    name?: string;
    description?: string;
    version?: string;
    kind?: PluginKind;
    configSchema?: SKYKOIPluginConfigSchema;
    register?: (api: SKYKOIPluginApi) => void | Promise<void>;
    activate?: (api: SKYKOIPluginApi) => void | Promise<void>;
};
export type SKYKOIPluginModule = SKYKOIPluginDefinition | ((api: SKYKOIPluginApi) => void | Promise<void>);
export type SKYKOIPluginApi = {
    id: string;
    name: string;
    version?: string;
    description?: string;
    source: string;
    config: SKYKOIConfig;
    pluginConfig?: Record<string, unknown>;
    runtime: PluginRuntime;
    logger: PluginLogger;
    registerTool: (tool: AnyKoiTool | SKYKOIPluginToolFactory, opts?: SKYKOIPluginToolOptions) => void;
    registerHook: (events: string | string[], handler: InternalHookHandler, opts?: SKYKOIPluginHookOptions) => void;
    registerHttpHandler: (handler: SKYKOIPluginHttpHandler) => void;
    registerHttpRoute: (params: {
        path: string;
        handler: SKYKOIPluginHttpRouteHandler;
    }) => void;
    registerChannel: (registration: SKYKOIPluginChannelRegistration | ChannelPlugin) => void;
    registerGatewayMethod: (method: string, handler: GatewayRequestHandler) => void;
    registerCli: (registrar: SKYKOIPluginCliRegistrar, opts?: {
        commands?: string[];
    }) => void;
    registerService: (service: SKYKOIPluginService) => void;
    registerProvider: (provider: ProviderPlugin) => void;
    /**
     * Register a custom command that bypasses the LLM koi.
     * Plugin commands are processed before built-in commands and before koi invocation.
     * Use this for simple state-toggling or status commands that don't need reasoning.
     */
    registerCommand: (command: SKYKOIPluginCommandDefinition) => void;
    resolvePath: (input: string) => string;
    /** Register a lifecycle hook handler */
    on: <K extends PluginHookName>(hookName: K, handler: PluginHookHandlerMap[K], opts?: {
        priority?: number;
    }) => void;
};
export type PluginOrigin = "bundled" | "global" | "workspace" | "config";
export type PluginDiagnostic = {
    level: "warn" | "error";
    message: string;
    pluginId?: string;
    source?: string;
};
export type PluginHookName = "before_koi_start" | "koi_end" | "before_compaction" | "after_compaction" | "message_received" | "message_sending" | "message_sent" | "before_tool_call" | "after_tool_call" | "tool_result_persist" | "session_start" | "session_end" | "gateway_start" | "gateway_stop";
export type PluginHookKoiContext = {
    koiId?: string;
    sessionKey?: string;
    workspaceDir?: string;
    messageProvider?: string;
};
export type PluginHookBeforeKoiStartEvent = {
    prompt: string;
    messages?: unknown[];
};
export type PluginHookBeforeKoiStartResult = {
    systemPrompt?: string;
    prependContext?: string;
};
export type PluginHookKoiEndEvent = {
    messages: unknown[];
    success: boolean;
    error?: string;
    durationMs?: number;
};
export type PluginHookBeforeCompactionEvent = {
    messageCount: number;
    tokenCount?: number;
};
export type PluginHookAfterCompactionEvent = {
    messageCount: number;
    tokenCount?: number;
    compactedCount: number;
};
export type PluginHookMessageContext = {
    channelId: string;
    accountId?: string;
    conversationId?: string;
};
export type PluginHookMessageReceivedEvent = {
    from: string;
    content: string;
    timestamp?: number;
    metadata?: Record<string, unknown>;
};
export type PluginHookMessageSendingEvent = {
    to: string;
    content: string;
    metadata?: Record<string, unknown>;
};
export type PluginHookMessageSendingResult = {
    content?: string;
    cancel?: boolean;
};
export type PluginHookMessageSentEvent = {
    to: string;
    content: string;
    success: boolean;
    error?: string;
};
export type PluginHookToolContext = {
    koiId?: string;
    sessionKey?: string;
    toolName: string;
};
export type PluginHookBeforeToolCallEvent = {
    toolName: string;
    params: Record<string, unknown>;
};
export type PluginHookBeforeToolCallResult = {
    params?: Record<string, unknown>;
    block?: boolean;
    blockReason?: string;
};
export type PluginHookAfterToolCallEvent = {
    toolName: string;
    params: Record<string, unknown>;
    result?: unknown;
    error?: string;
    durationMs?: number;
};
export type PluginHookToolResultPersistContext = {
    koiId?: string;
    sessionKey?: string;
    toolName?: string;
    toolCallId?: string;
};
export type PluginHookToolResultPersistEvent = {
    toolName?: string;
    toolCallId?: string;
    /**
     * The toolResult message about to be written to the session transcript.
     * Handlers may return a modified message (e.g. drop non-essential fields).
     */
    message: KoiMessage;
    /** True when the tool result was synthesized by a guard/repair step. */
    isSynthetic?: boolean;
};
export type PluginHookToolResultPersistResult = {
    message?: KoiMessage;
};
export type PluginHookSessionContext = {
    koiId?: string;
    sessionId: string;
};
export type PluginHookSessionStartEvent = {
    sessionId: string;
    resumedFrom?: string;
};
export type PluginHookSessionEndEvent = {
    sessionId: string;
    messageCount: number;
    durationMs?: number;
};
export type PluginHookGatewayContext = {
    port?: number;
};
export type PluginHookGatewayStartEvent = {
    port: number;
};
export type PluginHookGatewayStopEvent = {
    reason?: string;
};
export type PluginHookHandlerMap = {
    before_koi_start: (event: PluginHookBeforeKoiStartEvent, ctx: PluginHookKoiContext) => Promise<PluginHookBeforeKoiStartResult | void> | PluginHookBeforeKoiStartResult | void;
    koi_end: (event: PluginHookKoiEndEvent, ctx: PluginHookKoiContext) => Promise<void> | void;
    before_compaction: (event: PluginHookBeforeCompactionEvent, ctx: PluginHookKoiContext) => Promise<void> | void;
    after_compaction: (event: PluginHookAfterCompactionEvent, ctx: PluginHookKoiContext) => Promise<void> | void;
    message_received: (event: PluginHookMessageReceivedEvent, ctx: PluginHookMessageContext) => Promise<void> | void;
    message_sending: (event: PluginHookMessageSendingEvent, ctx: PluginHookMessageContext) => Promise<PluginHookMessageSendingResult | void> | PluginHookMessageSendingResult | void;
    message_sent: (event: PluginHookMessageSentEvent, ctx: PluginHookMessageContext) => Promise<void> | void;
    before_tool_call: (event: PluginHookBeforeToolCallEvent, ctx: PluginHookToolContext) => Promise<PluginHookBeforeToolCallResult | void> | PluginHookBeforeToolCallResult | void;
    after_tool_call: (event: PluginHookAfterToolCallEvent, ctx: PluginHookToolContext) => Promise<void> | void;
    tool_result_persist: (event: PluginHookToolResultPersistEvent, ctx: PluginHookToolResultPersistContext) => PluginHookToolResultPersistResult | void;
    session_start: (event: PluginHookSessionStartEvent, ctx: PluginHookSessionContext) => Promise<void> | void;
    session_end: (event: PluginHookSessionEndEvent, ctx: PluginHookSessionContext) => Promise<void> | void;
    gateway_start: (event: PluginHookGatewayStartEvent, ctx: PluginHookGatewayContext) => Promise<void> | void;
    gateway_stop: (event: PluginHookGatewayStopEvent, ctx: PluginHookGatewayContext) => Promise<void> | void;
};
export type PluginHookRegistration<K extends PluginHookName = PluginHookName> = {
    pluginId: string;
    hookName: K;
    handler: PluginHookHandlerMap[K];
    priority?: number;
    source: string;
};
