import { z } from 'zod/v4'; import { IncomingMessage, ServerResponse, Server } from 'http'; import { WebSocket } from 'ws'; import { EventEmitter } from 'events'; import { ChildProcess } from 'child_process'; type TipLevel = 'info' | 'warn' | 'error'; interface Tip { level: TipLevel; message: string; label?: string; } declare class TipCollector { private items; info(message: string, label?: string): void; warn(message: string, label?: string): void; error(message: string, label?: string): void; get collected(): Tip[]; } declare function normalizeTip(t: string | Tip): Tip; declare function normalizeTips(tips: Array | undefined): Tip[]; /** * Convert Tip[] back to string[] (message only). * Useful for archives, IPC boundaries, and legacy string[] consumers. */ declare function tipsToMessages(tips: Array | undefined): string[]; declare const tip: { info: (message: string, label?: string) => Tip; warn: (message: string, label?: string) => Tip; error: (message: string, label?: string) => Tip; }; interface CommandResult { success: boolean; data: T; message?: string; tips: Tip[]; meta?: { duration?: number; command?: string; site?: string; }; } /** * Build a success CommandResult. * Backward compatible: accepts both `string[]` (legacy plugins) and `Tip[]` (new). * The returned `tips` is always normalized to `Tip[]`. */ declare function ok(data: T, tips?: Array): CommandResult; /** * Build a failure CommandResult. * Backward compatible: accepts both `string[]` (legacy plugins) and `Tip[]` (new). * The returned `tips` is always normalized to `Tip[]`. */ declare function fail(message: string, tips?: Array): CommandResult; declare function withMeta(result: CommandResult, meta: CommandResult['meta']): CommandResult; declare function isCommandResult(value: unknown): value is CommandResult; declare function wrapResult(raw: T): CommandResult; type BaseScope = 'project' | 'module' | 'resource' | 'action'; type CommandScope = string; declare const BROWSER_SCOPE_ORDER: Record; declare const COMMAND_SCOPE_ORDER: Record; declare const DEFAULT_SCOPE$1: CommandScope; declare const OptionSchema: z.ZodObject<{ name: z.ZodString; short: z.ZodOptional; type: z.ZodDefault>; description: z.ZodString; default: z.ZodOptional; required: z.ZodOptional; }, z.core.$strip>; type Option = z.infer; declare const CommandSchema: z.ZodObject<{ name: z.ZodString; description: z.ZodString; requiresLogin: z.ZodDefault>; options: z.ZodOptional; type: z.ZodDefault>; description: z.ZodString; default: z.ZodOptional; required: z.ZodOptional; }, z.core.$strip>>>; examples: z.ZodOptional>>; tips: z.ZodOptional>; }, z.core.$strip>; type Command = z.infer; type CommandHandler = (params: Record, ctx: CommandContext) => Promise | Record>; interface CommandContext { args: string[]; options: Record; cwd: string; storage: StorageContext; output: OutputContext; error: (msg: string) => void; config: Record; site: SiteInstance; cliName: string; tips: TipCollector; /** * Host-injected members (#55): executors put these on every context at * runtime. Generic members are declared here; `page` is a host-domain * object, so hosts augment CommandContext with their own typed member * (xbrowser does this in .xcli/plugins/types.ts). */ cdpEndpoint?: string; sessionId?: string; waitForHuman?(options: { reason: string; timeout?: number; }): Promise<{ solved: boolean; }>; detectAntiBot?(): Promise; } type ContextExtender = (base: CommandContext) => Record | Promise>; interface StorageContext { get(key: string): Promise; set(key: string, value: T): Promise; delete(key: string): Promise; clear(): Promise; keys(): Promise; plugin: PluginStore; global: GlobalStore; cache: CacheStore; tmp: TmpStore; } interface PluginStore { get(key: string): Promise; set(key: string, value: T): Promise; delete(key: string): Promise; clear(): Promise; keys(): Promise; } interface GlobalStore { get(key: string): Promise; set(key: string, value: T): Promise; delete(key: string): Promise; keys(): Promise; } interface CacheStore { get(key: string, maxAge?: number): Promise; set(key: string, value: T, maxAge: number): Promise; delete(key: string): Promise; clear(): Promise; } interface TmpStore { path(filename: string): string; read(filename: string): Promise; write(filename: string, data: Buffer | string): Promise; clean(): Promise; } interface OutputContext { mode: OutputMode; showTips: boolean; color: boolean; emoji: boolean; } type OutputMode = 'text' | 'json' | 'yaml'; interface SiteConfig { name: string; url?: string; description?: string; requiresLogin?: boolean; isLogin?: (ctx: CommandContext) => Promise; } interface LoginConfig { handler: (ctx: CommandContext) => Promise; persist?: boolean; restore?: (ctx: CommandContext) => Promise; isLoginCheck?: (ctx: CommandContext) => Promise; persistHandler?: (ctx: CommandContext) => Promise; auto?: boolean; } interface SessionExtractor { extractCookies(ctx: CommandContext): Promise>; extractToken(ctx: CommandContext, source: 'localStorage' | 'sessionStorage' | 'cookie', key: string): Promise; } type ZodSchema = z.ZodType; interface XCLIAPI { createSite(config: SiteConfig): SiteInstance; registerCommand(cmd: Command & { handler: CommandHandler; }): this; registerFlag(flag: FlagConfig): this; registerTool(tool: ToolConfig): this; overrideTool(name: string, tool: ToolConfig): this; onLoad(handler: () => void | Promise): this; onUnload(handler: () => void | Promise): this; onEvent(event: string, handler: EventHandler): this; } interface CommandEntry { name: string; description: string; requiresLogin?: boolean; scope: CommandScope; override: boolean; parameters?: ZodSchema; result?: ZodSchema; examples?: Array<{ cmd: string; description: string; }>; tips?: string[]; handler: CommandHandler; previousHandler?: CommandHandler; } interface SiteInstance { name: string; url: string; config: SiteConfig; command

(name: string, config: { description: string; scope?: CommandScope; override?: boolean; parameters?: P; result?: R; requiresLogin?: boolean; loginRequired?: 'none' | 'optional' | 'required'; examples?: Array<{ cmd: string; description: string; }>; tips?: string[]; handler: (params: z.infer

, ctx: CommandContext) => Promise> | CommandResult | z.infer | Record>; }): SiteInstance; group(name: string): SiteInstance; login(handler: ((ctx: CommandContext) => Promise) | LoginConfig): SiteInstance; logout(handler: (ctx: CommandContext) => Promise): SiteInstance; isLoggedIn(): Promise; requireLogin(): Promise; getStorage(): StorageContext; getAllCommands(): Array<{ name: string; description: string; requiresLogin?: boolean; scope: CommandScope; }>; getCommand(name: string): CommandEntry | null; getOriginalHandler(commandName: string): CommandHandler | undefined; executeLogin(ctx: CommandContext): Promise; executeLogout(ctx: CommandContext): Promise; restoreLogin(ctx: CommandContext): Promise; } interface FlagConfig { name: string; short?: string; type?: 'string' | 'number' | 'boolean'; description: string; default?: unknown; global?: boolean; } interface ToolConfig { name: string; scope?: string; description: string; parameters?: Record; execute: (params: Record, signal?: AbortSignal) => Promise; } type EventHandler = (event: EventContext) => unknown; interface EventContext { type: string; cwd: string; args: Record; } interface HookContext { command: string; params: Record; ctx: CommandContext; } interface AfterHookContext extends HookContext { result: CommandResult; duration: number; } interface CommandHooks { beforeCommand?: (hookCtx: HookContext) => void | Promise; afterCommand?: (hookCtx: AfterHookContext) => void | Promise; } interface PipelineContext { argv: string[]; commandName?: string; commandArgs?: string[]; entry?: CommandEntry; site?: SiteInstance; params?: Record; ctx?: CommandContext; result?: unknown; exitCode: number; duration?: number; skipped?: boolean; } type Middleware = (pipeline: PipelineContext, next: () => Promise) => Promise; declare class CommandError extends Error { code: string; constructor(code: string, message: string); } declare class SiteInstanceImpl implements SiteInstance { name: string; url: string; config: SiteConfig; private commands; private loginHandler?; private loginConfig?; private logoutHandler?; private storage; private loggedIn; private cliName; private get loginStateKey(); constructor(config: SiteConfig, storage: StorageContext, cliName?: string); command

(name: string, cmd: { description: string; scope?: CommandScope; override?: boolean; parameters?: P; result?: R; requiresLogin?: boolean; loginRequired?: 'none' | 'optional' | 'required'; examples?: Array<{ cmd: string; description: string; }>; tips?: string[]; handler: (params: z.infer

, ctx: CommandContext) => Promise> | CommandResult | z.infer | Record>; }): SiteInstance; group(name: string): SiteInstance; login(handler: ((ctx: CommandContext) => Promise) | LoginConfig): SiteInstance; logout(handler: (ctx: CommandContext) => Promise): SiteInstance; getCommand(name: string): CommandEntry | null; getOriginalHandler(commandName: string): CommandHandler | undefined; getAllCommands(): Array<{ name: string; description: string; requiresLogin?: boolean; scope: CommandScope; }>; hasLoginCommand(): boolean; hasLogoutCommand(): boolean; isLoggedIn(): Promise; requireLogin(): Promise; getStorage(): StorageContext; executeLogin(ctx: CommandContext): Promise; executeLogout(ctx: CommandContext): Promise; restoreLogin(ctx: CommandContext): Promise; } declare class GroupedSiteInstance implements SiteInstance { name: string; url: string; config: SiteConfig; private prefix; private parent; constructor(parent: SiteInstanceImpl, groupName: string); command

(name: string, cmd: { description: string; scope?: CommandScope; override?: boolean; parameters?: P; result?: R; requiresLogin?: boolean; loginRequired?: 'none' | 'optional' | 'required'; examples?: Array<{ cmd: string; description: string; }>; tips?: string[]; handler: (params: z.infer

, ctx: CommandContext) => Promise> | CommandResult | z.infer | Record>; }): SiteInstance; group(name: string): SiteInstance; login(handler: ((ctx: CommandContext) => Promise) | LoginConfig): SiteInstance; logout(handler: (ctx: CommandContext) => Promise): SiteInstance; isLoggedIn(): Promise; requireLogin(): Promise; getStorage(): StorageContext; getAllCommands(): Array<{ name: string; description: string; requiresLogin?: boolean; scope: CommandScope; }>; getCommand(name: string): CommandEntry | null; getOriginalHandler(commandName: string): CommandHandler | undefined; executeLogin(ctx: CommandContext): Promise; executeLogout(ctx: CommandContext): Promise; restoreLogin(ctx: CommandContext): Promise; } declare function buildInputSchema(command: { parameters?: ZodSchema; options?: Option[]; }): ZodSchema; interface ScanOptions { priority?: 'first-wins' | 'last-wins'; validate?: (meta: PluginMeta) => boolean; ignoreDotFiles?: boolean; } interface ScanResult { loaded: string[]; failed: Array<{ path: string; error: string; }>; skipped: string[]; } interface PluginMeta { name: string; version?: string; description?: string; commands?: string[]; dependencies?: Record; } declare function validateArgs(command: { parameters?: ZodSchema; options?: Option[]; }, argv: Record): T; type PluginStatus = 'loaded' | 'unloaded' | 'error'; interface PluginLoaderHost { cleanupPluginRegistrations(instance: PluginInstance$1): void; loadPlugin(pluginPath: string, explicitId?: string): Promise; } declare class PluginInstance$1 { readonly id: string; readonly path: string; readonly siteName: string; private registeredSiteNames; private registeredCommands; private registeredFlags; private registeredTools; private overriddenCommands; private loadHandlers; private unloadHandlers; private eventHandlers; private _loaded; private _status; private _error?; private readonly loader; constructor(id: string, pluginPath: string, loader: PluginLoaderHost); get loaded(): boolean; get status(): PluginStatus; get error(): Error | undefined; addSiteName(name: string): void; addCommand(name: string): void; addFlag(name: string): void; addTool(name: string): void; addOverriddenCommand(name: string, original: Command & { handler: CommandHandler; }): void; getOverriddenCommands(): Map; addLoadHandler(handler: () => void | Promise): void; addUnloadHandler(handler: () => void | Promise): void; addEventHandler(event: string, handler: EventHandler): void; getRegisteredSiteNames(): string[]; getRegisteredCommands(): string[]; getRegisteredFlags(): string[]; getRegisteredTools(): string[]; getEventHandlers(): Map>; setError(err: Error): void; mount(): Promise; unmount(): Promise; reload(): Promise; } interface CoreHost { readonly config: { readonly name: string; readonly pluginPackageName?: string; }; readonly storageDir: string; readonly configDir: string; } interface BuiltinCommandEntry { name: string; scope: CommandScope; handler: (args: string[], values: Record) => Promise; } declare class PluginLoader { private commands; private builtinScopeMap; private sites; private flags; private tools; private globalEventHandlers; private plugins; private storage; private readonly core; private api; constructor(core: CoreHost); private createStorage; private createPluginStorage; private createAPI; private activeInstanceId; private getActiveInstance; getAPI(): XCLIAPI; loadPlugin(pluginPath: string, explicitId?: string): Promise; unloadPlugin(pluginId: string): Promise; reloadPlugin(pluginId: string): Promise; unloadAll(): Promise; getLoadedPlugins(): PluginInstance$1[]; getPluginStatus(pluginId: string): PluginStatus; getPlugin(pluginId: string): PluginInstance$1 | undefined; cleanupPluginRegistrations(instance: PluginInstance$1): void; loadFromFunction(setup: (xcli: XCLIAPI) => void): Promise; getCommand(name: string): (Command & { handler: CommandHandler; }) | undefined; registerBuiltinScope(name: string, scope: CommandScope): void; getBuiltinScope(name: string): CommandScope; findCommand(name: string, scope?: CommandScope): { entry: CommandEntry; site: SiteInstance; } | null; resolveCommand(name: string, siteName?: string): CommandEntry | null; resolveNestedCommand(argv: string[]): { entry: CommandEntry; site: SiteInstance; consumedArgs: number; } | null; getSubCommands(prefix: string): CommandEntry[]; getSiteCommand(siteName: string, cmdName: string): (Command & { handler: CommandHandler; }) | undefined; getAllCommands(): Array; getSite(name: string): SiteInstance | undefined; getSites(): Array; getFlag(name: string): FlagConfig | undefined; getAllFlags(): FlagConfig[]; getTool(name: string): ToolConfig | undefined; getAllTools(): ToolConfig[]; emitEvent(event: string, context: EventContext): Promise; scanAndLoad(dirs: string[], options?: ScanOptions): Promise; unload(): Promise; } declare function readPluginMeta(pluginDir: string, options?: { metadataField?: string; }): PluginMeta | null; interface ScopeDefinition { name: string; description: string; levels: ScopeLevel[]; guard?: (ctx: CommandContext, level: string) => string | null; inject?: (ctx: CommandContext, level: string) => Promise>; } interface ScopeLevel { name: string; description: string; order: number; requires?: string[]; guard?: (ctx: CommandContext) => string | null; } interface ScopeConfig { current: string; overrideTargets?: string[]; canOverride?: boolean; } declare const DEFAULT_SCOPE: ScopeDefinition; interface ScopedCommand { name: string; scope: string; config: ScopeConfig; } declare class ScopeRegistry { private scopes; private commandScopeMap; registerScope(definition: ScopeDefinition): void; getScope(name: string): ScopeDefinition | undefined; checkGuard(scopeName: string, level: string, ctx: CommandContext): string | null; injectContext(scopeName: string, level: string, ctx: CommandContext): Promise>; registerCommand(siteName: string, command: ScopedCommand): ScopedCommand | null; getCommandScope(siteName: string, commandName: string): ScopedCommand | undefined; resolveCommand(siteName: string, commandName: string, _currentScope: string): ScopedCommand | undefined; listCommands(siteName: string, scopeLevel?: string): ScopedCommand[]; getScopeForSite(siteName: string): ScopeDefinition | undefined; isValidScopeLevel(scopeName: string, levelName: string): boolean; getSortedLevels(scopeName: string): ScopeLevel[]; } interface CoreConfig { name: string; version: string; description: string; configDirName: string; envPrefix: string; pluginDirs: string[]; pluginPackageName?: string; } declare class Core { readonly config: CoreConfig; readonly loader: PluginLoader; readonly scopeRegistry: ScopeRegistry; readonly configDir: string; readonly sessionDir: string; readonly storageDir: string; private contextExtenders; private hooks; private pipeline; private handlerMiddlewareIndex; constructor(config: CoreConfig); use(middleware: Middleware): this; extendContext(extender: ContextExtender): this; registerHooks(hooks: CommandHooks): this; registerScope(definition: ScopeDefinition): this; get name(): string; get version(): string; get envPrefix(): string; envVar(suffix: string): string; run(argv: string[]): Promise; private executePipeline; private versionCheckMiddleware; private helpMiddleware; private commandResolveMiddleware; private paramParseMiddleware; private contextBuildMiddleware; private scopeGuardMiddleware; private loginGuardMiddleware; private hooksMiddleware; private handlerMiddleware; private resultMiddleware; private buildValidatedParams; private getZodShape; private suggestCommand; } declare function createPaths(config: CoreConfig): { configDir: string; sessionDir: string; storageDir: string; daemonConfigPath: string; daemonSocketPath: string; }; declare function getEnvVar(config: CoreConfig, suffix: string): string; declare function getDefaultPort(config: CoreConfig): number; /** * @deprecated These constants hardcode `.xcli` paths and should NOT be used in new code. * Use `createPaths(core.config)` or `core.configDir` / `core.sessionDir` / `core.storageDir` instead. * They are kept only for backward compatibility and will be removed in a future major version. */ /** @deprecated Use createPaths(core.config) instead */ declare const CONFIG_DIR: string; /** @deprecated Use createPaths(core.config) instead */ declare const SESSION_DIR: string; /** @deprecated Use createPaths(core.config) instead */ declare const DAEMON_CONFIG_PATH: string; /** @deprecated Use createPaths(core.config) instead */ declare const DAEMON_SOCKET_PATH: string; /** @deprecated Use getChromiumPath(core) instead */ declare const DEFAULT_CHROMIUM_PATH: string; /** @deprecated Use getDaemonPort(core) instead */ declare const DAEMON_PORT: number; interface SessionInfo { id: string; name: string; url: string; pid?: number; createdAt: string; } type CommandArgs = string[]; type CommandValues = Record; declare class PluginStorage { private filePath; private data; constructor(pluginId: string, storageDir: string); get(key: string): Promise; set(key: string, value: T): Promise; delete(key: string): Promise; clear(): Promise; keys(): Promise; } declare class GlobalStorage { private filePath; private data; constructor(configDir: string); get(key: string): Promise; set(key: string, value: T): Promise; delete(key: string): Promise; keys(): Promise; } declare class CacheStorage { private dir; constructor(pluginId: string, cacheDir: string); get(key: string, maxAge?: number): Promise; set(key: string, value: T, maxAge: number): Promise; delete(key: string): Promise; clear(): Promise; } declare class TmpStorage { private dir; constructor(cliName: string, pluginId: string); path(filename: string): string; read(filename: string): Promise; write(filename: string, data: Buffer | string): Promise; clean(): Promise; } declare class CompositeStorage { plugin: PluginStorage; global: GlobalStorage; cache: CacheStorage; tmp: TmpStorage; constructor(pluginId: string, configDir: string, cliName: string); get(key: string): Promise; set(key: string, value: T): Promise; delete(key: string): Promise; clear(): Promise; keys(): Promise; } interface HelpCommand { name?: string; description?: string; parameters?: ZodSchema; options?: Option[]; result?: ZodSchema; examples?: Array<{ cmd: string; description?: string; output?: string; }>; tips?: string[]; } interface HelpOptions { color: boolean; emoji: boolean; } declare class HelpGenerator { generate(command: HelpCommand, options?: HelpOptions): string; private header; private description; private zodParameters; private zodResult; /** * Extract the field shape from a Zod schema, unwrapping ZodDefault/ZodOptional/ * ZodNullable wrappers that may hide the underlying ZodObject. */ private extractShape; private getZodType; private options; private examples; private tips; generateList(commands: Command[], options?: HelpOptions): string; generateSiteHelp(siteName: string, url: string, commands: Array<{ name: string; description: string; }>, options?: HelpOptions & { cliName?: string; }): string; private groupCommands; } declare const helpGenerator: HelpGenerator; interface FormatOptions { mode: OutputMode; color: boolean; emoji: boolean; } interface EnvelopeFormatOptions { /** 命令名称,放进 meta.command */ command?: string; /** 额外 meta 字段,合并到 meta 对象 */ extraMeta?: Record; /** 输出模式(默认继承自调用方,或 json) */ mode?: OutputMode; } declare class OutputFormatter { format(data: unknown, options?: FormatOptions): string; private formatJson; private formatYaml; private toYamlLines; private formatText; formatError(error: Error | string, options?: { color: boolean; emoji: boolean; }): string; formatSuccess(message: string, options?: { color: boolean; emoji: boolean; }): string; /** * Wrap a CommandResult into a standardized JSON envelope. * * ```json * { "success": true, "command": "goto", "data": {...}, "error": null, "meta": { "duration": 1234 } } * ``` * * All xcli-core based CLI tools get a consistent output format by using this * instead of formatting `result.data` directly. */ formatEnvelope(result: CommandResult, options?: EnvelopeFormatOptions): string; } declare const outputFormatter: OutputFormatter; interface ParsedArgs { positional: string[]; options: Record; '--'?: string[]; } interface ParseArgsOptions { strict?: boolean; knownOptions?: string[]; /** Flags that should always be treated as booleans (never consume the next arg). */ booleanFlags?: string[]; } declare class UnknownOptionError extends Error { readonly option: string; constructor(option: string); } declare function parseArgs(argv: string[], opts?: ParseArgsOptions): ParsedArgs; declare function mergeArgsWithDefaults(options: Record, command: Command): Record; declare function resolveShortOptions(options: Record, command: Command): Record; declare function coerceCliArgs(schema: z.ZodType | undefined, rawArgs: Record): Record; declare function unquote(str: string): string; declare function extractPositionalParams(schema: z.ZodType): string[]; declare function mapPositionalValues(schema: z.ZodType, positional: string[], existing: Record): Record; /** @deprecated Use path.join(core.configDir, 'config.json') instead */ declare const CONFIG_FILE: string; interface RcConfig { viewer?: { host?: string; }; browser?: { executablePath?: string; }; daemon?: { port?: number; }; } /** * Minimal config source — accepts either a Core instance or * a plain object with configDir and optional envPrefix. * * Core is structurally compatible (has configDir + envPrefix getter). */ interface ConfigSource { configDir: string; envPrefix?: string; } declare const CONFIG_KEY_MAP: Record; /** * Load config from a config source. * * @param source - Either a Core instance or an object with configDir */ declare function loadConfig(source: ConfigSource): RcConfig; /** * Save config to a config source's directory. * * @param source - Either a Core instance or an object with configDir * @param config - The config object to persist */ declare function saveConfig(source: ConfigSource, config: RcConfig): void; /** * Get a config value by dotted key (e.g. "viewer.host"). * * @param source - Either a Core instance or an object with configDir * @param key - Dotted config key registered in CONFIG_KEY_MAP */ declare function getConfigValue(source: ConfigSource, key: string): string | number | undefined; /** * Set a config value by dotted key (e.g. "viewer.host"). * Returns true on success, false if the key is not registered. * * @param source - Either a Core instance or an object with configDir * @param key - Dotted config key registered in CONFIG_KEY_MAP * @param value - Value to persist */ declare function setConfigValue(source: ConfigSource, key: string, value: string): boolean; /** * Get a config value, checking environment variable first. * * Environment variable names follow the pattern `_`. * * @param source - Either a Core instance or an object with configDir+envPrefix * @param key - Dotted config key registered in CONFIG_KEY_MAP */ declare function getEffectiveValue(source: ConfigSource, key: string): string | number | undefined; declare function getViewerHost(source: ConfigSource): string; declare function getChromiumPath(source: ConfigSource): string; declare function getDaemonPort(source: ConfigSource): number; declare function getViewerUrl(source: ConfigSource, sessionId: string, daemonPort: number): string; declare function getAllConfigKeys(): string[]; interface GuardRule { match: string[]; block: string[]; message: string; } interface GuardConfig { identityKey: string; rules: Record; } declare function loadGuardConfig(core: Core): GuardConfig | null; declare function clearGuardCache(): void; declare function setGuardIdentityKey(core: Core, key: string): void; declare function addGuardRule(core: Core, identity: string, rule: GuardRule): void; declare function removeGuardRule(core: Core, identity: string): boolean; declare function listGuardRules(core: Core): GuardConfig | null; declare function checkGuard(core: Core, command: string, env?: Record): { blocked: boolean; message: string; } | null; interface ToolCallRecord$1 { tool: string; timestamp: number; duration: number; result: string; } interface ValidationResult { l1_functional: { status: 'pass' | 'fail'; detail: string; }; l2_behavior: { status: 'pass' | 'warn' | 'fail'; score: number; mdGap: number; offsetStd: number; moveClickRatio: number; instantClickRatio: number; details: string[]; }; l3_regression: { status: 'pass' | 'warn' | 'skip'; diff: string[]; }; } declare function validateExecution(success: boolean, data: unknown, toolCalls: ToolCallRecord$1[], sessionId: string, siteName: string, cmdName: string, currentDuration: number): ValidationResult; declare function formatValidationReport(v: ValidationResult): string[]; interface SessionMeta { id: string; name: string; config: Record; } /** * Generic session manager contract. * * Core provides a base implementation ({@link SessionManager}), * but downstream projects (e.g. xbrowser) can extend it with * their own session metadata type that carries domain-specific state such as * Playwright `Page` instances or WebSocket connections. * * @typeParam TMeta - The session metadata type. Must at minimum contain `id` * and `name` fields. */ interface SessionManagerContract { /** * Create a new session. * * @param name - Unique name for the session. * @param config - Implementation-specific configuration. * @returns The created session metadata. */ createSession(name: string, config: Record): Promise; /** * Destroy a session by name. * * @param name - The session name to destroy. * @returns The destroyed session metadata, or `undefined` if not found. */ destroySession(name: string): Promise; /** * Get session metadata by name. * * @param name - The session name. * @returns The session metadata, or `undefined` if not found. */ getSession(name: string): Promise; /** * List all active sessions. * * @returns Array of session metadata. */ listSessions(): Promise; } /** * Adapter interface for session persistence. * * Core provides a default JSON file implementation ({@link FileSessionPersistence}), * but downstream projects can implement their own adapter (e.g. Redis, SQLite). * * @typeParam TMeta - Session metadata type. Must contain at least `id` and `name`. */ interface SessionPersistence { /** Save session metadata (partial update — merges with existing data). */ save(name: string, data: Partial): void; /** Load session metadata by name. Returns `null` if not found. */ load(name: string): TMeta | null; /** Delete persisted session metadata by name. */ delete(name: string): void; /** List all persisted session metadata entries. */ list(): TMeta[]; } /** * Default file-based session persistence. * * Stores each session as a JSON file in `{baseDir}/{name}.json`. * * @typeParam TMeta - Session metadata type. */ declare class FileSessionPersistence implements SessionPersistence { private readonly dir; constructor(baseDir?: string); save(name: string, data: Partial): void; load(name: string): TMeta | null; delete(name: string): void; list(): TMeta[]; private filePath; } /** * Lifecycle hooks for session management. * * Downstream projects register hooks to inject domain-specific behavior * (e.g. browser cleanup, network teardown) into the standard session lifecycle. * * All hooks are optional — the base {@link SessionManager} calls them only when registered. * * @typeParam TMeta - Session metadata type. */ interface SessionLifecycle { /** Called after a session is created and stored. */ onCreate?(session: TMeta): void | Promise; /** Called before a session is removed from the store. */ onClose?(session: TMeta): void | Promise; /** Called when a session is restored from persistence. */ onRestore?(session: TMeta): void | Promise; } /** * Generic in-memory session store. * * @typeParam TMeta - Session metadata type. Must contain at least `id` and `name`. */ declare class SessionStore { private readonly map; /** Find a session by name. */ find(name: string): TMeta | undefined; /** Get a session by id. */ get(id: string): TMeta | undefined; /** Add a session to the store. Throws if the name already exists. */ add(session: TMeta): TMeta; /** * Set (upsert) a session by id — no duplicate-name check. * Use for restoring or replacing sessions where uniqueness is already guaranteed. */ set(session: TMeta): void; /** Remove a session by name and return it. */ remove(name: string): TMeta | undefined; /** Remove a session by id and return it. */ removeById(id: string): TMeta | undefined; /** List all sessions. */ list(): Array; /** Clear all sessions. */ clear(): void; /** Number of sessions. */ get size(): number; /** Raw Map access for advanced use. */ get rawMap(): Map; /** Iterate over sessions. */ [Symbol.iterator](): IterableIterator; } declare const defaultStore: SessionStore; declare function findSession(name: string): SessionMeta | undefined; declare function createSessionMeta(sessionName: string, config: Record, id?: string): SessionMeta; declare function removeSession(name: string): SessionMeta | undefined; declare function getSession(id: string): SessionMeta | undefined; declare function clearAll(): void; declare function listSessions(): Array; /** * Enhanced session manager with lifecycle hooks, pluggable persistence, * and session recovery support. * * **Extensible**: downstream projects subclass and override template methods * (`allocateSession`, `restoreSession`) to inject domain-specific behavior * (e.g. Playwright browser launch, CDP page matching). * * @typeParam TMeta - Session metadata type. Defaults to {@link SessionMeta}. */ declare class SessionManager implements SessionManagerContract { protected store: SessionStore; protected persistence?: SessionPersistence; protected lifecycle?: SessionLifecycle; constructor(); /** Register a persistence adapter for disk-based session recovery. */ setPersistence(adapter: SessionPersistence): this; /** Register lifecycle hooks for session events. */ setLifecycle(hooks: SessionLifecycle): this; /** * Create a new session. * * Flow: validate uniqueness → allocate → store → persist → notify lifecycle. */ createSession(name: string, config: Record): Promise; /** * Destroy a session by name. * * Flow: find → notify lifecycle → remove from store → unpersist. */ destroySession(name: string): Promise; /** Get session metadata by name. */ getSession(name: string): Promise; /** List all active sessions. */ listSessions(): Promise; /** Clear all sessions from the store. */ clearAll(): void; /** * Find a session by name, falling back to persistence recovery. * * Flow: check memory → check persistence → restore via {@link restoreSession}. * Returns `undefined` if the session cannot be found or restored. */ findOrRestore(name: string): Promise; /** * Allocate a new session instance. Called by {@link createSession}. * * Default implementation generates an id and wraps name + config. * Override in subclasses to add domain-specific fields (e.g. browser, page). */ protected allocateSession(name: string, config: Record): Promise; /** * Restore a session from persisted data. Called by {@link findOrRestore}. * * Default implementation returns the disk data as-is (no reconnection). * Override in subclasses to re-establish connections (e.g. reconnect CDP). */ protected restoreSession(disk: TMeta): Promise; } interface ToolCallRecord { tool: string; params: unknown[]; result: 'success' | 'failure'; duration: number; timestamp: number; } interface CommandArchiveEntry { step: number; command: string; params: Record; result: { success: boolean; data: unknown; message?: string; /** Plain string messages. Use `tipsToMessages(result.tips)` to convert from `Tip[]`. */ tips: string[]; }; toolCalls: ToolCallRecord[]; duration: number; timestamp: number; validation?: { l1_functional: { status: string; detail: string; }; l2_behavior: { status: string; score: number; details: string[]; }; l3_regression: { status: string; diff: string[]; }; }; } interface OutlineEntry { step: number; type: 'command'; command: string; status: 'success' | 'failure'; duration: number; } interface SessionArchive { id: string; name: string; createdAt: string; endedAt: string; outline: OutlineEntry[]; commands: CommandArchiveEntry[]; } interface ArchiveStoreConfig { archiveDir: string; configDirName?: string; } declare function configureArchiveStore(config: ArchiveStoreConfig): void; declare function saveArchive(archive: SessionArchive): string; declare function loadArchive(sessionId: string): SessionArchive | null; declare function listArchives(): SessionArchive[]; declare function searchArchives(options: { failed?: boolean; command?: string; from?: string; to?: string; }): SessionArchive[]; declare function diffArchives(archiveA: SessionArchive, archiveB: SessionArchive, commandFilter?: string): { commandA: CommandArchiveEntry | null; commandB: CommandArchiveEntry | null; differences: string[]; }[]; declare function appendCommandToArchive(sessionId: string, sessionName: string, entry: CommandArchiveEntry): void; interface IPCMessage { id: string; type: 'request' | 'response' | 'event' | 'error'; method: string; params: Record; sessionId: string; } interface IPCResponse { id: string; type: 'response' | 'error'; result?: unknown; error?: { code: string; message: string; tips: string[]; }; } interface WorkerContext { sessionId: string; sessionName: string; config: Record; ipc: { send(type: string, payload: unknown): void; onMessage(handler: (msg: IPCMessage) => void): void; }; } interface WorkerEntryPoint { init(ctx: WorkerContext): Promise; execute(method: string, params: Record): Promise; destroy(): Promise; } interface DaemonConfig { configDir: string; workerEntryPath: string; maxWorkers?: number; heartbeatInterval?: number; requestTimeout?: number; basePort?: number; } declare const DEFAULT_DAEMON_CONFIG: Required>; type RPCHandler = (method: string, params: Record) => Promise; interface HttpServerConfig$1 { port: number; rpcHandler: RPCHandler; extraRoutes?: Array<{ pathname: string; handler: (req: IncomingMessage, res: ServerResponse, rpcHandler: RPCHandler) => void; }>; } declare function startHttpServer(config: HttpServerConfig$1): Server; interface WSMessage$1 { type: 'broadcast' | 'emit' | 'on' | 'off' | 'ping' | 'pong' | 'subscribe-broadcast' | 'unsubscribe-broadcast'; channel?: string; event?: string; data?: unknown; id?: string; } interface WSServerConfig { port: number; host?: string; path?: string; } type WSMessageHandler = (data: unknown) => void; declare class WSServer { private config; private server; private channels; private clients; private eventHandlers; private broadcastListeners; constructor(config: WSServerConfig); start(): Promise; private handleConnection; private handleMessage; private handleDisconnection; bindToChannel(sessionId: string, ws: WebSocket): void; broadcast(channel: string, data: unknown): void; private addToBroadcastListeners; private removeFromBroadcastListeners; private emit; private on; private off; getSessionConnections(sessionId: string): WebSocket[]; stop(): Promise; getConnectedClients(): number; getChannelCount(channel: string): number; } interface DaemonHostConfig extends DaemonConfig { wsServer?: WSServerConfig; extraRoutes?: HttpServerConfig$1['extraRoutes']; eventHandler?: (event: string, data: unknown) => void; onReady?: (rpcHandler: RPCHandler) => void; } declare function runDaemonHost(config: DaemonHostConfig): Promise; interface ExtendedDaemonConfig extends DaemonConfig { wsServer?: WSServerConfig; } type DaemonLikeConfig = DaemonConfig | DaemonRpcConfig; declare function isDaemonRunning(config: DaemonLikeConfig): boolean; declare function startWSServer(config: WSServerConfig): Promise; declare function stopWSServer(): Promise; declare function getWSServer(): WSServer | null; interface DaemonRpcConfig { configDir: string; workerEntryPath?: string; basePort?: number; } declare function ensureDaemon(config: DaemonRpcConfig): Promise; declare function daemonRpc(config: DaemonRpcConfig, method: string, params?: Record): Promise>; declare function startDaemon(config: DaemonConfig): Promise<{ port: number; pid: number; }>; declare function stopDaemon(config: DaemonConfig): Promise; declare function getDaemonStatus(config: DaemonConfig): { running: boolean; port: number; pid: number; }; declare function killAllDaemon(config: DaemonConfig): Promise; interface WorkerEntry { process: ChildProcess; sessionId: string; status: 'starting' | 'ready' | 'busy' | 'crashed'; lastHeartbeat: number; } interface WorkerManagerConfig { workerEntryPath: string; requestTimeout?: number; heartbeatInterval?: number; heartbeatTimeout?: number; } declare class WorkerManager extends EventEmitter { private workers; private pendingRequests; private commandQueues; private heartbeatTimer; private readonly config; constructor(config: WorkerManagerConfig); spawnWorker(sessionId: string): Promise; killWorker(sessionId: string): Promise; sendCommand(sessionId: string, message: Omit): Promise; private sendCommandInternal; getWorkerStatus(sessionId: string): WorkerEntry['status'] | null; getActiveWorkers(): string[]; onWorkerCrash(sessionId: string): void; shutdown(): Promise; private handleWorkerMessage; private startHealthCheck; private cleanupWorker; private cleanupPendingForSession; } interface WSMessage { type: 'broadcast' | 'emit' | 'on' | 'off' | 'ping' | 'pong' | 'connected' | 'error' | 'event' | 'subscribed' | 'unsubscribed' | 'subscribe-broadcast' | 'unsubscribe-broadcast'; channel?: string; event?: string; data?: unknown; id?: string; } interface WSClientConfig { url: string; reconnectInterval?: number; maxReconnectAttempts?: number; } type WSMessageCallback = (msg: WSMessage) => void; type WSEventCallback = (data: unknown) => void; declare class WSClient { private config; private ws; private reconnectAttempts; private reconnectTimer; private messageHandlers; private eventHandlers; private pendingSubscriptions; private pendingId; constructor(config: WSClientConfig); connect(): Promise; private handleMessage; private handleDisconnect; send(type: WSMessage['type'], data?: unknown): void; broadcast(channel: string, data: unknown): void; subscribeToBroadcast(channel: string): void; unsubscribeFromBroadcast(channel: string): void; emit(event: string, data: unknown): void; subscribe(event: string, handler: WSEventCallback): void; unsubscribe(event: string): void; onMessage(handler: WSMessageCallback): void; offMessage(handler: WSMessageCallback): void; ping(): void; disconnect(): void; isConnected(): boolean; getReadyState(): number; } type PluginInstallerType = 'local' | 'npm' | 'git' | 'url' | 'builtin'; interface InstallOptions { force?: boolean; version?: string; registry?: string; } interface PluginInstance { id: string; name: string; version: string; type: PluginInstallerType; source: string; path: string; installedAt: number; } interface PluginInstaller { readonly type: PluginInstallerType; install(source: string, options?: InstallOptions): Promise; uninstall(pluginId: string): Promise; update(pluginId: string): Promise; list(): Promise; } interface InstallerRegistryConfig { pluginsDir: string; builtinDir?: string; } declare class PluginInstallerRegistry { private installers; constructor(config: InstallerRegistryConfig); registerInstaller(type: PluginInstallerType, installer: PluginInstaller): void; getInstaller(type: PluginInstallerType): PluginInstaller | undefined; install(type: PluginInstallerType, source: string, options?: InstallOptions): Promise; uninstall(pluginId: string): Promise; update(pluginId: string): Promise; listAll(): Promise; } /** * Plugin installer for the npm registry. * * Implementation follows the `fetch registry → download tarball → extract * → flatten package/ root → verify` pipeline used by the rest of the * installer family. We do not shell out to `npm install` so installation * works in environments where the npm CLI is unavailable or undesired * (e.g. inside a daemon process). */ declare class NpmInstaller implements PluginInstaller { readonly type: "npm"; private readonly pluginsDir; constructor(pluginsDir: string); install(source: string, options?: InstallOptions): Promise; uninstall(pluginId: string): Promise; update(pluginId: string): Promise; list(): Promise; private fetchMeta; private tryReadPackage; } interface PluginVerifyResult { valid: boolean; error?: string; warnings?: string[]; } interface VerifyPluginOptions { /** * package.json 内 metadata 字段名。 * - 默认 `'xcli'`:通用消费者无需配置 * - 消费者可显式传入自定义字段名(如 xbrowser 传 `'xbrowser'`) */ metadataField?: string; } /** * Download a URL (or copy a `file://` URL) to a local destination path. * * Supports http(s) URLs via fetch streaming and local `file://` URLs via * `cpSync`. Throws on non-2xx HTTP responses or empty bodies. */ declare function downloadToFile(url: string, destPath: string): Promise; /** * Extract a `.tar.gz` archive into the target directory by shelling out to * `tar -xzf`. Creates the target directory if it does not exist. */ declare function extractTarGz(tarballPath: string, targetDir: string): void; /** * Flatten a single nested `package/` directory produced by npm tarballs. * * If `targetDir` contains exactly one subdirectory and no files, the contents * of that subdirectory are moved up one level and the wrapper is removed. * In all other cases the directory is left unchanged. */ declare function flattenPackageRoot(targetDir: string): void; /** * Verify that `dir` looks like a valid plugin directory. * * Checks for an `index.ts` or `index.js` entry point. When `package.json` * exists, the parser checks for the presence of the metadata field specified * by `options.metadataField` (default `'xcli'`). Returns warnings instead of * failing for metadata issues. * * 消费者可通过 `options.metadataField` 自定义字段名: * - 通用消费者:默认 `'xcli'` * - xbrowser:传 `'xbrowser'` 以兼容现有插件 */ declare function verifyPlugin(dir: string, options?: VerifyPluginOptions): PluginVerifyResult; /** * Remove a directory tree, swallowing any errors (e.g. ENOENT, EPERM). * Useful in `finally` blocks where cleanup must not throw. */ declare function safeCleanup(dir: string): void; type SourceType = 'local' | 'npm' | 'git' | 'url' | 'builtin'; /** * Classify a plugin source string into one of the supported installer types. * * Order of detection is significant: * 1. `local` — any path-like string or `file://` URL * 2. `git` — anything that looks like a git URL * 3. `npm` — a valid npm package name (with optional version) * 4. `url` — plain http(s) URL * * @throws when the source cannot be classified. */ declare function detectSourceType(source: string): SourceType; /** * Derive a plugin name from a source string and its already-detected type. * * The rules are: * - `local`: trailing path segment, with trailing slashes stripped * - `npm`: package name (with scope if scoped), version stripped * - `git`: last URL path segment, `.git` suffix removed * - `url`: URL filename (extension stripped) or sanitised host as fallback * - `builtin`: returned unchanged (builtins are referenced by their own id) */ declare function deriveName(source: string, type: SourceType): string; interface TemplateFile { path: string; content: string; skipIfExists?: boolean; mode?: number; } interface TemplateVariable { name: string; description: string; default?: string; required?: boolean; validate?: (value: string) => boolean | string; } interface ScaffoldTemplate { name: string; description: string; variables: TemplateVariable[]; files: TemplateFile[]; postGenerate?: (projectDir: string, variables: Record) => Promise; } interface ScaffoldOptions { targetDir?: string; variables?: Record; force?: boolean; skipPostGenerate?: boolean; } interface ScaffoldResult { projectDir: string; files: string[]; skipped: string[]; overwritten: string[]; } declare class ScaffoldEngine { private templates; registerTemplate(template: ScaffoldTemplate): void; getTemplate(name: string): ScaffoldTemplate | undefined; listTemplates(): Array<{ name: string; description: string; }>; generate(templateName: string, projectName: string, options?: ScaffoldOptions): Promise; private resolveVariables; private interpolate; private toPascalCase; private toKebabCase; } declare const BASE_CLI_TEMPLATE: ScaffoldTemplate; declare const MINIMAL_PLUGIN_TEMPLATE: ScaffoldTemplate; declare const BROWSER_APP_TEMPLATE: ScaffoldTemplate; declare const DATABASE_CLI_TEMPLATE: ScaffoldTemplate; declare const API_CLI_TEMPLATE: ScaffoldTemplate; interface DebugHostOptions { cliName?: string; storageDir?: string; pluginDirs?: string[]; } interface ExecContext { page?: unknown; [key: string]: unknown; } type CommandMap = Record; result: unknown; }>; declare class TypedPluginHandle { private host; private _commandNames; constructor(host: DebugHost, commandNames: (keyof T & string)[]); get commandNames(): (keyof T & string)[]; exec(commandName: K, params?: T[K]['params'], context?: ExecContext): Promise>; } declare class DebugHost { private loader; private cliName; private pluginDirs; constructor(options?: DebugHostOptions); private defaultPluginDirs; resolvePluginPath(name: string): string | null; listAvailablePlugins(): string[]; load(name: string): Promise>; loadFunction(setup: (xcli: XCLIAPI) => void): Promise; exec(commandName: string, params?: Record, context?: ExecContext): Promise>; getCommandNames(): string[]; getSite(name: string): SiteInstance | undefined; get api(): XCLIAPI; private buildContext; } declare function createDebugHost(options?: DebugHostOptions): DebugHost; interface CommandDef { parameters: z.ZodType; result?: z.ZodType; } type CommandDefs = Record; type InferCommandMap = { [K in keyof T]: { params: z.infer; result: T[K] extends { result: z.ZodType; } ? z.infer : unknown; }; }; declare function defineCommands(defs: T): T; declare function generateTips(error: Error | string): Tip[]; /** * Read non-empty, non-comment lines from stdin. * * Returns an empty array when stdin is a TTY. Lines starting with `#` are * treated as comments and skipped. */ declare function readStdin(): Promise; /** * Read a command file and return non-empty, non-comment lines. */ declare function readCommandFile(filePath: string): string[]; /** * Split a single line by unquoted `|` pipe characters. * Respects single and double quotes. */ declare function splitFileLine(line: string): string[]; interface ParamFieldInfo { type: 'string' | 'number' | 'boolean' | 'enum' | 'array' | 'object' | 'unknown'; required: boolean; default?: unknown; enumValues?: string[]; description?: string; itemType?: ParamFieldInfo; } declare function extractParamFields(schema: ZodSchema): Record | null; declare function getCommandParamFields(entry: CommandEntry): Record | null; /** * Zod Schema 反射工具 * * 将 Zod 3 schema 反射为更结构化的数据,便于: * - 表单字段生成(FormField[]) * - LLM 友好的 contract 描述 * - 跨层(CLI / Web UI / LLM Agent)参数序列化 * * 设计原则: * 1. 防御性:所有输入都可能为 null/undefined/非 Zod schema * 2. 解构链:递归解开 ZodDefault / ZodOptional / ZodNullable * 3. 描述聚合:任意层级的 description 都会被收集 */ interface ZodUnwrapResult { /** 原始 schema(解开包装后) */ schema: unknown; /** 内部类型名,例如 'ZodString' / 'ZodObject' / 'unknown' */ typeName: string; /** 是否可空(optional / nullable / has default) */ optional: boolean; /** 任意层级出现的 description(最近的优先) */ description?: string; /** ZodDefault 提供的默认值(已求值) */ defaultValue?: unknown; } /** 表单字段契约(与 PluginFormField 对齐的子集) */ interface ReflectedField { name: string; type: string; required: boolean; default?: unknown; description?: string; enum?: string[]; itemType?: { type: string; required: boolean; }; multiple?: boolean; } /** * 递归解开 ZodDefault / ZodOptional / ZodNullable, * 提取出内部 typeName 与 optional / default / description 标志。 */ declare function unwrapZod(schema: unknown): ZodUnwrapResult; /** * 将 Zod typeName 映射为 contract 层的 type 字符串。 */ declare function zodTypeToContractType(typeName: string): string; /** * 提取 enum 的字符串值。 * - ZodEnum: 返回 options 数组 * - ZodNativeEnum: 返回 keys + string values(去重) * - 其它: 返回 undefined */ declare function extractEnumValues(schema: unknown): string[] | undefined; /** * 提取 ZodObject 的 shape 字段。 * - 非 ZodObject: 返回 [] * - ZodObject: 返回 ReflectedField[] */ declare function fieldsFromZodObject(schema: unknown): ReflectedField[]; type ChainOperator = '&&' | '||' | ';' | ',' | '->' | '+'; interface ChainStep { command: string; args: string[]; } interface ParsedChain { groups: ChainGroup[]; } interface ChainGroup { operator: ChainOperator; steps: ChainStep[]; } interface ChainStepResult { command: string; success: boolean; duration: number; error?: string; } interface ChainResult { success: boolean; steps: ChainStepResult[]; totalDuration: number; stoppedAt?: number; stoppedReason?: string; } declare function parseChain(input: string): ParsedChain; declare function isOperator(token: string): token is ChainOperator; declare function executeChain(chain: ParsedChain, executor: (command: string, args: string[]) => Promise<{ success: boolean; error?: string; }>, options?: { onStep?: (step: ChainStepResult) => void; }): Promise; /** * Split a command string into whitespace-separated tokens, respecting quotes. */ declare function splitCommand(cmdStr: string): string[]; /** * Register positional parameter names for a command used by {@link parseCommandArgs}. * * @param name - The command name. * @param positional - Ordered array of positional parameter names. */ declare function registerCommandDefinition(name: string, positional: string[]): void; declare function parseCommandArgs(name: string, args: string[], unquoteFn?: (raw: string) => string): { command: string; params: Record; }; interface HttpRequest { method: string; url: string; pathname: string; params: Record; query: Record; body: unknown; headers: Record; } interface HttpResponse { statusCode: number; headers: Record; body: unknown; } type HttpMiddleware = (req: HttpRequest, res: HttpResponse, next: () => Promise) => Promise; type RouteHandler = (req: HttpRequest) => Promise; interface HttpServerConfig { port: number; host?: string; } declare class HttpServer { private config; private middlewares; private router; private server; constructor(config: HttpServerConfig); use(middleware: HttpMiddleware): this; get(path: string, handler: RouteHandler): this; post(path: string, handler: RouteHandler): this; put(path: string, handler: RouteHandler): this; delete(path: string, handler: RouteHandler): this; start(): Promise; stop(): Promise; get address(): { port: number; host: string; } | null; private handleRequest; private runMiddlewares; private runRoute; private readBody; private normalizeHeaders; private sendResponse; } declare class Router { private routes; add(method: string, pattern: string, handler: RouteHandler): void; match(method: string, pathname: string): { handler: RouteHandler; params: Record; } | null; private tryMatch; } declare function cors(options?: { origins?: string[]; methods?: string[]; }): HttpMiddleware; declare function bearerTokenAuth(options: { tokens: string[]; publicPaths?: string[]; envTokenKey?: string; }): HttpMiddleware; declare function jsonBody(): HttpMiddleware; export { API_CLI_TEMPLATE, type AfterHookContext, type ArchiveStoreConfig, type ToolCallRecord as ArchiveToolCallRecord, BASE_CLI_TEMPLATE, BROWSER_APP_TEMPLATE, BROWSER_SCOPE_ORDER, type BaseScope, type BuiltinCommandEntry, COMMAND_SCOPE_ORDER, CONFIG_DIR, CONFIG_FILE, CONFIG_KEY_MAP, CacheStorage, type CacheStore, type ChainGroup, type ChainOperator, type ChainResult, type ChainStep, type ChainStepResult, type CommandArchiveEntry, type CommandArgs, type CommandContext, type CommandDef, type CommandDefs, type CommandEntry, CommandError, type CommandHandler, type CommandHooks, type CommandMap, type CommandResult, type CommandScope, type CommandValues, CompositeStorage, type ConfigSource, type ContextExtender, Core, type CoreConfig, DAEMON_CONFIG_PATH, DAEMON_PORT, DAEMON_SOCKET_PATH, DATABASE_CLI_TEMPLATE, DEFAULT_CHROMIUM_PATH, DEFAULT_DAEMON_CONFIG, DEFAULT_SCOPE as DEFAULT_GENERIC_SCOPE, DEFAULT_SCOPE$1 as DEFAULT_SCOPE, type DaemonConfig, type DaemonHostConfig, type DaemonRpcConfig, DebugHost, type DebugHostOptions, type EnvelopeFormatOptions, type EventContext, type EventHandler, type ExecContext, type ExtendedDaemonConfig, FileSessionPersistence, type FlagConfig, type FormatOptions, GlobalStorage, type GlobalStore, GroupedSiteInstance, type GuardConfig, type GuardRule, HelpGenerator, type HelpOptions, type HookContext, type HttpMiddleware, type HttpServerConfig as HttpMiddlewareServerConfig, type HttpRequest, type HttpResponse, HttpServer, type HttpServerConfig$1 as HttpServerConfig, type IPCMessage, type IPCResponse, type InferCommandMap, type InstallOptions, type PluginInstance as InstalledPluginInstance, type InstallerRegistryConfig, type LoginConfig, MINIMAL_PLUGIN_TEMPLATE, type Middleware, NpmInstaller, type OutlineEntry, type OutputContext, OutputFormatter, type OutputMode, type ParamFieldInfo, type ParseArgsOptions, type ParsedArgs, type ParsedChain, type PipelineContext, type PluginInstaller, PluginInstallerRegistry, type PluginInstallerType, PluginInstance$1 as PluginInstance, PluginLoader, type PluginLoaderHost, type PluginMeta, type PluginStatus, PluginStorage, type PluginStore, type PluginVerifyResult, type RPCHandler, type RcConfig, type ReflectedField, type RouteHandler, Router, SESSION_DIR, ScaffoldEngine, type ScaffoldOptions, type ScaffoldResult, type ScaffoldTemplate, type ScanOptions, type ScanResult, type ScopeConfig, type ScopeDefinition, type ScopeLevel, ScopeRegistry, type ScopedCommand, type SessionArchive, type SessionExtractor, type SessionInfo, type SessionLifecycle, SessionManager, type SessionManagerContract, type SessionMeta, type SessionPersistence, SessionStore, type SiteConfig, type SiteInstance, SiteInstanceImpl, type SourceType, type StorageContext, type TemplateFile, type TemplateVariable, type Tip, TipCollector, type TipLevel, TmpStorage, type TmpStore, type ToolCallRecord$1 as ToolCallRecord, type ToolConfig, UnknownOptionError, type ValidationResult, type VerifyPluginOptions, WSClient, type WSClientConfig, type WSEventCallback, type WSMessage$1 as WSMessage, type WSMessageCallback, type WSMessageHandler, WSServer, type WSServerConfig, type WorkerContext, type WorkerEntryPoint, WorkerManager, type WorkerManagerConfig, type XCLIAPI, type ZodSchema, type ZodUnwrapResult, addGuardRule, appendCommandToArchive, bearerTokenAuth, buildInputSchema, checkGuard, clearAll as clearAllSessions, clearGuardCache, coerceCliArgs, configureArchiveStore, cors, createDebugHost, createPaths, createSessionMeta, daemonRpc, defineCommands, deriveName, detectSourceType, diffArchives, downloadToFile, ensureDaemon, executeChain, extractEnumValues, extractParamFields, extractPositionalParams, extractTarGz, fail, fieldsFromZodObject as fieldsFromZodObjectReflected, findSession, flattenPackageRoot, formatValidationReport, generateTips, getAllConfigKeys, getChromiumPath, getCommandParamFields, getConfigValue, getDaemonPort, getDaemonStatus, getDefaultPort, getEffectiveValue, getEnvVar, getSession, getViewerHost, getViewerUrl, getWSServer, helpGenerator, isCommandResult, isDaemonRunning, isOperator, jsonBody, killAllDaemon, listArchives, listGuardRules, listSessions, loadArchive, loadConfig, loadGuardConfig, mapPositionalValues, mergeArgsWithDefaults, normalizeTip, normalizeTips, ok, outputFormatter, parseArgs, parseChain, parseCommandArgs, readCommandFile, readPluginMeta, readStdin, registerCommandDefinition, removeGuardRule, removeSession, resolveShortOptions, runDaemonHost, safeCleanup, saveArchive, saveConfig, searchArchives, defaultStore as sessions, setConfigValue, setGuardIdentityKey, splitCommand, splitFileLine, startDaemon, startHttpServer, startWSServer, stopDaemon, stopWSServer, tip, tipsToMessages, unquote, unwrapZod, validateArgs, validateExecution, verifyPlugin, withMeta, wrapResult, zodTypeToContractType };