export { DebugContext, DebugDetailLevel, DebugEntry, DebugExportOptions, DebugFilterOptions, DebugFormat, DebugLevel, DebugMeta, DebugOutput, DebugOutputOptions, DebugSection, DebugTrace, DebugTree, DebugTreeNode, DebugTreeOptions, HumanFormatterOptions, TraceOptions, createDebugTree, describeEntriesAI, describeEntriesHuman, describeEntriesTimeline, exportDebugEntries, exportToChromeFormat, exportToJSON, exportToPlainText, filterByLevel, filterByNamespace, filterByTimeRange, filterDebugEntries, formatDebugEntriesAI, formatDebugEntriesHuman, formatDebugEntryAI, formatDebugEntryHuman, formatDebugOutput, formatDebugOutputs, formatTimeline, formatTimelineNode, formatTimelineWithSummary, groupByGroup, groupByNamespace, searchInLogs, shouldUseAIFormat } from './debug.js'; import { CommandFailure, SelectChoice, MultiSelectChoice, UIFacade } from '@kb-labs/plugin-contracts'; export { ConfirmOptions, MultiSelectChoice, MultiSelectOptions, SelectChoice, SelectOptions, TextOptions, confirm, isInteractive, multiSelect, select, text } from './interactive/index.js'; /** * Minimalist color utilities for CLI output * Uses strategic color application - only for status, not decoration */ declare const colors: { success: (text: string) => string; error: (text: string) => string; warning: (text: string) => string; info: (text: string) => string; primary: (text: string) => string; accent: (text: string) => string; highlight: (text: string) => string; secondary: (text: string) => string; emphasis: (text: string) => string; muted: (text: string) => string; foreground: (text: string) => string; dim: (text: string) => string; bold: (text: string) => string; underline: (text: string) => string; inverse: (text: string) => string; }; declare const symbols: { success: string; error: string; warning: string; info: string; bullet: string; clock: string; folder: string; package: string; pointer: string; section: string; step: string; stepDone: string; arrow: string; diamond: string; }; declare const supportsColor: boolean; declare const safeColors: { success: (text: string) => string; error: (text: string) => string; warning: (text: string) => string; info: (text: string) => string; accent: (text: string) => string; primary: (text: string) => string; highlight: (text: string) => string; secondary: (text: string) => string; emphasis: (text: string) => string; foreground: (text: string) => string; muted: (text: string) => string; dim: (text: string) => string; bold: (text: string) => string; underline: (text: string) => string; inverse: (text: string) => string; }; declare const safeSymbols: { success: string; error: string; warning: string; info: string; bullet: string; clock: string; folder: string; package: string; pointer: string; section: string; step: string; stepDone: string; arrow: string; diamond: string; separator: string; border: string; topLeft: string; topRight: string; bottomLeft: string; bottomRight: string; leftT: string; rightT: string; }; /** * Progress indicators and loaders for CLI operations * * Periodic animation implementation (works in child processes as multi-line output). */ interface LoaderOptions { /** Text to show while loading */ text?: string; /** Whether to show spinner (true) or progress bar (false) */ spinner?: boolean; /** Total items for progress bar */ total?: number; /** Current item for progress bar */ current?: number; /** Whether JSON mode is enabled (disables all visual feedback) */ jsonMode?: boolean; } declare function setJsonMode(enabled: boolean): void; declare function isJsonMode(): boolean; declare class Loader { private isActive; private options; private frameIndex; private intervalId?; private currentText; constructor(options?: LoaderOptions); start(): void; update(options: Partial): void; stop(): void; succeed(message?: string): void; fail(message?: string): void; private clearInterval; private updateProgress; } /** * Create a simple spinner */ declare function createSpinner(text: string, jsonMode?: boolean): Loader; /** * Create a progress bar */ declare function createProgressBar(text: string, total: number, jsonMode?: boolean): Loader; /** * Simple loading message without spinner */ declare function showLoading(text: string, jsonMode?: boolean): void; /** * Show completion message */ declare function showSuccess(text: string, jsonMode?: boolean): void; /** * Show error message */ declare function showError(text: string, jsonMode?: boolean): void; /** * Create a loader for progress indication * * @param text - Text to display while loading * @param options - Optional configuration * @returns Loader instance * * @example * ```typescript * import { useLoader } from '@kb-labs/sdk'; * * const loader = useLoader('Processing data...'); * loader.start(); * // ... do work ... * loader.succeed('Processing complete!'); * ``` */ declare function useLoader(text: string, options?: Partial): Loader; /** * Output formatting utilities for structured CLI output */ declare function stripAnsi(input: string): string; declare function hasAnsi(input: string): boolean; /** * Create a boxed section with title */ declare function box(title: string, content?: string[], maxWidth?: number): string; /** * Add consistent indentation to lines */ declare function indent(lines: string[], level?: number): string[]; /** * Create a section with header and content */ declare function section(header: string, content: string[]): string[]; /** * Format a table with consistent spacing */ declare function table(rows: (string | number)[][], headers?: string[]): string[]; /** * Format key-value pairs */ interface KeyValueOptions { padKeys?: boolean; } declare function keyValue(pairs: Record, options?: KeyValueOptions): string[]; /** * Format a list with bullets */ declare function bulletList(items: string[]): string[]; interface SafeKeyValueOptions { indent?: number; pad?: boolean; valueColor?: (value: string, key: string) => string; } declare function safeKeyValue(pairs: Record, options?: SafeKeyValueOptions): string[]; /** * Apply primary headline styling */ declare function headline(text: string): string; /** * Accent label style (used for tags/pills) */ declare function accentLabel(text: string): string; /** * Muted helper */ declare function muted(text: string): string; /** * Format file size */ declare function formatSize(bytes: number): string; /** * Format relative time */ declare function formatRelativeTime(timestamp: string | Date): string; interface FormatTimestampOptions { mode?: 'local' | 'iso'; timeZone?: string; includeSeconds?: boolean; includeMilliseconds?: boolean; includeOffset?: boolean; } /** * Format timestamps as absolute values (local or ISO) with optional offsets */ declare function formatTimestamp(timestamp: string | Date, options?: FormatTimestampOptions): string; /** * Truncate text with ellipsis */ declare function truncate(text: string, maxLength: number): string; /** * Pad string to specific width */ declare function pad(text: string, width: number, align?: 'left' | 'right' | 'center'): string; /** * Command output formatting utilities * Provides consistent formatting for CLI command results */ interface CommandResult { title: string; summary: Record; timing?: number | Record; diagnostics?: string[]; warnings?: string[]; errors?: string[]; suggestions?: string[]; } /** * Format timing in milliseconds to human-readable string */ declare function formatTiming(ms: number): string; /** * Format timing breakdown as array of strings */ declare function formatTimingBreakdown(timings: Record): string[]; /** * Format complete command output with box, summary, timing, and additional info */ declare function formatCommandOutput(result: CommandResult): string; /** * Create a simple command result with just title, summary, and timing */ declare function createSimpleResult(title: string, summary: Record, timing?: number): CommandResult; /** * Create a detailed command result with all optional fields */ declare function createDetailedResult(title: string, summary: Record, options?: { timing?: number | Record; diagnostics?: string[]; warnings?: string[]; errors?: string[]; suggestions?: string[]; }): CommandResult; /** * Timing tracker utility for CLI commands * Provides checkpoint-based timing measurement */ declare class TimingTracker { private start; private checkpoints; constructor(); /** * Record a timing checkpoint */ checkpoint(name: string): void; /** * Get total elapsed time in milliseconds */ total(): number; /** * Get timing breakdown including total */ breakdown(): Record; /** * Get timing breakdown without total */ checkpointsOnly(): Record; /** * Reset the timer */ reset(): void; /** * Get elapsed time since last checkpoint or start */ sinceLastCheckpoint(): number; /** * Get elapsed time since a specific checkpoint */ sinceCheckpoint(checkpointName: string): number | null; } /** * Command suggestions and validation utilities */ interface CommandSuggestion { id: string; command: string; args: string[]; description: string; impact: 'safe' | 'disruptive'; when: string; available?: boolean; } interface CommandRegistry { commands: Set; groups: Map>; } /** * Create a command registry from available commands */ declare function createCommandRegistry(commands: string[]): CommandRegistry; /** * Check if a command is available in the registry */ declare function isCommandAvailable(command: string, registry: CommandRegistry): boolean; /** * Validate suggestions against available commands */ declare function validateSuggestions(suggestions: CommandSuggestion[], registry: CommandRegistry): CommandSuggestion[]; /** * Generate common devlink suggestions */ declare function generateDevlinkSuggestions(warningCodes: Set, context: { undo?: { available: boolean; }; }, registry: CommandRegistry): CommandSuggestion[]; /** * Generate quick actions for common scenarios */ declare function generateQuickActions(hasWarnings: boolean, registry: CommandRegistry, group?: string): CommandSuggestion[]; /** * Command discovery utilities for CLI systems */ interface CommandInfo { id: string; group: string; name: string; description: string; available: boolean; } /** * Discover available commands from CLI manifest or registry * This is a generic interface that can be implemented by different CLI systems */ interface CommandDiscovery { /** * Get all available commands */ getAvailableCommands(): Promise; /** * Get command info by ID */ getCommandInfo(commandId: string): Promise; /** * Check if a command is available */ isCommandAvailable(commandId: string): Promise; } /** * Simple command discovery that works with a predefined list * Can be extended to work with actual CLI registries */ declare class StaticCommandDiscovery implements CommandDiscovery { private commands; constructor(commands: string[]); getAvailableCommands(): Promise; getCommandInfo(commandId: string): Promise; isCommandAvailable(commandId: string): Promise; } /** * Create a command discovery instance from a command list */ declare function createCommandDiscovery(commands: string[]): CommandDiscovery; /** * CLI manifest parsing utilities */ interface CommandManifest { manifestVersion: string; id: string; aliases?: string[]; group: string; describe: string; longDescription?: string; requires?: string[]; flags?: FlagDefinition[]; examples?: string[]; loader: () => Promise<{ run: unknown; }>; } interface FlagDefinition { name: string; type: 'string' | 'boolean' | 'number' | 'array'; alias?: string; default?: string | boolean | number | string[]; description?: string; choices?: string[]; required?: boolean; } /** * Extract command IDs from a manifest */ declare function extractCommandIds(manifest: CommandManifest[]): string[]; /** * Extract command groups from a manifest */ declare function extractCommandGroups(manifest: CommandManifest[]): string[]; /** * Find commands by group */ declare function findCommandsByGroup(manifest: CommandManifest[], group: string): CommandManifest[]; /** * Find command by ID */ declare function findCommandById(manifest: CommandManifest[], id: string): CommandManifest | undefined; /** * Get command info for suggestions */ declare function getCommandInfo(manifest: CommandManifest[], commandId: string): { id: string; group: string; name: string; description: string; available: boolean; } | null; /** * Generate suggestions for a specific group */ declare function generateGroupSuggestions(manifest: CommandManifest[], group: string, _warningCodes: Set, _context: unknown): Array<{ id: string; command: string; args: string[]; description: string; impact: 'safe' | 'disruptive'; when: string; available: boolean; }>; /** * Multi-CLI suggestions system * Supports multiple CLI packages with their own manifests */ interface MultiCLIContext { warningCodes: Set; undo?: { available: boolean; }; [key: string]: unknown; } interface CLIPackage { name: string; group: string; commands: CommandManifest[]; priority: number; } /** * Multi-CLI suggestions manager */ declare class MultiCLISuggestions { private packages; private globalRegistry; /** * Register a CLI package */ registerPackage(pkg: CLIPackage): void; /** * Get or create global command registry */ private getGlobalRegistry; /** * Generate suggestions for a specific group */ generateGroupSuggestions(group: string, context: MultiCLIContext): CommandSuggestion[]; /** * Generate all suggestions across all packages */ generateAllSuggestions(context: MultiCLIContext): CommandSuggestion[]; /** * Get available commands for a group */ getAvailableCommands(group: string): string[]; /** * Get all registered packages */ getPackages(): CLIPackage[]; } /** * Dynamic command discovery that loads commands from actual manifests */ interface ManifestLoader { loadManifest(packageName: string): Promise; } /** * Dynamic command discovery that loads commands from manifests */ declare class DynamicCommandDiscovery implements CommandDiscovery { private manifestLoader; private packageNames; private manifestCache; private commandCache; constructor(manifestLoader: ManifestLoader, packageNames: string[]); getAvailableCommands(): Promise; getCommandInfo(commandId: string): Promise; isCommandAvailable(commandId: string): Promise; private loadManifest; } /** * Create a dynamic command discovery for KB Labs packages */ declare function createKBLabsCommandDiscovery(): DynamicCommandDiscovery; interface ArtifactInfo { name: string; path: string; size?: number; modified?: Date; description: string; } interface ArtifactDisplayOptions { showSize?: boolean; showTime?: boolean; showDescription?: boolean; maxItems?: number; title?: string; groupBy?: 'none' | 'type' | 'time'; } /** * Display artifacts information in CLI */ declare function displayArtifacts(artifacts: ArtifactInfo[], options?: ArtifactDisplayOptions): string[]; /** * Display a single artifact with full details */ declare function displaySingleArtifact(artifact: ArtifactInfo, title?: string): string[]; /** * Display artifacts in a compact format (for status-like displays) */ declare function displayArtifactsCompact(artifacts: ArtifactInfo[], options?: { maxItems?: number; showSize?: boolean; sortByTime?: boolean; showTime?: boolean; title?: string; }): string[]; /** * Discover artifacts in a directory based on patterns * * @param baseDir - Base directory to search for artifacts * @param patterns - Array of artifact patterns to search for * @returns Array of discovered artifacts * * @example * ```typescript * const artifacts = await discoverArtifacts('.kb/mind', [ * { name: 'Index', pattern: 'index.json', description: 'Main index' }, * { name: 'API Index', pattern: 'api-index.json', description: 'API index' }, * ]); * ``` */ declare function discoverArtifacts(baseDir: string, patterns: Array<{ name: string; pattern: string; description?: string; }>): Promise; /** * Table formatting utilities for CLI output * Handles proper column alignment accounting for emoji/unicode width */ interface TableColumn { header: string; width?: number; align?: 'left' | 'right' | 'center'; } interface TableOptions { header?: boolean; separator?: string; padding?: number; } /** * Format data as a table with proper column alignment */ declare function formatTable(columns: TableColumn[], rows: string[][], options?: TableOptions): string[]; /** * Format simple key-value pairs as a table */ declare function formatKeyValueTable(data: Record, options?: { keyWidth?: number; valueWidth?: number; }): string[]; interface CommandPresenter { info(message: string): void; warn?(message: string): void; error(message: string): void; write(payload: string): void; json(payload: unknown): void; } interface CommandContext { cwd: string; presenter: CommandPresenter; } interface CommandExecutionResult { summary: Record; artifacts?: ArtifactInfo[]; artifactsOptions?: ArtifactDisplayOptions; timing?: number | Record; diagnostics?: string[]; warnings?: string[]; errors?: string[]; data?: Record; } interface AnalyticsConfig { actor: string; started: string; finished: string; getPayload?: (flags: Record, result?: CommandExecutionResult) => Record; } interface CommandRunnerOptions { title: string; analytics?: AnalyticsConfig; execute: (ctx: CommandContext, flags: Record, tracker: TimingTracker) => Promise; } declare function createCommandRunner(options: CommandRunnerOptions): (ctx: CommandContext, argv: string[], flags: Record) => Promise; /** * Flag system for declarative CLI flag definition with type safety * * Usage: * ```typescript * // In contracts * export const myFlags = defineFlags({ * scope: { type: 'string', description: 'Filter by scope' }, * verbose: { type: 'boolean', default: false }, * }); * * // In command * export default defineCommand({ * flags: myFlags, * handler: { * async execute(ctx, input: typeof myFlags.type) { * const { scope, verbose } = input; * } * } * }); * ``` */ type FlagType = 'string' | 'boolean' | 'number'; interface BaseFlagSpec { type: T; description?: string; examples?: string[]; deprecated?: boolean | string; } interface StringFlagSpec extends BaseFlagSpec<'string'> { default?: string; validate?: (value: string) => void | Promise; } interface BooleanFlagSpec extends BaseFlagSpec<'boolean'> { default?: boolean; } interface NumberFlagSpec extends BaseFlagSpec<'number'> { default?: number; validate?: (value: number) => void | Promise; } type FlagSpec = StringFlagSpec | BooleanFlagSpec | NumberFlagSpec; type FlagsSchema = Record; type InferFlagType = T extends StringFlagSpec ? T extends { default: string; } ? string : string | undefined : T extends BooleanFlagSpec ? T extends { default: boolean; } ? boolean : boolean | undefined : T extends NumberFlagSpec ? T extends { default: number; } ? number : number | undefined : never; type InferFlagsType = { [K in keyof T]: InferFlagType; }; interface FlagsDefinition { /** Schema for manifest */ schema: T; /** Inferred TypeScript type */ type: InferFlagsType; /** Parse and validate flags from raw input */ parse: (input: unknown) => InferFlagsType; } /** * Define CLI flags with type safety and validation * * @example * ```typescript * export const commitFlags = defineFlags({ * scope: { * type: 'string', * description: 'Limit to package or path', * examples: ['@kb-labs/core', 'packages/**'], * }, * 'dry-run': { * type: 'boolean', * description: 'Preview without applying', * default: false, * }, * }); * * // Use in command * type MyInput = typeof commitFlags.type; * // Result: { scope?: string; 'dry-run': boolean } * ``` */ declare function defineFlags(schema: T): FlagsDefinition; /** * Parse flags from raw input with type validation and defaults */ declare function parseFlagsFromInput(input: unknown, schema: T): InferFlagsType; declare function parseBoolean(value: unknown, flagName: string): boolean; declare function parseString(value: unknown, flagName: string): string; declare function parseNumber(value: unknown, flagName: string): number; declare function parseNumberFlag(value: unknown): number | undefined; /** * Merge input.flags into input root (V3 compatibility helper) * * @example * ```typescript * const raw = { scope: 'old', flags: { scope: 'new', json: true } }; * const merged = mergeFlags(raw); * // Result: { scope: 'new', json: true, flags: {...} } * ``` */ declare function mergeFlags>(input: T): T; /** * Environment variable system for declarative env definition with type safety * * Usage: * ```typescript * // In contracts * export const myEnv = defineEnv({ * MY_API_KEY: { type: 'string', description: 'API key for service' }, * MY_ENABLED: { type: 'boolean', default: true }, * MY_TIMEOUT: { type: 'number', default: 5000 }, * }); * * // In command * export default defineCommand({ * handler: { * async execute(ctx, input) { * const env = myEnv.parse(ctx.runtime); * console.log(env.MY_API_KEY); // string | undefined * console.log(env.MY_ENABLED); // boolean * } * } * }); * ``` */ /** * Runtime API interface (minimal for env parsing) * Avoids dependency on @kb-labs/plugin-contracts */ interface RuntimeLike { env(key: string): string | undefined; } /** * Environment variable schema (reuses FlagSpec types) */ type EnvSchema = FlagsSchema; /** * Environment variable definition with parse method */ interface EnvDefinition { /** Schema for documentation and validation */ schema: T; /** Inferred TypeScript type */ type: InferFlagsType; /** Parse environment variables from RuntimeLike */ parse: (runtime: RuntimeLike) => InferFlagsType; } /** * Define environment variables with type safety and validation * * @example * ```typescript * export const commitEnv = defineEnv({ * KB_COMMIT_LLM_ENABLED: { * type: 'boolean', * default: true, * description: 'Enable LLM analysis', * }, * KB_COMMIT_LLM_TEMPERATURE: { * type: 'number', * default: 0.3, * description: 'LLM temperature (0-1)', * validate: (v) => { * if (v < 0 || v > 1) throw new Error('Must be 0-1'); * }, * }, * }); * * // Use in command * const env = commitEnv.parse(ctx.runtime); * // Type: { KB_COMMIT_LLM_ENABLED: boolean; KB_COMMIT_LLM_TEMPERATURE: number } * ``` */ declare function defineEnv(schema: T): EnvDefinition; /** * Parse environment variables from RuntimeLike with validation and defaults */ declare function parseEnvFromRuntime(runtime: RuntimeLike, schema: T): InferFlagsType; /** * Resolve the current working directory from a CLI context-like object. * Falls back to the process cwd when the context does not provide one. */ declare function getContextCwd(input: { cwd?: string; } | undefined): string; /** * Normalize filesystem paths to POSIX (forward-slash) form. */ declare function toPosixPath(input: string): string; interface RetryOptions { attempts?: number; delay?: number; backoff?: 'fixed' | 'exponential'; onRetry?: (error: unknown, attempt: number) => void; } declare function withRetry(fn: () => Promise, options?: RetryOptions): Promise; interface ErrorContext { ui?: { json?: (data: unknown) => void; error?: (message: string, opts?: Record) => void; }; } /** * Structured validation error — emits { ok: false, error: { code: 'INVALID_ARGS', ... } } in JSON mode. * Call before try/catch, right before `return { exitCode: 1 }`. */ declare function validationError(ctx: ErrorContext, message: string, hint?: string, isJson?: boolean): void; /** * Structured runtime/API error — emits { ok: false, error: { code: 'INTERNAL_ERROR', ... } } in JSON mode. * Call in catch blocks, right before `return { exitCode: 1 }`. */ declare function handleError(ctx: ErrorContext, err: unknown, isJson?: boolean): void; /** * Re-throws `err` as an HTTP-aware error for REST handlers. * Envelope middleware reads `err.statusCode` to set HTTP status. * If err already has statusCode — preserves it. Otherwise → 500. */ declare function rethrowForRest(err: unknown): never; /** * Destructive-action protocol (SOFT layer). * * A single, platform-wide way for a command to declare that an operation is * destructive — how bad, how broad, and whether it can be undone — and to gate * it behind explicit confirmation in EVERY mode (human and agent). * * This layer is intentionally SOFT: it informs and asks, it does not enforce. * Physical enforcement (can-this-token-even-invoke-this) is the platform's * future token/permission layer; it reads the SAME `severity`/`destructive` * declaration on the command. So one declaration drives both: * - now: this helper renders a clear signal + requires `--yes`; * - later: the permission layer filters discovery + blocks invocation by right. * * Declaring it is OPTIONAL for external plugins (commands work without it) but * strongly recommended — agents can only reason about blast radius they're told. */ type DestructiveSeverity = 'low' | 'medium' | 'high' | 'critical'; /** * Severity rubric — worst-case blast radius weighed against recovery cost * (keep consistent across plugins so agents can calibrate): * - low narrow scope AND trivially auto-rebuilt from source (idempotent) * - medium a bounded set is lost; rebuildable, but with effort/recompute * - high a WHOLE collection is destroyed (entire index/corpus), OR recovery * is slow / manual — even if rebuildable, the loss is large and * easy to mis-target * - critical irreversible, NO recovery (prod data, tenant wipe) */ interface DestructiveAction { /** Command identity, e.g. "mind drop". */ action: string; /** What is affected, e.g. 'index "code"'. */ resource: string; /** Plain-language effect, e.g. "deletes all vectors + the manifest". */ effect: string; /** Blast-radius tier. */ severity: DestructiveSeverity; /** Whether the data can be recovered afterwards. */ reversible: boolean; /** How to recover, if reversible (e.g. "re-run `kb mind index --full`"). */ recovery?: string; /** Quantified scope — how much, of what, how broad. */ blastRadius?: { count?: number; unit?: string; scope?: string; }; /** Flag that confirms the action (default `--yes`). */ confirmFlag?: string; } /** The machine-readable signal an agent receives when confirmation is missing. */ interface ConfirmationRequired { ok: false; confirmationRequired: true; destructive: true; irreversible: boolean; severity: DestructiveSeverity; action: string; resource: string; effect: string; reversible: boolean; blastRadius?: { count?: number; unit?: string; scope?: string; }; recovery?: string; confirmWith: string; message: string; } interface ConfirmContext { ui?: { json?: (data: unknown) => void; warn?: (message: string, opts?: Record) => void; error?: (message: string, opts?: Record) => void; }; } /** * Build the machine-readable signal an agent receives when confirmation is * missing in json mode. Exported so a non-CLI surface (REST 409, MCP) can reuse * the exact shape instead of re-deriving it. */ declare function buildConfirmationSignal(a: DestructiveAction): ConfirmationRequired; /** Render the one-line warning — leads with the scary part (irreversibility + severity). */ declare function renderDestructiveMessage(a: DestructiveAction): string; /** * Gate a destructive command. Returns the command result to return immediately * when NOT confirmed (in every mode — agents get the structured signal, not a * silent execution), or `null` when confirmed so the caller proceeds. * * const blocked = confirmDestructive(ctx, { confirmed: flags.yes, isJson, action }); * if (blocked) return blocked; */ declare function confirmDestructive(ctx: ConfirmContext, opts: { confirmed: boolean; isJson?: boolean; action: DestructiveAction; }): CommandFailure | null; /** * Modern CLI formatting utilities with side border design * Provides minimalist, modern UI components for CLI output */ /** * Side border box - Clack-style design * * @example * ``` * ◆ Command Name * │ * │ Section Header * │ Key: value * │ * └ ✓ Success 84ms * ``` */ interface SideBorderBoxOptions { title: string; sections: SectionContent[]; footer?: string; status?: 'success' | 'error' | 'warning' | 'info'; timing?: number; summary?: Record; } interface RichSectionItem { text: string; /** Render text in muted/dim color */ dim?: boolean; /** Hard-truncate to N visible chars instead of wrapping */ truncate?: number; } /** A section item — either a plain string or a rich descriptor */ type SectionItem = string | RichSectionItem; interface SectionContent { header?: string; items: SectionItem[]; } /** * Create a side-bordered box with modern design */ declare function sideBorderBox(options: SideBorderBoxOptions): string; /** * Format a section header */ declare function sectionHeader(text: string): string; /** * Format metrics list (key: value pairs with aligned values) */ declare function metricsList(metrics: Record): string[]; /** * Format status line for footer */ declare function statusLine(status: 'success' | 'error' | 'warning' | 'info', timing?: number): string; /** * A single block in a chained output — a title + sections with optional footer on the last block. */ interface SideBorderChainItem { title: string; sections: SectionContent[]; summary?: Record; status?: 'success' | 'error' | 'warning' | 'info'; timing?: number; } /** * Render multiple side-border blocks as a continuous visual chain. * * Every block opens with `◆ Title` on the shared rail. * Only the last block gets `└ status timing`. * * @example * ``` * ◆ workflow metrics * │ * │ Failed to fetch metrics * │ * ◆ Warning * │ * │ Make sure daemon is running * │ * └ ✗ 12ms * ``` */ declare function sideBorderChain(items: SideBorderChainItem[]): string; /** * Convert an Error or raw string into clean display lines for sideBorderBox items. * Splits on newlines, removes blank lines, and caps at maxLines with a "… N more" hint. * * @example * items: formatError(err, { maxLines: 6 }) */ declare function formatError(err: Error | string, opts?: { maxLines?: number; }): string[]; /** * Format command help in modern side-border style * * @example * ```typescript * const help = formatCommandHelp({ * title: 'kb version', * description: 'Show CLI version', * longDescription: 'Displays the current version...', * examples: ['kb version', 'kb version --json'], * flags: [{name: 'json', description: 'Output in JSON'}] * }); * ``` */ declare function formatCommandHelp(options: { title: string; description?: string; longDescription?: string; examples?: string[]; flags?: Array<{ name: string; alias?: string; description?: string; required?: boolean; }>; aliases?: string[]; }): string; /** * Command result formatting utilities * Provides high and low-level APIs for formatting command output */ /** * Command output with human and machine-readable formats * Extends CommandResult contract from command-kit */ interface CommandOutput { /** Whether command executed successfully - required by CommandResult contract */ ok: boolean; /** Execution status */ status?: 'success' | 'error' | 'warning' | 'info' | 'failed' | 'cancelled' | 'skipped'; /** Human-readable output (side border format) */ human: string; /** Machine-readable output (JSON) */ json: object; /** Agent-specific output (optional, for --agent flag) */ agent?: object; } /** * Parameters for formatting command results */ interface CommandResultParams { title: string; summary?: Record; details?: Array<{ section: string; items: string[]; }>; warnings?: string[]; errors?: string[]; timing?: number; status: 'success' | 'error' | 'warning' | 'info'; /** Custom JSON data (optional) */ jsonData?: object; } /** * Low-level: Format command result with full control * * @example * ```typescript * const output = formatCommandResult({ * title: 'System Diagnostics', * summary: { 'Total Checks': 4, 'OK': 3 }, * details: [ * { section: 'Environment', items: ['Node 20.11.0'] } * ], * warnings: ['Cache is old'], * timing: 150, * status: 'success', * }); * * console.log(output.human); // Pretty CLI output * console.log(output.json); // JSON for --json flag * ``` */ declare function formatCommandResult(params: CommandResultParams): CommandOutput; /** * High-level: Quick success result * * @example * ```typescript * return successResult('Version Info', { * summary: { 'CLI Version': '0.1.0' }, * timing: 5, * }); * ``` */ declare function successResult(title: string, data?: { summary?: Record; details?: Array<{ section: string; items: string[]; }>; timing?: number; json?: object; }): CommandOutput; /** * High-level: Quick error result * * @example * ```typescript * return errorResult('Command Failed', new Error('Something went wrong'), { * timing: 100, * suggestions: ['Try running with --debug flag'], * }); * ``` */ declare function errorResult(title: string, error: Error | string, options?: { timing?: number; suggestions?: string[]; }): CommandOutput; /** * High-level: Quick warning result * * @example * ```typescript * return warningResult('Configuration Updated', ['Deprecated option used'], { * summary: { 'Files Updated': 3 }, * timing: 50, * }); * ``` */ declare function warningResult(title: string, warnings: string[], options?: { summary?: Record; timing?: number; }): CommandOutput; /** * High-level: Info result * * @example * ```typescript * return infoResult('Help Information', { * details: [ * { section: 'Usage', items: ['kb command --flag'] } * ], * }); * ``` */ declare function infoResult(title: string, data?: { summary?: Record; details?: Array<{ section: string; items: string[]; }>; timing?: number; }): CommandOutput; /** * Structured log display for CLI output (watch/run/stream commands). * Not a spinner — for rendering log lines with level, timestamp, and message. */ type LogLevel = 'info' | 'warn' | 'error' | 'debug' | 'verbose'; declare function logLine(level: LogLevel, message: string): string; declare function logGroup(title: string, lines: string[]): string; declare function printLog(level: LogLevel, message: string): void; /** * Inline status badges for CLI output. * * @example * badge('ONLINE', 'success') → green [ONLINE] * badge('FAILED', 'error') → red [FAILED] * badge('PENDING', 'neutral') → muted [PENDING] */ type BadgeVariant = 'success' | 'error' | 'warning' | 'info' | 'neutral'; declare function badge(label: string, variant?: BadgeVariant): string; declare function statusBadge(status: string): string; /** * Multi-step task runner with visual progress. * Each task shows as ○ pending → spinner running → ● done / ✗ failed. * * @example * await runTasks([ * { title: 'Install dependencies', run: async () => { ... } }, * { title: 'Build', run: async () => { ... } }, * ]) */ interface Task { title: string; run: (updateTitle: (t: string) => void) => Promise; } declare function runTasks(tasks: Task[]): Promise; /** * All interactive prompt methods of UIFacade. * Required (not optional) so TypeScript catches missing implementations * when UIFacade gains a new prompt method. */ interface UIPrompts { confirm(msg: string, opts?: { defaultValue?: boolean; }): Promise; prompt(msg: string, opts?: { default?: string; mask?: boolean; }): Promise; select(msg: string, choices: SelectChoice[]): Promise; multiSelect(msg: string, choices: MultiSelectChoice[]): Promise; } /** * Safe-return prompts for non-interactive contexts (subprocess, sandbox). * All methods return the most sensible default without any I/O. */ declare const NOOP_PROMPTS: UIPrompts; /** * Shared stdout UIFacade factory for subprocess/worker contexts. * * Both params are required so TypeScript catches any new UIFacade interactive * method at the call site rather than silently inheriting a noop default. * * Uses `satisfies UIFacade` on the object literal — TypeScript will error here * (not just at the return type) if any UIFacade method is missing. */ declare function createBaseStdoutUI(prompts: UIPrompts, log: UIFacade['log']): UIFacade; export { type AnalyticsConfig, type ArtifactDisplayOptions, type ArtifactInfo, type BadgeVariant, type BaseFlagSpec, type BooleanFlagSpec, type CLIPackage, type CommandContext, type CommandDiscovery, type CommandExecutionResult, type CommandInfo, type CommandManifest, type CommandOutput, type CommandPresenter, type CommandRegistry, type CommandResult, type CommandResultParams, type CommandRunnerOptions, type CommandSuggestion, type ConfirmationRequired, type DestructiveAction, type DestructiveSeverity, DynamicCommandDiscovery, type EnvDefinition, type EnvSchema, type FlagDefinition, type FlagSpec, type FlagType, type FlagsDefinition, type FlagsSchema, type FormatTimestampOptions, type InferFlagsType, type KeyValueOptions, Loader, type LoaderOptions, type LogLevel, type ManifestLoader, type MultiCLIContext, MultiCLISuggestions, NOOP_PROMPTS, type NumberFlagSpec, type RetryOptions, type RichSectionItem, type RuntimeLike, type SafeKeyValueOptions, type SectionContent, type SectionItem, type SideBorderBoxOptions, type SideBorderChainItem, StaticCommandDiscovery, type StringFlagSpec, type TableColumn, type TableOptions, type Task, TimingTracker, type UIPrompts, accentLabel, badge, box, buildConfirmationSignal, bulletList, colors, confirmDestructive, createBaseStdoutUI, createCommandDiscovery, createCommandRegistry, createCommandRunner, createDetailedResult, createKBLabsCommandDiscovery, createProgressBar, createSimpleResult, createSpinner, defineEnv, defineFlags, discoverArtifacts, displayArtifacts, displayArtifactsCompact, displaySingleArtifact, errorResult, extractCommandGroups, extractCommandIds, findCommandById, findCommandsByGroup, formatCommandHelp, formatCommandOutput, formatCommandResult, formatError, formatKeyValueTable, formatRelativeTime, formatSize, formatTable, formatTimestamp, formatTiming, formatTimingBreakdown, generateDevlinkSuggestions, generateGroupSuggestions, generateQuickActions, getCommandInfo, getContextCwd, handleError, hasAnsi, headline, indent, infoResult, isCommandAvailable, isJsonMode, keyValue, logGroup, logLine, mergeFlags, metricsList, muted, pad, parseBoolean, parseEnvFromRuntime, parseFlagsFromInput, parseNumber, parseNumberFlag, parseString, printLog, renderDestructiveMessage, rethrowForRest, runTasks, safeColors, safeKeyValue, safeSymbols, section, sectionHeader, setJsonMode, showError, showLoading, showSuccess, sideBorderBox, sideBorderChain, statusBadge, statusLine, stripAnsi, successResult, supportsColor, symbols, table, toPosixPath, truncate, useLoader, validateSuggestions, validationError, warningResult, withRetry };